"""Unified Create Job API — POST /jobs?action=draft|rewrite|validate|publish."""

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.job_descriptions import (
    JOB_BODY_BY_ACTION,
    JOB_CREATE_OPENAPI_EXAMPLES,
    JobAction,
    JobCreateBody,
    JobCreateResponse,
)
from app.services.screening.job_descriptions import JobDescriptionsService

router = APIRouter(prefix="/jobs")
_service = JobDescriptionsService()


def _parse_job_body(action: JobAction, raw: Any) -> JobCreateBody:
    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,
                }
            ]
        )
    # `action` belongs only in the query string (not the JSON body).
    data = {k: v for k, v in raw.items() if k != "action"}
    model = JOB_BODY_BY_ACTION[action]
    try:
        return model.model_validate(data)  # type: ignore[return-value]
    except ValidationError as exc:
        raise RequestValidationError(exc.errors()) from exc


@router.post(
    "",
    response_model=JobCreateResponse,
    status_code=status.HTTP_200_OK,
    summary="Unified Create Job (AI)",
    description=(
        "Single Create Job entrypoint. Select the operation with query param "
        "`action` (safe in URLs/logs — do **not** put job description or candidate "
        "PII in the query string).\n\n"
        "| Query `action` | Body schema | Required body fields |\n"
        "|---|---|---|\n"
        "| `draft` | `JobDraftBody` | `role_title` |\n"
        "| `rewrite` | `JobRewriteBody` | `job_description` and/or `job_id` |\n"
        "| `validate` | `JobValidateBody` | `job_description` and/or `job_id` |\n"
        "| `publish` | `JobPublishBody` | `job_id` |\n\n"
        "In Swagger UI: set **action** under Parameters, then choose the matching "
        "request-body **Example** (draft / rewrite / validate / publish).\n\n"
        "Identity: prefer `X-Company-Id` / `X-User-Id` headers."
    ),
    openapi_extra={
        "requestBody": {
            "required": True,
            "description": (
                "JSON body schema depends on query parameter `action`. "
                "See components: JobDraftBody, JobRewriteBody, JobValidateBody, "
                "JobPublishBody."
            ),
            "content": {
                "application/json": {
                    "schema": {
                        "oneOf": [
                            {"$ref": "#/components/schemas/JobDraftBody"},
                            {"$ref": "#/components/schemas/JobRewriteBody"},
                            {"$ref": "#/components/schemas/JobValidateBody"},
                            {"$ref": "#/components/schemas/JobPublishBody"},
                        ],
                    },
                    "examples": JOB_CREATE_OPENAPI_EXAMPLES,
                }
            },
        }
    },
    dependencies=[Depends(verify_internal_token)],
)
async def create_job(
    request: Request,
    action: Annotated[
        JobAction,
        Query(
            description=(
                "Create Job operation (draft | rewrite | validate | publish). "
                "Safe for URLs and access logs — never put JD text or candidate "
                "PII in query parameters."
            ),
            examples=["draft"],
        ),
    ],
    actor: Annotated[PlatformActorContext, Depends(get_platform_actor_context)],
) -> JobCreateResponse:
    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

    payload = _parse_job_body(action, raw)
    return await _service.create_job(
        action,
        payload,
        company_id=actor.company_id,
        created_by=actor.user_id,
    )
