import sys, time
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 test_render():
    sync_worker_profile()
    test_img = Path("04_Assets/keyframes/ep01_scene01_shot01/start_frame_720p.png").resolve()
    
    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)
        
        # 1. Click "Đoạn chat phụ mới"
        print("[1/5] Mở luồng chat mới...")
        btn = page.locator('button[aria-label="Đoạn chat phụ mới"]').first
        if btn.count() > 0:
            btn.click()
            time.sleep(2)
            
        print("URL hiện tại:", page.url)
        
        # 2. Upload start frame
        print(f"[2/5] Đang upload Start Frame: {test_img.name}...")
        file_input = page.locator('input[type="file"]').first
        file_input.set_input_files(str(test_img))
        
        attached = False
        for _ in range(15):
            time.sleep(1)
            if page.locator('button[aria-label="Gỡ file đính kèm"]').count() > 0:
                attached = True
                print("      ✓ Đã đính kèm Start Frame thành công!")
                break
        if not attached:
            print("      [!] Chưa thấy xác nhận gỡ file đính kèm, kiểm tra tiếp...")
            
        # 3. Nhập Prompt
        prompt = (
            "Tạo video 10 giây điện ảnh cổ phong Á Đông: Đại cảnh dòng suối trong veo trôi êm ả dưới chân cầu đá cổ, "
            "ánh nắng sớm rực rỡ chiếu xuyên qua rặng liễu tơ mềm mại. Cỏ non xanh rờn tận chân trời. "
            "Chuyển động máy quay tracking shot mượt mà, chuyển động tự nhiên thuận chiều vật lý. "
            "Quy tắc âm thanh: Tuyệt đối KHÔNG sinh nhạc nền (no music/BGM), không âm thanh điện tử, không tạp âm rè nhiễu. "
            "Chỉ sinh âm thanh môi trường tự nhiên (foley, ambience) và tiếng suối róc rách."
        )
        print("[3/5] Nhập prompt...")
        chat_box = page.locator('textarea, [placeholder*="Nhắn tin"], [role="textbox"]').first
        chat_box.fill(prompt)
        time.sleep(1)
        
        # 4. Gửi lệnh
        print("[4/5] Bấm gửi lệnh...")
        send_btn = page.locator('button[aria-label="Gửi"]').first
        if send_btn.count() > 0 and send_btn.is_visible():
            send_btn.click()
        else:
            chat_box.press("Enter")
        time.sleep(2)
        
        # 5. Giám sát 30 giây đầu
        print("[5/5] Giám sát khởi động task...")
        for i in range(6):
            time.sleep(5)
            elapsed = (i + 1) * 5
            stop_count = page.locator('button:has-text("Dừng"), button[aria-label*="Dừng"]').count()
            dl_count = page.locator('button[aria-label="Tải video xuống"]').count()
            body_text = page.locator("body").inner_text()
            has_van_dang_gui = "Vẫn đang gửi" in body_text
            has_tu_choi = any(w in body_text.lower() for w in ["không dựng được", "từ chối", "không thể tạo"])
            print(f"      [{elapsed}s] Nút Dừng: {stop_count} | Nút Tải: {dl_count} | Đang gửi: {has_van_dang_gui} | Từ chối: {has_tu_choi}")

        page.screenshot(path="04_Assets/fresh_render_started.png")
        print("Đã lưu screenshot vào 04_Assets/fresh_render_started.png")

if __name__ == '__main__':
    test_render()
