import sys
import time
from pathlib import Path
from invisible_playwright import InvisiblePlaywright

if sys.platform == "win32":
    sys.stdout.reconfigure(encoding="utf-8", line_buffering=True)
    sys.stderr.reconfigure(encoding="utf-8", line_buffering=True)

pdir = Path.home() / 'AntigravityProfiles' / 'phu2234_worker'

with InvisiblePlaywright(profile_dir=pdir, headless=True) as ctx:
    page = ctx.pages[0] if ctx.pages else ctx.new_page()
    page.goto('https://muse.ai', wait_until='networkidle', timeout=30000)
    time.sleep(3)
    
    # Số lượng thread muốn archive
    count_to_archive = 15
    archived = 0
    
    print(f"Bắt đầu dọn dẹp {count_to_archive} sub-chat cũ...")
    for i in range(count_to_archive):
        # Lấy các div chứa text sub-chat (bỏ qua [0] là 'Tạo video 10 giây thập niên 1980')
        # Tìm div có text bắt đầu bằng 'Tạo video' hoặc 'Video'
        targets = page.locator('text="Tạo video cận cảnh", text="Tạo video hoàng hôn", text="Tạo video bàn tay", text="Tạo video cảnh rặng cau", text="Tạo video chân dung", text="Tạo video điện ảnh", text="Tạo video Kiều", text="Tạo video Kim Trọng", text="Video 10 giây", text="Tạo video cắt tóc", text="Tạo video 10 giây nâng", text="Tạo video cảnh Kiều"').all()
        
        if not targets:
            print("Không tìm thấy target nào nữa.")
            break
            
        target = targets[0]
        title = target.inner_text().strip()
        print(f"Targeting: {title}")
        
        target.hover()
        time.sleep(0.5)
        
        # Tìm nút 3 chấm aria-label="Hành động khác với cuộc trò chuyện"
        dots = page.locator('button[aria-label="Hành động khác với cuộc trò chuyện"]:visible').first
        if dots.count() > 0:
            dots.click()
            time.sleep(0.5)
            
            # Click Lưu trữ
            arch_btn = page.locator('div[role="menu"] *:has-text("Lưu trữ")').last
            if arch_btn.count() > 0:
                arch_btn.click()
                archived += 1
                print(f"[{archived}/{count_to_archive}] ✓ Đã lưu trữ thành công: {title}")
                time.sleep(1.2)
            else:
                page.keyboard.press("Escape")
                time.sleep(0.5)
        else:
            print("Không thấy nút 3 chấm, bỏ qua...")
            
    print(f"🎉 Hoàn tất dọn dẹp: Đã lưu trữ {archived} đoạn chat phụ cũ!")
