#!/usr/bin/env python3
"""
京ME SSO 登录态提取脚本（优化版 v2）

从京ME桌面客户端提取 me_token → 换取 sso.jd.com → 查询 ERP 用户信息。
输出 4 字段 JSON 并缓存到 ~/.joyclaw/workspace/jd-sso-token.json。

核心优化：
  ✓ WSL 下自动发现 Cookie 路径（修复 WS L 环境找不到 Cookie 的问题）
  ✓ SSO 流程自动重试（最多 2 次）
  ✓ --debug 模式输出详细调试信息
  ✓ --dry-run 检查 Cookie 位置但不执行完整流程
  ✓ 代码精简约 40%，去冗余注释，统一风格

用法：
  python extract_jdme_cookies.py
  python extract_jdme_cookies.py --cookie-path /path/to/Cookies
  python extract_jdme_cookies.py --url https://to.jd.com/
  python extract_jdme_cookies.py --debug --no-cache
"""

import argparse
import base64
import json
import os
import platform
import re
import sqlite3
import ssl
import subprocess
import sys
import time as _time
import uuid
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timezone
from pathlib import Path
from typing import Dict, List, Optional, Tuple

# ── 常量 ──────────────────────────────────────────────
CHROMIUM_COOKIE_PREFIX = b"v10"
KEY_COOKIE_NAMES = {"me_token", "focus-token"}
MAX_SSO_RETRIES = 1
# 平台 OS 标识
_OS_MAP = {
    "Darwin":  ("Macintosh; Intel Mac OS X 10_15_7", "mac", "Mac.local"),
    "Windows": ("Windows NT 10.0; Win64; x64",        "windows", "Win.local"),
}
_LINUX_OS = ("X11; Linux x86_64", "linux", "Linux.local")

_KNOWN_APP_DIRS = ["ME", "ME Meeting", "com.jd.me", "JDME", "jdme", "京ME"]
_COOKIE_SUB_PATHS = ["Cookies", "Network/Cookies", "Default/Cookies", "Default/Network/Cookies"]

_CDB_CACHED = {}  # SQLite 连接缓存（减少重复打开）


# ══ 工具函数 ══════════════════════════════════════════

def _utc_now_str() -> str:
    return datetime.now(timezone.utc).astimezone().strftime("%Y-%m-%d %H:%M:%S")


def _safe_exists(p: Path) -> bool:
    try:
        return p.exists()
    except (PermissionError, OSError):
        return False


def _connect_cookie_db(db_path: Path) -> sqlite3.Connection:
    """只读 + immutable 模式打开 Cookie 库（无锁冲突）"""
    key = str(db_path.resolve())
    if key not in _CDB_CACHED:
        uri = db_path.resolve().as_uri() + "?mode=ro&immutable=1"
        _CDB_CACHED[key] = sqlite3.connect(uri, uri=True)
    return _CDB_CACHED[key]


# ══ 平台检测 ══════════════════════════════════════════

def _is_wsl() -> bool:
    if platform.system() != "Linux":
        return False
    return bool(
        Path("/mnt/c/Windows").exists()
        or Path("/mnt/c/Users").exists()
        or "microsoft" in platform.uname().release.lower()
    )


def _get_app_data_roots() -> List[Path]:
    """获取当前平台可能存放 Electron 应用数据的根目录"""
    home, roots = Path.home(), []
    sysname = platform.system()

    if sysname == "Darwin":
        roots.append(home / "Library" / "Application Support")
    elif sysname == "Windows":
        for var in ("APPDATA", "LOCALAPPDATA"):
            if v := os.environ.get(var):
                roots.append(Path(v))
        roots.extend([home / "AppData" / "Roaming", home / "AppData" / "Local"])
    elif _is_wsl():
        # WSL：扫描 /mnt/{A-Z}/Users/*/AppData
        for mnt in sorted(Path("/mnt").glob("*")):
            users = mnt / "Users"
            if not users.is_dir():
                continue
            try:
                for user_dir in users.iterdir():
                    if not user_dir.is_dir():
                        continue
                    for sub in ("Roaming", "Local"):
                        if (p := user_dir / "AppData" / sub).is_dir():
                            roots.append(p)
            except (PermissionError, OSError):
                continue
        roots.append(home / ".config")
    else:
        roots.append(home / ".config")
        if xdg := os.environ.get("XDG_CONFIG_HOME"):
            roots.append(Path(xdg))

    seen = set()
    return [r for r in roots if r and str(r) not in seen and seen.add(str(r)) is None and _safe_exists(r)]


# ══ Cookie 数据库发现 ════════════════════════════════

def _db_has_jd_cookies(db_path: Path, require_key: bool = True) -> bool:
    """检测 Cookie 库是否含京东相关 Cookie"""
    try:
        cur = _connect_cookie_db(db_path).cursor()
        if require_key:
            ph = ",".join("?" * len(KEY_COOKIE_NAMES))
            cur.execute(f"SELECT COUNT(*) FROM cookies WHERE name IN ({ph}) AND host_key LIKE '%jd.com%'",
                        list(KEY_COOKIE_NAMES))
        else:
            cur.execute("SELECT COUNT(*) FROM cookies WHERE host_key LIKE '%jd.com%'")
        return cur.fetchone()[0] > 0
    except Exception:
        return False


