#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
搜索Query数据模型
"""

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


@dataclass
class SearchQuery:
    """搜索Query模型"""

    # 基本信息
    query_text: str                     # 搜索词文本
    score: float                        # LLM评分
    reasoning: str = ""                 # 推荐理由

    # 来源信息
    topic_point_name: str = ""          # 所属选题点
    used_candidates: List[str] = field(default_factory=list)  # 使用的候选词
    candidate_sources: List[str] = field(default_factory=list)  # 候选词来源

    # 搜索结果（Stage 3填充）
    search_result: Optional[Dict[str, Any]] = None
    search_metadata: Optional[Dict[str, Any]] = None

    # 评估结果（Stage 4填充）
    evaluation_result: Optional[Dict[str, Any]] = None

    def to_dict(self) -> Dict[str, Any]:
        """转为字典"""
        return {
            "query_text": self.query_text,
            "score": self.score,
            "reasoning": self.reasoning,
            "topic_point_name": self.topic_point_name,
            "used_candidates": self.used_candidates,
            "candidate_sources": self.candidate_sources,
            "search_result": self.search_result,
            "search_metadata": self.search_metadata,
            "evaluation_result": self.evaluation_result
        }

    @staticmethod
    def from_dict(data: Dict[str, Any]) -> 'SearchQuery':
        """从字典创建"""
        return SearchQuery(
            query_text=data.get('query_text', ''),
            score=data.get('score', 0.0),
            reasoning=data.get('reasoning', ''),
            topic_point_name=data.get('topic_point_name', ''),
            used_candidates=data.get('used_candidates', []),
            candidate_sources=data.get('candidate_sources', []),
            search_result=data.get('search_result'),
            search_metadata=data.get('search_metadata'),
            evaluation_result=data.get('evaluation_result')
        )

    def has_search_result(self) -> bool:
        """是否有搜索结果"""
        return self.search_result is not None

    def has_evaluation(self) -> bool:
        """是否有评估结果"""
        return self.evaluation_result is not None

    def get_note_count(self) -> int:
        """获取搜索到的帖子数量"""
        if not self.search_metadata:
            return 0
        return self.search_metadata.get('note_count', 0)


@dataclass
class TopicPointQueries:
    """选题点的搜索Query集合"""
    topic_point_name: str               # 选题点名称
    topic_point_level: str              # 选题点层级
    queries: List[SearchQuery] = field(default_factory=list)  # Query列表

    def to_dict(self) -> Dict[str, Any]:
        """转为字典"""
        return {
            "topic_point_name": self.topic_point_name,
            "topic_point_level": self.topic_point_level,
            "queries": [q.to_dict() for q in self.queries],
            "statistics": {
                "total_queries": len(self.queries),
                "with_search_results": sum(1 for q in self.queries if q.has_search_result()),
                "with_evaluations": sum(1 for q in self.queries if q.has_evaluation())
            }
        }

    @staticmethod
    def from_dict(data: Dict[str, Any]) -> 'TopicPointQueries':
        """从字典创建"""
        queries = [
            SearchQuery.from_dict(q)
            for q in data.get('queries', [])
        ]

        return TopicPointQueries(
            topic_point_name=data.get('topic_point_name', ''),
            topic_point_level=data.get('topic_point_level', ''),
            queries=queries
        )

    def get_top_n_queries(self, n: int = 10) -> List[SearchQuery]:
        """获取Top N个Query（按score降序）"""
        return sorted(
            self.queries,
            key=lambda q: q.score,
            reverse=True
        )[:n]


@dataclass
class PostQueries:
    """帖子的所有搜索Query"""
    post_id: str                        # 帖子ID
    topic_points_queries: List[TopicPointQueries] = field(default_factory=list)

    def to_dict(self) -> Dict[str, Any]:
        """转为字典"""
        total_queries = sum(len(tpq.queries) for tpq in self.topic_points_queries)
        total_with_results = sum(
            sum(1 for q in tpq.queries if q.has_search_result())
            for tpq in self.topic_points_queries
        )
        total_with_evaluations = sum(
            sum(1 for q in tpq.queries if q.has_evaluation())
            for tpq in self.topic_points_queries
        )

        return {
            "post_id": self.post_id,
            "topic_points_queries": [tpq.to_dict() for tpq in self.topic_points_queries],
            "statistics": {
                "total_topic_points": len(self.topic_points_queries),
                "total_queries": total_queries,
                "with_search_results": total_with_results,
                "with_evaluations": total_with_evaluations
            }
        }

    @staticmethod
    def from_dict(data: Dict[str, Any]) -> 'PostQueries':
        """从字典创建"""
        tpq_list = [
            TopicPointQueries.from_dict(tpq)
            for tpq in data.get('topic_points_queries', [])
        ]

        return PostQueries(
            post_id=data.get('post_id', ''),
            topic_points_queries=tpq_list
        )

    def get_topic_point_queries(self, topic_point_name: str) -> Optional[TopicPointQueries]:
        """获取指定选题点的Query"""
        for tpq in self.topic_points_queries:
            if tpq.topic_point_name == topic_point_name:
                return tpq
        return None

    def get_all_queries(self) -> List[SearchQuery]:
        """获取所有Query（扁平化）"""
        all_queries = []
        for tpq in self.topic_points_queries:
            all_queries.extend(tpq.queries)
        return all_queries
