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 DEFAULT_PROFILE

def test_new_thread_submission():
    with InvisiblePlaywright(profile_dir=DEFAULT_PROFILE, headless=True) as ctx:
        page = ctx.pages[0] if ctx.pages else ctx.new_page()
        
        page.on("console", lambda m: print(f"[CONSOLE {m.type}] {m.text}"))
        page.on("requestfailed", lambda r: print(f"[REQ FAILED] {r.method} {r.url}: {r.failure}"))
        page.on("response", lambda r: print(f"[RESP {r.status}] {r.url}") if "api" in r.url or "chat" in r.url or "thread" in r.url else None)
        
        print("Navigating to https://muse.ai/thread/new ...")
        page.goto("https://muse.ai/thread/new", wait_until="domcontentloaded", timeout=30000)
        time.sleep(3)
        print("Initial URL:", page.url)
        page.screenshot(path="04_Assets/step1_nav.png")
        
        # Attach image
        img_path = Path("04_Assets/keyframes/ep01_scene01_shot01/start_frame_720p.png").resolve()
        file_input = page.locator('input[type="file"]').first
        if file_input.count() > 0:
            print("Setting input files...")
            file_input.set_input_files(str(img_path))
            time.sleep(3)
        page.screenshot(path="04_Assets/step2_attached.png")
        
        # Fill prompt
        prompt = "Khai mở cảnh 1: Cú máy bay lướt êm ả dọc theo dòng sông biếc uốn lượn ngoại ô kinh thành. Mặt nước trong veo phản chiếu rặng liễu tơ mềm. Âm thanh: Tiếng nước sông vỗ nhẹ, tiếng gió xuân lướt qua rặng liễu. Quy tắc âm thanh: Tuyệt đối KHÔNG sinh nhạc nền, không âm thanh điện tử. Chỉ sinh foley và ambience."
        chat_box = page.locator('textarea, [placeholder*="Nhắn tin"], [placeholder*="Message"], [role="textbox"]').first
        chat_box.click()
        time.sleep(1)
        chat_box.fill(prompt)
        time.sleep(1)
        page.screenshot(path="04_Assets/step3_filled.png")
        
        # Click send button
        send_btn = page.locator('button[data-pel-click="chat_send_message"], button[aria-label="Gửi"], button[aria-label*="Gửi"]').first
        print("Send button visible:", send_btn.is_visible() if send_btn.count() > 0 else False)
        if send_btn.count() > 0 and send_btn.is_visible():
            print("Clicking send button...")
            send_btn.click()
        else:
            print("Pressing Enter...")
            chat_box.press("Enter")
            
        time.sleep(3)
        print("URL after 3s:", page.url)
        page.screenshot(path="04_Assets/step4_after_send.png")
        
        time.sleep(7)
        print("URL after 10s:", page.url)
        page.screenshot(path="04_Assets/step5_after_10s.png")

if __name__ == '__main__':
    test_new_thread_submission()