def _wsl_quick_paths() -> List[Path]:
    """WSL 下快速扫描可能的 Cookie 路径（不依赖环境变量）。用 _safe_exists 防 PermissionError。"""
    paths = []
    c_users = Path("/mnt/c/Users")
    if not _safe_exists(c_users):
        return paths
    try:
        for user_dir in c_users.iterdir():
            if not user_dir.is_dir():
                continue
            for base in (user_dir / "AppData" / "Roaming", user_dir / "AppData" / "Local"):
                if not _safe_exists(base):
                    continue
                for app in _KNOWN_APP_DIRS:
                    for sub in _COOKIE_SUB_PATHS:
                        p = base / app / sub
                        if _safe_exists(p):
                            paths.append(p)
    except (PermissionError, OSError):
        pass
    return paths


def find_jdme_cookie_db() -> Optional[Path]:
    """自动发现京ME Cookie 数据库路径"""
    # 阶段 0：WSL 快速路径
    if _is_wsl():
        for p in _wsl_quick_paths():
            if _safe_exists(p) and p.is_file() and _db_has_jd_cookies(p):
                return p

    # 阶段 1：Windows 标准路径
    if appdata := os.environ.get("APPDATA"):
        for p in (Path(appdata) / "ME" / "Network" / "Cookies",
                  Path(appdata) / "ME" / "Cookies"):
            if _safe_exists(p) and _db_has_jd_cookies(p):
                return p

    # 阶段 2：全盘扫描
    roots = _get_app_data_roots()
    # 优先已知应用名
    for root in roots:
        for app in _KNOWN_APP_DIRS:
            for sub in _COOKIE_SUB_PATHS:
                p = root / app / sub
                if _safe_exists(p) and _db_has_jd_cookies(p):
                    return p
    # 扫所有应用
    for root in roots:
        if not root.is_dir():
            continue
        try:
            for app_dir in root.iterdir():
                if not app_dir.is_dir():
                    continue
                for sub in _COOKIE_SUB_PATHS:
                    p = app_dir / sub
                    if _safe_exists(p) and _db_has_jd_cookies(p, require_key=False):
                        return p
        except (PermissionError, OSError):
            continue

    return None


# ══ Cookie 加密/解密 ══════════════════════════════════

def get_encryption_key() -> Optional[bytes]:
    """获取 Chromium Cookie 加密密钥（各平台）"""
    sysname = platform.system()
    try:
        if sysname == "Darwin":
            return _get_keychain_key()
        if sysname == "Windows":
            return _get_dpapi_key()
        return _get_linux_key()
    except Exception:
        return None


def _get_keychain_key() -> Optional[bytes]:
    import hashlib
    for svc in ["ME Safe Storage", "JDME Safe Storage", "Chromium Safe Storage"]:
        try:
            r = subprocess.run(["security", "find-generic-password", "-s", svc, "-w"],
                               capture_output=True, text=True, timeout=5)
            if r.returncode == 0 and r.stdout.strip():
                return hashlib.pbkdf2_hmac("sha1", r.stdout.strip().encode(), b"saltysalt", 1003, 16)
        except (subprocess.TimeoutExpired, subprocess.SubprocessError):
            continue
    return None


def _get_dpapi_key() -> Optional[bytes]:
    import ctypes, ctypes.wintypes
    try:
        for ls in _find_local_state_files():
            with open(ls, "r", encoding="utf-8") as f:
                ek = json.load(f).get("os_crypt", {}).get("encrypted_key", "")
            if not ek:
                continue
            raw = base64.b64decode(ek)
            if raw[:5] == b"DPAPI":
                raw = raw[5:]
            return _dpapi_decrypt(raw)
    except Exception:
        return None


def _dpapi_decrypt(data: bytes) -> Optional[bytes]:
    import ctypes, ctypes.wintypes
    class D(ctypes.Structure):
        _fields_ = [("cb", ctypes.wintypes.DWORD), ("pb", ctypes.POINTER(ctypes.c_char))]
    try:
        inp = D(len(data), ctypes.cast(ctypes.c_char_p(data), ctypes.POINTER(ctypes.c_char)))
        out = D()
        ok = ctypes.windll.crypt32.CryptUnprotectData(ctypes.byref(inp), None, None, None, None, 0, ctypes.byref(out))
        if ok:
            val = ctypes.create_string_buffer(out.cb).raw[:out.cb]
            ctypes.windll.kernel32.LocalFree(out.pb)
            return val
    except Exception:
        pass
    return None


def _get_linux_key() -> Optional[bytes]:
    import hashlib
    return hashlib.pbkdf2_hmac("sha1", b"peanuts", b"saltysalt", 1, 16)


def _find_local_state_files() -> List[Path]:
    files = []
    for root in _get_app_data_roots():
        try:
            for d in root.iterdir():
                if d.is_dir() and (f := d / "Local State").exists():
                    files.append(f)
        except (PermissionError, OSError):
            continue
    return files


def _needs_key(db_path: Path) -> bool:
    try:
        cur = _connect_cookie_db(db_path).cursor()
        cur.execute(
            "SELECT COUNT(*) FROM cookies WHERE host_key LIKE '%jd.com%' "
            "AND encrypted_value IS NOT NULL AND length(encrypted_value) > 0 "
            "AND (value IS NULL OR value = '')"
        )
        return cur.fetchone()[0] > 0
    except Exception:
        return False


