"""cortex/api/routes/memory/feedback.py — Feedback endpoints."""

from __future__ import annotations

import logging
from typing import Any

from fastapi import Depends, HTTPException, Response, status
from fastapi.responses import JSONResponse

from cortex.api.deps import PREFIX, _serialise, get_plugin
from cortex.api.deprecation import add_deprecation_headers
from cortex.api.models import FeedbackRequest

logger = logging.getLogger(__name__)


def _register(router, verify_api_key):
    """Register feedback endpoints."""

    # ---- Canonical: /memories/feedback  (issue #297) ----
    @router.post(
        f"{PREFIX}/memories/feedback",
        summary="Submit memory feedback",
        tags=["memory"],
        operation_id="memories_submit_feedback",
    )
    async def memories_submit_feedback(
        body: FeedbackRequest,
        _: None = Depends(verify_api_key),
        plugin: Any = Depends(get_plugin),
    ) -> JSONResponse:
        """Submit positive or negative feedback for a retrieved memory.

        Canonical path: ``POST /api/v1/memories/feedback``.
        """
        return await _do_submit_feedback(body, plugin)

    # ---- DEPRECATED: /feedback  (issue #297) ----
    @router.post(
        f"{PREFIX}/feedback",
        summary="Submit memory feedback — DEPRECATED, use /memories/feedback",
        tags=["memory (deprecated)"],
        operation_id="submit_feedback",
        deprecated=True,
    )
    async def submit_feedback(
        body: FeedbackRequest,
        response: Response,
        _: None = Depends(verify_api_key),
        plugin: Any = Depends(get_plugin),
    ) -> JSONResponse:
        """Submit positive or negative feedback for a retrieved memory.

        .. deprecated::
            Use ``POST /api/v1/memories/feedback``.
            Sunset: 2026-06-01  (issue #297)
        """
        add_deprecation_headers(response, f"{PREFIX}/memories/feedback")
        return await _do_submit_feedback(body, plugin)

    async def _do_submit_feedback(body: FeedbackRequest, plugin: Any) -> JSONResponse:
        """Shared implementation for feedback endpoints."""
        result = await plugin.feedback(
            memory_id=body.memory_id,
            helpful=body.helpful,
            context=body.context,
            target_type=body.target_type,
        )
        if result is None:
            raise HTTPException(
                status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
                detail="FeedbackSystem not available",
            )
        data = _serialise(result.__dict__) if hasattr(result, "__dict__") else str(result)
        return JSONResponse(content={"feedback": data})
