#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
智能版本：自动检测是否已登录，跳过不必要的登录步骤
"""

import os
import sys

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

print("="*60)
print("  智能版本 - 自动检测登录状态")
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)

# 兼容不同的配置文件格式
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_smart.py <EmployeeId> <CRM_Username>")
    sys.exit(1)

employee_id = sys.argv[1] if len(sys.argv) > 1 else "172034"

print(f"[OK] 配置已加载")
print(f"  CRM URL: {crm_url}")
print(f"  用户名: {username}")
print(f"  EmployeeId: {employee_id}")
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/4] 启动浏览器...")

    with sync_playwright() as p:
        print("  [2/4] 启动浏览器实例...")

        # 使用系统 Chrome + 强制 incognito
        browser = p.chromium.launch(
            headless=False,
            channel="msedge",  # 或 "chrome"
            slow_mo=100,
            args=[
                '--incognito',
                '--disable-blink-features=AutomationControlled',
                '--no-first-run',
                '--disable-web-security',
            ]
        )

        print("  [OK] 浏览器已启动")

        # 创建 context
        context = browser.new_context(
            ignore_https_errors=True,
            accept_downloads=False,
            storage_state=None,
        )

        page = context.new_page()

        print("  [3/4] 访问 CRM...")

        # 访问 CRM（不需要先访问 about:blank）
        login_url = f"{crm_url.rstrip('/')}/MDP/"
        print(f"  URL: {login_url}")

        page.goto(login_url, wait_until="domcontentloaded", timeout=30000)
        print(f"  [OK] 页面已加载")

        time.sleep(2)

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

        # ===== 关键逻辑：检测是否已登录 =====
        is_logged_in = 'main.aspx' in current_url and 'errorhandler.aspx' not in current_url

        if is_logged_in:
            print()
            print("  [OK] 检测到已登录状态！")
            print("  >> 跳过登录步骤，直接使用现有会话")
            print()

        elif 'errorhandler.aspx' in current_url:
            print()
            print("  [WARNING] 检测到错误页面")
            print("  >> 这意味着浏览器有缓存的旧会话（已禁用的用户）")
            print("  >> 解决方案：")
            print("     1. 手动关闭浏览器")
            print("     2. 在普通 Chrome/Edge 中访问 CRM 并登录")
            print("     3. 登录成功后，重新运行此脚本")
            print()
            print("  浏览器将保持打开 30 秒供你手动登录...")
            print("  请在浏览器中手动登录 CRM...")

            # 等待用户手动登录
            for i in range(30):
                time.sleep(1)
                if 'main.aspx' in page.url and 'errorhandler.aspx' not in page.url:
                    print(f"  [OK] 检测到登录成功！（{i+1}秒）")
                    is_logged_in = True
                    break
                if i % 5 == 0 and i > 0:
                    print(f"  等待中... {i}/30 秒")

            if not is_logged_in:
                print("  [ERROR] 30 秒内未检测到登录成功")
                print("  请手动登录后重新运行脚本")
                browser.close()
                sys.exit(1)

        else:
            print()
            print("  [INFO] 未检测到登录状态")
            print("  >> 需要登录 CRM")
            print()
            print("  请在浏览器中手动登录...")
            print("  （AD 集成登录会自动使用 Windows 凭证）")
            print()

            # 等待用户手动登录
            for i in range(60):
                time.sleep(1)
                if 'main.aspx' in page.url and 'errorhandler.aspx' not in page.url:
                    print(f"  [OK] 检测到登录成功！（{i+1}秒）")
                    is_logged_in = True
                    break
                if i % 10 == 0 and i > 0:
                    print(f"  等待中... {i}/60 秒")

            if not is_logged_in:
                print("  [ERROR] 60 秒内未检测到登录成功")
                browser.close()
                sys.exit(1)

        # 现在已经登录了，提取 cookies
        print()
        print("  [4/4] 提取 cookies...")

        time.sleep(1)

        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 req_client_id:
            print(f"  [OK] ReqClientId: {req_client_id[:20]}...")
        else:
            print(f"  [WARNING] 未找到 ReqClientId")

        if org_id:
            print(f"  [OK] orgId: {org_id[:20]}...")
        else:
            print(f"  [WARNING] 未找到 orgId")

        print(f"  总 cookies 数: {len(cookies)}")

        print()
        print("="*60)
        print("  [OK] 会话已建立！")
        print("="*60)
        print()
        print("现在可以：")
        print("  1. 在浏览器中手动搜索要 disable 的用户")
        print("  2. 或者让脚本自动执行 disable 操作")
        print()
        print("浏览器将保持打开 60 秒供你操作...")
        print("  >> 你可以在浏览器中搜索用户并查看详情")
        print()

        # 保持浏览器打开，供用户操作
        time.sleep(60)

        print("  关闭浏览器...")
        context.close()
        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("使用说明：")
print("  1. 如果已登录，脚本会自动跳过登录步骤")
print("  2. 如果出现错误页面，请在浏览器中手动登录")
print("  3. 登录成功后，可以搜索用户并执行 disable 操作")
print()
print("按回车退出...")
input()
