"""Workflow models for the Danube SDK."""

from typing import Any, Dict, List, Optional

from pydantic import BaseModel, Field


class WorkflowStep(BaseModel):
    """A single step in a workflow."""

    step_number: int
    tool_id: str
    tool_name: str = ""
    description: str = ""
    input_mapping: Dict[str, Any] = Field(default_factory=dict)


class Workflow(BaseModel):
    """A workflow summary returned from listing endpoints."""

    id: str
    name: str
    description: Optional[str] = None
    step_count: int = 0
    owner_id: str = ""
    visibility: str = "public"
    tags: List[str] = Field(default_factory=list)
    total_executions: int = 0
    success_rate: Optional[float] = None
    created_at: Optional[str] = None

    @classmethod
    def from_api_response(cls, data: Dict[str, Any]) -> "Workflow":
        return cls(
            id=data.get("id", ""),
            name=data.get("name", ""),
            description=data.get("description"),
            step_count=data.get("step_count", len(data.get("steps", []))),
            owner_id=data.get("owner_id", ""),
            visibility=data.get("visibility", "public"),
            tags=data.get("tags", []),
            total_executions=data.get("total_executions", 0),
            success_rate=data.get("success_rate"),
            created_at=data.get("created_at"),
        )


class WorkflowDetail(BaseModel):
    """Full workflow detail with steps."""

    id: str
    name: str
    description: Optional[str] = None
    steps: List[WorkflowStep] = Field(default_factory=list)
    owner_id: str = ""
    visibility: str = "public"
    tags: List[str] = Field(default_factory=list)
    created_at: Optional[str] = None
    updated_at: Optional[str] = None

    @classmethod
    def from_api_response(cls, data: Dict[str, Any]) -> "WorkflowDetail":
        steps = [
            WorkflowStep(**s) if isinstance(s, dict) else s
            for s in data.get("steps", [])
        ]
        return cls(
            id=data.get("id", ""),
            name=data.get("name", ""),
            description=data.get("description"),
            steps=steps,
            owner_id=data.get("owner_id", ""),
            visibility=data.get("visibility", "public"),
            tags=data.get("tags", []),
            created_at=data.get("created_at"),
            updated_at=data.get("updated_at"),
        )


class WorkflowCreateStep(BaseModel):
    """A step definition for creating a workflow."""

    step_number: int
    tool_id: str
    tool_name: str = ""
    description: str = ""
    input_mapping: Dict[str, Any] = Field(default_factory=dict)


class WorkflowCreateRequest(BaseModel):
    """Request body for creating a workflow."""

    name: str
    description: str = ""
    steps: List[WorkflowCreateStep] = Field(default_factory=list)
    visibility: str = "private"
    tags: List[str] = Field(default_factory=list)


class WorkflowStepResult(BaseModel):
    """Result from a single step execution."""

    step_number: int
    tool_id: str
    tool_name: str = ""
    status: str = "pending"
    result: Optional[Any] = None
    error: Optional[str] = None
    execution_time_ms: Optional[int] = None


class WorkflowExecution(BaseModel):
    """Full workflow execution result."""

    id: str
    workflow_id: str
    user_id: str = ""
    status: str = "pending"
    inputs: Dict[str, Any] = Field(default_factory=dict)
    step_results: List[WorkflowStepResult] = Field(default_factory=list)
    error: Optional[str] = None
    execution_time_ms: Optional[int] = None
    started_at: Optional[str] = None
    completed_at: Optional[str] = None
    created_at: Optional[str] = None

    @classmethod
    def from_api_response(cls, data: Dict[str, Any]) -> "WorkflowExecution":
        step_results = [
            WorkflowStepResult(**sr) if isinstance(sr, dict) else sr
            for sr in data.get("step_results", [])
        ]
        return cls(
            id=data.get("id", ""),
            workflow_id=data.get("workflow_id", ""),
            user_id=data.get("user_id", ""),
            status=data.get("status", "pending"),
            inputs=data.get("inputs", {}),
            step_results=step_results,
            error=data.get("error"),
            execution_time_ms=data.get("execution_time_ms"),
            started_at=data.get("started_at"),
            completed_at=data.get("completed_at"),
            created_at=data.get("created_at"),
        )
