"""
Validate Resource

QTI XML validation endpoints.
"""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

from timeback_common import serialize_input, validate_with_schema

from ..types.inputs import ValidateBatchInput, ValidateInput
from ..types.responses import BatchValidationResult, ValidationResult

if TYPE_CHECKING:
    from ..lib.transport import Transport


class ValidateResource:
    """Validation resource for checking QTI XML validity."""

    def __init__(self, transport: Transport) -> None:
        self._transport = transport

    @property
    def _base_path(self) -> str:
        return f"{self._transport.paths.base}/validate"

    async def validate(self, body: ValidateInput | dict[str, Any]) -> ValidationResult:
        """Validate a single QTI XML document."""
        validate_with_schema(ValidateInput, body, "validate request")
        result = await self._transport.post(self._base_path, serialize_input(body, ValidateInput))
        return ValidationResult.model_validate(result)

    async def batch(self, body: ValidateBatchInput | dict[str, Any]) -> BatchValidationResult:
        """Validate multiple QTI XML documents in batch."""
        validate_with_schema(ValidateBatchInput, body, "validate batch")

        # Explicit field ordering preserves TypeScript bodyKey parity. Pydantic
        # model_dump reorders fields alphabetically by alias, which changes
        # the first key from "xml" to "schema". The TS client sends the
        # caller's object as-is (JS insertion order), so we mirror that here.
        body_data = body if isinstance(body, dict) else serialize_input(body, ValidateBatchInput)
        payload: dict[str, Any] = {}

        if "xml" in body_data:
            payload["xml"] = body_data["xml"]
        if "schema" in body_data:
            payload["schema"] = body_data["schema"]
        if "entityIds" in body_data:
            payload["entityIds"] = body_data["entityIds"]

        result = await self._transport.post(f"{self._base_path}/batch", payload)

        return BatchValidationResult.model_validate(result)
