#!/usr/bin/env python3
"""남은 작업 D 갈래 실측 — 오늘 완주한 주행 데이터로.

D-2(#31) 참조 선별 검사 넷 · D-3(#97) era 캐시 적중률 · #106 버려진 샷.
"""
import json
import pathlib
import sys
from collections import Counter

ROOT = pathlib.Path("/Users/manta/Documents/Projects/TheRoad-I1")
PID = "759e2b63-52cf-4d1b-8953-8599ac2a6141"
EPI = "3e83f3ee-ded7-4f2a-aded-01584d6ea5c5"
REC = ROOT / f"projects/{PID}/images/{EPI}/scene/recipe/records.json"

rec = json.loads(REC.read_text(encoding="utf-8"))

print("═══ D-2 · 참조 선별 검사 넷 (#31) ═══\n")

gates, kept_hist, ungated, missing = [], Counter(), 0, 0
for key, val in rec.items():
    blob = json.dumps(val, ensure_ascii=False)
    if "fix_ref_gate" in blob:
        gates.append(key)
    # kept / mode 값을 실제로 꺼낸다 (문자열 세기로 끝내지 않는다)
    def walk(o, path=""):
        global ungated, missing
        if isinstance(o, dict):
            for k, v in o.items():
                if k in ("mode",) and v == "all_ungated":
                    ungated += 1
                if k == "missing_without_ref" and v:
                    missing += 1
                if k == "kept" and isinstance(v, list):
                    kept_hist[len(v)] += 1
                if k == "kept" and isinstance(v, int):
                    kept_hist[v] += 1
                walk(v, f"{path}.{k}")
        elif isinstance(o, list):
            for x in o:
                walk(x, path)
    walk(val)

print(f"① fix_ref_gate 기록이 남은 항목: {len(gates)} — {gates}")
print(f"② mode=all_ungated: {ungated}건  (기대 0)")
print(f"③ missing_without_ref 참: {missing}건  (기대 0)")
print(f"④ kept 분포: {dict(sorted(kept_hist.items()))}")

# 양성 확인 — 그런 칸이 실제로 존재하는지
allkeys = Counter()
def keys(o):
    if isinstance(o, dict):
        for k, v in o.items():
            allkeys[k] += 1
            keys(v)
    elif isinstance(o, list):
        for x in o:
            keys(x)
keys(rec)
for probe in ("mode", "kept", "missing_without_ref", "fix_ref_gate",
              "ref_gate", "gate", "selected", "refs", "labeled_refs"):
    print(f"     양성확인 · 칸 '{probe}' 등장 {allkeys.get(probe,0)}회")

print("\n═══ D-3 · era 캐시 신원 (#97) ═══\n")
era = {k: v for k, v in rec.items() if k.startswith("era_")}
print(f"era 기록 {len(era)}건: {list(era)}")
for k, v in era.items():
    if isinstance(v, dict):
        sub = {kk: (str(vv)[:70] if not isinstance(vv, (dict, list)) else
                    f"<{type(vv).__name__} {len(vv)}>")
               for kk, vv in list(v.items())[:14]}
        print(f"  {k}:")
        for kk, vv in sub.items():
            print(f"     {kk} = {vv}")
