#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
调试版本 - 显示所有步骤和错误
"""

import sys
import os
import json
import traceback

# 强制输出
sys.stdout.reconfigure(line_buffering=True)

print("="*60)
print("  MDP Termination - 调试模式")
print("="*60)
print()

# 步骤 1: 检查 Python
print("[步骤 1/7] 检查 Python 版本...")
print(f"  Python: {sys.version}")
print(f"  ✅ Python 3.8+: {sys.version_info >= (3, 8)}")
print()

# 步骤 2: 检查当前目录
print("[步骤 2/7] 检查当前目录...")
cwd = os.getcwd()
print(f"  当前目录: {cwd}")
print()

# 步骤 3: 检查配置文件
print("[步骤 3/7] 检查配置文件...")
if not os.path.exists("config.json"):
    print("  ❌ config.json 不存在")
    print("  请运行: python mdp_termination.py --config")
    sys.exit(1)

try:
    with open("config.json", "r", encoding="utf-8") as f:
        config = json.load(f)
    print("  ✅ config.json 存在且格式正确")
    print(f"  CRM URL: {config.get('crm_url', '未设置')}")
    print(f"  用户名: {config.get('crm_username', '未设置')}")
    print()
except Exception as e:
    print(f"  ❌ 读取配置失败: {e}")
    traceback.print_exc()
    sys.exit(1)

# 步骤 4: 检查密码文件
print("[步骤 4/7] 检查密码文件...")
password_file = config.get('password_file', 'password.enc')
if not os.path.exists(password_file):
    print(f"  ❌ 密码文件不存在: {password_file}")
    print("  请运行: python mdp_termination.py --config")
    sys.exit(1)
print(f"  ✅ 密码文件存在: {password_file}")
print()

# 步骤 5: 导入模块
print("[步骤 5/7] 导入必需模块...")
try:
    print("  导入 asyncio...")
    import asyncio
    print("  ✅ asyncio")

    print("  导入 playwright...")
    from playwright.async_api import async_playwright
    print("  ✅ playwright")

    print("  导入 mdp_termination...")
    import mdp_termination
    print("  ✅ mdp_termination")

    print()
except Exception as e:
    print(f"  ❌ 导入失败: {e}")
    traceback.print_exc()
    sys.exit(1)

# 步骤 6: 测试密码解密
print("[步骤 6/7] 测试密码解密...")
try:
    password = mdp_termination.PasswordManager.decrypt_password(password_file)
    print(f"  ✅ 密码解密成功")
    print(f"  密码长度: {len(password)} 字符")
    print()
except Exception as e:
    print(f"  ❌ 密码解密失败: {e}")
    traceback.print_exc()
    sys.exit(1)

# 步骤 7: 测试浏览器启动
print("[步骤 7/7] 测试浏览器启动...")
print("  正在启动 Chrome 浏览器...")
print("  (应该会看到浏览器窗口打开)")
print()

async def test_browser():
    """测试浏览器启动"""
    try:
        async with async_playwright() as p:
            print("  Playwright 已启动")

            # 使用系统 Chrome
            print("  正在启动 Chrome (channel=chrome)...")
            browser = await p.chromium.launch(
                headless=False,
                channel="chrome"
            )
            print("  ✅ Chrome 启动成功!")

            # 创建页面
            context = await browser.new_context()
            page = await context.new_page()

            # 访问测试页面
            print("  正在访问 CRM...")
            url = config['crm_url']
            await page.goto(f"{url}/MDP/", timeout=30000)
            print(f"  ✅ 页面加载成功: {url}")

            # 等待 3 秒让你看到浏览器
            print("  浏览器将保持打开 3 秒...")
            await asyncio.sleep(3)

            # 关闭浏览器
            await context.close()
            await browser.close()
            print("  ✅ 浏览器已关闭")

            print()
            print("="*60)
            print("  ✅ 所有测试通过!")
            print("="*60)
            print()
            print("现在可以运行:")
            print("  python mdp_termination.py --employee-id 172034")
            return True

    except Exception as e:
        print(f"  ❌ 浏览器测试失败: {e}")
        traceback.print_exc()
        return False

# 运行浏览器测试
try:
    result = asyncio.run(test_browser())
    if result:
        sys.exit(0)
    else:
        sys.exit(1)
except Exception as e:
    print(f"\n❌ 未预期的错误: {e}")
    traceback.print_exc()
    sys.exit(1)
