"""
Build CX API (typed) with endpoint groups per tag (misc, admin, auto, chat, ...).
Uses the typed group classes from _typed_cx and wires the generated client with header injection.
"""

from __future__ import annotations

from collections.abc import Callable, MutableMapping
from pathlib import Path

from stax_sdk.cx._typed_cx import CxAPI

GENERATED_API = Path(__file__).resolve().parent / "_generated" / "stax_cx_client" / "api"


def _tag_to_group_class(tag: str) -> str:
    """e.g. misc -> MiscGroup, api_token -> ApiTokenGroup."""
    return "".join(w.capitalize() for w in tag.split("_")) + "Group"


def build_cx_sync_api(
    base_url: str,
    inject_headers: Callable[[MutableMapping[str, str]], None] | None = None,
) -> CxAPI:
    """Build the CX sync API with typed endpoint groups (one per tag)."""
    from stax_sdk._http import sync_client
    from stax_sdk.cx._generated.stax_cx_client.client import AuthenticatedClient  # type: ignore[import-untyped]
    from stax_sdk.cx import _typed_cx

    httpx_client = sync_client(base_url=base_url.rstrip("/"), inject_headers=inject_headers)
    gen_client = AuthenticatedClient(base_url=base_url.rstrip("/"), token="")
    gen_client.set_httpx_client(httpx_client)

    api = CxAPI()
    api._client = gen_client

    if not GENERATED_API.is_dir():
        return api

    for d in sorted(GENERATED_API.iterdir()):
        if not d.is_dir() or d.name.startswith("_"):
            continue
        tag = d.name
        group_class_name = _tag_to_group_class(tag)
        group_class = getattr(_typed_cx, group_class_name, None)
        if group_class is None or not callable(group_class):
            continue
        group = group_class()
        group._client = gen_client
        setattr(api, tag, group)

    return api