def decrypt_value(enc_val: bytes, key: Optional[bytes]) -> Optional[str]:
    if not enc_val:
        return None
    if not enc_val.startswith(CHROMIUM_COOKIE_PREFIX):
        try:
            return enc_val.decode("utf-8")
        except UnicodeDecodeError:
            return None
    if not key:
        return None
    try:
        from cryptography.hazmat.primitives.ciphers.aead import AESGCM
        enc_val = enc_val[len(CHROMIUM_COOKIE_PREFIX):]
        return AESGCM(key).decrypt(enc_val[:12], enc_val[12:], None).decode("utf-8")
    except ImportError:
        print("提示: 缺 cryptography，pip install cryptography", file=sys.stderr)
    except Exception:
        pass
    return None


def extract_cookies(db_path: Path, key: Optional[bytes]) -> Dict:
    cookies = {}
    try:
        cur = _connect_cookie_db(db_path).cursor()
        cur.execute("SELECT name, value, encrypted_value, host_key, path FROM cookies "
                    "WHERE host_key LIKE '%jd.com%' OR host_key LIKE '%jdcloud%'")
        for name, plain, enc, host, path in cur.fetchall():
            if v := (plain or decrypt_value(enc, key) or ""):
                cookies[name] = {"value": v, "domain": host, "path": path}
    except sqlite3.OperationalError as e:
        print(f"Error: SQLite 查询失败: {e}", file=sys.stderr)
    return cookies


def extract_device_info(db_path: Path) -> Dict:
    info = {"deviceAccountName": os.environ.get("USER", os.environ.get("USERNAME", ""))}
    d = Path(db_path).parent
    for _ in range(4):
        if (d / "global.json").exists():
            try:
                info["uuid"] = json.load(open(d / "global.json")).get("DeviceId", "")
            except Exception:
                pass
        if (d / "login.json").exists():
            try:
                info["eid"] = json.load(open(d / "login.json")).get("KEY_RISK_JS_EID", "")
            except Exception:
                pass
        if d.parent == d:
            break
        d = d.parent
    return info


# ══ HTTP 请求 ═══════════════════════════════════════

def http_request(
    url: str,
    method: str = "GET",
    data: Optional[bytes] = None,
    headers: Optional[Dict] = None,
    cookies: Dict = None,
    timeout: int = 30,
    allow_redirects: bool = True,
) -> Tuple[int, Dict[str, str], str]:
    """
    支持手动跟随重定向链的 HTTP 请求。
    返回 (status_code, headers_dict, body_text)
    headers 字典额外包含 "_setcookie" 键（list），收集所有重定向中的 Set-Cookie。
    """
    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE

    class _NoRedir(urllib.request.HTTPRedirectHandler):
        def redirect_request(self, *a, **kw):
            return None

    opener = urllib.request.build_opener(_NoRedir, urllib.request.HTTPSHandler(context=ctx))

    if isinstance(data, str):
        data = data.encode("utf-8")

    def _mk_headers(h) -> Dict:
        out = dict(h or {})
        if cookies:
            if isinstance(cookies, dict):
                out["Cookie"] = "; ".join(f"{k}={v}" for k, v in cookies.items())
            else:
                out["Cookie"] = str(cookies)
        return out

    cur_url, cur_method, redir_cnt = url, method, 0
    all_setcookie = []

    while True:
        req = urllib.request.Request(
            cur_url,
            data=data if redir_cnt == 0 else b"",
            headers=_mk_headers(headers if redir_cnt == 0 else None),
            method=cur_method,
        )
        try:
            resp = opener.open(req, timeout=timeout)
            for sc in (resp.headers.get_all("Set-Cookie") or []):
                all_setcookie.append(sc)
            return resp.status, {"_setcookie": all_setcookie}, _decode_body(resp.read(), resp.headers)
        except urllib.error.HTTPError as e:
            body = _decode_body(e.read(), e.headers) if e.fp else ""
            for sc in (e.headers.get_all("Set-Cookie") or []):
                all_setcookie.append(sc)

            if allow_redirects and e.code in (301, 302, 303, 307, 308) and redir_cnt < 10:
                loc = e.headers.get("Location", "")
                if loc:
                    redir_cnt += 1
                    cur_url = urllib.parse.urljoin(cur_url, loc)
                    if e.code in (302, 303):
                        cur_method = "GET"
                    headers = None  # 清除自定义 headers，跟随浏览器行为
                    cookies = None  # 让 urllib 自动管理 CookieJar 不太可行，这里简单处理
                    continue
            return e.code, {"_setcookie": all_setcookie}, body


def _decode_body(raw: bytes, headers=None) -> str:
    if not raw:
        return ""
    charset = None
    if headers:
        ct = (headers.get("Content-Type", "") if hasattr(headers, "get") else "") or ""
        if "charset=" in ct.lower():
            charset = ct.lower().split("charset=")[1].split(";")[0].strip().strip("'\"")
    for enc in ([charset] if charset else []) + ["utf-8", "gb18030", "gbk", "utf-8"]:
        try:
            return raw.decode(enc)
        except (UnicodeDecodeError, LookupError):
            continue
    return raw.decode("utf-8", errors="replace")


# ══ SSO 登录流程 ════════════════════════════════════

def _get_os_info() -> Tuple[str, str, str, str]:
    """返回 (ua_os, client_val, brand, ua_extra)"""
    sysname = platform.system()
    if sysname in _OS_MAP:
        os_str, client, brand = _OS_MAP[sysname]
    else:
        os_str, client, brand = _LINUX_OS
    return os_str, client, brand, "jdme-desktop-election-tab-browser"


