"""
Pydantic models for tag system
"""
from pydantic import BaseModel, Field
from typing import Optional, List, Literal
from datetime import datetime

# Tag types
TagType = Literal['workflow', 'status', 'category', 'priority', 'billing', 'brand', 'type']
TagGroupBehavior = Literal['multi', 'single', 'toggle']


class TagGroupBase(BaseModel):
    name: str = Field(..., max_length=100)
    description: Optional[str] = None
    behavior: TagGroupBehavior = 'multi'


class TagGroupCreate(TagGroupBase):
    pass


class TagGroup(TagGroupBase):
    id: int
    created_at: datetime
    updated_at: datetime

    class Config:
        from_attributes = True

class TagBase(BaseModel):
    """Base tag model"""
    name: str = Field(..., max_length=100)
    type: TagType
    description: Optional[str] = None
    color: str = Field(..., pattern=r'^#[0-9A-Fa-f]{6}$')  # Hex color
    icon: Optional[str] = None
    is_active: bool = True
    tag_group_id: Optional[int] = None
    catch_words: Optional[List[str]] = None

class TagCreate(TagBase):
    """Tag creation model"""
    pass

class Tag(TagBase):
    """Full tag model"""
    id: int
    created_at: datetime
    updated_at: datetime
    
    class Config:
        from_attributes = True

class TagUpdate(BaseModel):
    """Tag update model - all fields optional"""
    name: Optional[str] = Field(None, max_length=100)
    description: Optional[str] = None
    color: Optional[str] = Field(None, pattern=r'^#[0-9A-Fa-f]{6}$')
    icon: Optional[str] = None
    is_active: Optional[bool] = None
    tag_group_id: Optional[int] = None
    catch_words: Optional[List[str]] = None


class EntityTagBase(BaseModel):
    """Base entity tag association"""
    entity_type: str = Field(..., max_length=50)
    entity_id: int
    tag_id: int

class EntityTagCreate(EntityTagBase):
    """Entity tag creation"""
    tagged_by: Optional[int] = None

class EntityTag(EntityTagBase):
    """Full entity tag model"""
    id: int
    tagged_by: Optional[int]
    tagged_at: datetime
    action: Optional[dict] = None
    
    class Config:
        from_attributes = True

class EntityWithTags(BaseModel):
    """Model for entities with their tags"""
    entity_type: str
    entity_id: int
    tags: List[Tag]


class TagWorkflowBase(BaseModel):
    """Base workflow configuration"""
    tag_id: int
    trigger_event: Literal['on_add', 'on_remove']
    action_type: str = Field(..., max_length=50)
    action_config: Optional[dict] = None
    is_active: bool = True

class TagWorkflowCreate(TagWorkflowBase):
    """Workflow creation model"""
    pass

class TagWorkflow(TagWorkflowBase):
    """Full workflow model"""
    id: int
    created_at: datetime
    
    class Config:
        from_attributes = True
