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

chrome_paths = [
    r"C:\Program Files\Google\Chrome\Application\chrome.exe",
    r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
]
chrome = None
for p in chrome_paths:
    if os.path.exists(p):
        chrome = p
        print(f"FOUND: {p}")
        break

if not chrome:
    print("Chrome not found!")
    sys.exit(1)

USER_DATA_DIR = r"C:\ChromeDebug_BJH"
PORT = 9223

print(f"Launching Chrome with debug port {PORT}...")
proc = subprocess.Popen(
    [chrome,
     f'--remote-debugging-port={PORT}',
     f'--user-data-dir={USER_DATA_DIR}',
     '--no-first-run',
     '--no-default-browser-check',
     'https://baijiahao.baidu.com'],
    creationflags=subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP
)

print(f"PID: {proc.pid}")

for i in range(15):
    time.sleep(1)
    try:
        data = json.loads(urllib.request.urlopen(f'http://localhost:{PORT}/json', timeout=2).read())
        pages = [t for t in data if t.get('type') == 'page']
        print(f"Chrome started! {len(pages)} pages")
        for t in pages:
            print(f"  {t['url'][:80]}")
        break
    except Exception as e:
        print(f"  waiting... ({i+1}s)")
