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

def clean_text(t):
    t=t.replace('\r\n','\n').replace('\r','\n')
    return re.sub(r'\n{3,}','\n\n',t.strip())

def split_sentences(p):
    return [s.strip() for s in re.split(r'(?<=[.!?])\s+', p.strip()) if s.strip()]

def section_title(raw):
    title=re.sub(r'^\d+\.\s*','',raw.strip())
    return title[:1]+title[1:].lower()

def visual_for(text, section, typ='visual_beat'):
    low=text.lower()
    if typ=='heading': return f'Title card for section: {section}'
    if 'chợ đất đỏ' in low or 'lựu đạn' in low: return 'Võ Thị Sáu giữa chợ Đất Đỏ thời kháng chiến, giây phút căng thẳng trước tiếng nổ, dân làng và bóng lính Pháp trong xa gần.'
    if 'côn đảo' in low or 'pháp trường' in low or 'xử bắn' in low: return 'Côn Đảo trong sương biển, nhà tù đá lạnh và Võ Thị Sáu hiên ngang trước pháp trường.'
    if 'nhà tù' in low or 'tra khảo' in low or 'thẩm vấn' in low: return 'Phòng giam thực dân u tối, Võ Thị Sáu trẻ tuổi vẫn nhìn thẳng, không khuất phục trước thẩm vấn.'
    if 'đất đỏ' in low or 'bà rịa' in low: return 'Làng quê Đất Đỏ, đường đất đỏ, hàng cây và không khí Nam Bộ kháng Pháp với bóng lính tuần tra.'
    if 'liên lạc' in low or 'giao liên' in low: return 'Cô gái giao liên trẻ lặng lẽ đi qua đường làng Nam Bộ, mang tin giữa các trạm gác thời Pháp tái chiếm.'
    if 'mộ' in low or 'hàng dương' in low: return 'Nghĩa trang Hàng Dương, hương khói tưởng niệm Võ Thị Sáu, biển Côn Đảo và ánh sáng bình minh.'
    return 'Cảnh lịch sử Việt Nam thời kháng chiến chống Pháp ở Nam Bộ, bố cục kể chuyện bằng mực nâu trên giấy cổ.'

