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

CHROME_PATH = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
PROFILE_DIR = r"Profile 5"
CDP_URL = "http://localhost:9222"

def ensure_chrome_cdp():
    import urllib.request
    try:
        urllib.request.urlopen(f"{CDP_URL}/json/version", timeout=2)
        print("Chrome CDP already running on port 9222.")
        return
    except Exception:
        pass

    print("Launching real Chrome with remote debugging on port 9222...")
    cmd = [
        CHROME_PATH,
        "--remote-debugging-port=9222",
        f"--profile-directory={PROFILE_DIR}",
        "--restore-last-session",
        "https://muse.ai"
    ]
    subprocess.Popen(cmd)
    
    # Wait for CDP to be available
    for _ in range(15):
        time.sleep(1)
        try:
            urllib.request.urlopen(f"{CDP_URL}/json/version", timeout=1)
            print("✓ Chrome CDP is ready!")
            return
        except Exception:
            pass
    print("[!] Warning: Could not connect to Chrome CDP within 15s")

def test_cdp():
    ensure_chrome_cdp()
    with sync_playwright() as p:
        browser = p.chromium.connect_over_cdp(CDP_URL)
        ctx = browser.contexts[0]
        page = ctx.pages[0] if ctx.pages else ctx.new_page()
        print("Connected to Chrome via CDP!")
        print("Page URL:", page.url)
        print("Page title:", page.title())
        time.sleep(3)
        page.screenshot(path="04_Assets/chrome_cdp_muse.png")
        print("Screenshot saved to 04_Assets/chrome_cdp_muse.png")
        
        # Check text
        content = page.content()
        print("Has 'Đang kết nối':", "Đang kết nối" in content)
        print("Has 'Nhắn tin':", "Nhắn tin" in content or "Message" in content)

if __name__ == '__main__':
    test_cdp()
