import sys, time
from playwright.sync_api import sync_playwright

sys.stdout.reconfigure(encoding="utf-8")
user_data = r"C:\Users\Admin\AppData\Local\Google\Chrome\User Data"

print("[1] Khởi chạy Playwright Chrome Profile 5...", flush=True)
try:
    with sync_playwright() as p:
        args = [
            "--profile-directory=Profile 5",
            "--disable-blink-features=AutomationControlled",
            "--exclude-switches=enable-automation",
            "--no-first-run",
            "--no-default-browser-check",
            "--disable-infobars",
        ]
        context = p.chromium.launch_persistent_context(
            user_data_dir=user_data,
            channel="chrome",
            headless=True,
            args=args,
            ignore_default_args=["--enable-automation"]
        )
        print("[2] Browser context opened successfully!", flush=True)
        page = context.pages[0] if context.pages else context.new_page()
        
        print("[3] Navigating to https://muse.ai...", flush=True)
        page.goto("https://muse.ai", wait_until="domcontentloaded", timeout=25000)
        print("[4] DOM Content loaded! Waiting 4 seconds...", flush=True)
        time.sleep(4)
        
        print(f"[5] Page URL: {page.url}", flush=True)
        print(f"[6] Page Title: {page.title()}", flush=True)
        page.screenshot(path="scratch_pw_muse_fast.png")
        print("[7] Screenshot saved to scratch_pw_muse_fast.png", flush=True)
        
        # Check text
        body = page.locator("body").inner_text()
        print("[8] Body excerpt:\n" + body[:300], flush=True)
        context.close()
        print("[9] Closed cleanly.", flush=True)
except Exception as e:
    print(f"[!] Error: {e}", flush=True)