def perform_sso_login(cookies: Dict, device: Dict, debug: bool = False) -> Dict:
    """
    完整 SSO 流程：me_token → eopen.getCode → OIDC authorize → jdmeUnionLogin → sso.jd.com

    带自动重试（MAX_SSO_RETRIES 次）。
    """
    me_token = cookies.get("me_token", {}).get("value", "")
    if not me_token:
        print("Error: me_token 未找到，请登录京ME", file=sys.stderr)
        return {}

    ua_os, client_val, brand, ua_extra = _get_os_info()
    version = "7.20.64"
    ua = (f"Mozilla/5.0 ({ua_os}) AppleWebKit/537.36 (KHTML, like Gecko) "
          f"ME/{version} Chrome/108.0.5359.215 Electron/22.3.27 Safari/537.36 {ua_extra}")

    eid = device.get("eid", "")
    dev_uuid = device.get("uuid", str(uuid.uuid4()))
    user = device.get("deviceAccountName", "")
    focus_team_id = cookies.get("focus-team-id", {}).get("value", "")
    jdsec = cookies.get("jdsec_client_info", {}).get("value", "")

    main_cookie = "; ".join(f"{k}={v['value']}" for k, v in cookies.items() if v.get("value"))
    default_brand = brand

    for attempt in range(1 + MAX_SSO_RETRIES):
        try:
            # ── Step 1: eopen.getCode ──
            t = str(int(_time.time() * 1000))
            request_id = uuid.uuid4().hex[:20]
            body_json = json.dumps({"appKey": "sL5qtKu71X8H25ysaaHB", "requestId": request_id, "jdmeAppId": "ee"},
                                   ensure_ascii=False)
            form = (
                f"appName=JDME&appid=JDME_DESKTOP&body={urllib.parse.quote(body_json, safe='')}"
                f"&client={client_val}&clientVersion={version}"
                f"&d_brand={urllib.parse.quote(default_brand, safe='')}&d_model="
                f"&eid={urllib.parse.quote(eid, safe='')}&functionId=eopen.getCode"
                f"&lang=zh_CN&loginType=15&networkType=unknown&osVersion="
                f"&t={t}&uuid={dev_uuid}"
            )

            _, _, resp = http_request(
                "https://api.m.jd.com/api/?functionId=eopen.getCode",
                method="POST", data=form.encode(),
                headers={
                    "Content-Type": "application/x-www-form-urlencoded",
                    "User-Agent": ua,
                    "X-Sso-DeviceAccountName": user,
                    "X-Sso-DeviceDomain": "360BUYAD",
                    "functionId": "eopen.getCode", "loginType": "15",
                    "x-language": "zh_CN", "x-team-id": focus_team_id,
                    "x-tenant-code": "CN.JD.GROUP",
                },
                cookies=main_cookie,
                timeout=30,
            )

            r = json.loads(resp)
            if r.get("code") != 0:
                print(f"[SSO] eopen.getCode 失败: {r.get('msg', '?')}", file=sys.stderr)
                raise RuntimeError(r.get("msg", "unknown"))

            auth_code = r["data"]["code"]
            expire = r["data"].get("expireIn", 300)

            if debug:
                print(f"[SSO] Step 1: getCode OK (auth_code={auth_code[:8]}..., {expire}s)", file=sys.stderr)

            # ── Step 2: OIDC authorize ──
            state = uuid.uuid4().hex[:43] + "="
            nonce = uuid.uuid4().hex[:43] + "="
            redirect_uri = "http%3A%2F%2Fkaoqin.jd.com%2F"
            client_id = "kaoqin.jd.com"

            oidc_url = (
                f"https://ssa.jd.com/oidc/authorize?"
                f"oauth2ParamPrefixPolicy=Default&scope=openid&response_type=code"
                f"&redirect_uri={redirect_uri}&state={state}&nonce={nonce}"
                f"&client_id={client_id}&hideUriCodeAndState=display"
            )

            _, h2, _ = http_request(
                oidc_url,
                headers={"Cookie": f"jdsec_client_info={jdsec}" if jdsec else "", "User-Agent": ua},
                timeout=30, allow_redirects=False,
            )
            ssa_cookies = _cookies_from_setcookie(h2.get("_setcookie", []))
            redirect_b64 = ""
            for sc in h2.get("_setcookie", []):
                if "redirect_uri=" in sc:
                    redirect_b64 = sc.split("redirect_uri=")[1].split("&")[0]

            if debug:
                print(f"[SSO] Step 2: OIDC authorize OK (ssa cookies: {list(ssa_cookies.keys())})", file=sys.stderr)

            # ── Step 3: SSA login page ──
            login_url = f"https://ssa.jd.com/sso/login?redirect_uri={redirect_b64}" if redirect_b64 else "https://ssa.jd.com/sso/login"
            _, h3, _ = http_request(
                login_url,
                headers={
                    "Cookie": f"jdsec_client_info={jdsec}; {'; '.join(f'{k}={v}' for k,v in ssa_cookies.items())}" if jdsec else f"{'; '.join(f'{k}={v}' for k,v in ssa_cookies.items())}",
                    "User-Agent": ua,
                },
                timeout=30, allow_redirects=False,
            )
            for k, v in _cookies_from_setcookie(h3.get("_setcookie", [])).items():
                ssa_cookies[k] = v

            if debug:
                print(f"[SSO] Step 3: SSO login page OK", file=sys.stderr)

            # ── Step 4: jdmeUnionLogin ──
            union_url = f"https://ssa.jd.com/sso/jdmeUnionLogin?redirect_uri={redirect_b64}"
            form2 = f"jme_auth_code={auth_code}&name=sL5qtKu71X8H25ysaaHB&source=ssa".encode()

            _, h4, body4 = http_request(
                union_url, method="POST", data=form2,
                headers={
                    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                    "User-Agent": ua, "Origin": "https://ssa.jd.com",
                    "Referer": "https://ssa.jd.com/sso/login",
                },
                cookies={**({"jdsec_client_info": jdsec} if jdsec else {}), **ssa_cookies},
                timeout=30,
            )
            sso_tickets = _cookies_from_setcookie(h4.get("_setcookie", []))

            login_msg = ""
            try:
                r4 = json.loads(body4.strip())
                login_msg = r4.get("REQ_MSG", "")
            except (json.JSONDecodeError, TypeError):
                pass

            if debug:
                print(f"[SSO] Step 4: jdmeUnionLogin OK (tickets: {list(sso_tickets.keys())}, msg: {login_msg})",
                      file=sys.stderr)

            if "sso.jd.com" in sso_tickets:
                return sso_tickets

            print(f"[SSO] 第 {attempt+1} 次尝试未获取 sso.jd.com，重试中...", file=sys.stderr)
            _time.sleep(2)

        except Exception as e:
            print(f"[SSO] 第 {attempt+1} 次尝试异常: {e}", file=sys.stderr)
            if attempt < MAX_SSO_RETRIES:
                _time.sleep(2)

    return {}


