"""Workflows resource client for V1."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from concentriq.client import ConcentriqClient


class Workflows:
    """Client for Workflow resources (/api/workflows).

    Workflows are finite state machines for defining special states of an ImageSet.
    - Workflow: Container for stages
    - Stage: State in the workflow with specific semantics
    - Action: Transition between stages (with associated functions)
    """

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

        Args:
            client: ConcentriqClient instance
        """
        self._client = client
        self._base_path = "/api/workflows"

    def list(
        self,
        organization_id: int | None = None,
        group_id: int | None = None,
    ) -> list[dict[str, Any]]:
        """List all workflows with nested stages and actions.

        Args:
            organization_id: Filter by organization ID (optional)
            group_id: Filter by group ID (optional)

        Returns:
            List of workflow dictionaries with nested stages and actions

        Raises:
            AuthenticationError: If not authenticated

        Example:
            workflows = client.v1.workflows.list()
            for workflow in workflows:
                print(f"Workflow: {workflow['name']}")
                for stage in workflow['stages']:
                    print(f"  Stage: {stage['name']}")
                    for action in stage['actions']:
                        print(f"    Action: {action['name']} -> Stage {action['targetStageId']}")

            # Filter by organization
            org_workflows = client.v1.workflows.list(organization_id=5)
        """
        params = {}
        if organization_id is not None:
            params["organizationId"] = organization_id
        if group_id is not None:
            params["groupId"] = group_id

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

        # V1 API returns workflows as array with nested stages and actions
        return data.get("data", {}).get("workflows", [])

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

        Note: Requires admin privileges and canManageWorkflows permission.

        Args:
            data: Workflow data
                - name: Workflow name (required)
                - groups: List of group IDs that use the workflow (optional)

        Returns:
            Created workflow dictionary with id and name

        Raises:
            AuthenticationError: If not authenticated
            AuthorizationError: If not admin or lacking canManageWorkflows permission
            ValidationError: If data is invalid

        Example:
            workflow = client.v1.workflows.create({
                "name": "Clinical Workflow",
                "groups": [1, 2, 3]
            })
            print(f"Created workflow {workflow['id']}: {workflow['name']}")
        """
        response = self._client._request("POST", self._base_path, json=data)
        result = response.json()

        # V1 API returns minimal data on create (id, name)
        return result.get("data", {})

    def update(self, id: int, data: dict[str, Any]) -> dict[str, Any]:
        """Update an existing workflow.

        Note: Requires admin privileges and canManageWorkflows permission.

        Args:
            id: Workflow ID
            data: Updated workflow data
                - name: Workflow name (optional)
                - groups: List of group IDs that use the workflow (optional)

        Returns:
            Updated workflow dictionary

        Raises:
            AuthenticationError: If not authenticated
            AuthorizationError: If not admin or lacking canManageWorkflows permission
            NotFoundError: If workflow not found
            ValidationError: If data is invalid

        Example:
            updated = client.v1.workflows.update(123, {
                "name": "Updated Workflow",
                "groups": [1, 2, 3, 4]
            })
        """
        response = self._client._request("PATCH", f"{self._base_path}/{id}", json=data)
        result = response.json()

        # V1 API returns updated workflow data
        return result.get("data", {})

    def delete(self, id: int) -> None:
        """Delete a workflow.

        Note: Requires admin privileges and canManageWorkflows permission.

        Args:
            id: Workflow ID

        Returns:
            None (backend returns success message)

        Raises:
            AuthenticationError: If not authenticated
            AuthorizationError: If not admin or lacking canManageWorkflows permission
            NotFoundError: If workflow not found

        Example:
            client.v1.workflows.delete(123)
        """
        self._client._request("DELETE", f"{self._base_path}/{id}")
        # DELETE returns success message, no need to return anything
