"""Central AI enhancement + server-managed prompts.

  POST /v1/enhance  {text, system_prompt}  -> {text}
  GET  /v1/prompts                          -> {prompts: [{id,name,prompt}]}

Both require the bearer key. The server's LLM key never appears in a response.
"""
from __future__ import annotations

import os

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

from .. import enhance as enhance_mod
from .. import prompts as prompts_mod
from ..auth import Principal
from ..config import ServerConfig
from ..deps import AuthDep, get_config

router = APIRouter()

# Bound the input so a client cannot ask the server to spend unbounded tokens.
_MAX_TEXT = 200_000
_MAX_PROMPT = 20_000


class EnhanceRequest(BaseModel):
    text: str = Field(min_length=1, max_length=_MAX_TEXT)
    system_prompt: str = Field(min_length=1, max_length=_MAX_PROMPT)


class EnhanceResponse(BaseModel):
    text: str


@router.post("/v1/enhance", response_model=EnhanceResponse)
async def enhance_route(
    body: EnhanceRequest,
    principal: Principal = AuthDep,
    config: ServerConfig = Depends(get_config),
) -> EnhanceResponse:
    if not enhance_mod.is_available(config):
        # 501: the client already knows from /v1/status; this guards direct use.
        raise HTTPException(status_code=501,
                            detail="Server enhancement is not configured.")
    try:
        out = await enhance_mod.enhance(
            config, text=body.text, system_prompt=body.system_prompt)
    except enhance_mod.EnhanceError as e:
        raise HTTPException(status_code=502, detail=e.client_message)
    return EnhanceResponse(text=out)


@router.get("/v1/prompts")
async def prompts_route(
    principal: Principal = AuthDep,
    config: ServerConfig = Depends(get_config),
) -> dict:
    data_dir = os.environ.get("VOXCAST_DATA_DIR") or config.data_dir or "."
    return {"prompts": prompts_mod.load_prompts(data_dir)}
