#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
带超时的版本 - 解决 DPAPI 卡住问题
"""

import os
import sys

# 强制立即输出
sys.stdout.reconfigure(line_buffering=True)
sys.stderr.reconfigure(line_buffering=True)

print("="*60)
print("  带 DPAPI 超时的版本")
print("="*60)
print()

# 导入
print(">>> 导入模块...")
from playwright.sync_api import sync_playwright
import json
import subprocess
import time

print("[OK] 所有模块已导入")
print()

# 加载配置
print(">>> 加载配置...")
config_file = "config.json"
with open(config_file, "r", encoding="utf-8") as f:
    config = json.load(f)

# 兼容不同的配置文件格式
password_file = (
    config.get('credentials', {}).get('password_file') or  # 新格式
    config.get('password_file') or                         # 旧格式
    'password.enc'                                         # 默认值
)

crm_url = (
    config.get('crm', {}).get('url') or   # 新格式
    config.get('crm_url')                 # 旧格式
)

# 获取用户名（优先从命令行获取）
username = sys.argv[2] if len(sys.argv) > 2 else None
if not username:
    # 尝试从配置文件读取
    username = (
        config.get('crm', {}).get('username') or  # 新格式
        config.get('crm_username')                # 旧格式
    )

if not username:
    print("请提供 CRM 用户名")
    print("用法: python mdp_termination_test.py <EmployeeId> <CRM_Username>")
    sys.exit(1)

# 获取 EmployeeId
if len(sys.argv) > 1:
    employee_id = sys.argv[1]
else:
    # 使用默认值 - 请替换为实际的 active user EmployeeId
    employee_id = "YOUR_EMPLOYEE_ID_HERE"  # 请修改为实际的 EmployeeId
    print(f"使用默认 EmployeeId，请修改为实际值")
    print(f"   用法: python mdp_termination_test.py <EmployeeId> <CRM_Username>")
    print()

print(f"[OK] 配置已加载")
print(f"  CRM URL: {crm_url}")
print(f"  用户名: {username}")
print(f"  EmployeeId: {employee_id}")
print()

# 跳过密码解密，直接使用明文密码（仅用于测试！）
print(">>> [临时方案] 使用明文密码进行测试")
print("  [WARNING] 注意：这仅用于测试，不会保存密码")
print()

import os

# 尝试从多个来源获取密码
password = None

# 1. 从环境变量获取
if not password:
    password = os.environ.get('CRM_PASSWORD')

# 2. 从命令行第三个参数获取
if not password and len(sys.argv) > 3:
    password = sys.argv[3]

# 3. 使用 getpass 提示输入
if not password:
    print("请输入 CRM 密码:")
    import getpass
    password = getpass.getpass("")

if not password:
    print("[ERROR] 密码为空")
    print("用法: python mdp_termination_test.py <EmployeeId> <CRM_Username> [Password]")
    print("或者设置环境变量: set CRM_PASSWORD=your_password")
    sys.exit(1)

print(f"[OK] 密码已输入 (长度: {len(password)})")
print()

# 查询 AD
print(f">>> 查询 AD: {employee_id}")
try:
    ps_command = [
        "powershell",
        "-Command",
        f"Import-Module ActiveDirectory; Get-ADUser -Filter \"EmployeeId -eq '{employee_id}'\" -Properties DisplayName, SamAccountName | ConvertTo-Json"
    ]

    result = subprocess.run(
        ps_command,
        capture_output=True,
        text=True,
        timeout=30,
        encoding='utf-8'
    )

    if result.stderr and "Cannot find" in result.stderr:
        print(f"[ERROR] 用户不存在: {employee_id}")
        sys.exit(1)

    if not result.stdout.strip():
        print(f"[ERROR] 用户不存在: {employee_id}")
        sys.exit(1)

    user_data = json.loads(result.stdout)

    if not user_data or not isinstance(user_data, dict):
        print(f"[ERROR] 用户不存在: {employee_id}")
        sys.exit(1)

    display_name = user_data.get('DisplayName')
    print(f"[OK] 找到用户: {display_name}")

except Exception as e:
    print(f"[ERROR] AD 查询失败: {e}")
    sys.exit(1)

print()

# CRM 登录
print(">>> CRM 登录（即将打开浏览器）")
print()

try:
    print("  [1/5] 启动 Playwright...")

    with sync_playwright() as p:
        print("  [2/5] 启动浏览器...")

        # 启动浏览器 - 使用 Playwright 自带的 Chromium（不用系统 Chrome）
        # 这样可以确保完全干净的会话，不会有任何缓存数据
        browser = p.chromium.launch(
            headless=False,      # 显示窗口
            slow_mo=100,        # 慢速模式
            # 不使用 channel="chrome"，避免读取系统缓存
            args=[
                '--disable-blink-features=AutomationControlled',  # 隐藏自动化特征
                '--no-sandbox',
                '--disable-infobars',
                '--disable-web-security',
                '--disable-features=IsolateOrigins,site-per-process'
            ]
        )

        print("  [OK] 浏览器已启动！（干净模式，无缓存）")

        # 创建完全隔离的 context
        context = browser.new_context(
            ignore_https_errors=True,
            accept_downloads=False,
            storage_state=None,  # 明确不使用任何存储状态
            viewport={'width': 1280, 'height': 720},
            user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
        )
        page = context.new_page()

        print("  [3/5] 访问 CRM...")
        login_url = f"{crm_url.rstrip('/')}/MDP/"
        page.goto(login_url)

        print(f"  [OK] 页面已加载")

        time.sleep(2)

        current_url = page.url
        print(f"  当前 URL: {current_url}")

        if 'main.aspx' not in current_url:
            print("  [4/5] 自动登录...")

            # 填写用户名
            print(f"    填写用户名: {username}")
            page.fill('input[name="username"]', username, timeout=5000)
            time.sleep(0.5)

            # 填写密码
            print("    填写密码...")
            page.fill('input[name="password"]', password, timeout=5000)
            time.sleep(0.5)

            # 点击登录
            print("    点击登录按钮...")
            page.click('button[type="submit"]', timeout=5000)

            # 等待登录
            print("    等待登录完成...")
            for i in range(30):
                time.sleep(1)
                if 'main.aspx' in page.url:
                    print(f"    [OK] 登录成功！")
                    break
                if i % 5 == 0:
                    print(f"      等待中... {i+1}/30")

        # 提取 cookies
        print("  [5/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("  [ERROR] 无法提取 cookies")
            print(f"  可用的 cookies: {[c['name'] for c in cookies]}")
        else:
            print(f"  [OK] ReqClientId: {req_client_id[:20]}...")
            print(f"  [OK] orgId: {org_id[:20]}...")

        print()
        print("="*60)
        print("  [OK] CRM 登录成功！")
        print("="*60)
        print()
        print("浏览器将保持打开 10 秒供你查看...")

        time.sleep(10)

        print("  关闭浏览器...")
        browser.close()
        print("  [OK] 完成")

except Exception as e:
    print(f"[ERROR] 错误: {e}")
    import traceback
    traceback.print_exc()

print()
print("="*60)
print("  [OK] 测试完成！")
print("="*60)
print()
print("按回车退出...")
input()
