"""
记忆系统数据模型

Memory System - 完整的记忆系统数据结构，支持多剧集一致性管理
"""
from pydantic import BaseModel, Field
from typing import Dict, List, Optional, Any
from datetime import datetime
from enum import Enum


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

class ImportanceLevel(str, Enum):
    """重要程度"""
    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"


class ThreadStatus(str, Enum):
    """待收线状态"""
    PENDING = "pending"
    IN_PROGRESS = "跟进中"
    RESOLVED = "已收线"


# ============================================
# 核心数据模型
# ============================================

class TimelineEvent(BaseModel):
    """
    时间线事件

    记录剧情中发生的关键事件，用于维护多集一致性
    """
    episode: int = Field(..., description="所在集数")
    event: str = Field(..., description="事件描述")
    timestamp: datetime = Field(default_factory=datetime.now, description="记录时间")
    characters_involved: List[str] = Field(default_factory=list, description="涉及的角色")
    importance: ImportanceLevel = Field(default=ImportanceLevel.MEDIUM, description="重要程度")
    tags: List[str] = Field(default_factory=list, description="事件标签")
    related_threads: List[str] = Field(default_factory=list, description="相关的待收线ID")


class PendingThread(BaseModel):
    """
    待收线问题（伏笔）

    记录剧情中引入的未解决问题，用于确保后续收线
    """
    id: str = Field(..., description="待收线唯一标识")
    description: str = Field(..., description="待收线描述")
    introduced_at: int = Field(..., description="引入的集数")
    importance: ImportanceLevel = Field(..., description="重要程度")
    resolved: bool = Field(default=False, description="是否已收线")
    resolved_at: Optional[int] = Field(default=None, description="收线的集数")
    reminder_episode: Optional[int] = Field(default=None, description="提醒收线的集数")
    status: ThreadStatus = Field(default=ThreadStatus.PENDING, description="当前状态")
    characters_involved: List[str] = Field(default_factory=list, description="涉及的角色")
    notes: str = Field(default="", description="备注信息")
    created_at: datetime = Field(default_factory=datetime.now, description="创建时间")
    updated_at: datetime = Field(default_factory=datetime.now, description="更新时间")


class CharacterStateChange(BaseModel):
    """
    角色状态变化

    记录角色在不同集数中的状态变化，保持角色发展的一致性
    """
    episode: int = Field(..., description="发生变化的集数")
    state: str = Field(..., description="当前状态")
    change: str = Field(..., description="状态变化描述")
    emotional_impact: Optional[str] = Field(default=None, description="情感影响")
    trigger_event: Optional[str] = Field(default=None, description="触发事件")
    timestamp: datetime = Field(default_factory=datetime.now, description="记录时间")


class ForeshadowingEvent(BaseModel):
    """
    伏笔事件

    记录剧情中的伏笔元素，用于后续呼应
    """
    id: str = Field(..., description="伏笔唯一标识")
    description: str = Field(..., description="伏笔描述")
    introduced_at: int = Field(..., description="引入集数")
    payoff_at: Optional[int] = Field(default=None, description="呼应集数")
    type: str = Field(default="plot", description="伏笔类型: plot/character/dialogue/object")
    importance: ImportanceLevel = Field(default=ImportanceLevel.MEDIUM, description="重要程度")
    is_payed_off: bool = Field(default=False, description="是否已呼应")
    related_events: List[str] = Field(default_factory=list, description="相关事件ID")
    notes: str = Field(default="", description="备注")


class ConsistencyIssue(BaseModel):
    """
    一致性问题

    记录检测到的一致性问题
    """
    id: str = Field(..., description="问题唯一标识")
    type: str = Field(..., description="问题类型: character/plot/setting/dialogue")
    severity: ImportanceLevel = Field(..., description="严重程度")
    description: str = Field(..., description="问题描述")
    location: Optional[str] = Field(default=None, description="问题位置（场景/段落）")
    conflicting_info: Dict[str, Any] = Field(default_factory=dict, description="冲突信息")
    suggestion: str = Field(default="", description="修复建议")
    detected_at: datetime = Field(default_factory=datetime.now, description="检测时间")


