"""
项目管理数据模型

Series Project - 剧集项目的完整数据结构
"""
from pydantic import BaseModel, Field
from typing import Dict, List, Optional, Any, TYPE_CHECKING
from datetime import datetime
from enum import Enum

# Use TYPE_CHECKING to avoid circular imports
if TYPE_CHECKING:
    from app.models.review import ReviewConfig, ReviewResult


# ============================================
# 枚举类型
# ============================================

class TaskType(str, Enum):
    """任务类型枚举"""
    DIALOGUE = "dialogue"          # 对话创作
    REVIEW = "review"              # 内容审核
    OUTLINE = "outline"            # 大纲生成
    STRUCTURE = "structure"        # 结构分析
    SCENE = "scene"                # 场景描写
    CONSISTENCY = "consistency"    # 一致性检查


# ============================================
# 嵌套模型
# ============================================

class CharacterProfile(BaseModel):
    """人物小传"""
    name: str
    description: str = ""
    personality: str = ""
    speechStyle: str = ""
    currentState: str = ""
    relationships: Dict[str, str] = Field(default_factory=dict)
    appearance: Optional[str] = None


class SceneSetting(BaseModel):
    """场景设定"""
    name: str
    description: str = ""
    atmosphere: str = ""


class GlobalContext(BaseModel):
    """全局上下文"""
    worldSetting: str = ""
    characterProfiles: Dict[str, CharacterProfile] = Field(default_factory=dict)
    sceneSettings: Dict[str, SceneSetting] = Field(default_factory=dict)
    overallOutline: str = ""
    styleGuide: str = ""
    uploadedScript: str = ""     # 上传的剧本内容
    inspiration: str = ""         # 创意灵感内容


class Memory(BaseModel):
    """记忆系统"""
    eventTimeline: List[Dict[str, Any]] = Field(default_factory=list)
    pendingThreads: List[Dict[str, Any]] = Field(default_factory=list)
    foreshadowing: List[Dict[str, Any]] = Field(default_factory=list)
    characterStates: Dict[str, List[Dict[str, Any]]] = Field(default_factory=dict)


class SkillSetting(BaseModel):
    """Skill 设置（保留用于兼容）"""
    enabled: bool = True
    parameterOverrides: Optional[Dict[str, Any]] = None


class SkillAssignment(BaseModel):
    """Skill 分配配置"""
    skill_id: str
    enabled: bool = True
    priority: int = 0
    parameter_overrides: Optional[Dict[str, Any]] = None


class TaskSkillConfig(BaseModel):
    """任务级 Skill 配置"""
    task_type: TaskType
    skills: List[SkillAssignment] = Field(default_factory=list)


class EpisodeSkillOverride(BaseModel):
    """单集 Skill 覆盖配置"""
    episode_number: int
    task_configs: List[TaskSkillConfig] = Field(default_factory=list)
    use_project_default: bool = True


class EpisodeIssue(BaseModel):
    """剧集问题"""
    type: str
    description: str
    severity: str  # low, medium, high
    suggestion: str = ""


# ============================================
# 核心模型
# ============================================

class SeriesProject(BaseModel):
    """剧集项目模型"""
    id: str = ""
    name: str
    type: str = "series"
    agentId: str = "series-creation"
    mode: str = "batch"  # auto, batch, step

    # 项目类型/风格（如：古风、现代、科幻等）
    genre: str = "古风"

    # 全局上下文
    globalContext: GlobalContext = Field(default_factory=GlobalContext)

    # 记忆系统
    memory: Memory = Field(default_factory=Memory)

    # 配置
    totalEpisodes: int = 30

    # 三级 Skills 配置
    defaultTaskSkills: List[TaskSkillConfig] = Field(default_factory=list)
    episodeSkillOverrides: Dict[int, EpisodeSkillOverride] = Field(default_factory=dict)

    # 保留现有字段用于兼容
    skillSettings: Dict[str, SkillSetting] = Field(default_factory=dict)
    autoRetryConfig: Optional[Dict[str, Any]] = None

    # 审核配置
    reviewConfig: Optional[Dict[str, Any]] = None

    # 时间戳
    createdAt: datetime = Field(default_factory=datetime.now)
    updatedAt: datetime = Field(default_factory=datetime.now)


class Episode(BaseModel):
    """单集模型"""
    id: str = ""
    projectId: str = ""
    number: int = 0
    title: str = ""
    status: str = "pending"  # pending, writing, review, completed, needs-review

    # 内容
    structure: Optional[Dict[str, Any]] = None
    outline: Optional[str] = None
    content: Optional[str] = None
    summary: Optional[str] = None

    # 质量信息
    qualityScore: Optional[float] = None
    retryCount: int = 0
    issues: List[EpisodeIssue] = Field(default_factory=list)

    # 审核结果
    reviewResult: Optional[Dict[str, Any]] = None

    # 时间戳
    createdAt: datetime = Field(default_factory=datetime.now)
    completedAt: Optional[datetime] = None


# ============================================
# 请求/响应模型
# ============================================

class SeriesProjectCreate(BaseModel):
    """创建项目请求"""
    name: str
    totalEpisodes: int = 30
    agentId: str = "series-creation"
    mode: str = "batch"
    genre: str = "古风"
    globalContext: GlobalContext = Field(default_factory=GlobalContext)
    skillSettings: Dict[str, SkillSetting] = Field(default_factory=dict)


class EpisodeExecuteRequest(BaseModel):
    """执行剧集请求"""
    episodeNumber: int
    title: str = ""
    contextOverrides: Optional[Dict[str, Any]] = None


class EpisodeExecuteResponse(BaseModel):
    """执行剧集响应"""
    episode: Episode
    success: bool
    message: str = ""
