"""AI Processors 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_processor import AIProcessor, AIProcessorHistory

if TYPE_CHECKING:
    from netorca_sdk.v2.client import NetOrcaClient


class AIProcessorsResource(BaseResource):
    """
    AI Processors resource.

    Provides access to AI processor management.

    Example:
        ```python
        # List all processors
        for processor in client.ai_processors.list():
            print(processor.name, processor.action_type)

        # Create a processor
        processor = client.ai_processors.create({
            "name": "sdktest-auto-approve",
            "service": 123,
            "llm_model": 1,
            "action_type": "approve",
            "prompt": "Analyze this request..."
        })

        # Get processor history
        history = client.ai_processors.get_history(processor_id=1)
        ```
    """

    endpoint = "ai_processors"
    model_class = AIProcessor

    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[AIProcessor, None, None]:
        """List all AI processors.

        Args:
            **filters: Optional filters including:
                - service_id: Filter by service
                - llm_model_id: Filter by LLM model
                - action_type: Filter by action type
                - active: Filter by active status
        """
        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[AIProcessor]:
        """Get AI processors as a list with filters."""
        return list(self.list(**filters))

    def get(self, id: int) -> AIProcessor:
        """Get a specific AI processor."""
        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]) -> AIProcessor:
        """Create a new AI processor."""
        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) -> AIProcessor:
        """Update an AI processor."""
        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 processor."""
        url = self._build_external_url(f"{self.endpoint}/{id}")
        response = self.client.auth.delete(url)
        return self.client._handle_response(response, self.endpoint)

    def get_history(self, processor_id: int) -> List[AIProcessorHistory]:
        """Get execution history for a processor.

        Args:
            processor_id: ID of the processor

        Returns:
            List of processor history records
        """
        url = self._build_external_url(f"{self.endpoint}/{processor_id}/history")
        response = self.client.auth.get(url)
        data = self.client._handle_response(response, self.endpoint)
        if isinstance(data, list):
            return [AIProcessorHistory(item) for item in data]
        elif "results" in data:
            return [AIProcessorHistory(item) for item in data["results"]]
        return [AIProcessorHistory(data)]

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

    def get_active(self) -> List[AIProcessor]:
        """Get all active processors."""
        return self.filter(active=True)
