import hashlib, re, sys, datetime as dt
from collections import defaultdict
sys.path.insert(0, "/Users/manta/Documents/Projects/TheRoad-I1/scratchpad")
from _opik_env import opik_target
from tools.opik_prompt_audit.audit.fetch import fetch_spans
BASE, WS, PROJ = opik_target()
sd = sorted((x for x in fetch_spans(BASE, WS, PROJ, "2026-08-24T16:00:00", "2026-08-26T00:00:00")
             if "op:scene_detail" in (x.get("tags") or [])), key=lambda x: x["start_time"])
g = defaultdict(list)
for x in sd:
    inp = x.get("input"); msgs = inp if isinstance(inp, list) else (inp or {}).get("messages") or []
    for m in msgs:
        if m.get("role") != "system": continue
        c = m.get("content")
        if isinstance(c, list): c = "\n".join(p.get("text","") for p in c if isinstance(p, dict))
        c = c or ""
        h = hashlib.sha256(c.encode()).hexdigest()[:12]
        g[(len(c), h, "광원대응표" if "the fluorescent tube flickers" in c else "없음",
           "envelope산문" if "card envelope 는 `schema_version`" in c else "없음")].append(x["start_time"])
for k, ts in sorted(g.items(), key=lambda kv: min(kv[1])):
    n, h, lamp, env = k
    a = (dt.datetime.fromisoformat(min(ts).replace("Z","+00:00"))+dt.timedelta(hours=9)).strftime("%H:%M:%S")
    b = (dt.datetime.fromisoformat(max(ts).replace("Z","+00:00"))+dt.timedelta(hours=9)).strftime("%H:%M:%S")
    print(f"{n:>7,}자  sha {h}  광원표={lamp:<6} envelope={env:<10} {len(ts):>3}컷  {a}~{b} KST")
