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 delete_broken_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)
        
        thread_item = page.locator(':text("Tạo video Thuy Kieu")').first
        if thread_item.count() > 0:
            print("Hovering thread...")
            thread_item.hover()
            time.sleep(1)
            
            action_btn = page.locator('button[aria-label*="Hành động khác"]').last
            action_btn.click()
            time.sleep(1)
            
            delete_opt = page.locator('text="Xóa"').first
            if delete_opt.count() > 0:
                print("Clicking 'Xóa' option...")
                delete_opt.click()
                time.sleep(1)
                
                # Check confirmation modal
                confirm_btn = page.locator('button:has-text("Xóa"), [role="dialog"] button:has-text("Xác nhận")').last
                if confirm_btn.count() > 0:
                    print("Confirming delete:", confirm_btn.inner_text())
                    confirm_btn.click()
                    time.sleep(2)
                    print("✓ Broken thread deleted successfully!")
                    
        page.screenshot(path="04_Assets/after_thread_delete.png")
        print("Current URL:", page.url)

if __name__ == '__main__':
    delete_broken_thread()