def _cookies_from_setcookie(setcookie_list: List[str]) -> Dict[str, str]:
    """从 Set-Cookie 列表解析 key=value"""
    out = {}
    for item in setcookie_list:
        if "=" in item:
            name = item.split(";")[0].strip()
            k, _, v = name.partition("=")
            if k:
                out[k] = v
    return out


# ══ ERP 用户信息查询 ════════════════════════════════

def query_erp(sso_jd_val: str) -> Optional[Dict]:
    _, _, body = http_request(
        "http://erp.jd.com/v2/menu/getUserInfo?random=1",
        headers={
            "Accept": "application/json, text/plain, */*",
            "Content-Type": "application/json",
            "Referer": "http://erp.jd.com/",
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Chrome/149.0.0.0 Safari/537.36",
            "X-Requested-With": "XMLHttpRequest",
        },
        cookies={"sso.jd.com": sso_jd_val},
        timeout=30,
    )
    try:
        r = json.loads(body)
        if r.get("success") and r.get("obj", {}).get("userCode"):
            return r["obj"]
    except (json.JSONDecodeError, TypeError):
        pass
    return None


# ══ 缓存管理 ════════════════════════════════════════

def _cache_file() -> Path:
    return Path.home() / ".joyclaw" / "workspace" / "jd-sso-token.json"


def read_cache() -> Optional[Dict]:
    p = _cache_file()
    if p.exists():
        try:
            return json.loads(p.read_text(encoding="utf-8"))
        except (json.JSONDecodeError, OSError):
            pass
    return None


def write_cache(data: Dict):
    p = _cache_file()
    try:
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")
    except OSError as e:
        print(f"[WARN] 缓存写入失败: {e}", file=sys.stderr)


# ══ URL 模式：兑换任意内部系统专属登录态（ssa.<app>）═══════════

def get_default_version() -> str:
    """返回默认的 JDME 客户端版本号。"""
    return "7.20.64"


def _system_cache_file(host: str) -> Path:
    """各系统登录态缓存文件（按 host 隔离，与 jd-sso-token.json 互不覆盖）。"""
    safe = host.replace(":", "_").replace("/", "_")
    return Path.home() / ".joyclaw" / "workspace" / ("jd-system-" + safe + ".json")


def _build_desktop_ua() -> str:
    """构造京ME桌面端 UA（按真实平台）。"""
    system = platform.system()
    if system == "Darwin":
        ua_os = "Macintosh; Intel Mac OS X 10_15_7"
    elif system == "Windows":
        ua_os = "Windows NT 10.0; Win64; x64"
    else:
        ua_os = "X11; Linux x86_64"
    return ("Mozilla/5.0 ({os}) AppleWebKit/537.36 (KHTML, like Gecko) "
            "ME/{ver} Chrome/108.0.5359.215 Electron/22.3.27 Safari/537.36 "
            "jdme-desktop-election-tab-browser").format(os=ua_os, ver=get_default_version())


