"""
Playbooks Route - System Prompt Verwaltung.
"""

import logging
from typing import Optional
from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel

from ..services.playbook_service import get_playbook_service, Playbook
from ..middleware.auth import verify_api_key

logger = logging.getLogger(__name__)

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


class PlaybookSummary(BaseModel):
    """Zusammenfassung eines Playbooks (ohne System Prompt)."""
    id: str
    name: str
    description: str
    prompt_version: str
    recommended_models: list[str]


class PlaybookDetail(BaseModel):
    """Vollständige Playbook-Details."""
    id: str
    name: str
    description: str
    system_prompt: str
    prompt_version: str
    recommended_models: list[str]
    tool_policy: dict
    status: str


class PlaybookListResponse(BaseModel):
    """Response für Playbook-Liste."""
    items: list[PlaybookSummary]


@router.get("", response_model=PlaybookListResponse)
async def list_playbooks(
    status: Optional[str] = "published",
    _: str = Depends(verify_api_key),
):
    """
    Liste verfügbarer Playbooks.

    Playbooks sind versionierte System-Prompt-Vorlagen für spezifische Schulkontexte.
    """
    service = get_playbook_service()
    playbooks = service.list_playbooks(status=status)

    return PlaybookListResponse(
        items=[
            PlaybookSummary(
                id=p.id,
                name=p.name,
                description=p.description,
                prompt_version=p.prompt_version,
                recommended_models=p.recommended_models,
            )
            for p in playbooks
        ]
    )


@router.get("/{playbook_id}", response_model=PlaybookDetail)
async def get_playbook(
    playbook_id: str,
    _: str = Depends(verify_api_key),
):
    """
    Details zu einem Playbook abrufen.

    Enthält den vollständigen System Prompt und Tool-Policies.
    """
    service = get_playbook_service()
    playbook = service.get_playbook(playbook_id)

    if not playbook:
        raise HTTPException(status_code=404, detail=f"Playbook {playbook_id} not found")

    return PlaybookDetail(
        id=playbook.id,
        name=playbook.name,
        description=playbook.description,
        system_prompt=playbook.system_prompt,
        prompt_version=playbook.prompt_version,
        recommended_models=playbook.recommended_models,
        tool_policy=playbook.tool_policy,
        status=playbook.status,
    )
