"""Pipeline 数据模型 - Harness风格YAML编排的数据结构定义"""

from enum import Enum
from typing import Any, Optional

from pydantic import BaseModel, Field


class StageStatus(str, Enum):
    """阶段执行状态"""
    PENDING = "pending"
    RUNNING = "running"
    COMPLETED = "completed"
    FAILED = "failed"
    SKIPPED = "skipped"


class PipelineStage(BaseModel):
    """Pipeline中的单个阶段定义"""
    name: str = Field(..., description="阶段名称，在Pipeline内唯一")
    agent: str = Field(..., description="执行此阶段的Agent名称，对应registry中的agent")
    action: str = Field(..., description="Agent要执行的动作类型")
    depends_on: list[str] = Field(
        default_factory=list,
        description="依赖的前置stage名称列表",
    )
    inputs: dict[str, Any] = Field(
        default_factory=dict,
        description="输入参数，支持${var}变量引用",
    )
    outputs: list[str] = Field(
        default_factory=list,
        description="输出变量名列表",
    )
    timeout_seconds: int = Field(
        default=300,
        description="超时时间（秒）",
    )
    retry_count: int = Field(
        default=0,
        description="失败后重试次数",
    )
    continue_on_failure: bool = Field(
        default=False,
        description="失败后是否继续执行下游阶段",
    )
    condition: Optional[str] = Field(
        default=None,
        description="条件执行表达式，为None或空字符串时无条件执行",
    )


class Pipeline(BaseModel):
    """Pipeline完整定义 - 对应一个YAML文件"""
    name: str = Field(..., description="Pipeline名称")
    version: str = Field(default="1.0", description="Pipeline版本")
    description: str = Field(default="", description="Pipeline描述")
    stages: list[PipelineStage] = Field(
        default_factory=list,
        description="阶段列表",
    )
    variables: dict[str, Any] = Field(
        default_factory=dict,
        description="全局变量/默认值",
    )


class StageResult(BaseModel):
    """单个阶段的执行结果"""
    stage_name: str = Field(..., description="阶段名称")
    status: StageStatus = Field(..., description="执行状态")
    outputs: dict[str, Any] = Field(
        default_factory=dict,
        description="阶段输出数据",
    )
    error: Optional[str] = Field(
        default=None,
        description="错误信息",
    )
    duration_ms: int = Field(
        default=0,
        description="执行耗时（毫秒）",
    )


class PipelineResult(BaseModel):
    """Pipeline完整执行结果"""
    pipeline_name: str = Field(..., description="Pipeline名称")
    status: StageStatus = Field(..., description="整体执行状态")
    stages_results: dict[str, StageResult] = Field(
        default_factory=dict,
        description="各阶段执行结果，key为stage名称",
    )
    duration_ms: int = Field(
        default=0,
        description="总执行耗时（毫秒）",
    )
    error: Optional[str] = Field(
        default=None,
        description="整体错误信息",
    )
