import sys
import 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_new_chat_flow():
    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] Bấm tạo Đoạn chat phụ mới...")
        new_chat_btn = page.locator('button[aria-label="Đoạn chat phụ mới"], [title="Đoạn chat phụ mới"]').first
        if new_chat_btn.count() > 0:
            new_chat_btn.click()
            print("      ✓ Đã bấm nút tạo Đoạn chat phụ mới!")
        else:
            print("      [!] Không tìm thấy nút Đoạn chat phụ mới!")
        time.sleep(3)
        
        # 2. Check connection status
        status_text = page.locator("body").inner_text()
        print("      Đã kết nối:", "Đã kết nối" in status_text)
        
        # 3. Upload image
        print("[2/5] Uploading image...")
        file_input = page.locator('input[type="file"]').first
        file_input.set_input_files(str(test_img))
        for _ in range(10):
            if page.locator('button[aria-label="Gỡ file đính kèm"]').count() > 0:
                print("      ✓ Image attached!")
                break
            time.sleep(1)
            
        # 4. Fill prompt
        prompt = "Tạo video 10 giây điện ảnh cổ phong Á Đông: Cảnh sắc mùa xuân thanh bình, dòng nước trong veo trôi êm ả, ánh sáng sớm mai chiếu rọi cầu đá cổ. Chuyển động máy quay mượt mà. Quy tắc âm thanh: Tuyệt đối KHÔNG sinh nhạc nền, chỉ sinh tiếng suối chảy và chim hót tự nhiên."
        chat_box = page.locator('textarea, [placeholder*="Nhắn tin"], [role="textbox"]').first
        chat_box.fill(prompt)
        time.sleep(1)
        
        # 5. Send
        print("[3/5] Gửi lệnh...")
        send_btn = page.locator('button[aria-label="Gửi"], button:has-text("Gửi")').first
        if send_btn.count() > 0:
            send_btn.click()
        else:
            chat_box.press("Enter")
        time.sleep(3)
        
        # 6. Monitor
        print("[4/5] Giám sát 25 giây...")
        for i in range(5):
            time.sleep(5)
            stop_btn = page.locator('button:has-text("Dừng"), button[aria-label*="Dừng"]').count()
            err_box = page.locator('[data-testid="chat-video-not-found"]').count()
            body = page.locator('body').inner_text()
            has_van_dang_gui = "Vẫn đang gửi" in body
            print(f"      [{(i+1)*5}s] Nút Dừng: {stop_btn}, Lỗi video: {err_box}, Vẫn đang gửi: {has_van_dang_gui}")
            
        screenshot_path = Path("04_Assets/test_new_chat_result.png").resolve()
        page.screenshot(path=str(screenshot_path))
        print("Saved screenshot to:", screenshot_path)

if __name__ == "__main__":
    test_new_chat_flow()
