#!/usr/bin/env python3
from pathlib import Path
import json, re
PROJECT=Path('/data/video-pipeline/Youtube-Video-Maker/Project/03072026-003-Nguyen-Van-Troi')
SRC=PROJECT/'script/source_story.txt'

def clean(t): return re.sub(r'\n{3,}','\n\n',t.replace('\r\n','\n').replace('\r','\n').strip())
def sents(p): return [s.strip() for s in re.split(r'(?<=[.!?])\s+',p.strip()) if s.strip()]
def title(x):
    t=re.sub(r'^\d+\.\s*','',x.strip()); return t[:1]+t[1:].lower()
def visual(text, section, typ='visual_beat'):
    low=text.lower()
    if typ=='heading': return f'Title card for section: {section}'
    if 'cầu công lý' in low or 'đặt mìn' in low or 'mcnamara' in low: return 'Nguyễn Văn Trỗi trong nhiệm vụ bí mật tại cầu Công Lý, Sài Gòn 1964, dây điện, bóng cảnh sát và xe quân sự trong căng thẳng.'
    if 'chí hòa' in low or 'pháp trường' in low or 'xử bắn' in low or 'nụ cười' in low: return 'Pháp trường khám Chí Hòa buổi sáng 15/10/1964, Nguyễn Văn Trỗi hiên ngang với nụ cười trước cái chết.'
    if 'nhà tù' in low or 'giam' in low or 'thẩm vấn' in low: return 'Phòng giam Sài Gòn u tối, người thợ điện trẻ bị thẩm vấn nhưng giữ vững khí tiết.'
    if 'sài gòn' in low or 'người thợ điện' in low or 'thợ điện' in low: return 'Sài Gòn đầu thập niên 1960, người thợ điện trẻ giữa phố xá, dây điện, xóm lao động và bóng cố vấn Mỹ.'
    if 'phan thị quyên' in low or 'người vợ' in low or 'hôn nhân' in low: return 'Nguyễn Văn Trỗi và Phan Thị Quyên trong mái ấm trẻ ngắn ngủi giữa thời chiến, ánh sáng buồn và dịu.'
    if 'venezuela' in low or 'smolen' in low or 'quốc tế' in low: return 'Bản đồ nối Việt Nam với Mỹ Latinh, phong trào quốc tế chú ý đến tên Nguyễn Văn Trỗi.'
    if 'quảng nam' in low or 'thanh quýt' in low: return 'Làng Thanh Quýt, Quảng Nam, miền Trung nghèo khó, tuổi thơ Nguyễn Văn Trỗi giữa biến động đất nước.'
    return 'Cảnh lịch sử Việt Nam thời kháng chiến chống Mỹ ở đô thị Sài Gòn, bố cục kể chuyện bằng mực nâu trên giấy cổ.'

def build(cleaned):
    body=re.sub(r'^Tiêu đề truyện:.*?^Nội dung:\s*','',cleaned,flags=re.S|re.M).strip(); chunks=re.split(r'(?m)^(\d+\.\s+[^\n]+)$',body)
    scenes=[]; sid=1; sec='Mở đầu'
    for ch in chunks:
        if not ch.strip(): continue
        if re.match(r'^\d+\.\s+',ch.strip()):
            sec=title(ch); scenes.append({'scene_id':f'scene_{sid:03d}','type':'heading','section':sec,'text':sec,'visual_beat':visual('',sec,'heading'),'estimated_seconds':4,'rule':'heading_must_be_own_scene'}); sid+=1; continue
        for p in [x.strip() for x in ch.split('\n\n') if x.strip()]:
            group=[]; wc=0
            for s in sents(p):
                group.append(s); wc+=len(s.split())
                if wc>=42 or len(group)>=3:
                    txt=' '.join(group); scenes.append({'scene_id':f'scene_{sid:03d}','type':'visual_beat','section':sec,'text':txt,'visual_beat':visual(txt,sec),'estimated_seconds':max(14,min(22,round(len(txt.split())/3.0))),'rule':'grouped_visual_beat_14_22_seconds'}); sid+=1; group=[]; wc=0
            if group:
                txt=' '.join(group)
                if scenes and scenes[-1]['type']=='visual_beat' and scenes[-1]['section']==sec and len(txt.split())<18:
                    scenes[-1]['text']+=' '+txt; scenes[-1]['visual_beat']=visual(scenes[-1]['text'],sec); scenes[-1]['estimated_seconds']=min(22,scenes[-1]['estimated_seconds']+5)
                else:
                    scenes.append({'scene_id':f'scene_{sid:03d}','type':'visual_beat','section':sec,'text':txt,'visual_beat':visual(txt,sec),'estimated_seconds':max(12,min(22,round(len(txt.split())/3.0))),'rule':'grouped_visual_beat_14_22_seconds'}); sid+=1
    return scenes
