#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
帖子数据模型
"""

from dataclasses import dataclass, field
from typing import List, Dict, Any, Optional


@dataclass
class PersonaMatch:
    """人设特征匹配结果"""
    persona_feature_name: str           # 人设特征名称
    persona_feature_level: str          # 人设特征层级（灵感点/关键点/目的点）
    feature_type: str                   # 特征类型（标签/分类）
    feature_classification: List[str]   # 特征分类路径
    similarity: float                   # 相似度得分
    match_reason: str                   # 匹配说明

    @staticmethod
    def from_dict(data: Dict[str, Any]) -> 'PersonaMatch':
        """从字典创建"""
        return PersonaMatch(
            persona_feature_name=data.get('人设特征名称', ''),
            persona_feature_level=data.get('人设特征层级', ''),
            feature_type=data.get('特征类型', ''),
            feature_classification=data.get('特征分类', []),
            similarity=data.get('相似度', 0.0),
            match_reason=data.get('说明', '')
        )

    def to_dict(self) -> Dict[str, Any]:
        """转为字典"""
        return {
            '人设特征名称': self.persona_feature_name,
            '人设特征层级': self.persona_feature_level,
            '特征类型': self.feature_type,
            '特征分类': self.feature_classification,
            '相似度': self.similarity,
            '说明': self.match_reason
        }


@dataclass
class TopicPoint:
    """选题点（灵感点/关键点/目的点下的每一项）"""
    id: str                             # ID
    name: str                           # 名称
    level: str                          # 层级（灵感点列表/关键点列表/目的点列表）
    type: str                           # 类型（实质/形式/场景等）
    description: str                    # 描述
    confidence: float                   # 置信度
    persona_matches: List[PersonaMatch] = field(default_factory=list)  # 人设匹配结果

    @staticmethod
    def from_dict(data: Dict[str, Any], level: str) -> 'TopicPoint':
        """从字典创建"""
        # 解析人设匹配结果
        matches = [
            PersonaMatch.from_dict(m)
            for m in data.get('匹配人设结果', [])
        ]

        return TopicPoint(
            id=data.get('ID', ''),
            name=data.get('名称', ''),
            level=level,
            type=data.get('类型', ''),
            description=data.get('描述', ''),
            confidence=data.get('置信度', 0.0),
            persona_matches=matches
        )

    def to_dict(self) -> Dict[str, Any]:
        """转为字典"""
        return {
            'ID': self.id,
            '名称': self.name,
            '层级': self.level,
            '类型': self.type,
            '描述': self.description,
            '置信度': self.confidence,
            '匹配人设结果': [m.to_dict() for m in self.persona_matches]
        }


@dataclass
class Post:
    """帖子模型"""
    post_id: str                        # 帖子ID
    post_details: Dict[str, Any]        # 帖子详情
    topic_points: List[TopicPoint]      # 所有选题点（灵感点+关键点+目的点）

    @staticmethod
    def from_json_file(file_path: str) -> 'Post':
        """从JSON文件加载"""
        import json
        with open(file_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
        return Post.from_dict(data)

    @staticmethod
    def from_dict(data: Dict[str, Any]) -> 'Post':
        """从字典创建"""
        # 解析选题点
        topic_points = []
        deconstruction = data.get('解构结果', {})

        # 灵感点列表
        for item in deconstruction.get('灵感点列表', []):
            topic_points.append(TopicPoint.from_dict(item, '灵感点列表'))

        # 关键点列表
        for item in deconstruction.get('关键点列表', []):
            topic_points.append(TopicPoint.from_dict(item, '关键点列表'))

        # 目的点列表
        for item in deconstruction.get('目的点列表', []):
            topic_points.append(TopicPoint.from_dict(item, '目的点列表'))

        return Post(
            post_id=data.get('帖子id', ''),
            post_details=data.get('帖子详情', {}),
            topic_points=topic_points
        )

    def to_dict(self) -> Dict[str, Any]:
        """转为字典"""
        # 按层级重组选题点
        inspiration_points = []
        key_points = []
        purpose_points = []

        for tp in self.topic_points:
            if tp.level == '灵感点列表':
                inspiration_points.append(tp.to_dict())
            elif tp.level == '关键点列表':
                key_points.append(tp.to_dict())
            elif tp.level == '目的点列表':
                purpose_points.append(tp.to_dict())

        return {
            '帖子id': self.post_id,
            '帖子详情': self.post_details,
            '解构结果': {
                '灵感点列表': inspiration_points,
                '关键点列表': key_points,
                '目的点列表': purpose_points
            }
        }

    def get_topic_point_by_name(self, name: str) -> Optional[TopicPoint]:
        """根据名称查找选题点"""
        for tp in self.topic_points:
            if tp.name == name:
                return tp
        return None
