"""cortex/api/routes/memory/belief_history.py — Belief history endpoint (#1280)."""

from __future__ import annotations

import logging
from typing import Any

from fastapi import Depends, HTTPException, Query, Request, status
from fastapi.responses import JSONResponse

from cortex.api.deps import PREFIX, _resolve_owner_id, get_plugin

logger = logging.getLogger(__name__)


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

    @router.get(
        f"{PREFIX}/memories/belief-history",
        status_code=status.HTTP_200_OK,
        summary="Get belief change history for a subject-predicate pair",
        tags=["memory"],
        operation_id="memories_belief_history",
    )
    async def belief_history(
        request: Request,
        subject: str = Query(..., description="Subject entity (e.g. 'user')"),
        predicate: str = Query(..., description="Predicate (e.g. 'lives_in')"),
        owner_id: str = Query("default", description="Memory namespace"),
        include_deprecated: bool = Query(True, description="Include deprecated claims"),
        _: None = Depends(verify_api_key),
        plugin: Any = Depends(get_plugin),
    ) -> JSONResponse:
        """Retrieve the full belief change history for a subject-predicate pair.

        Traces the superseded_by chain to show how a belief evolved over time.
        """
        owner_id = _resolve_owner_id(request, owner_id)

        storage = getattr(plugin, "storage", None)
        if storage is None:
            raise HTTPException(
                status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
                detail="Storage not available",
            )

        try:
            from cortex.core.belief_history import get_belief_history
            history = await get_belief_history(
                storage=storage,
                subject=subject,
                predicate=predicate,
                owner_id=owner_id,
                include_deprecated=include_deprecated,
            )
            return JSONResponse(content=history.to_dict())
        except Exception as exc:
            logger.error("belief_history failed: %s", exc, exc_info=True)
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="Failed to retrieve belief history",
            ) from exc

    @router.get(
        f"{PREFIX}/memories/belief-history/entity",
        status_code=status.HTTP_200_OK,
        summary="Get all belief changes for an entity",
        tags=["memory"],
        operation_id="memories_belief_history_entity",
    )
    async def belief_history_entity(
        request: Request,
        subject: str = Query(..., description="Subject entity (e.g. 'user')"),
        owner_id: str = Query("default", description="Memory namespace"),
        limit: int = Query(50, ge=1, le=200, description="Max predicates to return"),
        _: None = Depends(verify_api_key),
        plugin: Any = Depends(get_plugin),
    ) -> JSONResponse:
        """Retrieve belief change histories for all predicates of a given subject."""
        owner_id = _resolve_owner_id(request, owner_id)

        storage = getattr(plugin, "storage", None)
        if storage is None:
            raise HTTPException(
                status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
                detail="Storage not available",
            )

        try:
            from cortex.core.belief_history import get_belief_changes_for_entity
            histories = await get_belief_changes_for_entity(
                storage=storage,
                subject=subject,
                owner_id=owner_id,
                limit=limit,
            )
            return JSONResponse(content={
                "subject": subject,
                "predicates_with_changes": len(histories),
                "histories": [h.to_dict() for h in histories],
            })
        except Exception as exc:
            logger.error("belief_history_entity failed: %s", exc, exc_info=True)
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="Failed to retrieve belief history",
            ) from exc
