import re
import sys
import json
from pathlib import Path

sys.stdout.reconfigure(encoding='utf-8')

screenplay_path = Path("FilmMaker/TAP_01_XUAN_SAC_THE_NGUYEN_VA_GIONG_BAO_DOAN_TRUONG.md")
content = screenplay_path.read_text(encoding="utf-8")

# Extract scene headers and their ranges
scene_headers = list(re.finditer(r'####\s+CẢNH\s+(\d+):\s*([^\n]+)', content))
scenes_meta = {}
for i, m in enumerate(scene_headers):
    sc_num = int(m.group(1))
    sc_title = m.group(2).strip()
    start_pos = m.start()
    end_pos = scene_headers[i+1].start() if i+1 < len(scene_headers) else len(content)
    scenes_meta[sc_num] = {
        "title": sc_title,
        "content": content[start_pos:end_pos]
    }

shot_pattern = re.compile(
    r'#####\s+Shot\s+(\d+):\s*[`\x60](ep01_scene\d+_shot\d+)[`\x60]\s*\(([^)]+)\)\n'
    r'-\s*\*\*Cỡ cảnh & Máy quay\*\*:\s*([^\n]+)\n'
    r'-\s*\*\*Thị giác\*\*:\s*(.*?)\n'
    r'-\s*\*\*Âm thanh 4 Stems\*\*:\s*\n'
    r'(.*?)(?=(?:#####\s+Shot|####\s+CẢNH|\Z))',
    re.DOTALL
)

all_shots = []
for sc_num, sc_data in scenes_meta.items():
    sc_text = sc_data["content"]
    sc_shots = list(shot_pattern.finditer(sc_text))
    print(f"Scene {sc_num:02d}: {len(sc_shots)} shots - {sc_data['title'][:50]}")
    for m in sc_shots:
        shot_num = int(m.group(1))
        shot_id = m.group(2)
        duration = m.group(3)
        camera_info = m.group(4).strip()
        visual_info = m.group(5).strip()
        audio_info = m.group(6).strip()
        
        # Check dialogue / vocal
        vocal_match = re.search(r'\*Stem 4 \(Vocal\)\*:\s*([^\n]+)', audio_info)
        vocal_text = vocal_match.group(1).strip() if vocal_match else ""
        
        all_shots.append({
            "scene_num": sc_num,
            "scene_title": sc_data["title"],
            "shot_num": shot_num,
            "shot_id": shot_id,
            "duration": duration,
            "camera_info": camera_info,
            "visual_info": visual_info,
            "audio_info": audio_info,
            "vocal_text": vocal_text
        })

print(f"Total parsed: {len(all_shots)}")

# Analyze dialogues and offscreen calls
offscreen_shots = []
for s in all_shots:
    combined = s["visual_info"] + " " + s["audio_info"] + " " + s["camera_info"]
    if any(k in combined.lower() for k in ["từ xa", "ngoài khung", "bên kia tường", "khóa khẩu hình", "r5", "v.o."]):
        offscreen_shots.append(s["shot_id"])

print(f"Shots with offscreen/distant/V.O./Lip-sync cues: {len(offscreen_shots)}")
print("Sample offscreen shots:", offscreen_shots[:15])
