#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import json
from pathlib import Path

BASE_DIR = Path(r"c:\Projects\KieuStory")
sys.path.insert(0, str(BASE_DIR / "05_Production_Pipeline"))
import production_orchestrator as po

shots = po.get_all_shots("ep01")
ep01_shots = [(k, v) for k, v in sorted(shots.items()) if any(k.startswith(f"ep01_scene{i:02d}") for i in range(1, 11))]

print(f"Total Ep01 shots analyzed: {len(ep01_shots)}")

analysis = []
for sid, sdata in ep01_shots:
    sc = sid.split("_shot")[0]
    take_type = po.classify_shot_take(sid, shot_data=sdata)
    curr_anchor = po.get_character_anchor(sid, sdata)
    sf_path, r_type = po.resolve_start_frame(sid, sdata, return_classification=True)
    asset_ref = sdata.get("character_asset_ref")
    ref_sf = sdata.get("reference_start_frame")
    
    sf_exists = Path(sf_path).exists() if sf_path else False
    
    analysis.append({
        "shot_id": sid,
        "scene": sc,
        "take_type": take_type,
        "anchor": curr_anchor,
        "asset_ref": asset_ref,
        "ref_sf": ref_sf,
        "resolved_sf": sf_path,
        "sf_exists": sf_exists
    })

# Summary by scene
by_scene = {}
for a in analysis:
    sc = a["scene"]
    if sc not in by_scene:
        by_scene[sc] = {
            "total": 0,
            "cuts": 0,
            "takes": 0,
            "cut_resolved_exists": 0,
            "cut_resolved_missing": 0,
            "take_resolved_exists": 0,
            "take_resolved_none": 0,
            "cut_none_shots": [],
            "take_none_shots": []
        }
    st = by_scene[sc]
    st["total"] += 1
    if a["take_type"] == "CINEMATIC_CUT":
        st["cuts"] += 1
        if a["sf_exists"]:
            st["cut_resolved_exists"] += 1
        else:
            st["cut_resolved_missing"] += 1
            st["cut_none_shots"].append(a["shot_id"])
    else:
        st["takes"] += 1
        if a["sf_exists"]:
            st["take_resolved_exists"] += 1
        else:
            st["take_resolved_none"] += 1
            st["take_none_shots"].append(a["shot_id"])

print("\n" + "=" * 90)
print(f"{'Scene':<15} | {'Tot':<4} | {'Cuts':<5} | {'CutOK':<6} | {'CutNone':<8} | {'Takes':<6} | {'TakeOK':<7} | {'TakeNone':<8}")
print("-" * 90)
for sc in sorted(by_scene.keys()):
    st = by_scene[sc]
    print(f"{sc:<15} | {st['total']:<4} | {st['cuts']:<5} | {st['cut_resolved_exists']:<6} | {st['cut_resolved_missing']:<8} | {st['takes']:<6} | {st['take_resolved_exists']:<7} | {st['take_resolved_none']:<8}")
print("=" * 90)

print("\nDetails of CutNone shots:")
for sc, st in sorted(by_scene.items()):
    if st["cut_none_shots"]:
        print(f"  {sc}: {st['cut_none_shots']}")

print("\nDetails of TakeNone shots (Continuous takes where prev_tail does NOT exist yet AND fallback is None):")
for sc, st in sorted(by_scene.items()):
    if st["take_none_shots"]:
        print(f"  {sc}: {st['take_none_shots']}")

# Inspect where the 80 existing Cut SFs come from
print("\nSources of resolved Cut Start Frames:")
sources = {}
for a in analysis:
    if a["take_type"] == "CINEMATIC_CUT" and a["sf_exists"]:
        p = Path(a["resolved_sf"])
        rel = str(p.relative_to(BASE_DIR)) if p.is_relative_to(BASE_DIR) else str(p)
        parent_dir = str(Path(rel).parent)
        sources[parent_dir] = sources.get(parent_dir, 0) + 1
for s, c in sorted(sources.items()):
    print(f"  {s}: {c} shots")
