"""优先在线核验 GitCode 评分身份,临时网络故障才回退同凭证的短期缓存。"""

from __future__ import annotations

import asyncio
import hashlib
import weakref
from time import monotonic

import httpx

from app.config import settings
from lts_logger import lts_logger

_CURRENT_USER_URL = "https://api.gitcode.com/api/v5/user"
_SUCCESS_TTL_SECONDS = 300.0
# 只保留实际返回的 ID 和凭证摘要;认证失败即清除,不保存配置推定的身份。
_cached_identity: tuple[str, str, float] | None = None
_inflight_lookups: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary()


def _credentials() -> tuple[str, str]:
    token = settings.atomgit_user_token.strip() or settings.gitcode_token.strip()
    return token, hashlib.sha256(token.encode()).hexdigest() if token else ""


def gitcode_identity_key() -> str:
    """请求级凭证锚点,用于阻止恢复查询跨账号;不暴露原始 token。"""
    return _credentials()[1]


async def _query_identity(token: str, token_key: str) -> str:
    global _cached_identity

    for attempt in range(2):
        try:
            async with httpx.AsyncClient(timeout=3.0, follow_redirects=False) as client:
                response = await client.get(_CURRENT_USER_URL, headers={"PRIVATE-TOKEN": token})
                response.raise_for_status()
                data = response.json()
            user_id = data.get("id") if isinstance(data, dict) else None
            if isinstance(user_id, str) and user_id.strip() and len(user_id.strip()) <= 128:
                user_id = user_id.strip()
                _cached_identity = (token_key, user_id, monotonic() + _SUCCESS_TTL_SECONDS)
                return user_id
            lts_logger.log("realtime_eval_gitcode_identity_unavailable", reason="missing_user_id")
            return ""
        except httpx.HTTPStatusError as exc:
            status = exc.response.status_code
            if status in (401, 403):
                if _cached_identity is not None and _cached_identity[0] == token_key:
                    _cached_identity = None
                lts_logger.log("realtime_eval_gitcode_identity_unavailable", reason="authentication_failed")
                return ""
            lts_logger.log("realtime_eval_gitcode_identity_unavailable", reason=type(exc).__name__)
            if status != 429 and status < 500:
                return ""
        except httpx.HTTPError as exc:
            # 异常正文和 URL 可能包含凭证,只记录类型。
            lts_logger.log("realtime_eval_gitcode_identity_unavailable", reason=type(exc).__name__)
        except ValueError as exc:
            lts_logger.log("realtime_eval_gitcode_identity_unavailable", reason=type(exc).__name__)
            return ""
        if attempt == 0:
            await asyncio.sleep(0.1)

    # 仅在线重试仍失败后回退,缓存命中不会延长有效期。
    if _cached_identity is not None:
        key, user_id, expires_at = _cached_identity
        if key == token_key and monotonic() < expires_at:
            lts_logger.log("realtime_eval_gitcode_identity_cached", reason="transient_network_failure")
            return user_id
    return ""


async def resolve_gitcode_user_id(*, expected_credential_key: str | None = None) -> str:
    """每次新查询先联网;仅共享尚未结束的同凭证查询,取消调用方不取消其他查询。"""
    token, token_key = _credentials()
    if not token or (expected_credential_key is not None and token_key != expected_credential_key):
        return ""
    loop = asyncio.get_running_loop()
    inflight = _inflight_lookups.setdefault(loop, {})
    task = inflight.get(token_key)
    if task is None or task.done():
        task = loop.create_task(_query_identity(token, token_key))
        inflight[token_key] = task

        def discard(completed: asyncio.Task[str]) -> None:
            if inflight.get(token_key) is completed:
                inflight.pop(token_key, None)

        task.add_done_callback(discard)
    return await asyncio.shield(task)