import os
import sys
import time
import subprocess
from pathlib import Path
from playwright.sync_api import sync_playwright

if sys.platform == "win32":
    try:
        sys.stdout.reconfigure(encoding="utf-8")
        sys.stderr.reconfigure(encoding="utf-8")
    except Exception:
        pass

CHROME_USER_DATA = Path(r"C:\Users\Admin\AppData\Local\Google\Chrome\User Data")
TARGET_DIR = Path.home() / "AntigravityProfiles" / "chrome_muse"

def test_chromium():
    TARGET_DIR.mkdir(parents=True, exist_ok=True)
    src_profile = CHROME_USER_DATA / "Profile 5"
    dst_profile = TARGET_DIR / "Default"
    if src_profile.exists():
        dst_profile.mkdir(parents=True, exist_ok=True)
        cmd = f'robocopy "{src_profile}" "{dst_profile}" "Cookies*" "Login Data*" "Web Data*" /E /XD "Cache*" "Code Cache" "DawnGraphiteCache" "DawnWebGPUCache" /XF "*lock*" /NFL /NDL /NJH /NJS /nc /ns /np'
        subprocess.run(cmd, shell=True)
        
    print("Launching Chromium with profile:", dst_profile)
    with sync_playwright() as p:
        browser = p.chromium.launch_persistent_context(
            user_data_dir=str(TARGET_DIR),
            headless=True,
            args=["--disable-blink-features=AutomationControlled"]
        )
        page = browser.pages[0] if browser.pages else browser.new_page()
        page.goto("https://muse.ai", wait_until="domcontentloaded", timeout=30000)
        time.sleep(5)
        
        print("Page URL:", page.url)
        print("Page Title:", page.title())
        
        screenshot_path = Path("04_Assets/chromium_muse_state.png").resolve()
        page.screenshot(path=str(screenshot_path))
        print("Saved screenshot to:", screenshot_path)
        
        body = page.locator("body").inner_text()
        print("Body sample (300 chars):", body[:300].replace("\n", " "))
        browser.close()

if __name__ == "__main__":
    test_chromium()
