"""cortex/api/routes/contradictions.py — Contradiction audit trail endpoints.

Endpoints:
    GET   /api/v1/contradictions         — list contradictions for an owner
    PATCH /api/v1/contradictions/{id}    — resolve a contradiction
"""

from __future__ import annotations

import logging
from typing import Any, List, Optional

from fastapi import APIRouter, Depends, HTTPException, Query, status
from pydantic import BaseModel, field_validator

from cortex.api.deps import PREFIX, get_plugin
from cortex.core.contradiction_store import VALID_RESOLUTIONS, list_contradictions, mark_resolved

logger = logging.getLogger(__name__)

router = APIRouter()


# ---------------------------------------------------------------------------
# Request / Response models
# ---------------------------------------------------------------------------


class ContradictionItem(BaseModel):
    """A single contradiction row, as returned by the list endpoint."""

    id: int
    claim_a_id: str
    claim_b_id: str
    detected_at: str
    resolution: Optional[str] = None
    resolved_at: Optional[str] = None
    owner_id: str
    reason: str


class ContradictionListResponse(BaseModel):
    """Response envelope for GET /contradictions."""

    items: List[ContradictionItem]
    total: int
    owner_id: str


class ContradictionPatchRequest(BaseModel):
    """Request body for PATCH /contradictions/{id}."""

    resolution: str
    owner_id: str = "default"

    @field_validator("resolution")
    @classmethod
    def _validate_resolution(cls, v: str) -> str:
        if v not in VALID_RESOLUTIONS:
            raise ValueError(
                f"resolution must be one of {sorted(VALID_RESOLUTIONS)}"
            )
        return v


class ContradictionPatchResponse(BaseModel):
    """Response for PATCH /contradictions/{id}."""

    id: int
    resolution: str
    ok: bool


# ---------------------------------------------------------------------------
# Route factory
# ---------------------------------------------------------------------------


def _make_routes(verify_api_key) -> None:
    """Register contradiction routes with the given auth dependency."""

    @router.get(
        f"{PREFIX}/contradictions",
        response_model=ContradictionListResponse,
        summary="List contradictions for an owner",
        tags=["contradictions"],
        operation_id="list_contradictions",
    )
    async def list_contradictions_route(
        owner_id: str = Query("default", description="Multi-tenant owner scope"),
        resolved: Optional[bool] = Query(
            None,
            description="Filter: true=resolved only, false=unresolved only, omit=all",
        ),
        limit: int = Query(100, ge=1, le=500, description="Max results"),
        offset: int = Query(0, ge=0, description="Pagination offset"),
        _: None = Depends(verify_api_key),
        plugin: Any = Depends(get_plugin),
    ) -> ContradictionListResponse:
        """Return contradiction records from the audit trail.

        Supports filtering by resolution status and pagination.
        """
        rows = await list_contradictions(
            plugin.storage,
            owner_id=owner_id,
            resolved=resolved,
            limit=limit,
            offset=offset,
        )
        items = [ContradictionItem(**row) for row in rows]
        return ContradictionListResponse(
            items=items,
            total=len(items),
            owner_id=owner_id,
        )

    @router.patch(
        f"{PREFIX}/contradictions/{{contradiction_id}}",
        response_model=ContradictionPatchResponse,
        summary="Resolve a contradiction",
        tags=["contradictions"],
        operation_id="resolve_contradiction",
    )
    async def resolve_contradiction_route(
        contradiction_id: int,
        body: ContradictionPatchRequest,
        _: None = Depends(verify_api_key),
        plugin: Any = Depends(get_plugin),
    ) -> ContradictionPatchResponse:
        """Mark a contradiction as resolved with an explicit resolution.

        Valid resolution values: ``kept_a``, ``kept_b``, ``merged``.
        """
        try:
            ok = await mark_resolved(
                plugin.storage,
                contradiction_id=contradiction_id,
                resolution=body.resolution,
            )
        except ValueError as exc:
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                detail=str(exc),
            ) from exc

        if not ok:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Contradiction id={contradiction_id} not found.",
            )

        return ContradictionPatchResponse(
            id=contradiction_id,
            resolution=body.resolution,
            ok=True,
        )
