"""Domain API: generic CRUD for all 9 Life OS domains."""

from __future__ import annotations

from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel

from agntspace.domains.base import DOMAIN_NAMES

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


class DomainFileRequest(BaseModel):
    content: str
    metadata: dict | None = None


@router.get("")
async def list_domains(request: Request) -> list[dict]:
    """List all domains with file counts."""
    domains = request.app.state.domains
    return [
        {"name": name, "files": svc.file_count}
        for name, svc in domains.items()
    ]


@router.get("/{domain}")
async def list_domain_files(request: Request, domain: str) -> list[dict]:
    """List files in a specific domain."""
    svc = _get_domain(request, domain)
    return svc.list_files()


@router.get("/{domain}/{slug}")
async def get_domain_file(request: Request, domain: str, slug: str) -> dict:
    """Get a file from a domain."""
    svc = _get_domain(request, domain)
    doc = svc.get_file(slug)
    if not doc:
        raise HTTPException(status_code=404, detail=f"Not found: {domain}/{slug}")
    return {
        "slug": slug,
        "content": doc.content,
        "metadata": doc.metadata,
    }


@router.put("/{domain}/{slug}")
async def upsert_domain_file(
    request: Request, domain: str, slug: str, body: DomainFileRequest
) -> dict:
    """Create or update a file in a domain."""
    svc = _get_domain(request, domain)
    path = svc.update_file(slug, body.content, body.metadata)
    return {"path": path}


def _get_domain(request: Request, domain: str):  # noqa: ANN202
    domains = request.app.state.domains
    if domain not in domains:
        raise HTTPException(
            status_code=404,
            detail=f"Unknown domain: {domain}. Valid: {', '.join(DOMAIN_NAMES)}",
        )
    return domains[domain]
