# -*- coding: utf-8 -*-
"""
Start Chrome debug mode for Baijiahao.
Uses a fresh isolated profile (no login needed - login in the opened window).
Port: 9223
"""
import sys, subprocess, time, urllib.request, json, os

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

# ========================================
# 配置 - 统一使用 9222 端口
# 与微信公众号 Skill 保持一致，确保跨电脑兼容性
# ========================================
HOST = "127.0.0.1"
PORT = 9222

# 用户数据目录（与微信公众号 Skill 一致）
USER_DATA_DIR = r"C:\ChromeDebug"

# 自动检测 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 p in CHROME_PATHS:
    if os.path.exists(p):
        CHROME = p
        break

if not CHROME:
    print("[ERROR] 未找到 Chrome，请手动指定路径")
    sys.exit(1)

print(f"[INFO] Chrome 路径: {CHROME}")
print(f"[INFO] 用户数据目录: {USER_DATA_DIR}")
print(f"[INFO] 调试端口: {PORT}")
print(f"[INFO] 用户数据目录: {USER_DATA_DIR}")

# ========================================
# 检查 Chrome 是否已在调试模式运行
# ========================================
def check_debug_port():
    try:
        data = json.loads(urllib.request.urlopen(f'http://{HOST}:{PORT}/json', timeout=2).read())
        return data
    except Exception:
        return None

data = check_debug_port()
if data is not None:
    print(f"\n[OK] Chrome 已在调试模式运行（端口 {PORT}）")
    print(f"       共 {len(data)} 个页面")
    for t in data:
        if t.get('type') == 'page':
            print(f"       - {t['id'][:8]}... {t['url'][:70]}")
    print("\n[提示] 如需导航到百家号编辑器，请运行: python bjh_navigate_cdp.py")
    sys.exit(0)

# ========================================
# 启动 Chrome 调试模式
# ========================================
print(f"\n[INFO] 启动 Chrome 调试模式...")
print(f"       端口: {PORT}")
print(f"       用户数据: {USER_DATA_DIR}")

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

# ========================================
# 等待 Chrome 启动完成
# ========================================
print("\n[INFO] 等待 Chrome 启动...")
for i in range(15):
    time.sleep(1)
    data = check_debug_port()
    if data is not None:
        pages = [t for t in data if t.get('type') == 'page']
        print(f"\n[OK] Chrome 已启动！{len(pages)} 个页面")
        for t in pages:
            print(f"       - {t['id'][:8]}... {t['url'][:70]}")
        print("\n" + "=" * 60)
        print("下一步:")
        print("  1. 如需导航到百家号: python bjh_navigate_cdp.py")
        print("  2. 如需直接填写文章: python bjh_fill_article_v6.py")
        print("=" * 60)
        sys.exit(0)
    print(f"       等待中... ({i+1}s)")

print("\n[FAIL] Chrome 未在 15 秒内响应")
print("[提示] 请手动检查 Chrome 是否已启动")
sys.exit(1)