def build_scenes(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; current='Mở đầu'
    for chunk in chunks:
        if not chunk.strip(): continue
        if re.match(r'^\d+\.\s+', chunk.strip()):
            current=section_title(chunk)
            scenes.append({'scene_id':f'scene_{sid:03d}','type':'heading','section':current,'text':current,'visual_beat':visual_for('',current,'heading'),'estimated_seconds':4,'rule':'heading_must_be_own_scene'}); sid+=1; continue
        for p in [x.strip() for x in chunk.split('\n\n') if x.strip()]:
            group=[]; wc=0
            for s in split_sentences(p):
                group.append(s); wc+=len(s.split())
                if wc>=42 or len(group)>=3:
                    text=' '.join(group)
                    scenes.append({'scene_id':f'scene_{sid:03d}','type':'visual_beat','section':current,'text':text,'visual_beat':visual_for(text,current),'estimated_seconds':max(14,min(22,round(len(text.split())/3.0))),'rule':'grouped_visual_beat_14_22_seconds'}); sid+=1; group=[]; wc=0
            if group:
                text=' '.join(group)
                if scenes and scenes[-1]['type']=='visual_beat' and scenes[-1]['section']==current and len(text.split())<18:
                    scenes[-1]['text']+=' '+text; scenes[-1]['visual_beat']=visual_for(scenes[-1]['text'],current); scenes[-1]['estimated_seconds']=min(22,scenes[-1]['estimated_seconds']+5)
                else:
                    scenes.append({'scene_id':f'scene_{sid:03d}','type':'visual_beat','section':current,'text':text,'visual_beat':visual_for(text,current),'estimated_seconds':max(12,min(22,round(len(text.split())/3.0))),'rule':'grouped_visual_beat_14_22_seconds'}); sid+=1
    return scenes

characters=[
 {'name':'Võ Thị Sáu tuổi thiếu nữ','role':'Main heroine, teenage liaison and resistance fighter from Đất Đỏ','estimated_age':'14-16','appearance':'young Vietnamese girl, small build, bright determined eyes, black hair tied simply, innocent but resolute face','costume':'simple 1940s Nam Bộ rural áo bà ba, dark trousers, khăn rằn or simple scarf, no glamour','temperament':'brave, quick, stubborn, pure-hearted, unbowed','historical_cultural_context':'Đất Đỏ, Bà Rịa during French return to southern Vietnam after 1945','visual_keywords':['Vo Thi Sau','Dat Do','teenage liaison','ao ba ba'],'negative_notes':'no modern school uniform, no tactical gear, no fantasy heroine look'},
 {'name':'Võ Thị Sáu trong tù Côn Đảo','role':'Main heroine in imprisonment and final defiance','estimated_age':'17-19','appearance':'young Vietnamese woman, thin but upright, calm fearless eyes, black hair, dignified expression','costume':'plain prisoner clothing or simple dark áo bà ba, minimal details, no shackles unless scene requires','temperament':'steadfast, serene, defiant before death','historical_cultural_context':'Côn Đảo prison under French colonial rule, early 1950s','visual_keywords':['Vo Thi Sau prison','Con Dao','execution ground','fearless'],'negative_notes':'no gore, no sensational violence, no modern prison uniform'},
 {'name':'Dân làng Đất Đỏ','role':'Recurring civilians, market people, oppressed villagers','estimated_age':'varied','appearance':'Vietnamese rural southern civilians, weathered faces, farmers, vendors, children','costume':'1940s Nam Bộ áo bà ba, nón lá, simple market clothes','temperament':'anxious, resilient, quietly patriotic','historical_cultural_context':'rural Bà Rịa - Vũng Tàu under French occupation','visual_keywords':['Dat Do villagers','southern Vietnam market','red earth road'],'negative_notes':'no modern city clothes, no contemporary vehicles'},
 {'name':'Lực lượng kháng chiến Đất Đỏ','role':'Local resistance members and public security volunteers','estimated_age':'young adults to middle-aged','appearance':'Vietnamese resistance fighters, lean, discreet, alert eyes','costume':'simple dark áo bà ba, khăn rằn, basic satchels, period weapons only when needed','temperament':'secretive, committed, protective of villages','historical_cultural_context':'Nam Bộ anti-French resistance network late 1940s','visual_keywords':['Vietnamese resistance','Nam Bo','liaison network'],'negative_notes':'no modern uniforms, no Viet Cong 1960s gear emphasis'},
 {'name':'Lính Pháp và tay sai','role':'Colonial adversary forces and local collaborators','estimated_age':'adult men','appearance':'French colonial soldiers and local auxiliaries, stern, suspicious, intimidating patrol presence','costume':'late 1940s French colonial khaki uniforms, helmets, boots; local collaborators in mixed uniforms','temperament':'oppressive, watchful, harsh','historical_cultural_context':'French colonial control in southern Vietnam after 1945','visual_keywords':['French colonial soldiers','Dat Do patrol','market control'],'negative_notes':'no Nazis, no modern riot police, no American Vietnam War uniforms'},
 {'name':'Mẹ và gia đình Võ Thị Sáu','role':'Family memory, home, ordinary life sacrificed by war','estimated_age':'mother middle-aged, family varied','appearance':'southern Vietnamese rural family, gentle weathered faces, simple dignity','costume':'plain áo bà ba, nón lá, home clothes','temperament':'loving, worried, resilient','historical_cultural_context':'family life in Đất Đỏ under colonial conflict','visual_keywords':['Vietnamese mother','rural family','home memory'],'negative_notes':'no modern appliances, no urban wealthy interior'}]

def main():
    cleaned=clean_text(SRC.read_text(encoding='utf-8'))
    (PROJECT/'script/cleaned_story.txt').write_text(cleaned,encoding='utf-8')
    scenes=build_scenes(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, Vietnamese anti-French resistance 1940s-1950s, ink-wash window centered on warm antique paper, muted red earth / sepia / charcoal watercolor, no modern/fantasy drift.','consistency_rules':['Use Võ Thị Sáu tuổi thiếu nữ for Đất Đỏ and liaison/market scenes.','Use Võ Thị Sáu trong tù Côn Đảo for prison, trial, and execution scenes.','Keep French colonial period uniforms and Nam Bộ rural material culture 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: 1940s-1952 southern Vietnam anti-French resistance, Đất Đỏ Bà Rịa and Côn Đảo prison, accurate áo bà ba, khăn rằn, French colonial uniforms, red earth roads and tropical southern landscape. Negative: no modern objects, no American Vietnam War gear, 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()
