"""
ME Token 获取 - 按优先级依次尝试

优先级：
1. 环境变量 ME_TOKEN（平台注入，信任有效性）
2. 缓存文件 ~/.jd-sso/me_token
3. Playwright 浏览器认证（内置 browser_login.py）
"""

import logging
import os
import sys
from pathlib import Path

_log = logging.getLogger("joyspace_core.auth.me")
if not _log.handlers:
    _log.setLevel(logging.DEBUG)
    _log.propagate = False
    try:
        _log_dir = Path.home() / ".jd-sso"
        _log_dir.mkdir(parents=True, exist_ok=True)
        _fh = logging.FileHandler(str(_log_dir / "get_token.log"), encoding="utf-8")
        _fh.setFormatter(logging.Formatter("%(asctime)s [me-core] %(message)s", datefmt="%Y-%m-%d %H:%M:%S"))
        _log.addHandler(_fh)
    except OSError:
        pass


def _validate_token(token: str) -> bool:
    try:
        import requests
        resp = requests.post(
            "https://api.m.jd.com/api",
            headers={
                "x-device-type": "web",
                "x-team-id": "00046419",
                "Cookie": f"me_token={token}",
                "Content-Type": "application/x-www-form-urlencoded",
            },
            data={
                "appid": "JDME_DESKTOP",
                "body": '{"jdmeAppId":"ee"}',
                "client": "web",
                "functionId": "login.getUserProfile",
                "loginType": "15",
            },
            timeout=5,
        )
        data = resp.json()
        return data.get("errorCode") == "0"
    except Exception:
        return True


def _try_playwright_auth() -> str:
    """通过内置 browser_login.py 的 Playwright 认证获取 ME Token"""
    try:
        from playwright.sync_api import sync_playwright  # noqa: F401
    except ImportError:
        _log.debug("Playwright 未安装，跳过浏览器认证")
        return ""

    try:
        from auth.browser_login import get_tokens_via_browser
        _sso_token, me_token, error = get_tokens_via_browser()
        if me_token:
            _log.info("Playwright 浏览器认证获取成功")
            return me_token
        _log.debug("浏览器认证未获取到 me_token: %s", error)
    except Exception as e:
        _log.debug("浏览器认证失败: %s", e)
    return ""


def get_me_token() -> str:
    """获取 ME Token，按优先级依次尝试。获取失败返回空字符串。"""

    # 1. 环境变量
    for key in ("ME_TOKEN", "me_token"):
        token = os.environ.get(key, "").strip()
        if token:
            _log.info("从环境变量 ME_TOKEN 获取成功")
            return token

    # 2. 缓存文件
    cache_file = Path.home() / ".jd-sso" / "me_token"
    try:
        if cache_file.exists():
            token = cache_file.read_text(encoding="utf-8").strip()
            if token and _validate_token(token):
                _log.info("从缓存文件获取成功")
                return token
            elif token:
                _log.info("缓存 me_token 已过期")
    except OSError:
        pass

    # 3. Playwright 浏览器认证
    token = _try_playwright_auth()
    if token:
        return token

    return ""


if __name__ == "__main__":
    token = get_me_token()
    if token:
        print(token, end="")
    else:
        print("ERROR: ME Token 获取失败", file=sys.stderr)
        sys.exit(1)
