import os
import sys
import time
import subprocess
from pathlib import Path

# Đảm bảo UTF-8
if sys.platform == "win32":
    try:
        sys.stdout.reconfigure(encoding="utf-8")
        sys.stderr.reconfigure(encoding="utf-8")
    except Exception:
        pass

BASE_DIR = Path(__file__).resolve().parent.parent
VIDEOS_DIR = BASE_DIR / "04_Assets" / "videos"
DOWNLOADS_DIR = Path.home() / "Downloads"
TARGET_FILE = VIDEOS_DIR / "ep01_scene01_shot01_10s.mp4"

print("[*] Bắt đầu theo dõi tiến độ render Muse.ai cho EP01 Scene 01 Shot 01...")

initial_downloads = set(DOWNLOADS_DIR.glob("*.mp4"))

for attempt in range(40): # Tối đa ~3-4 phút
    time.sleep(6)
    res = subprocess.run("agent-browser --session muse snapshot -i", shell=True, capture_output=True, text=True, encoding="utf-8")
    output = res.stdout
    
    # Kiểm tra xem nút "Dừng" còn không
    is_generating = "Dừng" in output or "Đang tạo video" in output
    print(f"[{attempt * 6}s] Trạng thái: {'Đang render...' if is_generating else 'Đang phản hồi...'}")
    
    # Kiểm tra nút tải video xuống mới nhất
    if "Tải video xuống" in output:
        # Tìm ref của nút tải video xuống cuối cùng
        ref = None
        for line in output.splitlines():
            if "Tải video xuống" in line and "[ref=" in line:
                ref = line.split("[ref=")[-1].split("]")[0]
        
        if ref:
            print(f"[✓] Phát hiện nút tải video xuống: @{ref}. Đang bấm tải...")
            subprocess.run(f"agent-browser --session muse click '@{ref}'", shell=True, capture_output=True, text=True)
            time.sleep(5)
            
            # Kiểm tra file trong Downloads
            current_downloads = set(DOWNLOADS_DIR.glob("*.mp4"))
            new_files = current_downloads - initial_downloads
            if not new_files:
                recent = sorted(DOWNLOADS_DIR.glob("*.mp4"), key=lambda f: f.stat().st_mtime, reverse=True)
                if recent and (time.time() - recent[0].stat().st_mtime < 180):
                    new_files = [recent[0]]
            
            if new_files:
                downloaded_file = list(new_files)[0]
                print(f"[✓] Đã tải về: {downloaded_file}")
                # Di chuyển và đổi tên vào 04_Assets/videos
                import shutil
                shutil.copy2(downloaded_file, TARGET_FILE)
                print(f"[✓] Đã lưu thành công: {TARGET_FILE}")
                sys.exit(0)
            else:
                print("[!] Chưa thấy file xuất hiện trong Downloads, tiếp tục chờ...")

print("[!] Đã hết thời gian chờ (timeout). Vui lòng kiểm tra lại trạng thái.")
