"""Pack Service Profiles 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.pack_profile import PackServiceProfile

if TYPE_CHECKING:
    from netorca_sdk.v2.client import NetOrcaClient


class PackProfilesResource(BaseResource):
    """
    Pack Service Profiles resource.

    Provides access to AI pack profile management for services.

    Example:
        ```python
        # List all profiles
        for profile in client.pack_profiles.list():
            print(profile.service_id, profile.config)

        # Create a profile for a service
        profile = client.pack_profiles.create_for_service(
            service_id=123,
            data={"config": {"key": "value"}}
        )

        # Get config for a service
        config = client.pack_profiles.get_service_config(service_id=123)
        ```
    """

    endpoint = "pack/profiles"
    model_class = PackServiceProfile

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

    def list(self, **filters) -> Generator[PackServiceProfile, None, None]:
        """List all pack profiles."""
        url = self._build_ai_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[PackServiceProfile]:
        """Get pack profiles as a list with filters."""
        return list(self.list(**filters))

    def get(self, id: int) -> PackServiceProfile:
        """Get a specific pack profile."""
        url = self._build_ai_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]) -> PackServiceProfile:
        """Create a new pack profile."""
        url = self._build_ai_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) -> PackServiceProfile:
        """Update a pack profile."""
        url = self._build_ai_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 a pack profile."""
        url = self._build_ai_url(f"{self.endpoint}/{id}")
        response = self.client.auth.delete(url)
        return self.client._handle_response(response, self.endpoint)

    def create_for_service(self, service_id: int, data: Optional[Dict[str, Any]] = None) -> PackServiceProfile:
        """Create a profile for a specific service."""
        url = self._build_ai_url(f"{self.endpoint}/service/{service_id}")
        response = self.client.auth.post(url, data=data or {})
        result = self.client._handle_response(response, self.endpoint)
        return self._to_model(result)

    def update_for_service(self, service_id: int, data: Dict[str, Any], partial: bool = True) -> PackServiceProfile:
        """Update profile for a specific service."""
        url = self._build_ai_url(f"{self.endpoint}/service/{service_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 get_service_config(self, service_id: int) -> Dict[str, Any]:
        """Get configuration for a specific service.

        Args:
            service_id: ID of the service

        Returns:
            Service configuration dict
        """
        url = self._build_ai_url(f"{self.endpoint}/service/{service_id}/config")
        response = self.client.auth.get(url)
        return self.client._handle_response(response, self.endpoint)

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