def _eopen_get_code(cookies: Dict, device: Dict, ua: str) -> Optional[str]:
    """用 me_token 调 eopen.getCode 换取一次性授权码（jdmeUnionLogin 需要）。"""
    me_token = cookies.get("me_token", {}).get("value", "")
    if not me_token:
        print("Error: me_token not found, cannot perform SSO login.", file=sys.stderr)
        return None

    eid = device.get("eid", "")
    dev_uuid = device.get("uuid", str(uuid.uuid4()))
    focus_team_id = cookies.get("focus-team-id", {}).get("value", "")
    user = device.get("deviceAccountName", "")
    version = get_default_version()

    system = platform.system()
    client_val = "mac" if system == "Darwin" else ("windows" if system == "Windows" else "linux")
    default_brand = "Mac.local" if system == "Darwin" else ("Win.local" if system == "Windows" else "Linux.local")

    main_cookie_header = "; ".join(
        f"{k}={v['value']}" for k, v in cookies.items() if v.get("value", "")
    )

    t = str(int(_time.time() * 1000))
    request_id = uuid.uuid4().hex[:20]
    body_json = '{"appKey":"sL5qtKu71X8H25ysaaHB","requestId":"' + request_id + '","jdmeAppId":"ee"}'
    form_data = (
        f"appName=JDME&appid=JDME_DESKTOP&body={urllib.parse.quote(body_json, safe='')}"
        f"&client={client_val}&clientVersion={version}&d_brand={device.get('d_brand', default_brand)}"
        f"&d_model={device.get('d_model', '')}&eid={urllib.parse.quote(eid, safe='')}"
        f"&functionId=eopen.getCode&lang=zh_CN&loginType=15&networkType=unknown"
        f"&osVersion={device.get('osVersion', '')}&t={t}&uuid={dev_uuid}"
    )

    _, _, body = http_request(
        "https://api.m.jd.com/api/?functionId=eopen.getCode",
        method="POST",
        data=form_data,
        headers={
            "Content-Type": "application/x-www-form-urlencoded",
            "User-Agent": ua,
            "X-Sso-DeviceAccountName": user,
            "X-Sso-DeviceDomain": "360BUYAD",
            "functionId": "eopen.getCode",
            "loginType": "15",
            "x-device-type": client_val,
            "x-language": "zh_CN",
            "x-team-id": focus_team_id,
            "x-tenant-code": "CN.JD.GROUP",
        },
        cookies=main_cookie_header,
        timeout=30,
    )
    try:
        resp = json.loads(body)
        if resp.get("code") != 0:
            print(f"Error: eopen.getCode failed: {resp.get('msg', 'unknown')}", file=sys.stderr)
            return None
        return resp["data"]["code"]
    except Exception as e:
        print(f"Error: eopen.getCode parse failed: {e}", file=sys.stderr)
        return None


def cookie_header_for(jar, url: str) -> str:
    """用 CookieJar 按 domain/path 规则算出"浏览器会发给该 url"的精确 Cookie 头。"""
    req = urllib.request.Request(url)
    jar.add_cookie_header(req)
    return req.get_header("Cookie", "")


def _looks_like_login_page(html: str, final_url: str) -> bool:
    """判定响应是否被打回了 SSA 登录页（兑换失败的标志）。"""
    if "ssa.jd.com/sso/login" in (final_url or ""):
        return True
    return ("账密登录" in html) or ("login_form" in html and "<title>ERP登录</title>" in html)


def login_to_system(target_url: str, cookies: Dict, device: Dict) -> Dict:
    """对任意京东内部系统 URL 兑换其专属登录态（如 to.jd.com -> ssa.ispman）。

    返回 {url, host, clientId, cookieHeader, cookies, finalUrl, title, createTime}，
    失败返回 {"error": "..."}。
    """
    import http.cookiejar
    from urllib.parse import urlparse, parse_qs, quote

    ua = _build_desktop_ua()
    parsed = urlparse(target_url)
    host = parsed.hostname or target_url

    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE
    jar = http.cookiejar.CookieJar()
    opener = urllib.request.build_opener(
        urllib.request.HTTPSHandler(context=ctx),
        urllib.request.HTTPCookieProcessor(jar),
    )

    def _open(url, method="GET", data=None, headers=None):
        h = {"User-Agent": ua}
        if headers:
            h.update(headers)
        if isinstance(data, str):
            data = data.encode("utf-8")
        req = urllib.request.Request(url, data=data, headers=h, method=method)
        try:
            resp = opener.open(req, timeout=30)
            return resp.status, resp.geturl(), _decode_body(resp.read(), resp.headers)
        except urllib.error.HTTPError as e:
            body = _decode_body(e.read(), e.headers) if e.fp else ""
            return e.code, e.url, body

    # Step 1: me_token -> 一次性授权码
    auth_code = _eopen_get_code(cookies, device, ua)
    if not auth_code:
        return {"error": "eopen.getCode 失败，me_token 可能已过期，请重新登录京ME。"}
    print(f"[sys-login] Step 1/3: eopen.getCode OK (code={auth_code[:8]}...)", file=sys.stderr)

    # Step 2: GET 目标 URL，跟随 302 链到 ssa.jd.com/sso/login（jar 累积会话态）
    status, final_url, _ = _open(target_url)
    qs = parse_qs(urlparse(final_url).query)
    redirect_uri_b64 = qs.get("redirect_uri", [""])[0]

    # 从重定向链中发现 client_id（app cookie 名 = ssa.<client_id>）
    client_id = ""
    if redirect_uri_b64:
        try:
            decoded = base64.b64decode(redirect_uri_b64 + "===").decode("utf-8", "ignore")
            cid = parse_qs(decoded).get("client_id", [""])[0]
            if cid:
                client_id = cid
        except Exception:
            pass

    if "ssa.jd.com/sso/login" not in final_url:
        return {
            "error": f"目标站未跳转到 SSA 登录页（final={final_url}）。"
                     f"该系统可能不走 ssa.<app> 体系，或已是登录态。",
            "finalUrl": final_url,
        }
    print(f"[sys-login] Step 2/3: 跳转 SSA 登录页 OK (client_id={client_id or '?'}, "
          f"jar={[c.name for c in jar]})", file=sys.stderr)

    # Step 3: POST jdmeUnionLogin（同 jar 会话）→ 自动回调目标站，种下 ssa.<app>
    union = "https://ssa.jd.com/sso/jdmeUnionLogin?redirect_uri=" + quote(redirect_uri_b64, safe="")
    form2 = f"jme_auth_code={auth_code}&name=sL5qtKu71X8H25ysaaHB&source=ssa"
    _open(union, "POST", form2, {
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        "Origin": "https://ssa.jd.com",
        "Referer": "https://ssa.jd.com/sso/login",
    })

    # 再 GET 目标 URL：完成 code 回调，确认登录态
    status, final_url, html = _open(target_url)
    m_title = re.search(r"<title>(.*?)</title>", html, re.S)
    title = m_title.group(1).strip() if m_title else ""

    if _looks_like_login_page(html, final_url):
        return {
            "error": "兑换后仍被打回登录页（me_token 可能过期或该系统需额外授权）。",
            "finalUrl": final_url, "title": title,
        }

    # 用 jar 计算发给目标站的精确 Cookie 头
    cookie_header = cookie_header_for(jar, target_url)
    cookie_map = {}
    for part in cookie_header.split("; "):
        if "=" in part:
            k, _, v = part.partition("=")
            cookie_map[k] = v

    if client_id and ("ssa." + client_id) not in cookie_map:
        print(f"[sys-login] 警告：未在目标站 cookie 中发现 ssa.{client_id}，"
              f"实际 cookie：{list(cookie_map)}", file=sys.stderr)

    print(f"[sys-login] Step 3/3: 登录成功 (title={title}, cookies={list(cookie_map)})", file=sys.stderr)

    return {
        "url": target_url,
        "host": host,
        "clientId": client_id,
        "cookieHeader": cookie_header,
        "cookies": cookie_map,
        "finalUrl": final_url,
        "title": title,
        "createTime": _utc_now_str(),
    }


