"""Typed response models for operator-facing manager APIs."""

from __future__ import annotations

from typing import Any

from pydantic import BaseModel, ConfigDict


def _to_camel(field_name: str) -> str:
    first, *rest = field_name.split("_")
    return first + "".join(part.capitalize() for part in rest)


class ManagerApiModel(BaseModel):
    model_config = ConfigDict(alias_generator=_to_camel, populate_by_name=True)


class ManagerAdminResponse(ManagerApiModel):
    admin_user_id: str
    username: str
    display_name: str
    role: str
    status: str


class ManagerConfigResponse(ManagerApiModel):
    rp_id: str
    rp_name: str
    origins: list[str]
    bootstrap_enabled: bool
    has_admins: bool
    passkeys_available: bool


class ManagerSessionResponse(ManagerApiModel):
    authenticated: bool
    admin: ManagerAdminResponse | None = None
    has_admins: bool


class ManagerOverviewTotalsResponse(ManagerApiModel):
    partners: int
    admins: int
    passkeys: int


class ManagerOverviewJobResponse(ManagerApiModel):
    job_id: str
    status: str
    priority: int
    created_at: str
    completed_at: str | None = None


class ManagerOverviewEventResponse(ManagerApiModel):
    event_type: str
    actor: str | None = None
    detail: str | None = None
    created_at: str


class ManagerPartnerBalanceResponse(ManagerApiModel):
    partner_id: str
    name: str
    credits_usd: float


class ManagerOverviewResponse(ManagerApiModel):
    jobs: dict[str, int]
    workers: dict[str, int]
    totals: ManagerOverviewTotalsResponse
    recent_jobs: list[ManagerOverviewJobResponse]
    recent_events: list[ManagerOverviewEventResponse]
    partner_balances: list[ManagerPartnerBalanceResponse]


def build_manager_session_response(admin: dict[str, Any] | None, *, has_admins: bool) -> ManagerSessionResponse:
    return ManagerSessionResponse(
        authenticated=bool(admin),
        admin=ManagerAdminResponse.model_validate(admin) if admin else None,
        has_admins=has_admins,
    )
