import os
import sys
import time
import subprocess
import shutil
import cv2
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"
KEYFRAMES_DIR = BASE_DIR / "04_Assets" / "keyframes"
DOWNLOADS_DIR = Path.home() / "Downloads"

TARGET_VIDEO = VIDEOS_DIR / "ep01_scene01_shot03_10s.mp4"
PREV_VIDEO = VIDEOS_DIR / "ep01_scene01_shot02_10s.mp4"

print("[*] Bắt đầu theo dõi tiến độ Shot 3 trên Muse.ai...")
initial_downloads = set(DOWNLOADS_DIR.glob("*.mp4"))

for attempt in range(40): # 40 * 5s = 200s
    time.sleep(5)
    snap = subprocess.run("agent-browser --session muse snapshot -i", shell=True, capture_output=True, text=True, encoding="utf-8").stdout
    
    is_busy = "Dừng nhiệm vụ" in snap
    print(f"[{attempt * 5}s] Trạng thái: {'Đang render video Shot 3...' if is_busy else 'Đã xong hoặc đang xử lý...'}")
    
    if not is_busy and ("Tải video xuống" in snap):
        # Lấy ref của nút tải cuối cùng
        last_dl_ref = None
        for line in snap.splitlines():
            if "Tải video xuống" in line and "[ref=" in line:
                last_dl_ref = line.split("[ref=")[-1].split("]")[0]
        
        if last_dl_ref:
            print(f"[✓] Tìm thấy nút tải mới nhất: @{last_dl_ref}. Đang bấm tải...")
            subprocess.run(f'agent-browser --session muse click "@{last_dl_ref}"', shell=True, capture_output=True, text=True)
            time.sleep(5)
            
            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 < 120):
                    new_files = [recent[0]]
            
            if new_files:
                downloaded = list(new_files)[0]
                shutil.copy2(downloaded, TARGET_VIDEO)
                print(f"[✓] Đã lưu video Shot 3 vào: {TARGET_VIDEO}")
                
                # Trích xuất Tail Frame của Shot 3
                cap = cv2.VideoCapture(str(TARGET_VIDEO))
                total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
                cap.set(cv2.CAP_PROP_POS_FRAMES, max(0, total_frames - 1))
                ret, tail_frame = cap.read()
                cap.release()
                
                shot3_dir = KEYFRAMES_DIR / "ep01_scene01_shot03"
                shot3_dir.mkdir(parents=True, exist_ok=True)
                tail_path = shot3_dir / "clean_frame_239.jpg"
                if ret and tail_frame is not None:
                    cv2.imwrite(str(tail_path), tail_frame)
                    print(f"[✓] Đã trích xuất Tail Frame của Shot 3: {tail_path}")
                
                # Chạy continuity_checker
                print("[*] Đang đối soát tính liên tục giữa Shot 2 và Shot 3...")
                from continuity_checker import check_shot_continuity
                is_smooth, score = check_shot_continuity(str(PREV_VIDEO), str(TARGET_VIDEO))
                print(f"[✓] Kết quả: {'MẠCH PHIM LIỀN MẠCH' if is_smooth else 'LỆCH NHỊP - CẦN TRANSITION'}")
                sys.exit(0)

print("[!] Hết thời gian chờ.")
