#!/usr/bin/env python3
"""W-L canary 검증 — checkpoint(구조필드/라벨) + DB(asset/lineage) 실측."""
import json
import subprocess
from pathlib import Path

PID = "b0ad5c18-5140-4022-a2b0-805de0e5a385"
EID = "0d30302a-51c8-4ac9-98e2-6cd9180512bf"
ROOT = Path("/Users/manta/Documents/Projects/TheRoad-I1")
CP = ROOT / "projects" / PID / "checkpoints" / "episodes" / EID / "background_render" / "manifest.json"

m = json.loads(CP.read_text())
data = m.get("data", {})
groups = data.get("groups", {})
la = data.get("location_aerials", {})

print("=== manifest 요약 ===")
print("config_hash:", m.get("config_hash"))
print("completed/applicable/failed:",
      m.get("completed_count"), "/", m.get("applicable_count"), "/", m.get("failed_count"))

print("\n=== location_aerials ===")
for loc, e in sorted(la.items()):
    print(f"  {loc}: status={e.get('status')} cached={e.get('cached')} "
          f"fp_used={e.get('building_fp_used')} attempts={e.get('attempts')} "
          f"png={'OK' if e.get('png_path') and Path(e['png_path']).exists() else 'MISSING'}")

print("\n=== groups: aerial 치환 실측 ===")
outdoor_ok, indoor_ok, problems = [], [], []
for bid, g in sorted(groups.items()):
    if not isinstance(g, dict) or g.get("status") != "ok":
        continue
    lin = g.get("attached_reference_lineage") or {}
    labels = lin.get("attached_ref_labels") or []
    has_aerial = bool(g.get("aerial_ref"))
    fp_labels = [x for x in labels if x.startswith("fp:")]
    aerial_labels = [x for x in labels if x.startswith("aerial:")]
    if has_aerial:
        outdoor_ok.append(bid)
        ok_first = bool(labels) and labels[0].startswith("aerial:")
        if not ok_first or fp_labels:
            problems.append((bid, "aerial 첨부인데 라벨 순서/fp 잔존 이상", labels))
        print(f"  {bid} [loc {g.get('location_id')}] aerial_ref={g.get('aerial_ref')} "
              f"replaced={g.get('fp_ref_replaced_by_aerial')} labels={labels} ref_used={g.get('ref_used')}")
    else:
        indoor_ok.append(bid)
        if aerial_labels:
            problems.append((bid, "aerial_ref 없는데 aerial 라벨", labels))

print("\n  aerial 첨부 bg:", len(outdoor_ok), outdoor_ok)
print("  비대상(실내/실패) bg:", len(indoor_ok))

print("\n=== 실내 bg 무변경 확인 (fp 라벨 유지 샘플) ===")
for bid in [b for b in indoor_ok if b.startswith(("L04", "L09B02", "L12", "L15", "L19"))][:6]:
    g = groups[bid]
    labels = (g.get("attached_reference_lineage") or {}).get("attached_ref_labels") or []
    print(f"  {bid}: labels={labels}")

print("\n=== DB: location_aerial asset + bg lineage ===")
sql = f"""
SELECT a.variant_type, a.id, a.input_image_ids
FROM image_asset a WHERE a.episode_id='{EID}' AND a.asset_type='location_aerial'
ORDER BY a.variant_type;
"""
r = subprocess.run(
    ["psql", "-h", "localhost", "-U", "theroad", "-d", "theroad", "-tAc", sql],
    env={"PGPASSWORD": "theroad_dev_2026", "PATH": "/usr/bin:/bin:/opt/homebrew/bin"},
    capture_output=True, text=True)
print(r.stdout or r.stderr)

sql2 = f"""
SELECT a.variant_type, a.input_image_ids
FROM image_asset a WHERE a.episode_id='{EID}' AND a.asset_type='chain_bg'
  AND a.variant_type IN ('L03B01','L03B02','L08B01','L10B01','L10B02','L13B01','L17B01','L04B01','L09B02')
ORDER BY a.variant_type;
"""
r2 = subprocess.run(
    ["psql", "-h", "localhost", "-U", "theroad", "-d", "theroad", "-tAc", sql2],
    env={"PGPASSWORD": "theroad_dev_2026", "PATH": "/usr/bin:/bin:/opt/homebrew/bin"},
    capture_output=True, text=True)
print(r2.stdout or r2.stderr)

print("\n=== 판정 ===")
if problems:
    print("PROBLEMS:")
    for p in problems:
        print("  ", p)
else:
    print("구조필드/라벨 이상 없음")
