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_send_simple():
    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)
        
        # New chat
        btn = page.locator('button[aria-label="Đoạn chat phụ mới"]').first
        btn.click()
        time.sleep(4)
        
        # Ensure connected
        for _ in range(10):
            if "Đang kết nối" not in page.locator('body').inner_text():
                print("✓ Page is fully connected!")
                break
            time.sleep(1)
            
        chat_box = page.locator('textarea, [placeholder*="Nhắn tin"]').first
        chat_box.click()
        time.sleep(1)
        
        prompt = "Tạo video 10 giây điện ả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ùa xuân, 24fps cinematic. Âm thanh: Tiếng nước sông vỗ nhẹ, tiếng gió xuân mát rượi. 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.fill(prompt)
        time.sleep(1)
        
        send_btn = page.locator('button[data-pel-click="chat_send_message"]').first
        print("Send button visible:", send_btn.is_visible())
        send_btn.click()
        time.sleep(3)
        
        # Check every 5s for 30s
        for i in range(6):
            time.sleep(5)
            sec = (i+1)*5
            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
            has_sending = "Vẫn đang gửi" in page.locator('body').inner_text()
            has_conn = "Đang kết nối" in page.locator('body').inner_text()
            print(f"[{sec:2d}s] stop={has_stop}, dl={has_dl}, still_sending={has_sending}, connecting={has_conn}")
            
        page.screenshot(path="04_Assets/simple_send_result.png")

if __name__ == '__main__':
    test_send_simple()
