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 sync_worker_profile, DEFAULT_PROFILE

def test_fresh_thread():
    sync_worker_profile()
    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)
        
        # Click '+' to create a new secondary chat
        plus_btn = page.locator('button[aria-label*="chat phụ mới"], button:has-text("+"), [aria-label*="Đoạn chat phụ mới"]').first
        if plus_btn.count() > 0:
            print("Clicking new chat (+) button:", plus_btn)
            plus_btn.click()
            time.sleep(2)
        else:
            print("Plus button not found, clicking 'Đoạn chat chính'...")
            main_chat = page.locator('text="Đoạn chat chính"').first
            if main_chat.count() > 0:
                main_chat.click()
                time.sleep(2)
                
        page.screenshot(path="04_Assets/fresh_thread_state.png")
        print("Fresh thread URL:", page.url)
        
        # Now try to delete the broken thread while not active
        thread_item = page.locator(':text("Tạo video Thuy Kieu ho")').first
        if thread_item.count() > 0:
            print("Hovering old broken thread...")
            thread_item.hover()
            time.sleep(1)
            action_btn = page.locator('button[aria-label*="Hành động khác"]').last
            if action_btn.count() > 0:
                action_btn.click()
                time.sleep(1)
                delete_opt = page.locator('text="Xóa"').first
                if delete_opt.count() > 0:
                    delete_opt.click()
                    time.sleep(1)
                    confirm_btn = page.locator('button:has-text("Xóa"), [role="dialog"] button:has-text("Xác nhận")').last
                    if confirm_btn.count() > 0:
                        confirm_btn.click()
                        time.sleep(2)
                        print("Deleted while inactive!")
                        
        page.screenshot(path="04_Assets/fresh_thread_after_cleanup.png")

if __name__ == '__main__':
    test_fresh_thread()
