"""
异步任务模型

用于管理 AI 生成等耗时任务的进度和状态
"""
from pydantic import BaseModel, Field
from typing import Optional, Dict, Any, List
from datetime import datetime
from enum import Enum


class TaskStatus(str, Enum):
    """任务状态枚举"""
    PENDING = "pending"          # 等待执行
    RUNNING = "running"          # 执行中
    COMPLETED = "completed"      # 完成
    FAILED = "failed"            # 失败
    CANCELLED = "cancelled"      # 已取消


class TaskType(str, Enum):
    """任务类型枚举"""
    GENERATE_CHARACTERS = "generate_characters"
    GENERATE_OUTLINE = "generate_outline"
    GENERATE_WORLD = "generate_world"
    ANALYZE_SCRIPT = "analyze_script"
    WORLD_FROM_SCRIPT = "world_from_script"
    GENERATE_ALL = "generate_all"
    EPISODE_CREATE = "episode_create"
    GENERATE_SKILL = "generate_skill"


class TaskProgress(BaseModel):
    """任务进度"""
    current: int = Field(0, description="当前进度")
    total: int = Field(100, description="总进度")
    message: str = Field("", description="进度消息")
    stage: Optional[str] = Field(None, description="当前阶段")


class AsyncTask(BaseModel):
    """异步任务"""
    id: str
    type: TaskType
    status: TaskStatus = TaskStatus.PENDING
    progress: TaskProgress = Field(default_factory=TaskProgress)

    # 任务参数
    params: Dict[str, Any] = Field(default_factory=dict)

    # 任务结果
    result: Optional[Dict[str, Any]] = None
    error: Optional[str] = None

    # 关联信息
    project_id: Optional[str] = None

    # 时间戳
    created_at: datetime = Field(default_factory=datetime.now)
    started_at: Optional[datetime] = None
    completed_at: Optional[datetime] = None
    updated_at: datetime = Field(default_factory=datetime.now)


class TaskCreateRequest(BaseModel):
    """创建任务请求"""
    type: TaskType
    params: Dict[str, Any] = Field(default_factory=dict)
    project_id: Optional[str] = None


class TaskResponse(BaseModel):
    """任务响应"""
    id: str = Field(serialization_alias="taskId")
    type: TaskType
    status: TaskStatus
    progress: TaskProgress
    params: Dict[str, Any] = Field(default_factory=dict)
    result: Optional[Dict[str, Any]] = None
    error: Optional[str] = None
    project_id: Optional[str] = None
    created_at: datetime
    updated_at: datetime
