"""MetadataValues resource client for V1."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any, List

from concentriq.models.v1.filters import MetadataValueFilters

if TYPE_CHECKING:
    from concentriq.client import ConcentriqClient


class MetadataValues:
    """Client for metadata values (/api/metadata-values)."""

    def __init__(self, client: "ConcentriqClient"):
        """Initialize with client instance.

        Args:
            client: ConcentriqClient instance
        """
        self._client = client
        self._base_path = "/api/metadata-values"

    def list(self, filters: MetadataValueFilters | None = None) -> list[dict[str, Any]]:
        """List metadata values with filters.

        Args:
            filters: Filter criteria (MetadataValueFilters model)

        Returns:
            List of metadata value dictionaries

        Raises:
            AuthenticationError: If not authenticated

        Example:
            filters = MetadataValueFilters(imageSetId=[1, 2], imageId=[100])
            values = client.v1.metadata_values.list(filters=filters)
            for value in values:
                print(f"Field {value['fieldId']}: {value['content']}")
        """
        params = {}

        if filters is not None:
            params["filters"] = filters.model_dump_json(exclude_none=True)

        response = self._client._request("GET", self._base_path, params=params)
        data = response.json()

        # V1 API returns data in envelope format
        return data.get("data", [])

    def update(self, values: List[dict[str, Any]]) -> None:
        """Update metadata values in batch.

        Args:
            values: List of metadata value objects with fieldId, resourceId, content

        Returns:
            None

        Raises:
            AuthenticationError: If not authenticated
            ValidationError: If data is invalid

        Example:
            client.v1.metadata_values.update([
                {"fieldId": 1, "resourceId": 100, "content": "Patient A"},
                {"fieldId": 2, "resourceId": 100, "content": 42}
            ])
        """
        self._client._request(
            "PATCH", self._base_path, json={"metadataValues": values}
        )
        # PATCH returns empty data object, no need to return anything
