"""Configuration API endpoints."""

from __future__ import annotations
from fastapi import APIRouter
from api.schemas.config import ServiceConfigResponse, ServiceConfigUpdate
from crystallise.config.registry import get_registry
from crystallise.prompts.registry import list_prompts

router = APIRouter()


@router.get("/services", response_model=list[ServiceConfigResponse])
async def list_service_configs():
    """List all service configurations."""
    registry = get_registry()
    return [
        ServiceConfigResponse(
            service_id=c.service_id,
            model=c.model,
            system_prompt=c.system_prompt,
            prompt_template_id=c.prompt_template_id,
            temperature=c.temperature,
            max_output_tokens=c.max_output_tokens,
            extra=c.extra,
        )
        for c in registry.list_configs()
    ]


@router.get("/services/{service_id}", response_model=ServiceConfigResponse)
async def get_service_config(service_id: str):
    """Get configuration for a specific service."""
    registry = get_registry()
    c = registry.get_config(service_id)
    return ServiceConfigResponse(
        service_id=c.service_id,
        model=c.model,
        system_prompt=c.system_prompt,
        prompt_template_id=c.prompt_template_id,
        temperature=c.temperature,
        max_output_tokens=c.max_output_tokens,
        extra=c.extra,
    )


@router.put("/services/{service_id}", response_model=ServiceConfigResponse)
async def update_service_config(service_id: str, update: ServiceConfigUpdate):
    """Update service configuration."""
    registry = get_registry()
    overrides = {k: v for k, v in update.model_dump().items() if v is not None}
    c = registry.update_config(service_id, overrides)
    return ServiceConfigResponse(
        service_id=c.service_id,
        model=c.model,
        system_prompt=c.system_prompt,
        prompt_template_id=c.prompt_template_id,
        temperature=c.temperature,
        max_output_tokens=c.max_output_tokens,
        extra=c.extra,
    )


@router.get("/prompts")
async def list_prompt_registry():
    """List all AI prompt definitions with metadata."""
    return list_prompts()
