import json
import re
import sys

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

print("=== AUDIT CHECK 1: BANANA PROMPTS SCHEMA & INTEGRITY ===")
with open('02_AI_Prompts/gemini_banana_prompts.json', 'r', encoding='utf-8') as f:
    banana = json.load(f)

sub_prompts = banana.get('ep01_start_frames', {})
assert len(sub_prompts) == 188, f"Expected 188 in subdict, got {len(sub_prompts)}"

for sid, entry in sub_prompts.items():
    assert sid.startswith('ep01_scene'), f"Bad ID: {sid}"
    assert entry.get('resolution') == '1280x720', f"Bad resolution in {sid}: {entry.get('resolution')}"
    assert len(entry.get('character_anchor', '')) > 0, f"Empty character_anchor in {sid}"
    assert len(entry.get('environment_anchor', '')) > 0, f"Empty environment_anchor in {sid}"
    assert len(entry.get('prompt', '')) >= 100, f"Too short prompt in {sid}"
    assert sid in banana, f"Top-level missing {sid}"
print("CHECK 1 PASS: All 188 Banana start frames have complete schema, resolution 1280x720, rich anchors.")

print("=== AUDIT CHECK 2: MUSE.AI MOTION PROMPTS & AUDIO GUARDS ===")
with open('02_AI_Prompts/muse_ai_video_prompts.json', 'r', encoding='utf-8') as f:
    muse = json.load(f)

m_prompts = {k: v for k, v in muse.get('motion_prompts', {}).items() if k.startswith('ep01_scene')}
assert len(m_prompts) == 188, f"Expected 188 in muse, got {len(m_prompts)}"

audio_guard_count = 0
motion_vector_count = 0
for sid, val in m_prompts.items():
    text = json.dumps(val, ensure_ascii=False)
    assert len(text) >= 100, f"Too short in {sid}"
    if 'tuyệt đối không sinh nhạc nền' in text or 'no music' in text:
        audio_guard_count += 1
    if any(w in text.lower() for w in ['camera', 'chuyển động', 'bước', 'bay', 'tiến', 'pan', 'dolly', 'track', 'tilt', 'zoom']):
        motion_vector_count += 1

assert audio_guard_count == 188, f"Expected 188 audio guards, got {audio_guard_count}"
assert motion_vector_count == 188, f"Expected 188 motion vectors, got {motion_vector_count}"
print("CHECK 2 PASS: 100% of 188 Muse prompts have Audio Guards and active motion vectors.")

print("=== AUDIT CHECK 3: LIP-SYNC & CLOSED-LIPS IN OFF-SCREEN / VO SHOTS ===")
offscreen_vo_shots = []
closed_lips_present = []

for sid, val in m_prompts.items():
    text = json.dumps(val, ensure_ascii=False).lower()
    is_offscreen_or_vo = any(k in text for k in ['từ xa', 'ngoài khung', 'v.o.', 'o.s.', 'thoại xa', 'tiếng gọi từ xa'])
    if is_offscreen_or_vo:
        offscreen_vo_shots.append(sid)
        has_guard = any(w in text for w in ['khép chặt', 'lips closed', 'không mấp máy', 'khóa khẩu hình'])
        if has_guard:
            closed_lips_present.append(sid)
        else:
            print(f"WARNING: Offscreen/VO shot {sid} missing closed-lips guard!")

print(f"Found {len(offscreen_vo_shots)} offscreen/VO shots; {len(closed_lips_present)} guarded.")
assert len(offscreen_vo_shots) == len(closed_lips_present), "Some offscreen/VO shots missing closed-lips guard!"
print("CHECK 3 PASS: 100% of off-screen / VO dialogue shots have mandatory closed-lips guard.")

