"""3a recording 오프라인 검증 — 재렌더 없이 production 로직(_compose_bg_input_image_ids)을
기존 background_render manifest + 실 DB 로 돌려 예상 input_image_ids/엣지를 계산.
커밋 금지(scratchpad). 실행: backend/.venv/bin/python scratchpad/p3a_offline_verify.py
"""
import json
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app.core.steps.background_render_step import _compose_bg_input_image_ids  # noqa: E402

PROJ = "a7f80ab9-e97b-420c-a380-3beccb0bcfe5"
EP = "286f3ba4-5738-49b7-a7e4-ce0295fd4352"
MF = (f"projects/{PROJ}/checkpoints/episodes/{EP}/background_render/manifest.json")


def _psql(sql):
    import subprocess
    env = dict(os.environ, PGPASSWORD="theroad_dev_2026")
    out = subprocess.run(
        ["psql", "-h", "localhost", "-U", "theroad", "-d", "theroad",
         "-t", "-A", "-F", "\t", "-c", sql],
        env=env, capture_output=True, text=True).stdout
    return [ln.split("\t") for ln in out.strip().splitlines() if "\t" in ln]


def main():
    d = json.load(open(os.path.join(
        os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "..", MF)))
    groups = d["data"].get("groups", {})
    # DB resolver: bg variant_type -> uuid, fp variant_type -> uuid
    bg_uuid = {vt: i for vt, i in _psql(
        f"SELECT variant_type,id FROM image_asset WHERE episode_id='{EP}' "
        f"AND pipeline_role='background_render' AND variant_type IS NOT NULL")}
    fp_uuid = {vt: i for vt, i in _psql(
        f"SELECT variant_type,id FROM image_asset WHERE episode_id='{EP}' "
        f"AND pipeline_role='floor_plan' AND variant_type IS NOT NULL")}

    rows = []
    n_edge = 0
    n_reuse = 0
    n_unresolved = 0
    for bid in sorted(groups):
        g = groups[bid]
        if g.get("status") != "ok":
            continue
        lin = g.get("attached_reference_lineage") or {}
        prior = [str(b) for b in (lin.get("prior_bg_ids") or []) if b]
        reuse = (lin.get("ref_used") == "reused_plate")
        fpid = lin.get("fp_id") or ""
        fpu = fp_uuid.get(fpid)
        iids, meta = _compose_bg_input_image_ids(prior, fpu, bg_uuid, reuse=reuse)
        if len(iids) >= 2:
            n_edge += 1
        if reuse:
            n_reuse += 1
        if meta.get("unresolved_inputs"):
            n_unresolved += 1
        rows.append((bid, g.get("location_id"), prior, meta["lineage_kind"],
                     len(iids), meta.get("unresolved_inputs")))

    print(f"{'bg_id':10} {'loc':6} {'prior_bg_ids':22} {'kind':16} "
          f"{'n_iids':6} unresolved")
    for bid, loc, prior, kind, n, unres in rows:
        print(f"{bid:10} {str(loc):6} {str(prior):22} {kind:16} {n:<6} {unres or ''}")
    print(f"\n총 ok bg: {len(rows)} | 엣지(n_iids>=2): {n_edge} | reuse_alias: "
          f"{n_reuse} | unresolved 있는 bg: {n_unresolved}")
    # dedup/fp 무결성 체크
    fp_missing = [r[0] for r in rows if r[3] != "reuse_alias"
                  and r[4] and False]  # placeholder
    print("(fp resolver 크기:", len(fp_uuid), "| bg resolver 크기:", len(bg_uuid), ")")


if __name__ == "__main__":
    main()
