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)
    
    count_to_archive = 25
    archived = 0
    print(f"Bắt đầu lưu trữ {count_to_archive} thread cũ theo data-testid='hatch-thread-row'...")
    
    for i in range(count_to_archive):
        rows = page.locator('div[data-testid="hatch-thread-row"]').all()
        print(f"Tổng số thread rows hiện tại: {len(rows)}")
        if len(rows) <= 2:
            print("Đã hết thread cũ cần dọn!")
            break
            
        # Bỏ qua row 0 (thread mới nhất), lấy row 1
        target_row = rows[1]
        txt = target_row.inner_text().strip().replace('\n', ' ')
        print(f"[{i+1}] Lưu trữ: {txt[:40]}...")
        
        target_row.hover()
        time.sleep(0.5)
        
        dots = target_row.locator('button[aria-label="Hành động khác với cuộc trò chuyện"]').first
        if dots.count() == 0:
            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)
            
            menu = page.locator('div[role="menu"]')
            arch_btn = menu.locator('*:has-text("Lưu trữ")').last
            if arch_btn.count() > 0:
                arch_btn.click()
                archived += 1
                print(f"      ✓ Đã lưu trữ thành công!")
                time.sleep(1.2)
            else:
                page.keyboard.press("Escape")
                time.sleep(0.5)
        else:
            print("      Không tìm thấy nút 3 chấm.")
            break
            
    print(f"\n🎉 Hoàn thành: Đã lưu trữ {archived} đoạn chat phụ cũ!")
