"""
Watchdog script: Tu dong phat hien khi Tap 1 (ep1) hoan thanh 4K
va lap tuc dung tien trinh batch_upscaler de giai phong GPU theo yeu cau cua nguoi dung.
"""

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

# Force UTF-8 encoding on Windows console
if sys.platform.startswith("win"):
    try:
        sys.stdout.reconfigure(encoding="utf-8")
        sys.stderr.reconfigure(encoding="utf-8")
    except Exception:
        pass

STATE_FILE = Path("upscale_state.json")
OUT_FILE = Path("content/videos_4k/ep1_4k.mp4")

print("[*] Watchdog da kich hoat: Se tu dong dung tien trinh ngay khi Tap 1 hoan thanh 4K...")

while True:
    time.sleep(5)
    is_done = False
    
    if STATE_FILE.exists():
        try:
            with open(STATE_FILE, "r", encoding="utf-8") as f:
                data = json.load(f)
                if "ep1" in data.get("completed", {}):
                    is_done = True
        except Exception:
            pass

    if OUT_FILE.exists() and OUT_FILE.stat().st_size > 10 * 1024 * 1024:
        temp_dirs = [d for d in Path("downloads").glob("_temp_upscale_*") if d.is_dir()]
        if is_done or len(temp_dirs) == 0:
            is_done = True

    if is_done:
        print("\n" + "="*60)
        print("✓ TAP 1 (ep1.mp4) DA HOAN THANH XUAT 4K!")
        print(f"File luu tai: {OUT_FILE.resolve()}")
        print("Dang dung toan bo tien trinh batch_upscaler de bao luu trang thai...")
        print("="*60)
        
        # Dung tien trinh batch_upscaler
        subprocess.run(
            ["powershell", "-Command", "Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like '*batch_upscaler*' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }"],
            capture_output=True
        )
        print("[✓] DA TAM DUNG THANH CONG. GPU DA DUOC GIAI PHONG HOAN TOAN.")
        break
