"""
SystemFunction Schemas
系統功能明細 API 資料結構
"""
from typing import List, Optional
from pydantic import BaseModel, Field, field_validator
from datetime import datetime


class SystemFunctionBase(BaseModel):
    """系統功能基礎 Schema"""
    code: str = Field(..., max_length=200, description="系統功能代碼/功能英文名稱")
    upper_function_id: int = Field(0, description="上層功能代碼 (0為初始層)")
    name: str = Field(..., max_length=200, description="系統功能中文名稱")
    function_type: int = Field(..., description="系統功能類型 (1:node, 2:function)")
    order: int = Field(..., description="系統功能次序")
    function_icon: str = Field("", max_length=200, description="功能圖示")
    module_code: Optional[str] = Field(None, max_length=200, description="功能模組名稱")
    module_functions: List[str] = Field(default_factory=list, description="模組項目")
    description: str = Field("", description="說明 (富文本格式)")
    is_mana: bool = Field(True, description="系統管理")
    is_active: bool = Field(True, description="啟用")

    @field_validator('function_type')
    @classmethod
    def validate_function_type(cls, v):
        """驗證功能類型"""
        if v not in [1, 2]:
            raise ValueError('function_type 必須為 1 (node) 或 2 (function)')
        return v

    @field_validator('module_functions')
    @classmethod
    def validate_module_functions(cls, v):
        """驗證模組項目"""
        allowed_functions = ['View', 'Create', 'Read', 'Update', 'Delete', 'Print', 'File']
        for func in v:
            if func not in allowed_functions:
                raise ValueError(f'module_functions 只能包含: {", ".join(allowed_functions)}')
        return v

    @field_validator('upper_function_id')
    @classmethod
    def validate_upper_function_id(cls, v, values):
        """驗證上層功能代碼"""
        # upper_function_id 必須是 function_type=1 且 is_active=1 的功能, 或 0 (初始層)
        if v < 0:
            raise ValueError('upper_function_id 不能小於 0')
        return v


class SystemFunctionCreate(SystemFunctionBase):
    """系統功能建立 Schema"""
    edit_by: int = Field(..., description="資料建立者")

    @field_validator('module_code')
    @classmethod
    def validate_module_code_create(cls, v, info):
        """驗證 module_code (function_type=2 必填)"""
        function_type = info.data.get('function_type')
        if function_type == 2 and not v:
            raise ValueError('function_type=2 時, module_code 為必填')
        if function_type == 1 and v:
            raise ValueError('function_type=1 時, module_code 不能輸入')
        return v

    @field_validator('module_functions')
    @classmethod
    def validate_module_functions_create(cls, v, info):
        """驗證 module_functions (function_type=2 必填)"""
        function_type = info.data.get('function_type')
        if function_type == 2 and not v:
            raise ValueError('function_type=2 時, module_functions 為必填')
        return v


class SystemFunctionUpdate(BaseModel):
    """系統功能更新 Schema (部分更新)"""
    code: Optional[str] = Field(None, max_length=200)
    upper_function_id: Optional[int] = None
    name: Optional[str] = Field(None, max_length=200)
    function_type: Optional[int] = None
    order: Optional[int] = None
    function_icon: Optional[str] = Field(None, max_length=200)
    module_code: Optional[str] = Field(None, max_length=200)
    module_functions: Optional[List[str]] = None
    description: Optional[str] = None
    is_mana: Optional[bool] = None
    is_active: Optional[bool] = None
    edit_by: int = Field(..., description="資料編輯者")


class SystemFunctionInDB(SystemFunctionBase):
    """系統功能資料庫 Schema"""
    id: int
    edit_by: int
    created_at: datetime
    updated_at: Optional[datetime] = None

    class Config:
        from_attributes = True


class SystemFunctionResponse(SystemFunctionInDB):
    """系統功能回應 Schema"""
    pass


class SystemFunctionListResponse(BaseModel):
    """系統功能列表回應"""
    total: int
    items: List[SystemFunctionResponse]
    page: int
    page_size: int