characters=[
 {'name':'Nguyễn Văn Trỗi người thợ trẻ','role':'Main hero as young electrician and urban resistance member','estimated_age':'22-24','appearance':'young Vietnamese man, lean worker build, honest bright face, short black hair, determined eyes, simple smile','costume':'early 1960s Sài Gòn worker clothes, plain shirt, dark trousers, tool satchel, electrical tools','temperament':'warm, brave, practical, quietly resolute','historical_cultural_context':'Sài Gòn under U.S.-backed Republic of Vietnam, early 1960s urban labor life','visual_keywords':['Nguyen Van Troi','electrician','Saigon 1964','worker'],'negative_notes':'no modern fashion, no late-war American gear, no fantasy action hero'},
 {'name':'Nguyễn Văn Trỗi trước pháp trường','role':'Main hero as condemned prisoner at Chí Hòa','estimated_age':'24','appearance':'young Vietnamese man, thin but upright, calm fearless eyes, slight smile, dignified face','costume':'plain prisoner/worker clothes of 1964, restrained and respectful, no gore','temperament':'defiant, serene, patriotic, unbowed','historical_cultural_context':'Khám Chí Hòa, Sài Gòn, execution morning 15 October 1964','visual_keywords':['Nguyen Van Troi execution','Chi Hoa','fearless smile'],'negative_notes':'no gore, no sensational violence, no modern prison uniform'},
 {'name':'Phan Thị Quyên','role':'Young wife of Nguyễn Văn Trỗi and symbol of private loss','estimated_age':'early 20s','appearance':'young Vietnamese woman, gentle face, worried yet strong eyes, simple southern urban style','costume':'modest early 1960s Vietnamese blouse or áo dài/áo bà ba depending scene, subdued colors','temperament':'loving, grieving, resilient','historical_cultural_context':'young family life in wartime Sài Gòn','visual_keywords':['Phan Thi Quyen','young wife','wartime family'],'negative_notes':'no modern bridal fashion, no glamour'},
 {'name':'Biệt động Sài Gòn và đồng đội','role':'Urban resistance network and comrades','estimated_age':'young adults to middle-aged','appearance':'Vietnamese underground fighters disguised as workers and civilians, alert eyes','costume':'1960s Sài Gòn civilian/work clothes, small satchels, discreet tools','temperament':'secretive, disciplined, committed','historical_cultural_context':'urban revolutionary operations in Sài Gòn during early anti-American war','visual_keywords':['Saigon special forces','urban resistance','secret meeting'],'negative_notes':'no overt modern tactical uniforms'},
 {'name':'Cảnh sát Sài Gòn và cố vấn Mỹ','role':'Adversary forces, police, security, U.S. presence','estimated_age':'adult men','appearance':'South Vietnamese police/security and American military advisers, stern, suspicious, official posture','costume':'1960s Republic of Vietnam police/military uniforms, U.S. adviser khaki uniforms, period vehicles','temperament':'watchful, controlling, oppressive','historical_cultural_context':'Sài Gòn 1964 under U.S. military and political influence','visual_keywords':['Saigon police','US advisers','1964 security'],'negative_notes':'no modern SWAT, no post-1975 uniforms, no sci-fi'},
 {'name':'Dân lao động Sài Gòn','role':'Recurring workers, civilians, city crowd','estimated_age':'varied','appearance':'Vietnamese urban workers, vendors, cyclists, families, tired but resilient faces','costume':'early 1960s Sài Gòn everyday clothes, work shirts, áo dài, conical hats, bicycles','temperament':'busy, anxious, resilient','historical_cultural_context':'Sài Gòn streets and working neighborhoods during war','visual_keywords':['Saigon workers','1960s street','urban crowd'],'negative_notes':'no modern skyscrapers, no contemporary motorcycles'}]
def main():
    cleaned=clean(SRC.read_text(encoding='utf-8')); (PROJECT/'script/cleaned_story.txt').write_text(cleaned,encoding='utf-8')
    scenes=build(cleaned)
    (PROJECT/'script/scenes.json').write_text(json.dumps({'project_id':PROJECT.name,'target_beat_seconds':'14-22','split_rule':'Headings standalone; narration grouped into visual beats of about 14-22 seconds.','total_scenes':len(scenes),'scenes':scenes},ensure_ascii=False,indent=2),encoding='utf-8')
    (PROJECT/'script/scenes_validation.json').write_text(json.dumps({'project_id':PROJECT.name,'total_scenes':len(scenes),'metadata_removed_from_scenes':True,'headings_standalone':True,'each_scene_has_visual_beat':all('visual_beat' in s for s in scenes),'status':'passed'},ensure_ascii=False,indent=2),encoding='utf-8')
    bible={'project_id':PROJECT.name,'visual_style_global':'16:9 horizontal historical storytelling image, Sài Gòn and Quảng Nam 1940s-1964, ink-wash window centered on warm antique paper, muted sepia, charcoal, faded urban green, no modern/fantasy drift.','consistency_rules':['Use Nguyễn Văn Trỗi người thợ trẻ for worker, family, and mission scenes.','Use Nguyễn Văn Trỗi trước pháp trường for prison, trial, and execution scenes.','Keep 1964 Sài Gòn uniforms, vehicles, clothing, and urban context accurate.'],'characters':characters}
    (PROJECT/'script/character_bible.json').write_text(json.dumps(bible,ensure_ascii=False,indent=2),encoding='utf-8')
    dense=[]
    for sc in scenes:
        prompt=('16:9 horizontal historical storytelling image, ink-wash narrative window on warm antique paper, painted content only 65-70% of frame with clean parchment negative space. '+f"Scene: {sc['visual_beat']} Narration beat: {sc['text']} Historical grounding: Việt Nam 1940s-1964, Quảng Nam, Sài Gòn, cầu Công Lý, khám Chí Hòa, accurate early 1960s Vietnamese worker clothes, Sài Gòn police and U.S. adviser presence. Negative: no modern objects, no post-1975 uniforms, no fantasy armor, no 3D game art, no full-frame glossy poster, no text labels or watermark.")
        dense.append({**sc,'summary':sc['visual_beat'],'narration':sc['text'],'visual_prompt':prompt})
    (PROJECT/'script/dense_scene_plan.json').write_text(json.dumps({'project_id':PROJECT.name,'approved_for_next_step':True,'total_scenes':len(dense),'scenes':dense},ensure_ascii=False,indent=2),encoding='utf-8')
    print(json.dumps({'project':str(PROJECT),'total_scenes':len(scenes)},ensure_ascii=False))
if __name__=='__main__': main()
