"""Unified Candidate Performance — JD-style ?action= on one path.

GET  /candidates/{id}/performance?action=overall|ai|assessments
POST /candidates/{id}/performance?action=ai|assessments
"""

from __future__ import annotations

from typing import Annotated, Any

from fastapi import APIRouter, Depends, Query, Request, status
from fastapi.exceptions import RequestValidationError
from pydantic import ValidationError

from app.deps import PlatformActorContext, get_platform_actor_context, verify_internal_token
from app.schemas.candidate_performance import (
    PERFORMANCE_INGEST_BODY_BY_ACTION,
    PERFORMANCE_INGEST_OPENAPI_EXAMPLES,
    AiPerformanceIngestBody,
    AssessmentAttemptIngestBody,
    CandidateAiPerformanceResponse,
    CandidateAssessmentsPerformanceResponse,
    CandidateOverallPerformanceResponse,
    PerformanceGetAction,
    PerformanceIngestAction,
)
from app.services.talent.performance import CandidatePerformanceService

router = APIRouter(prefix="/candidates")
_service = CandidatePerformanceService()

CandidatePerformanceReadResponse = (
    CandidateOverallPerformanceResponse
    | CandidateAiPerformanceResponse
    | CandidateAssessmentsPerformanceResponse
)
CandidatePerformanceWriteResponse = (
    CandidateAiPerformanceResponse | CandidateAssessmentsPerformanceResponse
)


def _parse_ingest_body(action: PerformanceIngestAction, raw: Any):
    if raw is None:
        raw = {}
    if not isinstance(raw, dict):
        raise RequestValidationError(
            [
                {
                    "type": "dict_type",
                    "loc": ("body",),
                    "msg": "JSON body must be an object",
                    "input": raw,
                }
            ]
        )
    data = {k: v for k, v in raw.items() if k != "action"}
    model = PERFORMANCE_INGEST_BODY_BY_ACTION[action]
    try:
        return model.model_validate(data)
    except ValidationError as exc:
        raise RequestValidationError(exc.errors()) from exc


@router.get(
    "/{candidate_id}/performance",
    response_model=CandidatePerformanceReadResponse,
    status_code=status.HTTP_200_OK,
    summary="Unified Candidate Performance (read)",
    description=(
        "Single performance read entrypoint. Select the facet with query param "
        "`action` (same pattern as Create Job).\n\n"
        "| Query `action` | Returns |\n"
        "|---|---|\n"
        "| `overall` (default) | Combined 0–100 rollup + AI/assessment cards |\n"
        "| `ai` | AI Performance dimensions, strengths, recommendation |\n"
        "| `assessments` | Assessment history, retakes, status |\n\n"
        "Does **not** call LLMs — reads persisted snapshots only. "
        "CRM filters / recruiter actions stay on the Platform. "
        "Prefer `X-Company-Id` for tenant isolation."
    ),
    responses={
        200: {
            "description": "Performance facet for the selected action",
            "content": {
                "application/json": {
                    "schema": {
                        "oneOf": [
                            {
                                "$ref": (
                                    "#/components/schemas/"
                                    "CandidateOverallPerformanceResponse"
                                )
                            },
                            {
                                "$ref": (
                                    "#/components/schemas/"
                                    "CandidateAiPerformanceResponse"
                                )
                            },
                            {
                                "$ref": (
                                    "#/components/schemas/"
                                    "CandidateAssessmentsPerformanceResponse"
                                )
                            },
                        ]
                    }
                }
            },
        }
    },
    dependencies=[Depends(verify_internal_token)],
)
async def get_candidate_performance(
    candidate_id: str,
    action: Annotated[
        PerformanceGetAction,
        Query(
            description="Performance facet: overall | ai | assessments",
            examples=["overall"],
        ),
    ] = PerformanceGetAction.OVERALL,
    actor: PlatformActorContext = Depends(get_platform_actor_context),
) -> CandidatePerformanceReadResponse:
    if action is PerformanceGetAction.AI:
        return _service.get_ai(candidate_id, actor=actor)
    if action is PerformanceGetAction.ASSESSMENTS:
        return _service.get_assessments(candidate_id, actor=actor)
    return _service.get_overall(candidate_id, actor=actor)


@router.post(
    "/{candidate_id}/performance",
    response_model=CandidatePerformanceWriteResponse,
    status_code=status.HTTP_200_OK,
    summary="Unified Candidate Performance (ingest)",
    description=(
        "Single performance write entrypoint. Select the operation with query "
        "param `action` (same pattern as Create Job).\n\n"
        "| Query `action` | Body schema | Purpose |\n"
        "|---|---|---|\n"
        "| `ai` | `AiPerformanceIngestBody` | Upsert AI Performance snapshot |\n"
        "| `assessments` | `AssessmentAttemptIngestBody` | Record/retake assessment |\n\n"
        "In Swagger UI: set **action** under Parameters, then choose the matching "
        "request-body **Example** (ai / assessments).\n\n"
        "Does not generate scores — persists Platform/gateway results only."
    ),
    openapi_extra={
        "requestBody": {
            "required": True,
            "description": (
                "JSON body schema depends on query parameter `action`. "
                "See AiPerformanceIngestBody / AssessmentAttemptIngestBody."
            ),
            "content": {
                "application/json": {
                    "schema": {
                        "oneOf": [
                            {"$ref": "#/components/schemas/AiPerformanceIngestBody"},
                            {
                                "$ref": (
                                    "#/components/schemas/AssessmentAttemptIngestBody"
                                )
                            },
                        ],
                    },
                    "examples": PERFORMANCE_INGEST_OPENAPI_EXAMPLES,
                }
            },
        }
    },
    dependencies=[Depends(verify_internal_token)],
)
async def ingest_candidate_performance(
    candidate_id: str,
    request: Request,
    action: Annotated[
        PerformanceIngestAction,
        Query(
            description="Ingest operation: ai | assessments",
            examples=["ai"],
        ),
    ],
    actor: PlatformActorContext = Depends(get_platform_actor_context),
) -> CandidatePerformanceWriteResponse:
    try:
        raw = await request.json()
    except Exception as exc:  # noqa: BLE001
        raise RequestValidationError(
            [
                {
                    "type": "json_invalid",
                    "loc": ("body",),
                    "msg": "Invalid JSON body",
                    "input": None,
                }
            ]
        ) from exc

    body = _parse_ingest_body(action, raw)
    if action is PerformanceIngestAction.AI:
        assert isinstance(body, AiPerformanceIngestBody)
        return _service.ingest_ai(candidate_id, body, actor=actor)
    assert isinstance(body, AssessmentAttemptIngestBody)
    return _service.ingest_assessment(candidate_id, body, actor=actor)
