"""cortex/api/routes/dialectic.py — Dialectic/ask endpoints."""

from __future__ import annotations

import logging
from typing import Any, Dict, List

from fastapi import APIRouter, Depends, HTTPException, status

from cortex.api.deps import PREFIX, get_plugin
from cortex.api.models import AskRequest, AskResponse

logger = logging.getLogger(__name__)

router = APIRouter()


def _make_routes(verify_api_key):
    """Register dialectic routes with the given auth dependency."""

    @router.post(
        f"{PREFIX}/ask",
        response_model=AskResponse,
        summary="Ask a question — synthesise answer from memory",
        tags=["dialectic"],
        operation_id="ask",
    )
    async def ask(
        body: AskRequest,
        _: None = Depends(verify_api_key),
        plugin: Any = Depends(get_plugin),
    ) -> AskResponse:
        """
        Dialectic fast path: retrieve relevant memories and synthesise a
        grounded answer via LLM.
        """
        result = await plugin.ask(
            query=body.query,
            owner_id=body.owner_id,
            history=body.history or None,
            mode=body.mode,
            max_steps=body.max_steps,
        )
        if not result.ok:
            raise HTTPException(
                status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
                detail=result.errors[0] if result.errors else "Dialectic engine error",
            )
        return AskResponse(
            answer=result.answer,
            sources=result.sources,
            confidence=result.confidence,
            reasoning=result.reasoning,
            ok=result.ok,
            errors=result.errors,
        )
