import sys
import time
import base64
from pathlib import Path

sys.path.insert(0, '05_Production_Pipeline')
if sys.platform == 'win32':
    sys.stdout.reconfigure(encoding='utf-8')
from invisible_playwright import InvisiblePlaywright

pdir = Path.home() / 'AntigravityProfiles' / 'phu2234_worker'
with InvisiblePlaywright(profile_dir=pdir, headless=True) as ctx:
    page = ctx.pages[0] if ctx.pages else ctx.new_page()
    page.goto('https://muse.ai/thread/new', wait_until='domcontentloaded', timeout=25000)
    time.sleep(3)
    
    # Click vào Shot 01
    for b in page.locator('button').all():
        txt = b.inner_text().strip()
        if 'làng quê 1980' in txt or '10:03' in txt:
            b.click()
            print('Clicked Shot 01 thread')
            break
            
    time.sleep(3)
    
    # Lấy base64 từ blob video
    b64_data = page.evaluate("""
        async () => {
            const v = document.querySelector('video');
            if (!v || !v.src) return null;
            const res = await fetch(v.src);
            const blob = await res.blob();
            return new Promise((resolve) => {
                const reader = new FileReader();
                reader.onloadend = () => resolve(reader.result.split(',')[1]);
                reader.readAsDataURL(blob);
            });
        }
    """)
    
    if b64_data:
        raw_bytes = base64.b64decode(b64_data)
        out_path = Path('04_Assets/videos/ep01_scene01_shot01_10s_v1.mp4')
        out_path.parent.mkdir(parents=True, exist_ok=True)
        out_path.write_bytes(raw_bytes)
        print(f"🎉 THÀNH CÔNG RỰC RỠ: Đã lưu {out_path.name} ({len(raw_bytes)} bytes)!")
    else:
        print("Không lấy được video blob")
