"""Opik trace v2 실물 확인 — 모델 호출 0건, 자체 호스팅에만 쓴다.

`theroad-trace-v2-smoke` 프로젝트에 쓴다. 프로덕션 감사 데이터는 안 건드린다.
"""
import json
import os
import time
import urllib.request

os.environ["OPIK_PROJECT_NAME"] = "theroad-trace-v2-smoke"
os.environ["OPIK_TRACE_V2_ENABLED"] = "true"

from app.modules.llm.opik_trace import (  # noqa: E402
    build_axis_tags, current_trace, episode_thread_id, open_trace)

BASE = "http://192.168.133.87:5173/api"
HDR = {"Comet-Workspace": "default"}


def get(path):
    return json.load(urllib.request.urlopen(
        urllib.request.Request(f"{BASE}{path}", headers=HDR), timeout=30))


thread = episode_thread_id(project_name="스모크", episode_title="1회",
                          episode_id="deadbeef-0000-0000-0000-000000000000")
print("thread_id =", thread)

with open_trace(name="step:scene_image_pipeline",
                tags=build_axis_tags(step="scene_image_pipeline"),
                metadata={"project_id": "p", "episode_id": "e"},
                thread_id=thread) as step_h:
    assert step_h is not None, "trace 가 안 열렸다"
    for i in range(2):
        with open_trace(name=f"still:smoke{i} · still_recipe",
                        tags=build_axis_tags(step="still_recipe"),
                        metadata={"still_id": f"smoke{i}"},
                        thread_id=thread) as shot_h:
            from app.modules.llm.image_tracer import get_image_tracer
            for op in ("roll", "judge", "fix"):
                get_image_tracer().log(
                    step="still_recipe", model="probe-model",
                    prompt="확인용", duration_ms=1,
                    params={"role": op}, provider="probe",
                    extra_metadata={"still_id": f"smoke{i}"})
            print(f"  샷 {i}: trace={shot_h.uid[:8]} 부모={step_h.uid[:8]}")

time.sleep(4)
projs = get("/v1/private/projects?page=1&size=100")
pid = next(p["id"] for p in projs["content"]
           if p["name"] == "theroad-trace-v2-smoke")
tr = get(f"/v1/private/traces?project_id={pid}&page=1&size=50")
print(f"\ntrace {tr['total']}건")
bad_name, bad_tag, threads = 0, [], set()
for t in tr["content"]:
    print(f"  · {t['name']:34s} span={t['span_count']} thread={t['thread_id']}")
    if t["name"] == "chat.completion":
        bad_name += 1
    bad_tag += [x for x in (t.get("tags") or []) if ":" not in x]
    threads.add(t["thread_id"])

print(f"\n관문 1 chat.completion 0건 : {'OK' if bad_name == 0 else f'FAIL {bad_name}'}")
print(f"관문 2 thread 1개          : {'OK' if len(threads) == 1 else f'FAIL {threads}'}")
print(f"관문 3 계층(span>1)        : "
      f"{'OK' if any(t['span_count'] > 1 for t in tr['content']) else 'FAIL'}")
print(f"관문 4 접두사 없는 trace 태그 0 : {'OK' if not bad_tag else f'FAIL {bad_tag}'}")
