"""
Prompt Template Models - 提示词模板数据模型
"""
from datetime import datetime
from typing import Optional, List
from sqlmodel import SQLModel, Field, Relationship
import uuid


class PromptTemplateBase(SQLModel):
    """提示词模板基础模型"""
    name: str = Field(..., description="模板名称")
    description: Optional[str] = Field(default=None, description="模板描述")
    content: str = Field(..., description="模板内容，使用 {prompt} 作为占位符")
    category: str = Field(default="general", description="模板分类")
    tags: Optional[str] = Field(default=None, description="标签，逗号分隔")
    target_type: str = Field(default="image", description="目标类型: image/video/audio/music/both")
    is_public: bool = Field(default=True, description="是否公开")
    usage_count: int = Field(default=0, description="使用次数")


class PromptTemplate(PromptTemplateBase, table=True):
    """提示词模板数据库模型"""
    __tablename__ = "prompt_templates"
    
    id: str = Field(default_factory=lambda: str(uuid.uuid4()), primary_key=True)
    user_id: Optional[str] = Field(default=None, description="创建者用户ID，None表示系统模板")
    created_at: datetime = Field(default_factory=datetime.utcnow)
    updated_at: datetime = Field(default_factory=datetime.utcnow)
    
    # 关联收藏
    favorites: List["PromptTemplateFavorite"] = Relationship(back_populates="template")


class PromptTemplateCreate(SQLModel):
    """创建模板请求模型"""
    name: str
    description: Optional[str] = None
    content: str
    category: str = "general"
    tags: Optional[str] = None
    target_type: str = "image"
    is_public: bool = True


class PromptTemplateUpdate(SQLModel):
    """更新模板请求模型"""
    name: Optional[str] = None
    description: Optional[str] = None
    content: Optional[str] = None
    category: Optional[str] = None
    tags: Optional[str] = None
    target_type: Optional[str] = None
    is_public: Optional[bool] = None


class PromptTemplateResponse(PromptTemplateBase):
    """模板响应模型"""
    id: str
    user_id: Optional[str]
    created_at: datetime
    updated_at: datetime
    is_favorite: bool = False


class PromptTemplateFavorite(SQLModel, table=True):
    """模板收藏模型"""
    __tablename__ = "prompt_template_favorites"
    
    id: str = Field(default_factory=lambda: str(uuid.uuid4()), primary_key=True)
    user_id: str = Field(..., description="用户ID")
    template_id: str = Field(foreign_key="prompt_templates.id", description="模板ID")
    created_at: datetime = Field(default_factory=datetime.utcnow)
    
    # 关联模板
    template: PromptTemplate = Relationship(back_populates="favorites")


class PromptTemplateCategory(SQLModel):
    """模板分类"""
    value: str
    label: str
    count: int = 0