"""
CogProfile 数据模型

核心结构：CogProfile（认知身份证）
输入结构：Memory（对话记忆）
内部结构：各维度的洞察类型
"""

from __future__ import annotations

from datetime import datetime
from enum import Enum
from typing import Optional

from pydantic import BaseModel, Field


# ============================================================
# 输入：记忆
# ============================================================

# ============================================================
# 内部：洞察类型（检测器输出，不直接暴露给用户）
# ============================================================

class InsightType(str, Enum):
    EMOTION_TREND = "emotion_trend"
    TOPIC_ANOMALY = "topic_anomaly"
    GOAL_DRIFT = "goal_drift"
    RELATIONSHIP_SHIFT = "relationship_shift"
    BEHAVIORAL_PATTERN = "behavioral_pattern"


class Insight(BaseModel):
    """洞察基类（内部使用）"""
    type: InsightType
    confidence: float = Field(ge=0.0, le=1.0, default=0.5)
    summary: str = ""
    evidence: list[str] = Field(default_factory=list)
    generated_at: datetime = Field(default_factory=datetime.now)


class DetectedEmotionTrend(Insight):
    type: InsightType = InsightType.EMOTION_TREND
    direction: str = "stable"
    period_days: int = 14
    start_score: float = 0.0
    end_score: float = 0.0
    delta: float = 0.0


class TopicAnomaly(Insight):
    type: InsightType = InsightType.TOPIC_ANOMALY
    topic: str = ""
    frequency_recent: int = 0
    frequency_baseline: int = 0
    spike_ratio: float = 1.0


class DetectedGoalDrift(Insight):
    type: InsightType = InsightType.GOAL_DRIFT
    goal: str = ""
    first_mentioned: datetime = Field(default_factory=datetime.now)
    last_mentioned: datetime = Field(default_factory=datetime.now)
    mention_count: int = 0
    days_silent: int = 0
    status: str = "active"


# ============================================================
# 输入：记忆
# ============================================================

class MemoryCategory(str, Enum):
    PERSONAL_INFO = "personal_info"
    PREFERENCE = "preference"
    EMOTION = "emotion"
    EVENT = "event"
    RELATIONSHIP = "relationship"
    GOAL = "goal"
    OPINION = "opinion"
    OTHER = "other"


class MemoryImportance(str, Enum):
    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"
    CRITICAL = "critical"


class Memory(BaseModel):
    """一条对话记忆 —— CogProfile 的输入单元"""
    id: str
    user_id: str
    content: str
    category: MemoryCategory = MemoryCategory.OTHER
    importance: MemoryImportance = MemoryImportance.MEDIUM
    created_at: datetime
    sentiment_score: Optional[float] = None
    entities: list[str] = Field(default_factory=list)
    topics: list[str] = Field(default_factory=list)
    metadata: dict = Field(default_factory=dict)


# ============================================================
# 输出：CogProfile（认知身份证）
# ============================================================

class IdentityFact(BaseModel):
    key: str
    value: str
    confidence: float = 0.5
    source_date: Optional[str] = None
    last_confirmed: Optional[str] = None


class Preference(BaseModel):
    category: str
    value: str
    confidence: float = 0.5
    source_date: Optional[str] = None


class EmotionState(BaseModel):
    valence: float = 0.0            # -1.0 到 1.0
    label: str = "unknown"
    confidence: float = 0.0
    assessed_at: Optional[str] = None


class EmotionTrend(BaseModel):
    direction: str = "stable"       # rising / declining / stable / volatile
    slope: float = 0.0
    period_days: int = 14
    start_valence: float = 0.0
    end_valence: float = 0.0
    confidence: float = 0.0


class EmotionTrigger(BaseModel):
    topic: str
    effect: str = "negative"        # positive / negative / mixed
    strength: float = 0.5
    occurrence_count: int = 1


class EmotionSection(BaseModel):
    current: EmotionState = Field(default_factory=EmotionState)
    baseline: Optional[EmotionState] = None
    trend: Optional[EmotionTrend] = None
    triggers: list[EmotionTrigger] = Field(default_factory=list)


class HotTopic(BaseModel):
    topic: str
    frequency_7d: int = 0
    frequency_30d: int = 0
    trend: str = "stable"           # intensifying / stable / declining
    spike_ratio: float = 1.0


class FadingTopic(BaseModel):
    topic: str
    last_mentioned: Optional[str] = None
    days_silent: int = 0
    previous_frequency: int = 0


class AttentionSection(BaseModel):
    hot_topics: list[HotTopic] = Field(default_factory=list)
    fading_topics: list[FadingTopic] = Field(default_factory=list)
    stable_topics: list[dict] = Field(default_factory=list)


class Goal(BaseModel):
    description: str
    first_mentioned: Optional[str] = None
    last_mentioned: Optional[str] = None
    mention_count: int = 0
    days_silent: int = 0
    commitment_strength: float = 0.5
    status: str = "active"          # active / fading / abandoned / completed


class GoalsSection(BaseModel):
    active: list[Goal] = Field(default_factory=list)
    fading: list[Goal] = Field(default_factory=list)
    completed: list[Goal] = Field(default_factory=list)
    abandoned: list[Goal] = Field(default_factory=list)


class SentimentPoint(BaseModel):
    date: str
    sentiment: float


class Person(BaseModel):
    name: str
    role: str = "unknown"
    current_sentiment: float = 0.0
    sentiment_trend: str = "stable"  # improving / deteriorating / stable
    sentiment_history: list[SentimentPoint] = Field(default_factory=list)
    mention_count: int = 0
    last_mentioned: Optional[str] = None
    context_summary: str = ""


class RelationshipsSection(BaseModel):
    people: list[Person] = Field(default_factory=list)


class Pattern(BaseModel):
    name: str
    trigger: str
    response: str
    average_delay_days: float = 0.0
    occurrence_count: int = 0
    confidence: float = 0.0
    first_observed: Optional[str] = None
    last_observed: Optional[str] = None


class PatternsSection(BaseModel):
    discovered: list[Pattern] = Field(default_factory=list)


class Prediction(BaseModel):
    prediction: str
    confidence: float = 0.0
    based_on: list[str] = Field(default_factory=list)
    generated_at: Optional[str] = None


class ProfileMeta(BaseModel):
    generator: str = "cogprofile-python/0.1.0"
    llm_provider: str = ""
    llm_model: str = ""
    total_memories_processed: int = 0
    earliest_memory: Optional[str] = None
    latest_memory: Optional[str] = None
    source_applications: list[str] = Field(default_factory=list)


class CogProfile(BaseModel):
    """
    认知身份证 —— CogProfile 的核心输出。

    这不是一个静态画像，而是一份持续自我进化的认知档案。
    每次输入新的对话记忆，档案会自动更新。
    """
    cogprofile_version: str = "0.1.0"
    user_id: str
    created_at: str = Field(default_factory=lambda: datetime.now().isoformat())
    updated_at: str = Field(default_factory=lambda: datetime.now().isoformat())
    update_count: int = 0

    identity: dict = Field(default_factory=lambda: {"facts": [], "preferences": []})
    emotion: EmotionSection = Field(default_factory=EmotionSection)
    attention: AttentionSection = Field(default_factory=AttentionSection)
    goals: GoalsSection = Field(default_factory=GoalsSection)
    relationships: RelationshipsSection = Field(default_factory=RelationshipsSection)
    patterns: PatternsSection = Field(default_factory=PatternsSection)
    predictions: list[Prediction] = Field(default_factory=list)
    meta: ProfileMeta = Field(default_factory=ProfileMeta)
