#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Topic Parser
主题解析器 - 从原项目迁移，解析AI生成的主题内容
"""

import json
import re
import logging
from typing import List, Dict, Any, Optional

logger = logging.getLogger(__name__)


class TopicParser:
    """
    主题解析器
    负责从AI生成的文本中解析出结构化的主题数据
    """

    def __init__(self):
        """初始化解析器"""
        self.json_pattern = re.compile(r'```json\s*(.*?)\s*```', re.DOTALL)
        self.fallback_patterns = [
            re.compile(r'\{.*\}', re.DOTALL),  # 匹配JSON对象
            re.compile(r'\[.*\]', re.DOTALL),  # 匹配JSON数组
        ]

    def parse(self, raw_content: str) -> List[Dict[str, Any]]:
        """
        解析主题内容

        Args:
            raw_content: AI生成的原始内容

        Returns:
            解析后的主题列表
        """
        if not raw_content or not raw_content.strip():
            logger.warning("输入内容为空")
            return []

        # 尝试多种解析方法
        topics = (
            self._parse_json_block(raw_content) or
            self._parse_direct_json(raw_content) or
            self._parse_structured_text(raw_content) or
            []
        )

        if topics:
            logger.info(f"成功解析出 {len(topics)} 个主题")
            return self._validate_topics(topics)
        else:
            logger.error("未能解析出任何有效主题")
            return []

    def _parse_json_block(self, content: str) -> Optional[List[Dict[str, Any]]]:
        """解析```json```代码块中的JSON"""
        try:
            matches = self.json_pattern.findall(content)
            if matches:
                json_str = matches[0].strip()
                data = json.loads(json_str)
                
                if isinstance(data, list):
                    return data
                elif isinstance(data, dict):
                    # 如果是字典，尝试提取topics字段
                    if 'topics' in data:
                        return data['topics']
                    else:
                        return [data]
            return None
        except (json.JSONDecodeError, Exception) as e:
            logger.debug(f"JSON代码块解析失败: {e}")
            return None

    def _parse_direct_json(self, content: str) -> Optional[List[Dict[str, Any]]]:
        """直接解析JSON内容"""
        try:
            # 尝试直接解析整个内容
            data = json.loads(content.strip())
            
            if isinstance(data, list):
                return data
            elif isinstance(data, dict):
                if 'topics' in data:
                    return data['topics']
                else:
                    return [data]
            return None
        except (json.JSONDecodeError, Exception):
            # 尝试使用fallback patterns
            for pattern in self.fallback_patterns:
                matches = pattern.findall(content)
                for match in matches:
                    try:
                        data = json.loads(match)
                        if isinstance(data, list) and len(data) > 0:
                            return data
                        elif isinstance(data, dict):
                            return [data]
                    except json.JSONDecodeError:
                        continue
            return None

    def _parse_structured_text(self, content: str) -> Optional[List[Dict[str, Any]]]:
        """解析结构化文本格式"""
        try:
            topics = []
            lines = content.split('\n')
            current_topic = {}
            
            for line in lines:
                line = line.strip()
                if not line:
                    continue
                
                # 检测主题开始（数字编号）
                if re.match(r'^\d+[\.\)]\s*', line):
                    if current_topic:
                        topics.append(current_topic)
                    current_topic = {}
                    title = re.sub(r'^\d+[\.\)]\s*', '', line)
                    current_topic['title'] = title
                
                # 检测字段
                elif ':' in line and current_topic:
                    key, value = line.split(':', 1)
                    key = key.strip().lower()
                    value = value.strip()
                    
                    # 映射中文字段到英文
                    field_mapping = {
                        '标题': 'title',
                        '主题': 'title', 
                        '目标': 'target',
                        '目标人群': 'target',
                        '内容': 'content',
                        '描述': 'content',
                        '关键词': 'keywords',
                        '标签': 'tags'
                    }
                    
                    mapped_key = field_mapping.get(key, key)
                    current_topic[mapped_key] = value
            
            # 添加最后一个主题
            if current_topic:
                topics.append(current_topic)
            
            return topics if topics else None
            
        except Exception as e:
            logger.debug(f"结构化文本解析失败: {e}")
            return None

    def _validate_topics(self, topics: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """验证和标准化主题数据"""
        validated_topics = []
        
        for i, topic in enumerate(topics):
            if not isinstance(topic, dict):
                logger.warning(f"主题 {i+1} 不是字典格式，跳过")
                continue
            
            # 确保必需字段存在
            validated_topic = {
                'id': topic.get('id', f"topic_{i+1}"),
                'title': topic.get('title', topic.get('主题', f"主题{i+1}")),
                'content': topic.get('content', topic.get('描述', topic.get('内容', ''))),
                'target': topic.get('target', topic.get('目标人群', '通用')),
                'keywords': topic.get('keywords', topic.get('关键词', [])),
                'tags': topic.get('tags', topic.get('标签', [])),
                'metadata': topic.get('metadata', {})
            }
            
            # 确保keywords和tags是列表
            if isinstance(validated_topic['keywords'], str):
                validated_topic['keywords'] = [kw.strip() for kw in validated_topic['keywords'].split(',')]
            if isinstance(validated_topic['tags'], str):
                validated_topic['tags'] = [tag.strip() for tag in validated_topic['tags'].split(',')]
            
            # 只保留有标题的主题
            if validated_topic['title']:
                validated_topics.append(validated_topic)
            else:
                logger.warning(f"主题 {i+1} 缺少标题，跳过")
        
        return validated_topics

    def parse_single_topic(self, content: str) -> Optional[Dict[str, Any]]:
        """
        解析单个主题

        Args:
            content: 主题内容

        Returns:
            解析后的主题字典
        """
        topics = self.parse(content)
        return topics[0] if topics else None 