# =============================================================================
# 企微IT智能服务台 — 待办事项 Pydantic Schema
# =============================================================================
# 说明：定义待办事项的 CRUD 数据结构
# 包含：创建、更新、响应 Schema
# =============================================================================

from datetime import datetime
from typing import Any, Dict, List, Optional

from pydantic import BaseModel, Field, field_validator


# --------------------------------------------------------------------------
# 待办类型和优先级的合法值
# --------------------------------------------------------------------------
VALID_TODO_TYPES = {"ticket", "approval", "device"}
VALID_TODO_PRIORITIES = {"urgent", "high", "normal"}
VALID_TODO_STATUSES = {"pending", "processing", "resolved"}


# --------------------------------------------------------------------------
# 创建待办事项 Schema
# --------------------------------------------------------------------------
class TodoItemCreate(BaseModel):
    """创建待办事项请求 Schema。

    Attributes:
        type: 待办类型（ticket/approval/device）
        title: 待办标题
        priority: 优先级（urgent/high/normal）
        description: 详细描述（JSON）
        assigned_agent_id: 分配的坐席ID（可选）
        corp_id: 企业微信企业ID
    """

    type: str = Field(default="ticket", description="待办类型: ticket/approval/device")
    title: str = Field(..., min_length=1, max_length=256, description="待办标题")
    priority: str = Field(default="normal", description="优先级: urgent/high/normal")
    description: Dict[str, Any] = Field(default_factory=dict, description="详细描述")
    assigned_agent_id: Optional[str] = Field(None, max_length=64, description="分配的坐席ID")
    corp_id: str = Field(default="", max_length=64, description="企业微信企业ID")

    @field_validator("type")
    @classmethod
    def validate_type(cls, v: str) -> str:
        """校验待办类型是否合法。"""
        if v not in VALID_TODO_TYPES:
            raise ValueError(f"无效的待办类型: {v}，合法值为: {VALID_TODO_TYPES}")
        return v

    @field_validator("priority")
    @classmethod
    def validate_priority(cls, v: str) -> str:
        """校验优先级是否合法。"""
        if v not in VALID_TODO_PRIORITIES:
            raise ValueError(f"无效的优先级: {v}，合法值为: {VALID_TODO_PRIORITIES}")
        return v


# --------------------------------------------------------------------------
# 更新待办事项 Schema
# --------------------------------------------------------------------------
class TodoItemUpdate(BaseModel):
    """更新待办事项请求 Schema。

    所有字段可选，只更新传入的字段。

    Attributes:
        type: 待办类型
        title: 待办标题
        priority: 优先级
        description: 详细描述
        status: 状态
        assigned_agent_id: 分配的坐席ID
    """

    type: Optional[str] = Field(None, description="待办类型: ticket/approval/device")
    title: Optional[str] = Field(None, max_length=256, description="待办标题")
    priority: Optional[str] = Field(None, description="优先级: urgent/high/normal")
    description: Optional[Dict[str, Any]] = Field(None, description="详细描述")
    status: Optional[str] = Field(None, description="状态: pending/processing/resolved")
    assigned_agent_id: Optional[str] = Field(None, max_length=64, description="分配的坐席ID")

    @field_validator("type")
    @classmethod
    def validate_type(cls, v: Optional[str]) -> Optional[str]:
        """校验待办类型是否合法。"""
        if v is not None and v not in VALID_TODO_TYPES:
            raise ValueError(f"无效的待办类型: {v}，合法值为: {VALID_TODO_TYPES}")
        return v

    @field_validator("priority")
    @classmethod
    def validate_priority(cls, v: Optional[str]) -> Optional[str]:
        """校验优先级是否合法。"""
        if v is not None and v not in VALID_TODO_PRIORITIES:
            raise ValueError(f"无效的优先级: {v}，合法值为: {VALID_TODO_PRIORITIES}")
        return v

    @field_validator("status")
    @classmethod
    def validate_status(cls, v: Optional[str]) -> Optional[str]:
        """校验状态是否合法。"""
        if v is not None and v not in VALID_TODO_STATUSES:
            raise ValueError(f"无效的状态: {v}，合法值为: {VALID_TODO_STATUSES}")
        return v


# --------------------------------------------------------------------------
# 待办事项响应 Schema
# --------------------------------------------------------------------------
class TodoItemResponse(BaseModel):
    """待办事项响应 Schema。

    返回给前端的待办事项数据结构。
    使用 from_attributes=True 支持从 SQLAlchemy 模型直接转换。

    Attributes:
        id: 待办唯一标识
        type: 待办类型
        title: 待办标题
        priority: 优先级
        description: 详细描述
        status: 状态
        assigned_agent_id: 分配的坐席ID
        corp_id: 企业微信企业ID
        created_at: 创建时间
        updated_at: 更新时间
    """

    id: str
    type: str
    title: str
    priority: str
    description: Dict[str, Any]
    status: str
    assigned_agent_id: Optional[str] = None
    corp_id: str
    created_at: datetime
    updated_at: datetime

    model_config = {"from_attributes": True}


# --------------------------------------------------------------------------
# 待办事项列表响应 Schema
# --------------------------------------------------------------------------
class TodoItemListResponse(BaseModel):
    """待办事项列表响应 Schema。

    Attributes:
        items: 待办事项列表
        total: 总数
    """

    items: List[TodoItemResponse]
    total: int
