import sys
import subprocess
import time
import urllib.request
import json

sys.stdout.reconfigure(encoding='utf-8')

import os

# 自动检测Chrome路径
CHROME_PATHS = [
    r"C:\Program Files\Google\Chrome\Application\chrome.exe",
    r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
    os.path.expandvars(r"%LOCALAPPDATA%\Google\Chrome\Application\chrome.exe"),
]

CHROME = None
for path in CHROME_PATHS:
    if os.path.exists(path):
        CHROME = path
        print(f"[INFO] Found Chrome at: {path}")
        break

if not CHROME:
    print("[ERROR] Chrome not found in standard locations")
    sys.exit(1)
USER_DATA_DIR = r"C:\ChromeDebug"

# 先检查是否已经在调试模式运行
try:
    data = json.loads(urllib.request.urlopen('http://localhost:9222/json', timeout=2).read())
    print(f"[OK] Chrome already running in debug mode, {len(data)} pages")
    for i, t in enumerate(data):
        if t.get('type') == 'page':
            print(f"  {i} {t['id']} {t['url'][:80]}")
    sys.exit(0)
except Exception:
    pass

print("[INFO] Starting Chrome with remote debugging...")
subprocess.Popen(
    [CHROME, '--remote-debugging-port=9222', f'--user-data-dir={USER_DATA_DIR}', '--no-first-run', '--no-default-browser-check'],
    creationflags=subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP
)

# 等待启动
for i in range(10):
    time.sleep(1)
    try:
        data = json.loads(urllib.request.urlopen('http://localhost:9222/json', timeout=2).read())
        pages = [t for t in data if t.get('type') == 'page']
        print(f"[OK] Chrome started! {len(pages)} page(s) detected")
        for j, t in enumerate(pages):
            print(f"  {j} {t['id']} {t['url'][:80]}")
        sys.exit(0)
    except Exception:
        print(f"  waiting... ({i+1}s)")

print("[FAIL] Chrome did not respond after 10s, please start manually:")
print(f'  "{CHROME}" --remote-debugging-port=9222 --user-data-dir={USER_DATA_DIR}')
