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'

def archive_old_subchats(target_count=25):
    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)
        
        archived_count = 0
        print(f"Bắt đầu dọn dẹp {target_count} đoạn chat phụ cũ...")
        
        for i in range(target_count):
            try:
                # Tìm các item trong sidebar
                # Sub-chats nằm sau mục "Đoạn chat phụ"
                # Thường các item có aria-label hoặc text
                # Chúng ta hover vào một item bất kỳ dưới danh sách
                # Tìm tất cả các button có thể là thread trong sidebar
                sub_items = page.locator('nav button, aside button, div[class*="sidebar"] button').all()
                
                # Hoặc tìm theo text đại diện của các sub-chat
                found = False
                for btn in sub_items:
                    txt = btn.inner_text().strip()
                    # Tránh click vào "Đoạn chat chính", "Đoạn chat phụ", "Khám phá", v.v.
                    if any(prefix in txt for prefix in ["Tạo video", "Video 10", "Kiểm tra", "Tạo cảnh", "Chèn ghi chú"]):
                        # Tránh lưu trữ thread hiện tại đang dùng nếu nó là Shot 1 mới nhất
                        if "Tạo video 10 giây thập" in txt and i == 0:
                            # Bỏ qua thread hiện tại để giữ lại
                            continue
                        
                        btn.hover()
                        time.sleep(0.5)
                        
                        # Tìm nút 3 chấm
                        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)
                            
                            # Tìm nút 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_count += 1
                                print(f"[{archived_count}/{target_count}] Đã lưu trữ: {txt[:35]}...")
                                time.sleep(1.2)
                                found = True
                                break
                            else:
                                # Đóng menu nếu không có nút Lưu trữ
                                page.keyboard.press("Escape")
                
                if not found:
                    print("Không tìm thấy thêm đoạn chat phụ nào cần lưu trữ.")
                    break
            except Exception as e:
                print(f"Lỗi ở lượt {i}: {e}")
                time.sleep(1)
                
        print(f" Hoàn tất dọn dẹp: Đã lưu trữ thành công {archived_count} đoạn chat phụ cũ!")

if __name__ == "__main__":
    archive_old_subchats(target_count=20)
