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_insert_and_send():
    with InvisiblePlaywright(profile_dir=DEFAULT_PROFILE, headless=True) as ctx:
        page = ctx.pages[0] if ctx.pages else ctx.new_page()
        page.on("request", lambda r: print(f"[REQ] {r.method} {r.url}") if any(k in r.url for k in ["chat", "thread", "message", "api"]) else None)
        page.on("response", lambda r: print(f"[RESP {r.status}] {r.url}") if any(k in r.url for k in ["chat", "thread", "message", "api"]) 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)
        
        # Click '+' attachment button if we have an 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("Uploading image...")
            file_input.set_input_files(str(img_path))
            time.sleep(3)
            
        textarea = page.locator('textarea[placeholder*="Nhắn tin"], textarea').first
        textarea.click()
        time.sleep(1)
        
        prompt = "Tạo video 10 giây điện ảnh: Tiếp diễn sau cổng thành Đại Minh Gia Tĩnh: 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 như ngọc phản chiếu rặng liễu tơ mềm và làn sương sớm mai lảng bảng. Cảnh sắc mùa xuân thanh bình, xa xa thoáng bóng thuyền nan lướt nhẹ, 24fps cinematic drama. Âm thanh: Tiếng nước sông vỗ nhẹ vào bờ đất, tiếng mái chèo khua nước êm đềm từ xa, tiếng gió xuân mát rượi 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ử, không tạp âm rè nhiễu. Chỉ sinh foley và ambience."
        
        print("Inserting text via page.keyboard.insert_text...")
        page.keyboard.insert_text(prompt)
        time.sleep(1)
        page.keyboard.press("Space")
        time.sleep(1)
        
        send_btn = page.locator('button[data-pel-click="chat_send_message"], button[aria-label="Gửi"]').first
        print("Send button count:", send_btn.count())
        print("Send button visible:", send_btn.is_visible() if send_btn.count() > 0 else False)
        print("Send button enabled:", send_btn.is_enabled() 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...")
            page.keyboard.press("Enter")
            
        time.sleep(5)
        page.screenshot(path="04_Assets/insert_send_5s.png")
        print("URL after 5s:", page.url)
        
        # Check messages
        for i in range(6):
            time.sleep(5)
            print(f"[{ (i+2)*5 }s] Monitoring...")
            # Check if stop button or assistant message appears
            has_stop = page.locator('button:has-text("Dừng"), button[aria-label*="Dừng"]').count() > 0
            has_dl = page.locator('button[aria-label*="Tải video xuống"]').count() > 0
            print(f"       has_stop={has_stop}, has_dl={has_dl}")
            
        page.screenshot(path="04_Assets/insert_send_35s.png")

if __name__ == '__main__':
    test_insert_and_send()