class ResolutionSuggestion(BaseModel):
    """
    收线建议

    为待收线问题提供收线建议
    """
    thread_id: str = Field(..., description="待收线ID")
    suggested_episode: int = Field(..., description="建议收线集数")
    approach: str = Field(..., description="收线方式描述")
    key_elements: List[str] = Field(default_factory=list, description="关键要素")
    character_involvement: Dict[str, str] = Field(default_factory=dict, description="角色参与方式")
    potential_twists: List[str] = Field(default_factory=list, description="可能的反转")
    estimated_impact: str = Field(default="", description="预估影响")


class EnhancedMemory(BaseModel):
    """
    增强记忆系统

    完整的记忆系统，包含所有记忆相关数据
    """
    # 事件时间线
    eventTimeline: List[TimelineEvent] = Field(
        default_factory=list,
        description="按时间顺序排列的关键事件"
    )

    # 待收线问题
    pendingThreads: List[PendingThread] = Field(
        default_factory=list,
        description="未解决的伏笔和待收线"
    )

    # 角色状态历史
    characterStates: Dict[str, List[CharacterStateChange]] = Field(
        default_factory=dict,
        description="每个角色的状态变化历史"
    )

    # 伏笔追踪
    foreshadowing: List[ForeshadowingEvent] = Field(
        default_factory=list,
        description="伏笔事件列表"
    )

    # 角色关系
    relationships: Dict[str, Dict[str, str]] = Field(
        default_factory=dict,
        description="角色关系网络"
    )

    # 一致性问题记录
    consistencyIssues: List[ConsistencyIssue] = Field(
        default_factory=list,
        description="检测到的一致性问题"
    )

    # 元数据
    last_updated: datetime = Field(
        default_factory=datetime.now,
        description="最后更新时间"
    )
    last_episode_processed: int = Field(
        default=0,
        description="最后处理的集数"
    )


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

class ThreadCreateRequest(BaseModel):
    """创建待收线请求"""
    description: str
    importance: ImportanceLevel
    reminder_episode: Optional[int] = None
    characters_involved: List[str] = Field(default_factory=list)
    notes: str = Field(default="")


class ThreadUpdateRequest(BaseModel):
    """更新待收线请求"""
    description: Optional[str] = None
    importance: Optional[ImportanceLevel] = None
    status: Optional[ThreadStatus] = None
    reminder_episode: Optional[int] = None
    characters_involved: Optional[List[str]] = None
    notes: Optional[str] = None


class ThreadResolveRequest(BaseModel):
    """收线请求"""
    thread_id: str
    resolved_at: int
    resolution_summary: str = Field(default="", description="收线摘要")


class MemoryUpdateRequest(BaseModel):
    """记忆更新请求"""
    episode_number: int
    episode_content: str
    extract_events: bool = Field(default=True, description="是否提取事件")
    detect_foreshadowing: bool = Field(default=True, description="是否检测伏笔")
    update_characters: bool = Field(default=True, description="是否更新角色状态")
    check_consistency: bool = Field(default=True, description="是否检查一致性")


class MemoryExtractionResult(BaseModel):
    """记忆提取结果"""
    success: bool
    events_extracted: int = Field(default=0, description="提取的事件数")
    foreshadowing_detected: int = Field(default=0, description="检测到的伏笔数")
    character_states_updated: int = Field(default=0, description="更新的角色状态数")
    consistency_issues_found: int = Field(default=0, description="发现的一致性问题数")
    threads_suggested: int = Field(default=0, description="建议的待收线数")
    new_threads: List[PendingThread] = Field(default_factory=list, description="新识别的待收线")
    message: str = Field(default="", description="结果消息")
