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_connection_and_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/thread/new", wait_until="domcontentloaded", timeout=30000)
        time.sleep(3)
        
        # 1. Wait for connection
        print("Waiting for Muse connection status...")
        connected = False
        for i in range(15):
            status_text = page.locator("text='Đã kết nối'").count()
            if status_text > 0:
                print(f"Connected in {i}s!")
                connected = True
                break
            time.sleep(1)
            
        print("Status connected:", connected)
        
        # 2. Upload file
        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 successfully!")
                break
            time.sleep(1)
            
        # 3. Fill clean prompt with Audio Guard
        prompt = "Tạo video điện ảnh 10 giây nối tiếp mượt mà: Toàn cảnh buổi sớm mùa xuân thanh bình, ánh nắng vàng rọi qua cầu đá cổ, dòng nước trôi lững lờ. Quy tắc âm thanh: Tuyệt đối KHÔNG sinh nhạc nền, chỉ sinh tiếng chim hót và tiếng nước chảy tự nhiên."
        chat_box = page.locator('textarea, [placeholder*="Nhắn tin"], [role="textbox"]').first
        chat_box.fill(prompt)
        time.sleep(1)
        
        # 4. Click Send
        send_btn = page.locator('button[aria-label="Gửi"], button:has-text("Gửi"), button[data-pel-click="chat_send_message"]').first
        if send_btn.count() > 0:
            send_btn.click()
            print("Clicked send button!")
        else:
            chat_box.press("Enter")
            print("Pressed Enter!")
            
        # 5. Monitor response for 30s
        for t in range(6):
            time.sleep(5)
            stop_count = page.locator('button:has-text("Dừng")').count()
            not_found = page.locator('[data-testid="chat-video-not-found"]').count()
            print(f"[{(t+1)*5}s] Stop button: {stop_count}, Video not found: {not_found}")
            
        screenshot_path = Path("04_Assets/test_send_state.png").resolve()
        page.screenshot(path=str(screenshot_path))
        print("Screenshot saved to:", screenshot_path)

if __name__ == "__main__":
    test_connection_and_render()
