"""Wave5 통합 배선 검증 드라이버 (커밋 금지).

load_indoor_shared_pose_guides 를 기존 7f325c39/fbf15266 에 직접 호출 →
gate→judge→guide+QC→capture 전체 체인이 실데이터에서 발동하는지 저렴하게 검증.
풀 이미지 재렌더 없이 indoor precompute + capture + canvas 만 확인.
"""
import os
import sys

# ★ 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 cwd 로 이동 — pydantic env_file=".env" 가 backend/.env(BACKGROUND_CHAIN_ENABLED=true
# 등 production flag)를 읽도록. 안 하면 root cwd 에서 bgmap=0(background_chain disabled).
_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"


def main():
    from app.core.config import settings
    print("flags:", settings.indoor_shared_pose_guide_enabled,
          settings.indoor_shared_pose_guide_judge_enabled,
          "| judge_model:", settings.indoor_shared_pose_guide_judge_model,
          "| qc_model:", settings.indoor_shared_pose_guide_qc_model)

    from app.core.database import SessionLocal
    from app.services.scene_checkpoint_loaders import (
        load_background_chain_bg_map,
        load_shot_staging_map,
    )
    from app.core.steps.indoor_shared_pose_guide_context import (
        load_indoor_shared_pose_guides,
        _load_bg_loc_by_id,
        _load_indoor_outdoor_locs,
        _load_bg_asset_by_id,
    )
    from app.services.scene_persistence_service import ScenePersistenceService

    db = SessionLocal()
    try:
        persistence = ScenePersistenceService(db, PID)
        stills, _orm = persistence.load_episode_still_dicts(EID)
        print(f"stills: {len(stills)}")

        staging_map = load_shot_staging_map(settings.projects_dir, PID, EID)
        bgmap = load_background_chain_bg_map(settings.projects_dir, PID, EID)
        print(f"staging_map: {len(staging_map)} | bgmap: {len(bgmap)}")

        bg_loc = _load_bg_loc_by_id(settings.projects_dir, PID, EID)
        indoor_locs, outdoor_locs = _load_indoor_outdoor_locs(settings.projects_dir, PID, EID)
        bg_asset = _load_bg_asset_by_id(db, PID, EID)
        print(f"bg_loc_by_id: {len(bg_loc)} | indoor_locs: {sorted(indoor_locs)} | "
              f"outdoor_locs: {sorted(outdoor_locs)} | bg_asset_by_id: {len(bg_asset)}")

        # openai_client=None → 서비스 내부 _resolve_openai_client() 가 적절 client 해결.
        ctx = load_indoor_shared_pose_guides(
            project_id=PID, episode_id=EID, stills=stills, staging_map=staging_map,
            background_chain_bg_map=bgmap, zoom_ctx=None, db=db, openai_client=None,
        )
        print("\n=== RESULT ===")
        print(f"guides generated: {len(ctx.get('guide_by_shot') or {})}")
        for k, v in (ctx.get("guide_by_shot") or {}).items():
            print(f"  guide shot {k}: group={v['group_id']} png={len(v['png'])}B focus={v['visible_focus']}")
        print(f"diagnostics: {len(ctx.get('diagnostics') or [])}")
        for d in (ctx.get("diagnostics") or []):
            print(f"  diag: {d}")
    finally:
        db.close()


if __name__ == "__main__":
    main()