def _emit_system_result(result: Dict, cache_file: Path, header_only: bool) -> None:
    """输出 --url 模式结果。header_only=True 时仅打印 Cookie 头（便于直接 curl）。"""
    if header_only:
        print(result.get("cookieHeader", ""))
        return
    print(f"登录态缓存位置：{cache_file}")
    print(json.dumps(result, indent=2, ensure_ascii=False))


# ══ 主入口 ══════════════════════════════════════════

def main():
    for s in (sys.stdout, sys.stderr):
        try:
            s.reconfigure(encoding="utf-8")
        except (AttributeError, ValueError):
            pass

    ap = argparse.ArgumentParser(description="京ME SSO 登录态提取")
    ap.add_argument("--cookie-path", help="Cookie 数据库路径（默认自动探测）")
    ap.add_argument("--url", help="兑换目标系统专属 SSA 登录态")
    ap.add_argument("--cookie-header", action="store_true", help="仅输出 Cookie 头")
    ap.add_argument("--no-cache", action="store_true", help="强制重新兑换")
    ap.add_argument("--debug", action="store_true", help="调试模式")
    ap.add_argument("--dry-run", action="store_true", help="只检查环境不执行 SSO")
    args = ap.parse_args()

    # 强制 UTF-8 环境
    os.environ.setdefault("PYTHONIOENCODING", "utf-8")

    # ── 1. 探测 Cookie 数据库 ──
    if args.dry_run:
        p = find_jdme_cookie_db()
        if p:
            print(f"✓ Cookie 数据库: {p}", file=sys.stderr)
        else:
            print("✗ Cookie 数据库未找到", file=sys.stderr)
            print("  → WSL: 检查 /mnt/c/Users/<用户名>/AppData/Roaming/ME/Network/Cookies", file=sys.stderr)
        return

    db = args.cookie_path and Path(args.cookie_path) or find_jdme_cookie_db()
    if db is None or not db.exists():
        print("Error: 未找到京ME Cookie 数据库。", file=sys.stderr)
        print("请确保京ME桌面客户端已安装并运行。", file=sys.stderr)
        print("WSL 下（本机环境）:", file=sys.stderr)
        print("  /mnt/c/Users/你的用户名/AppData/Roaming/ME/Network/Cookies", file=sys.stderr)
        sys.exit(1)

    if args.debug:
        print(f"[DEBG] Cookie 数据库: {db.resolve()}", file=sys.stderr)

    # ── 2. 获取加密密钥 ──
    key = get_encryption_key() if _needs_key(db) else None

    # ── 3. 提取 Cookie ──
    cookies = extract_cookies(db, key)
    if "me_token" not in cookies:
        print("Error: me_token 未找到。请登录京ME。", file=sys.stderr)
        sys.exit(1)

    if args.debug:
        print(f"[DEBG] 提取到 Cookie: {list(cookies.keys())}", file=sys.stderr)

    # ── 4. 设备信息 ──
    device = extract_device_info(db)

    # ── 4.5 URL 模式：兑换目标系统专属 ssa.<app> 登录态 ──
    if args.url:
        from urllib.parse import urlparse
        host = urlparse(args.url).hostname or args.url
        cache_file = _system_cache_file(host)

        # 缓存命中校验：实访目标确认未被打回登录页
        if not args.no_cache and cache_file.exists():
            try:
                cached = json.loads(cache_file.read_text(encoding="utf-8"))
                hdr = cached.get("cookieHeader", "")
                if hdr:
                    ctx2 = ssl.create_default_context()
                    ctx2.check_hostname = False
                    ctx2.verify_mode = ssl.CERT_NONE
                    op2 = urllib.request.build_opener(urllib.request.HTTPSHandler(context=ctx2))
                    rq = urllib.request.Request(args.url, headers={"Cookie": hdr, "User-Agent": _build_desktop_ua()})
                    try:
                        rsp = op2.open(rq, timeout=15)
                        body2 = _decode_body(rsp.read(), rsp.headers)
                        if not _looks_like_login_page(body2, rsp.geturl()):
                            print("[sys-login] 缓存登录态有效，跳过重新兑换", file=sys.stderr)
                            _emit_system_result(cached, cache_file, args.cookie_header)
                            return
                        print("[sys-login] 缓存登录态已失效，重新兑换中...", file=sys.stderr)
                    except Exception:
                        print("[sys-login] 缓存校验请求失败，重新兑换中...", file=sys.stderr)
            except Exception:
                print("[sys-login] 缓存文件损坏，重新兑换...", file=sys.stderr)

        result = login_to_system(args.url, cookies, device)
        if result.get("error"):
            print(f"Error: {result['error']}", file=sys.stderr)
            sys.exit(1)

        try:
            cache_file.parent.mkdir(parents=True, exist_ok=True)
            cache_file.write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8")
        except OSError:
            print(f"Warning: Failed to save to {cache_file}", file=sys.stderr)

        _emit_system_result(result, cache_file, args.cookie_header)
        return

    # ── 5. 读缓存（非 --url 模式）──
    if not args.url and not args.no_cache:
        cached = read_cache()
        if cached and cached.get("sso.jd.com"):
            user = query_erp(cached["sso.jd.com"])
            if user and user.get("userCode"):
                if args.debug:
                    print("[DEBG] 缓存 token 有效，跳过 SSO", file=sys.stderr)
                _emit(cached)
                return
            if args.debug:
                print("[DEBG] 缓存 token 已过期", file=sys.stderr)

    # ── 6. SSO 流程 ──
    sso_tickets = perform_sso_login(cookies, device, debug=args.debug)
    sso_val = sso_tickets.get("sso.jd.com", "")
    if not sso_val:
        print("Error: SSO 获取 sso.jd.com 失败", file=sys.stderr)
        sys.exit(1)

    # ── 7. 查询 ERP ──
    info = query_erp(sso_val)
    if not info or not info.get("userCode"):
        print("Error: ERP 查询失败（token 可能无效）", file=sys.stderr)
        sys.exit(1)

    # ── 8. 输出 ──
    result = {
        "sso.jd.com": sso_val,
        "userCode": info["userCode"],
        "userName": info.get("userName", ""),
        "createTime": _utc_now_str(),
    }
    write_cache(result)
    _emit(result)


