"""
AI 工作流 Schema
"""
from typing import Optional, List, Any
from datetime import datetime

from pydantic import BaseModel, Field, ConfigDict

from app.base_schema import CSTDatetime


class WorkflowCreate(BaseModel):
    """创建工作流"""
    application_id: Optional[str] = Field(None, description="所属应用ID")
    is_global: bool = Field(default=False, description="是否在子应用中可见")
    name: str = Field(..., max_length=100, description="工作流名称")
    code: str = Field(..., max_length=100, pattern=r"^[a-zA-Z][a-zA-Z0-9_]*$", description="工作流编码（字母开头，只能包含字母、数字和下划线）")
    workflow_type: str = Field(default="general", description="工作流类型: general/application/form/report/data_process/automation")
    description: str = Field(default="", description="描述")
    definition: dict = Field(default_factory=dict, description="工作流定义")
    input_variables: List[dict] = Field(default_factory=list, description="输入变量")
    output_variables: List[dict] = Field(default_factory=list, description="输出变量")


class WorkflowUpdate(BaseModel):
    """更新工作流"""
    application_id: Optional[str] = None
    is_global: Optional[bool] = None
    name: Optional[str] = None
    code: Optional[str] = Field(None, max_length=100, pattern=r"^[a-zA-Z][a-zA-Z0-9_]*$", description="工作流编码（字母开头，只能包含字母、数字和下划线）")
    workflow_type: Optional[str] = None
    description: Optional[str] = None
    definition: Optional[dict] = None
    input_variables: Optional[List[dict]] = None
    output_variables: Optional[List[dict]] = None


class WorkflowResponse(BaseModel):
    """工作流输出"""
    id: str
    application_id: Optional[str] = None
    is_global: bool = False
    name: str
    code: str
    workflow_type: str = "general"
    description: str = ""
    status: str = "draft"
    version: int = 1
    published_version: Optional[int] = None
    published_at: Optional[CSTDatetime] = None
    published_definition: Optional[dict] = None
    definition: dict = Field(default_factory=dict)
    input_variables: List[dict] = Field(default_factory=list)
    output_variables: List[dict] = Field(default_factory=list)
    run_count: int = 0
    success_count: int = 0
    sort: int = 0
    sys_create_datetime: Optional[CSTDatetime] = None
    sys_update_datetime: Optional[CSTDatetime] = None
    
    model_config = ConfigDict(from_attributes=True)


class WorkflowListResponse(BaseModel):
    """工作流列表输出"""
    id: str
    application_id: Optional[str] = None
    application_name: str = ""
    is_global: bool = False
    name: str
    code: str
    workflow_type: str = "general"
    description: str = ""
    status: str = "draft"
    version: int = 1
    run_count: int = 0
    success_count: int = 0
    sys_create_datetime: Optional[CSTDatetime] = None
    
    model_config = ConfigDict(from_attributes=True)


class WorkflowRunInput(BaseModel):
    """运行工作流"""
    inputs: dict = Field(default_factory=dict, description="输入数据")
    use_draft: bool = Field(default=False, description="是否使用草稿版本（编辑器调试用）")


class WorkflowResumeInput(BaseModel):
    """恢复工作流执行"""
    user_input: Any = Field(..., description="用户输入的值")


class WorkflowRunResponse(BaseModel):
    """工作流运行记录输出"""
    id: str
    workflow_id: str
    workflow_name: str = ""
    status: str = "pending"
    trigger_type: str = "api"
    use_draft: bool = False
    workflow_version: Optional[int] = None
    definition_snapshot: dict = Field(default_factory=dict)
    inputs: dict = Field(default_factory=dict)
    outputs: dict = Field(default_factory=dict)
    execution_log: List[dict] = Field(default_factory=list)
    current_node_id: str = ""
    waiting_config: dict = Field(default_factory=dict)
    error_message: str = ""
    total_tokens: int = 0
    total_steps: int = 0
    elapsed_time: int = 0
    started_at: Optional[CSTDatetime] = None
    completed_at: Optional[CSTDatetime] = None
    sys_create_datetime: Optional[CSTDatetime] = None
    
    model_config = ConfigDict(from_attributes=True)


class WorkflowRunListResponse(BaseModel):
    """工作流运行记录列表输出"""
    id: str
    workflow_id: str
    workflow_name: str = ""
    status: str = "pending"
    trigger_type: str = "api"
    total_steps: int = 0
    total_tokens: int = 0
    elapsed_time: int = 0
    error_message: str = ""
    started_at: Optional[CSTDatetime] = None
    completed_at: Optional[CSTDatetime] = None
    
    model_config = ConfigDict(from_attributes=True)


class WorkflowImportCheckIn(BaseModel):
    """工作流导入预检查请求"""
    code: str = Field(..., description="工作流编码")


class WorkflowImportCheckOut(BaseModel):
    """工作流导入预检查结果"""
    code_exists: bool = Field(..., description="工作流编码是否已存在")
    can_import: bool = Field(..., description="是否可以直接导入（编码不冲突）")


class WorkflowImportIn(BaseModel):
    """工作流配置导入"""
    application_id: Optional[str] = Field(None, description="所属应用ID")
    is_global: bool = Field(default=False, description="是否在子应用中可见")
    name: str = Field(..., description="工作流名称")
    code: str = Field(..., description="工作流编码")
    workflow_type: str = Field(default="general", description="工作流类型")
    description: str = Field(default="", description="描述")
    definition: dict = Field(default_factory=dict, description="工作流定义")
    input_variables: List[dict] = Field(default_factory=list, description="输入变量")
    output_variables: List[dict] = Field(default_factory=list, description="输出变量")


class NodeSchemaResponse(BaseModel):
    """节点 Schema 输出"""
    type: str
    name: str
    category: str = ""
    icon: str = ""
    description: str = ""
    inputs: List[dict] = Field(default_factory=list)
    outputs: List[dict] = Field(default_factory=list)
    supports_branches: bool = False
