#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
使用系统 Chrome + 完全清空缓存的版本
"""

import os
import sys

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

print("="*60)
print("  使用系统 Chrome + 完全清空缓存")
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_system_chrome.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()

# 获取密码
print(">>> 获取密码...")
import os

password = os.environ.get('CRM_PASSWORD')
if not password and len(sys.argv) > 3:
    password = sys.argv[3]
if not password:
    print("请输入 CRM 密码:")
    import getpass
    password = getpass.getpass("")

if not password:
    print("[ERROR] 密码为空")
    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] 启动浏览器（系统 Chrome）...")

            # 使用标准启动方式 - 尝试 Edge（如果 Chrome 有问题）
            # 如果 Edge 也不行，可以改成 "chrome"
            channel = "msedge"  # 或者 "chrome"

            browser = p.chromium.launch(
                headless=False,
                channel=channel,
                slow_mo=100,
                args=[
                    '--disable-blink-features=AutomationControlled',
                    '--no-first-run',
                    '--no-default-browser-check',
                    '--disable-gpu',
                    '--disable-dev-shm-usage',
                    '--disable-web-security',
                    '--disable-features=VizDisplayCompositor',  # 禁用某些特性
                    '--disable-background-networking',  # 禁用后台网络
                    '--disable-background-timer-throttling',
                    '--disable-backgrounding-occluded-windows',
                    '--disable-breakpad',
                    '--disable-component-extensions-with-background-pages',
                    '--disable-extensions',
                    '--disable-features=TranslateUI,BlinkGenPropertyTrees',
                    '--disable-ipc-flooding-protection',
                    '--disable-renderer-backgrounding',
                    '--enable-features=NetworkService,NetworkServiceInProcess',
                    '--force-color-profile=srgb',
                    '--metrics-recording-only',
                    '--no-first-run',
                    '--enable-automation=false',
                    '--password-store=basic',
                    '--use-mock-keychain',
                    '--no-sandbox',
                    # 禁用 Windows 集成认证（重要！）
                    '--disable-auth-negotiate',
                    '--disable-sspi',
                ]
            )

            print(f"  [OK] 浏览器已启动 ({channel})")

            # 创建新的 context（无痕模式）
            context = browser.new_context(
                ignore_https_errors=True,
                accept_downloads=False,
                # 明确设置存储状态为空
                storage_state=None,
            )

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

            # 关键：先访问空白页面，并清除所有存储
            print("  清除所有浏览器存储...")
            page.goto("about:blank")

            # 使用 JavaScript 清除所有可能的存储
            page.evaluate("""() => {
                // 清除 localStorage
                localStorage.clear();
                // 清除 sessionStorage
                sessionStorage.clear();
                // 尝试清除 IndexedDB（需要更复杂的操作）
                indexedDB.databases().then(dbs => {
                    dbs.forEach(db => indexedDB.deleteDatabase(db.name));
                });
            }""")

            # 清空所有 cookies
            context.clear_cookies()
            context.clear_permissions()

            print("  [OK] 所有存储已清除")

            print("  [3/5] 访问 CRM...")
            login_url = f"{crm_url.rstrip('/')}/MDP/"

            # 先清空所有 cookies
            print("  清空所有 cookies...")
            context = page.context
            context.clear_cookies()
            context.clear_permissions()

            page.goto(login_url)
            print(f"  [OK] 页面已加载")

            time.sleep(2)

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

            # 检查是否跳转到错误页面
            if 'errorhandler.aspx' in current_url:
                print(f"  [WARNING] 跳转到错误页面！")
                print(f"  这表明仍有缓存的会话数据")
                print(f"  URL: {current_url}")
                print()
                print("  尝试直接访问登录页面...")

                # 尝试访问登录页面
                page.goto(f"{crm_url.rstrip('/')}/MDP/default.aspx")
                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}")
                filled = False
                for selector in [
                    'input[name="username"]',
                    'input[type="text"]',
                    'input[id*="user" i]',
                    'input[placeholder*="user" i]'
                ]:
                    try:
                        if page.is_visible(selector, timeout=1000):
                            page.fill(selector, username, timeout=5000)
                            filled = True
                            print(f"    [OK] 已填写 (使用选择器: {selector})")
                            break
                    except:
                        continue

                if not filled:
                    print("    [ERROR] 无法找到用户名输入框")
                    print("    可用的输入框:")
                    inputs = page.query_selector_all("input")
                    for i, inp in enumerate(inputs):
                        inp_type = inp.get_attribute("type") or "text"
                        inp_name = inp.get_attribute("name") or "unnamed"
                        inp_id = inp.get_attribute("id") or "no-id"
                        print(f"      {i+1}. type={inp_type}, name={inp_name}, id={inp_id}")
                    raise Exception("用户名输入框未找到")

                time.sleep(0.5)

                # 填写密码
                print("    填写密码...")
                filled = False
                for selector in [
                    'input[name="password"]',
                    'input[type="password"]',
                    'input[id*="pass" i]'
                ]:
                    try:
                        if page.is_visible(selector, timeout=1000):
                            page.fill(selector, password, timeout=5000)
                            filled = True
                            print(f"    [OK] 已填写")
                            break
                    except:
                        continue

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

                time.sleep(0.5)

                # 点击登录
                print("    点击登录按钮...")
                clicked = False
                for selector in [
                    'button[type="submit"]',
                    'button:has-text("Log")',
                    'button:has-text("Sign")',
                    'input[type="submit"]'
                ]:
                    try:
                        if page.is_visible(selector, timeout=1000):
                            page.click(selector, timeout=5000)
                            clicked = True
                            print(f"    [OK] 已点击")
                            break
                    except:
                        continue

                if not clicked:
                    page.keyboard.press("Enter")
                    print(f"    [OK] 已按回车")

                # 等待登录
                print("    等待登录完成...")
                for i in range(30):
                    time.sleep(1)
                    if 'main.aspx' in page.url:
                        print(f"    [OK] 登录成功！")
                        break
                    elif 'errorhandler.aspx' in page.url:
                        print(f"    [ERROR] 登录失败，跳转到错误页面")
                        print(f"    URL: {page.url}")
                        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("  [WARNING] 无法提取 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("  关闭浏览器...")
            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("按回车退出...")
input()