def _emit(result: Dict):
    print(f"登录态缓存位置：{_cache_file()}")
    print(json.dumps(result, indent=2, ensure_ascii=False))


# ══ 供下游 skill/模块调用的便捷接口 ═══════════════════

def get_sso_jd_token(force: bool = False, debug: bool = False) -> str:
    """获取 sso.jd.com 登录态（供 joyspace-pro 等下游认证链调用）。

    策略：
      1. 读缓存 ~/.joyclaw/workspace/jd-sso-token.json，用 query_erp 校验有效性（有效即返回）
      2. 缓存缺失/失效 → 自动探测京ME Cookie 并走完整 SSO 流程重兑

    返回 sso.jd.com token 字符串；失败返回空字符串（错误已打印到 stderr）。
    """
    if not force:
        cached = read_cache()
        if cached and cached.get("sso.jd.com"):
            user = query_erp(cached["sso.jd.com"])
            if user and user.get("userCode"):
                if debug:
                    print(f"[jdme_sso] 缓存 token 有效（{user.get('userCode')}）", file=sys.stderr)
                return cached["sso.jd.com"]
            if debug:
                print("[jdme_sso] 缓存 token 已失效，重新兑换", file=sys.stderr)

    db = find_jdme_cookie_db()
    if db is None or not db.exists():
        print("Error: 未找到京ME Cookie 数据库，请确保京ME桌面客户端已安装并运行。", file=sys.stderr)
        return ""
    key = get_encryption_key() if _needs_key(db) else None
    cookies = extract_cookies(db, key)
    if "me_token" not in cookies:
        print("Error: me_token 未找到，请先在京ME中登录。", file=sys.stderr)
        return ""
    device = extract_device_info(db)
    sso_tickets = perform_sso_login(cookies, device, debug=debug)
    sso_val = sso_tickets.get("sso.jd.com", "")
    if not sso_val:
        print("Error: SSO 获取 sso.jd.com 失败", file=sys.stderr)
        return ""
    info = query_erp(sso_val)
    if not info or not info.get("userCode"):
        print("Error: ERP 查询失败（token 可能无效）", file=sys.stderr)
        return ""
    result = {
        "sso.jd.com": sso_val,
        "userCode": info["userCode"],
        "userName": info.get("userName", ""),
        "createTime": _utc_now_str(),
    }
    write_cache(result)
    if debug:
        print(f"[jdme_sso] 重新兑换成功（{info.get('userCode')}）", file=sys.stderr)
    return sso_val


if __name__ == "__main__":
    main()