"""Flows resource for Worqhat SDK."""

from typing import TYPE_CHECKING, Optional, Dict, Any, BinaryIO, Union

if TYPE_CHECKING:
    from ..http_client import HTTPClient


class FlowsResource:
    """Workflow operations resource."""

    def __init__(self, client: "HTTPClient"):
        """Initialize the flows resource."""
        self._client = client

    def trigger(self, flow_id: str, input_data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """
        Trigger a workflow by ID.

        Args:
            flow_id: Workflow ID.
            input_data: Input data for the workflow.

        Returns:
            Workflow response.
        """
        return self._client.post(f"/api/flows/trigger/{flow_id}", json=input_data or {})

    def trigger_with_file(
        self,
        flow_id: str,
        file: Optional[Union[BinaryIO, bytes]] = None,
        url: Optional[str] = None,
        data: Optional[Dict[str, Any]] = None,
        **kwargs: Any,
    ) -> Dict[str, Any]:
        """
        Trigger a workflow with a file upload or URL.

        Args:
            flow_id: Workflow ID.
            file: File object or bytes to upload.
            url: URL to download file from.
            data: Additional data for the workflow.
            **kwargs: Additional form fields.

        Returns:
            Workflow response.
        """
        files = {}
        form_data: Dict[str, Any] = {}

        if file:
            files["file"] = file

        if url:
            form_data["url"] = url

        if data:
            import json

            form_data["data"] = json.dumps(data)

        # Add any additional fields
        form_data.update(kwargs)

        return self._client.post(f"/api/flows/file/{flow_id}", data=form_data, files=files or None)

    def get_metrics(
        self,
        start_date: Optional[str] = None,
        end_date: Optional[str] = None,
        status: Optional[str] = None,
    ) -> Dict[str, Any]:
        """
        Retrieve workflow metrics from analytics.

        Args:
            start_date: Start date (YYYY-MM-DD).
            end_date: End date (YYYY-MM-DD).
            status: Filter by status ('completed', 'failed', 'in_progress').

        Returns:
            Workflow metrics and analytics.
        """
        params: Dict[str, str] = {}

        if start_date:
            params["start_date"] = start_date
        if end_date:
            params["end_date"] = end_date
        if status:
            params["status"] = status

        return self._client.get("/api/flows/metrics", params=params or None)
