"""AI Validators resource."""

from __future__ import annotations

from typing import Any, Dict, Generator, List, Optional, TYPE_CHECKING

from netorca_sdk.v2.base import BaseResource
from netorca_sdk.v2.models.ai_validator import AIValidator, AIValidatorResponse

if TYPE_CHECKING:
    from netorca_sdk.v2.client import NetOrcaClient


class AIValidatorsResource(BaseResource):
    """
    AI Validators resource.

    Provides access to AI validator management.

    Example:
        ```python
        # List all validators
        for validator in client.ai_validators.list():
            print(validator.name, validator.active)

        # Create a validator
        validator = client.ai_validators.create({
            "name": "sdktest-schema-validator",
            "service": 123,
            "llm_model": 1,
            "validation_prompt": "Validate this submission..."
        })

        # Trigger validation
        result = client.ai_validators.trigger(validator_id=1)

        # Evaluate validation
        result = client.ai_validators.evaluate(validator_id=1)
        ```
    """

    endpoint = "ai_validators"
    model_class = AIValidator

    def _build_external_url(self, path: str) -> str:
        """Build URL for external endpoints."""
        pov = self.client.context
        return f"{self.client.fqdn}/external/{pov}/{path}/"

    def list(self, **filters) -> Generator[AIValidator, None, None]:
        """List all AI validators."""
        url = self._build_external_url(self.endpoint)
        next_url: Optional[str] = url

        while next_url:
            response = self.client.auth.get(next_url, filters=filters if next_url == url else None)
            data = self.client._handle_response(response, self.endpoint)

            for item in data.get('results', []):
                yield self._to_model(item)

            next_url = data.get('next')

    def filter(self, **filters) -> List[AIValidator]:
        """Get AI validators as a list with filters."""
        return list(self.list(**filters))

    def get(self, id: int) -> AIValidator:
        """Get a specific AI validator."""
        url = self._build_external_url(f"{self.endpoint}/{id}")
        response = self.client.auth.get(url)
        data = self.client._handle_response(response, self.endpoint)
        return self._to_model(data)

    def create(self, data: Dict[str, Any]) -> AIValidator:
        """Create a new AI validator."""
        url = self._build_external_url(self.endpoint)
        response = self.client.auth.post(url, data=data)
        result = self.client._handle_response(response, self.endpoint)
        return self._to_model(result)

    def update(self, id: int, data: Dict[str, Any], partial: bool = True) -> AIValidator:
        """Update an AI validator."""
        url = self._build_external_url(f"{self.endpoint}/{id}")
        if partial:
            response = self.client.auth.patch(url, data=data)
        else:
            response = self.client.auth.put(url, data=data)
        result = self.client._handle_response(response, self.endpoint)
        return self._to_model(result)

    def delete(self, id: int) -> Dict[str, Any]:
        """Delete an AI validator."""
        url = self._build_external_url(f"{self.endpoint}/{id}")
        response = self.client.auth.delete(url)
        return self.client._handle_response(response, self.endpoint)

    def trigger(self, validator_id: int) -> Dict[str, Any]:
        """Trigger an AI validator.

        Args:
            validator_id: ID of the validator to trigger

        Returns:
            Trigger result
        """
        url = self._build_external_url(f"{self.endpoint}/{validator_id}/trigger")
        response = self.client.auth.get(url)
        return self.client._handle_response(response, self.endpoint)

    def evaluate(self, validator_id: int) -> Dict[str, Any]:
        """Evaluate an AI validator.

        Args:
            validator_id: ID of the validator to evaluate

        Returns:
            Evaluation result
        """
        url = self._build_external_url(f"{self.endpoint}/{validator_id}/evaluate")
        response = self.client.auth.get(url)
        return self.client._handle_response(response, self.endpoint)

    def by_service(self, service_id: int) -> List[AIValidator]:
        """Get all validators for a specific service."""
        return self.filter(service_id=service_id)

    def get_active(self) -> List[AIValidator]:
        """Get all active validators."""
        return [v for v in self.list() if v.active]


class AIValidatorResponsesResource(BaseResource):
    """
    AI Validator Responses resource.

    Provides access to AI validator response records.

    Example:
        ```python
        # List all responses
        for response in client.ai_validator_responses.list():
            print(response.state, response.reasoning)

        # Filter by validator
        responses = client.ai_validator_responses.by_validator(validator_id=1)

        # Filter by change instance
        responses = client.ai_validator_responses.by_change_instance(change_instance_id=123)
        ```
    """

    endpoint = "ai_validator_responses"
    model_class = AIValidatorResponse

    def _build_external_url(self, path: str) -> str:
        """Build URL for external endpoints."""
        pov = self.client.context
        return f"{self.client.fqdn}/external/{pov}/{path}/"

    def list(self, **filters) -> Generator[AIValidatorResponse, None, None]:
        """List all AI validator responses.

        Args:
            **filters: Optional filters including:
                - ai_validator_id: Filter by validator
                - change_instance_id: Filter by change instance
                - state: Filter by state (e.g., 'approved', 'rejected')
        """
        url = self._build_external_url(self.endpoint)
        next_url: Optional[str] = url

        while next_url:
            response = self.client.auth.get(next_url, filters=filters if next_url == url else None)
            data = self.client._handle_response(response, self.endpoint)

            for item in data.get('results', []):
                yield self._to_model(item)

            next_url = data.get('next')

    def filter(self, **filters) -> List[AIValidatorResponse]:
        """Get AI validator responses as a list with filters."""
        return list(self.list(**filters))

    def get(self, id: int) -> AIValidatorResponse:
        """Get a specific AI validator response."""
        url = self._build_external_url(f"{self.endpoint}/{id}")
        response = self.client.auth.get(url)
        data = self.client._handle_response(response, self.endpoint)
        return self._to_model(data)

    def by_validator(self, validator_id: int) -> List[AIValidatorResponse]:
        """Get all responses for a specific validator."""
        return self.filter(ai_validator_id=validator_id)

    def by_change_instance(self, change_instance_id: int) -> List[AIValidatorResponse]:
        """Get all responses for a specific change instance."""
        return self.filter(change_instance_id=change_instance_id)

    def get_approved(self) -> List[AIValidatorResponse]:
        """Get all approved responses."""
        return self.filter(state="approved")

    def get_rejected(self) -> List[AIValidatorResponse]:
        """Get all rejected responses."""
        return self.filter(state="rejected")