print("=== AUDIT CHECK 4: ANTI-MALE-TEARS ZERO TOLERANCE ===")
# Specific check: No male character is described as crying or weeping
forbidden_male_crying_patterns = [
    r'(kim trọng|vương quan|vương ông|từ hải|thúc sinh|kim trong|vuong quan|vuong ong|tu hai|thuc sinh)[^.]*(rơi lệ|rơi nước mắt|khóc ròng|khóc nghẹn|khóc thét|gào khóc|weeping(?! willow)|crying)',
    r'(rơi lệ|rơi nước mắt|khóc ròng|khóc nghẹn|khóc thét|gào khóc)\s+(của|bởi)?\s*(kim trọng|vương quan|vương ông|từ hải|thúc sinh)',
    r'(tears\s+on\s+(kim trong|vuong quan|vuong ong|tu hai|male)\b)'
]

for dataset_name, dset in [('Banana', sub_prompts), ('Muse', m_prompts)]:
    for sid, entry in dset.items():
        text = json.dumps(entry, ensure_ascii=False)
        pos_text = text.split('--no')[0].lower() # only look before negative prompt
        for pat in forbidden_male_crying_patterns:
            matches = list(re.finditer(pat, pos_text))
            for m in matches:
                matched_snippet = pos_text[m.start():m.end()]
                # If explicitly negated like 'tuyệt đối không khóc' or 'not a single tear'
                if not any(neg in matched_snippet for neg in ['không', 'zero', 'not a single']):
                    raise AssertionError(f"ACTIVE MALE TEARS DETECTED in {dataset_name} {sid}: {matched_snippet}")
print("CHECK 4 PASS: Zero active male weeping detected across all 188 Banana & 188 Muse prompts.")

print("=== AUDIT CHECK 5: CHARACTER BIBLE EXPANSIONS & DIRECTIVES ===")
with open('00_Project_Bible/CHARACTER_BIBLE.md', 'r', encoding='utf-8') as f:
    cb = f.read()

assert 'MA TRẬN ĐỐI CHIẾU 4 TRỤC SONG SINH THÚY KIỀU & THÚY VÂN' in cb, "Missing Twin Matrix"
assert 'Áo chẽn nẹp vạt lính tráng' in cb, "Missing Sai Nha authentic attire"
assert 'Nón dấu sơn son chóp nhọn' in cb, "Missing Sai Nha helmet"
assert 'đao bản rộng cổ' in cb.lower(), "Missing Sai Nha broad saber"
assert 'QUY CHUẨN DIỄN XUẤT PHỔ QUÁT & BẢO TOÀN LỄ GIÁO' in cb, "Missing Acting Directives Summary"
print("CHECK 5 PASS: CHARACTER_BIBLE.md has complete Twin Matrix, medieval Sai Nha, and acting directives.")

print("=== AUDIT CHECK 6: UNIVERSAL ACTING DIRECTIVES BIBLE ===")
with open('00_Project_Bible/UNIVERSAL_ACTING_DIRECTIVES.md', 'r', encoding='utf-8') as f:
    uad = f.read()
assert 'ANTI-MALE-TEARS DIRECTIVE' in uad
assert '4 Vi Biểu Cảm Khắc Kỷ' in uad
assert 'KHÓA KHẨU HÌNH BẮT BUỘC' in uad
assert 'SWEET-SPOT START FRAME 2 BƯỚC' in uad
assert 'VERSIONING VIDEO MP4' in uad
print("CHECK 6 PASS: UNIVERSAL_ACTING_DIRECTIVES.md is comprehensive and authoritative.")

print("=== AUDIT CHECK 7: SCREENPLAY 188-SHOT SYNCHRONIZATION ===")
with open('FilmMaker/TAP_01_XUAN_SAC_THE_NGUYEN_VA_GIONG_BAO_DOAN_TRUONG.md', 'r', encoding='utf-8') as f:
    sc = f.read()
sc_shots = set(re.findall(r'ep01_scene\d{2}_shot\d{2}', sc, re.IGNORECASE))
assert len(sc_shots) == 188, f"Screenplay has {len(sc_shots)} shots"
assert sc_shots == set(sub_prompts.keys()), "Mismatch between screenplay and Banana prompts"
assert sc_shots == set(m_prompts.keys()), "Mismatch between screenplay and Muse prompts"
print("CHECK 7 PASS: Screenplay, Banana prompts, and Muse prompts are 100% synchronized across all 188 shots.")

print("ALL 7 FORENSIC AUDIT CHECKS PASSED EMPIRICALLY!")
