"""
Tenants router.

POST /tenants              — register a new tenant
GET  /tenants              — list all tenants
GET  /tenants/{tenant_id}  — get a specific tenant
"""

from __future__ import annotations

from datetime import datetime, timezone

from fastapi import APIRouter, HTTPException, status

from zia.api.auth import AuthDep
from zia.api.models import TenantCreateRequest, TenantResponse
from zia.tenants.context import TenantRegistry

router = APIRouter(prefix="/tenants", tags=["Tenants"])

# In-memory tenant metadata store (augments TenantRegistry with timestamps)
_tenant_meta: dict[str, TenantResponse] = {}


@router.post(
    "",
    response_model=TenantResponse,
    status_code=status.HTTP_201_CREATED,
    summary="Register a new tenant",
)
async def create_tenant(body: TenantCreateRequest, _key: AuthDep) -> TenantResponse:
    """Register a new tenant. Returns 409 if tenant_id already exists."""
    registry = TenantRegistry()
    if registry.exists(body.tenant_id):
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail=f"Tenant '{body.tenant_id}' already exists",
        )
    registry.register(tenant_id=body.tenant_id, name=body.name)

    # Initialize SIF graph namespace for this tenant
    try:
        from zia.sif.graph.adapter import KuzuAdapter
        adapter = KuzuAdapter()
        adapter.initialize_schema(body.tenant_id)
    except Exception:
        pass  # kuzu may not be installed; graph ops degrade gracefully

    resp = TenantResponse(
        tenant_id=body.tenant_id,
        name=body.name,
        metadata=body.metadata,
        created_at=datetime.now(timezone.utc),
    )
    _tenant_meta[body.tenant_id] = resp
    return resp


@router.get("", response_model=list[TenantResponse], summary="List all tenants")
async def list_tenants(_key: AuthDep) -> list[TenantResponse]:
    return list(_tenant_meta.values())


@router.get(
    "/{tenant_id}",
    response_model=TenantResponse,
    summary="Get tenant details",
)
async def get_tenant(tenant_id: str, _key: AuthDep) -> TenantResponse:
    tenant = _tenant_meta.get(tenant_id)
    if not tenant:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Tenant '{tenant_id}' not found",
        )
    return tenant
