"""Wiki 内部 API 交互。

从原 ``rust/wiki/wiki_api.py`` 提取。cookie 路径参数化,所有函数不再依赖
全局 cookie 文件。
"""
from __future__ import annotations

import logging
import time
from typing import Any
from urllib.parse import urlencode

from .config import WIKI_BASE, load_cookies

logger = logging.getLogger(__name__)

# Sentinel returned by wiki_api_get when the response indicates the cookie
# has expired (403, login redirect, or HTML login page).  Callers can check
# ``result is COOKIE_EXPIRED`` to distinguish auth failure from other errors.
COOKIE_EXPIRED = "COOKIE_EXPIRED"

# Substrings in a response body that indicate a login/auth page rather than
# real wiki content.
_LOGIN_SIGNALS = ("w3.huawei.com/login", "login.huawei.com", "idp.huawei.com",
                  '"login"', "请先登录", "登录失效", "session timeout")

# API 路径
API_PATHS = {
    "get_document": "/devops-knowledge-management/api/getWiki",
    "list_kanbans": "/devops-knowledge-management/api/wiki/kanban",
    "query_tree": "/devops-knowledge-management/api/queryWikiClansTree",
    "query_kanban_children": "/devops-knowledge-management/api/queryKanBanWikiChildren",
    "get_attachment_detail": "/devops-knowledge-management/api/attachment/detail",
    "download_file": "/devops-knowledge-management/api/file/download",
    "query_structure": "/devops-knowledge-management/api/queryWikiStructure",
    "enter_kanban": "/devops-knowledge-management/api/kanban/enter_kanban",
    "domain_simple": "/vision-platform/api/domains/{domain_id}/simple",
    "domain_roles": "/vision-platform/api/domain/{domain_id}/roles",
    "children_wiki_by_sn": "/devops-knowledge-management/api/childrenWikiAndRevisionTitleBySn",
}


def get_session(cookie_file: str | None = None):
    """获取 requests Session,携带登录 cookie。

    ``requests`` 在此懒导入——仅在真正拉取 wiki 时需要,避免 bot-brain
    核心功能强制依赖 requests。
    """
    try:
        import requests
    except ImportError as e:
        raise ImportError(
            "wiki 拉取需要 requests 库,请安装:pip install requests"
        ) from e

    try:
        import urllib3
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    except ImportError:
        pass

    session = requests.Session()
    session.verify = False

    cookies_data = load_cookies(cookie_file)
    if cookies_data:
        for cookie in cookies_data:
            name = cookie.get("name", "")
            value = cookie.get("value", "")
            domain = cookie.get("domain", "")
            path = cookie.get("path", "/")
            if name and value:
                session.cookies.set(name, value, domain=domain, path=path)
                if domain.startswith("."):
                    session.cookies.set(name, value, domain=domain.lstrip("."), path=path)

    session.headers.update({
        "User-Agent": (
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
            "AppleWebKit/537.36 (KHTML, like Gecko) "
            "Chrome/120.0.0.0 Safari/537.36"
        ),
        "Accept": "application/json, text/plain, */*",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
        "Referer": "https://wiki.huawei.com/",
        "X-Requested-With": "XMLHttpRequest",
        "x-app-key": "wiki",
        "language": "zh",
    })
    return session


def wiki_api_get(
    session,
    domain_id,
    kanban_id,
    api_type: str,
    params: dict | None = None,
    post_data: dict | None = None,
    cookie_file: str | None = None,
) -> Any:
    """调用 Wiki 内部 API。

    ``cookie_file`` 用于 ``build_cookie_header``(下载附件等需要显式 Cookie 头)。
    """
    api_path = API_PATHS.get(api_type)
    if not api_path:
        return None

    path = (
        api_path
        .replace("{domain_id}", str(domain_id))
        .replace("{kanban_id}", str(kanban_id))
    )
    url = f"{WIKI_BASE}{path}"

    try:
        if post_data is not None:
            if "request_tag" not in post_data:
                post_data["request_tag"] = str(int(time.time() * 1000))
            resp = session.post(url, json=post_data, timeout=30)
        else:
            if params:
                url = f"{url}?{urlencode(params)}"
            resp = session.get(url, timeout=30)

        if resp.status_code == 200:
            content_type = resp.headers.get("Content-Type", "")
            body_text = resp.text
            # Detect cookie expiry: a 200 response that is actually a login
            # page (HTML with login signals) means the session cookie died.
            if "application/json" not in content_type and not body_text.strip().startswith("{"):
                body_lower = body_text[:2000].lower()
                if any(sig in body_lower for sig in _LOGIN_SIGNALS):
                    logger.warning("Wiki API 返回登录页,cookie 可能已失效")
                    return COOKIE_EXPIRED
            if "application/json" in content_type or body_text.strip().startswith("{"):
                data = resp.json()
                if isinstance(data, dict) and "code" in data and "data" in data:
                    if data.get("code") == 200 or data.get("success") is not False:
                        return data.get("data")
                    msg = data.get("message", "未知错误")
                    # Some API responses use a code/message to signal auth expiry.
                    if any(sig in str(msg).lower() for sig in ("login", "登录", "unauthorized", "token")):
                        logger.warning("Wiki API 返回认证错误: %s", msg)
                        return COOKIE_EXPIRED
                    logger.warning("API 返回错误: %s", msg)
                    return None
                if isinstance(data, list):
                    logger.warning("可能权限不够,无法访问该文档")
                    return None
                return data
            logger.warning("API 返回非 JSON: %s", body_text[:500])
            return None
        if resp.status_code in (401, 403):
            logger.warning("Wiki API 返回 %d,cookie 可能已失效", resp.status_code)
            return COOKIE_EXPIRED
        logger.warning("API 请求失败: %s", resp.status_code)
        return None
    except Exception as e:
        logger.warning("API 请求异常: %s", e)
        return None