"""Pipeline 数据模型"""

from enum import Enum
from typing import Any

from pydantic import BaseModel, Field

from agentkit.orchestrator.retry import StepRetryPolicy


class StageStatus(str, Enum):
    PENDING = "pending"
    RUNNING = "running"
    COMPLETED = "completed"
    FAILED = "failed"
    SKIPPED = "skipped"


class ReviewIssue(BaseModel):
    """单条审查问题"""
    severity: str = Field(description="问题严重程度: critical/major/minor")
    category: str = Field(description="问题类别: logic_error/security/style/test_failure/architecture")
    description: str = Field(description="问题描述")
    location: str | None = Field(default=None, description="文件路径/行号")
    suggestion: str | None = Field(default=None, description="修复建议")


class ReviewFeedback(BaseModel):
    """Verifier 返回的结构化审查反馈"""
    passed: bool = Field(description="是否通过审查")
    issues: list[ReviewIssue] = Field(default_factory=list, description="问题列表")
    summary: str = Field(description="自然语言审查报告")
    score: float = Field(description="质量评分 (0-1)")


class AdversarialState(BaseModel):
    """对抗轮次状态追踪"""
    current_round: int = Field(default=0, description="当前对抗轮次")
    max_rounds: int = Field(default=3, description="最大对抗轮次")
    feedback_history: list[ReviewFeedback] = Field(default_factory=list, description="反馈历史")
    last_feedback: ReviewFeedback | None = Field(default=None, description="最后一次反馈")


class PipelineStage(BaseModel):
    name: str
    agent: str
    action: str
    depends_on: list[str] = []
    inputs: dict[str, Any] = {}
    outputs: list[str] = []
    timeout_seconds: int = 300
    retry_count: int = 0
    continue_on_failure: bool = False
    condition: str | None = None
    retry_policy: StepRetryPolicy | None = None
    compensate: str | None = None
    
    # 对抗闭环相关字段
    verifier: str | None = Field(default=None, description="Verifier Agent 名称，配置后启用对抗模式")
    max_adversarial_rounds: int = Field(default=3, description="最大对抗轮次")
    feedback_mode: str = Field(default="structured+natural", description="反馈模式: structured+natural / structured / natural")
    escalate_on_exhaust: str | None = Field(default=None, description="对抗轮次耗尽后的升级目标")

    model_config = {"arbitrary_types_allowed": True}


class Pipeline(BaseModel):
    name: str
    version: str
    description: str
    stages: list[PipelineStage]
    variables: dict[str, Any] = {}


class StageResult(BaseModel):
    stage_name: str
    status: StageStatus = StageStatus.PENDING
    output_data: dict[str, Any] | None = None
    error_message: str | None = None
    started_at: str | None = None
    completed_at: str | None = None


class PipelineResult(BaseModel):
    pipeline_name: str
    status: StageStatus = StageStatus.PENDING
    stage_results: dict[str, StageResult] = {}
    variables: dict[str, Any] = {}
    error_message: str | None = None
    metadata: dict[str, Any] = {}


class AdaptiveConfig(BaseModel):
    """Configuration for adaptive pipeline execution with reflection-replanning."""

    enabled: bool = False
    max_reflections: int = 3
    reflection_model: str = "default"
    skip_stages: list[str] = []

    model_config = {"arbitrary_types_allowed": True}


class ReflectionReport(BaseModel):
    """Structured report from pipeline reflection analysis."""

    failure_type: str  # input_error, resource_error, logic_error, timeout
    root_cause: str
    suggested_fix: str
    failed_stage: str
    reflection_number: int = 1
