"""TASK① 실증 드라이버 (커밋 금지) — indoor guide가 실제 nb2 최종샷 gen 입력으로
끝까지 가는지 end-to-end 증명.

scene 5/14/21/29의 selected(is_primary=1) still 10개를 비파괴 reset
(is_primary=0 + checkpoint 엔트리 제거, 기존 PNG 보존) 후 generate_images(resume)
→ 내부 precompute가 indoor guide admit + 그 샷들만 재생성 + attach_indoor_pose_guide_ref
발동 → scene_image_gen.reference_image_ids에 [INDOOR POSE GUIDE] 기록되는지 검증.
"""
import os
import sys
import json
import shutil

# ★ flag ON — app import 전에 (pydantic BaseSettings는 import 시 env 읽음).
os.environ["INDOOR_SHARED_POSE_GUIDE_ENABLED"] = "true"
os.environ["INDOOR_SHARED_POSE_GUIDE_JUDGE_ENABLED"] = "true"

_BACKEND = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "backend"))
os.chdir(_BACKEND)
sys.path.insert(0, _BACKEND)

PID = "7f325c39-7478-4386-a562-27daadd44353"
EID = "fbf15266-989c-4cc8-8d82-699ea5f628aa"

# scene 5/14/21/29의 selected(is_primary=1) still_id (admitted: s5/12,s14/5,s21/6,s29/10 포함)
TARGET_STILLS = [
    "4af20d76-93e5-4261-ba70-222bc9d7d3a4",  # s5 sh4
    "b78850f4-20bb-4429-9230-c64c22e45188",  # s5 sh9
    "2e22767d-c7d4-4ed7-b658-0a6d9bc3e332",  # s5 sh12 (admitted)
    "22ed65ab-7785-40f8-9485-8306ff7d4756",  # s14 sh5 (admitted)
    "e80999c6-a229-4fc8-a552-77ce2553d920",  # s14 sh8
    "83b4b93b-a1f3-458f-a9e4-266ef269a2e2",  # s21 sh6 (admitted)
    "ce57010f-9fe5-4ef6-8b57-6c1b267f624c",  # s21 sh10
    "d37df2a8-3918-48c4-b358-5063994354c8",  # s29 sh5
    "4262a1ac-8112-49cb-8fe7-345d2f6383eb",  # s29 sh7
    "7a9b108a-a920-4dad-81d6-9bf86cbfe542",  # s29 sh10 (admitted)
]

CP = ("/Users/manta/Documents/Projects/TheRoad-I1/projects/" + PID +
      "/checkpoints/images/" + EID + "/scene_checkpoint.json")


def reset_targets(db):
    from sqlalchemy import text
    # 1) DB: 대상 still의 scene asset is_primary=0 (비파괴 — PNG/row 보존)
    n = db.execute(text(
        "UPDATE image_asset SET is_primary=0 "
        "WHERE project_id=:pid AND episode_id=:eid AND asset_type='scene' "
        "AND still_id = ANY(:sids) AND is_primary=1"
    ), {"pid": PID, "eid": EID, "sids": TARGET_STILLS})
    db.commit()
    print(f"[reset] is_primary=0 applied rows={n.rowcount}")
    # 2) checkpoint: 대상 cp_id 엔트리 제거 (원본 백업 1회만 — 재실행시 보존)
    if not os.path.exists(CP + ".e2e_bak"):
        shutil.copy(CP, CP + ".e2e_bak")
    d = json.load(open(CP))
    comp = d.get("completed", {})
    removed = [t for t in TARGET_STILLS if t in comp]
    for t in removed:
        comp.pop(t, None)
    d["completed"] = comp
    json.dump(d, open(CP, "w"), ensure_ascii=False, indent=2)
    print(f"[reset] checkpoint removed {len(removed)} entries (backup .e2e_bak)")


def main():
    from app.core.config import settings
    print("flags:", settings.indoor_shared_pose_guide_enabled,
          settings.indoor_shared_pose_guide_judge_enabled)
    from app.core.database import SessionLocal, register_models
    register_models()  # FK 해소 (entity_canon.project_id → project_registry)
    from app.services.scene_image_service import SceneImageService

    db = SessionLocal()
    try:
        reset_targets(db)
    finally:
        db.close()

    print("\n=== generate_images(resume) 시작 (precompute+attach+gen) ===", flush=True)
    db2 = SessionLocal()
    try:
        svc = SceneImageService(db=db2, project_id=PID, actor_id="e2e-proof")
        svc.generate_images(EID, mode="resume")
    finally:
        db2.close()

    print("\n=== 검증: 방금 scene_image_gen 호출에 [INDOOR POSE GUIDE] 첨부? ===", flush=True)
    from app.core.database import SessionLocal as SL
    from sqlalchemy import text
    db3 = SL()
    try:
        rows = db3.execute(text("""
            SELECT (metadata_json::json->>'scene_index') AS si,
                   (metadata_json::json->>'shot_index') AS shi,
                   (reference_image_ids ILIKE '%INDOOR POSE GUIDE%') AS has_guide,
                   created_at
            FROM llm_call_log
            WHERE operation_type='scene_image_gen' AND project_id=:pid
            ORDER BY created_at DESC LIMIT 20
        """), {"pid": PID}).fetchall()
        for r in rows:
            print(f"  scene={r[0]} shot={r[1]} has_indoor_guide={r[2]} at={r[3]}")
    finally:
        db3.close()


if __name__ == "__main__":
    main()
