"""
设备类型相关的Pydantic Schema
"""
from typing import Optional, List, Dict, Any
from datetime import datetime
from pydantic import BaseModel, Field, field_validator


# ===== 设备类型Schema =====

class DeviceTypeBase(BaseModel):
    """设备类型基础Schema"""
    type_code: str = Field(..., min_length=1, max_length=50, description="设备类型代码")
    type_name: str = Field(..., min_length=1, max_length=200, description="设备类型名称")
    category: Optional[str] = Field(None, max_length=50, description="设备分类")
    description: Optional[str] = Field(None, description="描述")
    icon: Optional[str] = Field(None, max_length=100, description="图标名称")
    sort_order: int = Field(default=0, description="排序")


class DeviceTypeCreate(DeviceTypeBase):
    """创建设备类型Schema"""
    pass


class DeviceTypeUpdate(BaseModel):
    """更新设备类型Schema"""
    type_name: Optional[str] = Field(None, min_length=1, max_length=200)
    category: Optional[str] = Field(None, max_length=50)
    description: Optional[str] = None
    icon: Optional[str] = Field(None, max_length=100)
    status: Optional[str] = Field(None, pattern="^(active|inactive)$")
    sort_order: Optional[int] = None


class DeviceTypeInDB(BaseModel):
    """数据库中的设备类型Schema"""
    id: int
    type_code: str
    type_name: str
    category: Optional[str]
    description: Optional[str]
    icon: Optional[str]
    status: str
    sort_order: int
    created_at: datetime
    updated_at: datetime

    class Config:
        from_attributes = True


class DeviceTypeResponse(DeviceTypeInDB):
    """设备类型响应Schema"""
    field_count: int = Field(default=0, description="字段数量")

    class Config:
        from_attributes = True


class DeviceTypeWithFields(DeviceTypeResponse):
    """带字段列表的设备类型响应Schema"""
    fields: List["DeviceTypeFieldResponse"] = Field(default_factory=list, description="字段列表")

    class Config:
        from_attributes = True


# ===== 设备类型字段Schema =====

class DeviceTypeFieldBase(BaseModel):
    """设备类型字段基础Schema"""
    field_code: str = Field(..., min_length=1, max_length=50, description="字段代码")
    field_name: str = Field(..., min_length=1, max_length=100, description="字段名称")
    field_type: str = Field(..., pattern="^(text|number|date|select|multiselect|boolean|textarea)$", description="字段类型")
    is_required: bool = Field(default=False, description="是否必填")
    default_value: Optional[str] = Field(None, description="默认值")
    placeholder: Optional[str] = Field(None, max_length=200, description="占位符")
    help_text: Optional[str] = Field(None, description="帮助文本")
    sort_order: int = Field(default=0, description="排序")


class DeviceTypeFieldCreate(DeviceTypeFieldBase):
    """创建设备类型字段Schema"""
    options: Optional[List[Dict[str, Any]]] = Field(None, description="选项列表（用于select/multiselect类型）")
    validation_rules: Optional[Dict[str, Any]] = Field(None, description="验证规则")

    @field_validator("field_type")
    @classmethod
    def validate_field_type(cls, v: str) -> str:
        """验证字段类型"""
        valid_types = ["text", "number", "date", "select", "multiselect", "boolean", "textarea"]
        if v not in valid_types:
            raise ValueError(f"字段类型必须是以下之一: {', '.join(valid_types)}")
        return v


class DeviceTypeFieldUpdate(BaseModel):
    """更新设备类型字段Schema"""
    field_name: Optional[str] = Field(None, min_length=1, max_length=100)
    field_type: Optional[str] = Field(None, pattern="^(text|number|date|select|multiselect|boolean|textarea)$")
    is_required: Optional[bool] = None
    default_value: Optional[str] = None
    options: Optional[List[Dict[str, Any]]] = None
    validation_rules: Optional[Dict[str, Any]] = None
    placeholder: Optional[str] = Field(None, max_length=200)
    help_text: Optional[str] = None
    status: Optional[str] = Field(None, pattern="^(active|inactive)$")
    sort_order: Optional[int] = None


class DeviceTypeFieldInDB(BaseModel):
    """数据库中的设备类型字段Schema"""
    id: int
    device_type_id: int
    field_code: str
    field_name: str
    field_type: str
    is_required: bool
    default_value: Optional[str]
    options: Optional[List[Dict[str, Any]]]
    validation_rules: Optional[Dict[str, Any]]
    placeholder: Optional[str]
    help_text: Optional[str]
    sort_order: int
    status: str
    created_at: datetime
    updated_at: datetime

    class Config:
        from_attributes = True


class DeviceTypeFieldResponse(DeviceTypeFieldInDB):
    """设备类型字段响应Schema"""
    pass


# ===== 查询参数Schema =====

class DeviceTypeQueryParams(BaseModel):
    """设备类型查询参数"""
    category: Optional[str] = Field(None, description="设备分类")
    status: Optional[str] = Field(None, pattern="^(active|inactive)$", description="状态")
    keyword: Optional[str] = Field(None, description="搜索关键词")
    page: int = Field(default=1, ge=1, description="页码")
    page_size: int = Field(default=20, ge=1, le=100, description="每页数量")


# 更新前向引用
DeviceTypeWithFields.model_rebuild()

