from __future__ import annotations

from pydantic import BaseModel

from safe_genai.providers.base import BaseProvider
from safe_genai.result import Usage

_VALIDATOR_SYSTEM_TEMPLATE = """\
You are a semantic validator. Review the provided JSON output and determine whether it is accurate, complete, and appropriate.
Respond with a JSON object containing:
- "passed": true if the output is acceptable, false otherwise
- "feedback": a brief explanation of your decision
{extra}"""


class _ValidationResult(BaseModel):
    passed: bool
    feedback: str


class Validator:
    def __init__(
        self,
        provider: BaseProvider,
        model: str,
        additional_instructions: str | None = None,
    ) -> None:
        self._provider = provider
        self._model = model
        self._system_prompt = _VALIDATOR_SYSTEM_TEMPLATE.format(
            extra=f"\nAdditional instructions:\n{additional_instructions}"
            if additional_instructions
            else ""
        )

    def validate(self, formatted_output: BaseModel) -> tuple[_ValidationResult, Usage]:
        result, usage = self._provider.generate_structured(
            self._model,
            self._system_prompt,
            formatted_output.model_dump_json(indent=2),
            _ValidationResult,
        )
        return result, usage  # type: ignore[return-value]

    async def avalidate(self, formatted_output: BaseModel) -> tuple[_ValidationResult, Usage]:
        result, usage = await self._provider.agenerate_structured(
            self._model,
            self._system_prompt,
            formatted_output.model_dump_json(indent=2),
            _ValidationResult,
        )
        return result, usage  # type: ignore[return-value]
