"""Request schemas for POST /ai/adaptive_optimize."""

from __future__ import annotations

from typing import Self

from pydantic import BaseModel, model_validator


class AdaptiveOptimizedCandidate(BaseModel):
    """
    A single candidate from a previous optimization attempt.
    """

    optimization_id: str
    source_code: str
    explanation: str
    source: str
    speedup: str | None = None


class AdaptiveOptimizeRequest(BaseModel):
    """
    Request body for POST /ai/adaptive_optimize.
    """

    trace_id: str
    original_source_code: str
    candidates: list[AdaptiveOptimizedCandidate]
    python_version: str | None = None
    language_version: str | None = None
    language: str = "python"
    dependency_code: str | None = None

    @model_validator(mode="after")
    def resolve_python_version(self) -> Self:
        """
        Resolve python_version from language_version for backward compat.
        """
        if (
            self.python_version is None
            and self.language_version is not None
            and self.language == "python"
        ):
            self.python_version = self.language_version
        return self
