import sys, time, base64, subprocess
from pathlib import Path
sys.path.append(str(Path("05_Production_Pipeline").resolve()))
from invisible_playwright import InvisiblePlaywright
from muse_invpw_driver import sync_worker_profile, DEFAULT_PROFILE

def extract_blob():
    sync_worker_profile()
    with InvisiblePlaywright(profile_dir=DEFAULT_PROFILE, headless=True) as ctx:
        page = ctx.pages[0] if ctx.pages else ctx.new_page()
        page.goto('https://muse.ai', wait_until='domcontentloaded', timeout=30000)
        time.sleep(3)
        
        videos = page.locator('video').all()
        print('Total video tags:', len(videos))
        if not videos:
            print("No videos found")
            return
            
        v = videos[-1]
        blob_url = v.get_attribute("src") or v.evaluate("el => el.currentSrc")
        print("Blob URL:", blob_url)
        
        b64_data = page.evaluate("""async (url) => {
            const res = await fetch(url);
            const blob = await res.blob();
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onloadend = () => resolve(reader.result.split(',')[1]);
                reader.onerror = reject;
                reader.readAsDataURL(blob);
            });
        }""", blob_url)
        
        if b64_data:
            data = base64.b64decode(b64_data)
            out_file = Path("04_Assets/test_extracted_video.mp4").resolve()
            out_file.write_bytes(data)
            print(f"Extracted video saved to {out_file} ({len(data)} bytes)")
            
            # Run ffprobe
            ffprobe_cmd = [
                "ffprobe", "-v", "error", "-show_entries",
                "stream=width,height,duration,codec_name,codec_type",
                "-of", "default=noprint_wrappers=1", str(out_file)
            ]
            res = subprocess.run(ffprobe_cmd, capture_output=True, text=True)
            print("FFPROBE info:\n", res.stdout)
            
            # Also test the download button
            dl_btn = page.locator('button[aria-label="Tải video xuống"]').last
            if dl_btn.count() > 0:
                print("Download button found, testing expect_download...")
                try:
                    with page.expect_download(timeout=10000) as dl_info:
                        dl_btn.click(force=True)
                    download = dl_info.value
                    dl_path = Path("04_Assets/test_clicked_download.mp4").resolve()
                    download.save_as(str(dl_path))
                    print(f"Direct download succeeded! Saved to {dl_path} ({dl_path.stat().st_size} bytes)")
                    res2 = subprocess.run([
                        "ffprobe", "-v", "error", "-show_entries",
                        "stream=width,height,duration,codec_name,codec_type",
                        "-of", "default=noprint_wrappers=1", str(dl_path)
                    ], capture_output=True, text=True)
                    print("Direct download FFPROBE info:\n", res2.stdout)
                except Exception as e_dl:
                    print(f"expect_download failed: {e_dl}")

if __name__ == '__main__':
    extract_blob()
