"""pinn tenant_init 管理 — export · active 切换。"""

from __future__ import annotations

from typing import TYPE_CHECKING, Annotated, Any

from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field

from niannian.http.core_auth import require_admin_owner
from niannian.tenant.tenant_init import TenantInitStore

if TYPE_CHECKING:
    from niannian.client import NianNian


class ExportInitBody(BaseModel):
    label: str = Field(..., min_length=1)
    set_active: bool = True


class SetActiveBody(BaseModel):
    init_id: str = Field(..., min_length=1)
    label: str | None = None


def create_tenant_init_admin_router(nn: NianNian) -> APIRouter:
    router = APIRouter(prefix="/v1/admin/tenant-init", tags=["admin"])
    store = TenantInitStore(nn._home)

    @router.get("")
    def get_active(_role: Annotated[str, Depends(require_admin_owner)]) -> dict[str, Any]:
        active = store.get_active()
        archives = store.list_archives()
        return {"active": active, "archives": archives}

    @router.post("/export")
    def export_init(
        body: ExportInitBody,
        _role: Annotated[str, Depends(require_admin_owner)],
    ) -> dict[str, Any]:
        result = store.export_init(
            config=nn._config,
            label=body.label,
            activated_by="pinn",
            set_active=body.set_active,
        )
        active = store.get_active()
        return {"export": result, "active": active}

    @router.patch("/active")
    def set_active(
        body: SetActiveBody,
        _role: Annotated[str, Depends(require_admin_owner)],
    ) -> dict[str, Any]:
        try:
            active = store.set_active(body.init_id, label=body.label, activated_by="pinn")
        except KeyError:
            raise HTTPException(
                status_code=404,
                detail={"code": "init_not_found", "message": "tenant init archive not found"},
            ) from None
        return {"active": active}

    return router
