"""法国工商名录（annuaire-entreprises）查询：按 SIREN/SIRET 取 NAF/APE 代码。"""
from __future__ import annotations

import httpx

from app.core.logger import get_logger

logger = get_logger(__name__)

_SEARCH_URL = "https://recherche-entreprises.api.gouv.fr/search"


def _extract_naf(result: dict) -> str | None:
    """从 API 结果里取 NAF/APE 代码：单位法人 → 总机构(siège) → 首个匹配机构。"""
    if not isinstance(result, dict):
        return None
    value = result.get("activite_principale")  # 单位法人 NAF/APE
    if value:
        return str(value).strip()
    siege = result.get("siege") or {}
    value = siege.get("activite_principale")  # 总机构（établissement siège）
    if value:
        return str(value).strip()
    ests = result.get("matching_etablissements") or []
    if ests and isinstance(ests[0], dict):
        value = ests[0].get("activite_principale")
        if value:
            return str(value).strip()
    return None


def get_naf_code(siren: str) -> str | None:
    """按 SIREN/SIRET 查询 NAF/APE 代码；未查到/失败返回 None（不阻断生成）。"""
    siren = (siren or "").strip()
    if not siren:
        return None
    try:
        with httpx.Client(timeout=15.0, follow_redirects=True) as client:
            resp = client.get(_SEARCH_URL, params={"q": siren, "per_page": 1})
            resp.raise_for_status()
            data = resp.json()
        results = data.get("results") or []
        if not results:
            logger.warning("法国名录未查到 SIREN=%s", siren)
            return None
        return _extract_naf(results[0])
    except Exception as exc:  # noqa: BLE001
        logger.warning("法国名录查询失败 SIREN=%s: %s", siren, exc)
        return None
