#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
完全独立的调试版本 - 不依赖 mdp_termination 模块
"""

import os
import sys

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

print("="*60)
print("  完全独立调试版本")
print("="*60)
print()

# 步骤 1: 导入
print(">>> [1/8] 导入模块...")
try:
    from playwright.sync_api import sync_playwright
    print("✓ Playwright")
except Exception as e:
    print(f"✗ Playwright: {e}")
    input("按回车退出...")
    sys.exit(1)

try:
    import json
    print("✓ json")
except Exception as e:
    print(f"✗ json: {e}")
    input("按回车退出...")
    sys.exit(1)

try:
    import subprocess
    print("✓ subprocess")
except Exception as e:
    print(f"✗ subprocess: {e}")
    input("按回车退出...")
    sys.exit(1)

print()

# 步骤 2: 检查配置
print(">>> [2/8] 检查配置...")
config_file = "config.json"

if not os.path.exists(config_file):
    print(f"✗ 配置不存在: {config_file}")
    input("按回车退出...")
    sys.exit(1)

print(f"✓ 配置存在")

try:
    with open(config_file, "r", encoding="utf-8") as f:
        config = json.load(f)
    print(f"✓ 配置已加载")
    print(f"  CRM URL: {config.get('crm_url')}")
    print(f"  用户名: {config.get('crm_username')}")
except Exception as e:
    print(f"✗ 配置读取失败: {e}")
    import traceback
    traceback.print_exc()
    input("按回车退出...")
    sys.exit(1)

print()

# 步骤 3: 检查密码文件
print(">>> [3/8] 检查密码文件...")
password_file = config.get('password_file', 'password.enc')

if not os.path.exists(password_file):
    print(f"✗ 密码文件不存在: {password_file}")
    input("按回车退出...")
    sys.exit(1)

print(f"✓ 密码文件存在: {password_file}")
print(f"  文件大小: {os.path.getsize(password_file)} bytes")

print()

# 步骤 4: 测试解密 - 使用 dpapi 库
print(">>> [4/8] 测试 dpapi 库解密...")
password = None

try:
    import dpapi
    print("  ✓ dpapi 库已安装")

    with open(password_file, 'rb') as f:
        encrypted_bytes = f.read()

    print(f"  加密数据: {len(encrypted_bytes)} bytes")

    decrypted_bytes = dpapi.decrypt(encrypted_bytes)
    password = decrypted_bytes.decode('utf-8')

    print(f"✓ 使用 dpapi 解密成功!")
    print(f"  密码长度: {len(password)}")

except ImportError:
    print("  ✗ dpapi 库未安装，尝试 ctypes...")
except Exception as e:
    print(f"  ✗ dpapi 解密失败: {e}")
    import traceback
    traceback.print_exc()

# 如果 dpapi 失败，尝试 ctypes
if not password:
    print("  >>> 尝试 ctypes DPAPI...")
    try:
        import ctypes
        from ctypes import wintypes

        crypt32 = ctypes.windll.crypt32

        class DATA_BLOB(ctypes.Structure):
            _fields_ = [
                ("cbData", wintypes.DWORD),
                ("pbData", ctypes.POINTER(ctypes.c_byte))
            ]

        with open(password_file, 'rb') as f:
            encrypted_bytes = f.read()

        buffer_type = ctypes.c_byte * len(encrypted_bytes)
        buffer = buffer_type.from_buffer_copy(encrypted_bytes)

        input_blob = DATA_BLOB()
        input_blob.cbData = len(encrypted_bytes)
        input_blob.pbData = buffer

        output_blob = DATA_BLOB()

        print("  调用 CryptUnprotectData...")

        result = crypt32.CryptUnprotectData(
            ctypes.byref(input_blob),
            None,
            None,
            None,
            None,
            0
        )

        if not result:
            error_code = ctypes.get_last_error()
            print(f"  ✗ DPAPI 解密失败，错误代码: {error_code}")
            input("按回车退出...")
            sys.exit(1)

        decrypted_buffer = (ctypes.c_byte * output_blob.cbData)()
        ctypes.memmove(decrypted_buffer, output_blob.pbData, output_blob.cbData)
        decrypted_bytes = bytes(decrypted_buffer)

        ctypes.windll.kernel32.LocalFree(output_blob.pbData)

        password = decrypted_bytes.decode('utf-8')

        print("✓ 使用 ctypes 解密成功!")
        print(f"  密码长度: {len(password)}")

    except Exception as e:
        print(f"✗ ctypes 解密也失败: {e}")
        import traceback
        traceback.print_exc()
        input("按回车退出...")
        sys.exit(1)

if not password:
    print("✗ 无法解密密码")
    input("按回车退出...")
    sys.exit(1)

print()

# 步骤 5: 获取 EmployeeId
print(">>> [5/8] 获取 EmployeeId...")
if len(sys.argv) > 1:
    employee_id = sys.argv[1]
    print(f"✓ EmployeeId: {employee_id}")
else:
    employee_id = "172034"
    print(f"✓ 使用默认 EmployeeId: {employee_id}")

print()

# 步骤 6: 查询 AD
print(">>> [6/8] 查询 AD...")
print(f"  EmployeeId: {employee_id}")

try:
    ps_command = [
        "powershell",
        "-Command",
        f"Import-Module ActiveDirectory; Get-ADUser -Filter \"EmployeeId -eq '{employee_id}'\" -Properties DisplayName, SamAccountName | ConvertTo-Json"
    ]

    print("  执行 PowerShell...")
    result = subprocess.run(
        ps_command,
        capture_output=True,
        text=True,
        timeout=30,
        encoding='utf-8'
    )

    if result.stderr:
        error = result.stderr.strip()
        if "Cannot find" in error:
            print(f"✗ 用户不存在: {employee_id}")
            print(f"  错误: {error}")
            input("按回车退出...")
            sys.exit(1)
        elif "Access is denied" in error:
            print(f"✗ 访问被拒绝")
            print(f"  错误: {error}")
            input("按回车退出...")
            sys.exit(1)

    if not result.stdout.strip():
        print(f"✗ 用户不存在: {employee_id}")
        input("按回车退出...")
        sys.exit(1)

    user_data = json.loads(result.stdout)

    if not user_data or not isinstance(user_data, dict):
        print(f"✗ 用户不存在: {employee_id}")
        input("按回车退出...")
        sys.exit(1)

    display_name = user_data.get('DisplayName')
    if not display_name:
        print(f"✗ DisplayName 为空")
        input("按回车退出...")
        sys.exit(1)

    print(f"✓ 找到用户: {display_name}")

except Exception as e:
    print(f"✗ AD 查询失败: {e}")
    import traceback
    traceback.print_exc()
    input("按回车退出...")
    sys.exit(1)

print()

# 步骤 7: CRM 登录（会打开浏览器！）
print(">>> [7/8] CRM 登录...")
print("  即将打开浏览器窗口...")
print()

try:
    logger = __import__('logging').getLogger(__name__)

    print("  [7.1] 启动 Playwright...")

    with sync_playwright() as p:
        print("  [7.2] 启动浏览器...")

        browser = p.chromium.launch(
            headless=False,        # 显示窗口
            slow_mo=100,          # 慢速模式
            channel="chrome"      # 系统 Chrome
        )

        print("  ✓ 浏览器已启动！你应该能看到窗口")
        print()

        context = browser.new_context()
        page = context.new_page()

        try:
            print("  [7.3] 访问 CRM...")
            crm_url = config['crm_url']
            login_url = f"{crm_url.rstrip('/')}/MDP/"
            print(f"  URL: {login_url}")

            page.goto(login_url)
            print("  ✓ 页面已加载")

            import time
            time.sleep(2)

            current_url = page.url
            print(f"  当前 URL: {current_url}")

            if 'main.aspx' not in current_url:
                print()
                print("  [7.4] 需要登录...")

                # 填写用户名
                print(f"  [7.4.1] 填写用户名: {config['crm_username']}")
                filled = False
                for selector in ['input[name="username"]', 'input[type="text"]']:
                    try:
                        page.fill(selector, config['crm_username'], timeout=2000)
                        filled = True
                        print(f"  ✓ 已填写")
                        break
                    except:
                        continue

                if not filled:
                    print("  ✗ 无法找到用户名输入框")
                    raise Exception("用户名输入框未找到")

                time.sleep(0.5)

                # 填写密码
                print("  [7.4.2] 填写密码...")
                filled = False
                for selector in ['input[name="password"]', 'input[type="password"]']:
                    try:
                        page.fill(selector, password, timeout=2000)
                        filled = True
                        print(f"  ✓ 已填写")
                        break
                    except:
                        continue

                if not filled:
                    print("  ✗ 无法找到密码输入框")
                    raise Exception("密码输入框未找到")

                time.sleep(0.5)

                # 点击登录
                print("  [7.4.3] 点击登录...")
                clicked = False
                for selector in ['button[type="submit"]', 'button:has-text("Log")', 'button:has-text("Sign")']:
                    try:
                        page.click(selector, timeout=2000)
                        clicked = True
                        print(f"  ✓ 已点击")
                        break
                    except:
                        continue

                if not clicked:
                    # 尝试回车
                    page.keyboard.press("Enter")
                    print(f"  ✓ 已按回车")

                # 等待登录
                print("  [7.4.4] 等待登录完成...")
                for i in range(30):
                    time.sleep(1)
                    if 'main.aspx' in page.url:
                        print(f"  ✓ 登录成功！")
                        break
                    if i % 5 == 0:
                        print(f"    等待中... {i+1}/30")

            # 提取 cookies
            print()
            print("  [7.5] 提取 cookies...")
            cookies = context.cookies()

            req_client_id = None
            org_id = None

            for cookie in cookies:
                if cookie['name'] == 'ReqClientId':
                    req_client_id = cookie['value']
                elif cookie['name'] == 'orgId':
                    org_id = cookie['value']

            if not req_client_id or not org_id:
                print("  ✗ 无法提取 cookies")
                print("  可用的 cookies:")
                for cookie in cookies:
                    print(f"    - {cookie['name']}")
                input("按回车退出...")
                sys.exit(1)

            print(f"  ✓ ReqClientId: {req_client_id[:20]}...")
            print(f"  ✓ orgId: {org_id[:20]}...")

            print()
            print("="*60)
            print("  ✓ CRM 登录成功！")
            print("="*60)
            print()
            print("浏览器将保持打开 5 秒供你查看...")
            time.sleep(5)

        finally:
            print()
            print("  关闭浏览器...")
            browser.close()
            print("  ✓ 浏览器已关闭")

except Exception as e:
    print(f"✗ CRM 登录失败: {e}")
    import traceback
    traceback.print_exc()
    input("按回车退出...")
    sys.exit(1)

# 步骤 8: 完成
print()
print("="*60)
print("  ✓ 所有测试通过！")
print("="*60)
print()
print("按回车退出...")
input()
