"""Orders resource client for V1."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from concentriq.client import ConcentriqClient


class Orders:
    """Client for Order resources (/api/orders and /api/stains).

    Orders represent requests for staining or re-cutting tissue samples.
    - Stain Orders: Request specific immunohistochemistry stains (Ki-67, HER2, etc.)
    - Recut Orders: Request re-cutting of tissue blocks with specified layers
    """

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

        Args:
            client: ConcentriqClient instance
        """
        self._client = client
        self._base_path = "/api/orders"
        self._stains_path = "/api/stains"

    def list_stains(self) -> dict[str, str]:
        """List all available stains for ordering.

        Returns:
            Dictionary mapping stain IDs (as strings) to stain names

        Raises:
            AuthenticationError: If not authenticated

        Example:
            stains = client.v1.orders.list_stains()
            for stain_id, stain_name in stains.items():
                print(f"{stain_id}: {stain_name}")
            # Output: "1: Ki-67", "2: HER2", "3: ER", etc.
        """
        response = self._client._request("GET", self._stains_path)
        data = response.json()

        # V1 API returns stains as keyed object: {"1": "Ki-67", "2": "HER2", ...}
        return data.get("data", {}).get("stains", {})

    def list(
        self,
        image_set_id: int | None = None,
        image_id: int | None = None,
        not_completed: bool | None = None,
    ) -> list[dict[str, Any]]:
        """List all orders with optional filters.

        Args:
            image_set_id: Filter orders by image set ID (optional)
            image_id: Filter orders by image ID (optional)
            not_completed: Filter by completion status - True for incomplete orders (optional)

        Returns:
            List of order dictionaries with nested stain data and signed URLs

        Raises:
            AuthenticationError: If not authenticated

        Example:
            # Get all orders
            orders = client.v1.orders.list()

            # Get incomplete orders for a specific image
            pending = client.v1.orders.list(image_id=100, not_completed=True)

            for order in orders:
                print(f"Order {order['id']} for image {order['imageId']}")
                if order['isRecut']:
                    print(f"  Recut with {order['layers']} layers")
                else:
                    print(f"  Stains: {[s['name'] for s in order['stains']]}")
                print(f"  Thumbnail: {order['slideThumb']}")
        """
        params: dict[str, Any] = {}
        if image_set_id is not None:
            params["imageSetId"] = image_set_id
        if image_id is not None:
            params["imageId"] = image_id
        if not_completed is not None:
            params["notCompleted"] = str(not_completed).lower()

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

        # V1 API returns orders as array with nested stains and signed URLs
        return data.get("data", {}).get("orders", [])

    def create(self, data: dict[str, Any]) -> dict[str, Any]:
        """Create a new stain order or recut order.

        Args:
            data: Order data
                For stain orders:
                - imageId: Image ID (required)
                - stains: List of stain IDs (required for stain orders)
                - comments: Additional comments (optional)

                For recut orders:
                - imageId: Image ID (required)
                - layers: Number of layers to recut (required for recut, mutually exclusive with stains)
                - comments: Additional comments (optional)

        Returns:
            Created order dictionary

        Raises:
            AuthenticationError: If not authenticated
            NotFoundError: If image not found
            ValidationError: If data is invalid

        Example:
            # Create stain order
            stain_order = client.v1.orders.create({
                "imageId": 100,
                "stains": [1, 2, 3],  # Ki-67, HER2, ER
                "comments": "Urgent stain request"
            })

            # Create recut order
            recut_order = client.v1.orders.create({
                "imageId": 101,
                "layers": 5,
                "comments": "Recut needed for analysis"
            })

            print(f"Order {stain_order['id']} created")
            print(f"Is recut: {stain_order['isRecut']}")
        """
        response = self._client._request("POST", self._base_path, json=data)
        result = response.json()

        # V1 API returns created order data
        return result.get("data", {}).get("orders", {})
