# -*- coding: utf-8 -*-
"""
JSON生成器模块 - LLM增强版
将提取的需求和章节结构转换为结构化JSON输出
"""

import json
import logging
from datetime import datetime
from typing import List, Dict, Any, Optional
from .document_parser import Section
from .requirement_extractor import Requirement
from .settings import AppSettings

logger = logging.getLogger(__name__)


class JSONGenerator:
    """JSON输出生成器"""
    
    def __init__(self, config: Dict = None):
        self.config = config or {}
        self.settings = AppSettings(self.config)
    
    def generate(self, sections: List[Section], requirements: List[Requirement],
                 document_title: str = "SRS Document") -> Dict[str, Any]:
        """
        生成JSON输出
        
        Args:
            sections: 章节列表
            requirements: 需求列表
            document_title: 文档标题
            
        Returns:
            结构化JSON字典
        """
        # 按章节组织需求
        reqs_by_section = self._group_requirements_by_section(requirements)
        
        # 统计需求类型
        type_stats = self._calculate_type_statistics(requirements)
        
        # 构建输出结构
        output = {
            "文档元数据": {
                "标题": document_title,
                "生成时间": datetime.now().isoformat(),
                "总需求数": len(requirements),
                "需求类型统计": type_stats
            },
            "需求内容": self._build_requirement_content(sections, reqs_by_section)
        }
        
        logger.info(f"生成JSON输出，共{len(requirements)}个需求")
        return output
    
    def _group_requirements_by_section(self, requirements: List[Requirement]) -> Dict[str, List[Requirement]]:
        """按章节编号分组需求"""
        grouped = {}
        for req in requirements:
            section_key = req.section_uid or req.section_number or 'unknown'
            if section_key not in grouped:
                grouped[section_key] = []
            grouped[section_key].append(req)
        return grouped
    
    def _calculate_type_statistics(self, requirements: List[Requirement]) -> Dict[str, int]:
        """计算需求类型统计"""
        stats = {}
        for req in requirements:
            type_chinese = self.settings.type_chinese.get(req.type, '其他需求')
            if type_chinese not in stats:
                stats[type_chinese] = 0
            stats[type_chinese] += 1
        return stats
    
    def _should_include_section(self, section: Section) -> bool:
        """判断章节是否应该包含在输出中"""
        return not self.settings.is_non_requirement_section(section.title)
    
    def _build_requirement_content(self, sections: List[Section],
                                   reqs_by_section: Dict[str, List[Requirement]]) -> Dict[str, Any]:
        """构建需求内容的层次结构"""
        content = {}
        
        for section in sections:
            # 只处理需求相关章节
            if not self._should_include_section(section):
                # 但仍需检查子章节
                for child in section.children:
                    child_content = self._build_section_content_recursive(child, reqs_by_section)
                    if child_content:
                        key = f"{child.number} {child.title}" if child.number else child.title
                        content[key] = child_content
                continue
            
            section_content = self._build_section_content_recursive(section, reqs_by_section)
            if section_content:
                key = f"{section.number} {section.title}" if section.number else section.title
                content[key] = section_content
        
        return content
    
    def _build_section_content_recursive(self, section: Section,
                                         reqs_by_section: Dict[str, List[Requirement]]) -> Optional[Dict[str, Any]]:
        """递归构建章节内容"""
        # 检查是否应该包含此章节
        if not self._should_include_section(section):
            return None
        
        # 章节基本信息
        result = {
            "章节信息": {
                "章节编号": section.number or "",
                "章节标题": section.title,
                "章节级别": section.level
            }
        }
        
        # 检查是否有子章节
        has_valid_children = False
        subsections = {}
        
        for child in section.children:
            child_content = self._build_section_content_recursive(child, reqs_by_section)
            if child_content:
                has_valid_children = True
                key = f"{child.number} {child.title}" if child.number else child.title
                subsections[key] = child_content
        
        # 添加当前章节需求
        reqs = reqs_by_section.get(section.uid or section.number or 'unknown', [])
        reqs = sorted(reqs, key=lambda r: getattr(r, 'source_order', 0))
        if reqs:
            result["需求列表"] = []
            for req in reqs:
                # 需求类型放在最前面
                type_chinese = self.settings.type_chinese.get(req.type, '功能需求')
                req_dict = {
                    "需求类型": type_chinese,
                    "需求编号": req.id,
                    "需求描述": req.description
                }
                # 接口需求增加额外字段
                if req.type == 'interface':
                    req_dict["接口名称"] = req.interface_name
                    req_dict["接口类型"] = req.interface_type
                    req_dict["数据来源"] = req.source
                    req_dict["数据目的地"] = req.destination
                result["需求列表"].append(req_dict)
        
        # 如果有子章节，添加子章节
        if has_valid_children:
            result["子章节"] = subsections
        
        # 如果章节既没有需求也没有子章节，返回None
        if "需求列表" not in result and "子章节" not in result:
            return None
        
        return result
    
    def save_to_file(self, output: Dict[str, Any], file_path: str) -> None:
        """
        将输出保存到文件
        
        Args:
            output: 输出字典
            file_path: 输出文件路径
        """
        try:
            output_cfg = self.config.get("output", {})
            indent = output_cfg.get("indent", 2)
            pretty = output_cfg.get("pretty_print", True)
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(output, f, ensure_ascii=False, indent=indent if pretty else None)
            logger.info(f"成功保存JSON到: {file_path}")
        except Exception as e:
            logger.error(f"保存JSON文件失败: {e}")
            raise
    
    def generate_and_save(self, sections: List[Section], requirements: List[Requirement],
                         document_title: str, file_path: str) -> Dict[str, Any]:
        """
        生成并保存JSON
        
        Args:
            sections: 章节列表
            requirements: 需求列表
            document_title: 文档标题
            file_path: 输出文件路径
            
        Returns:
            生成的输出字典
        """
        output = self.generate(sections, requirements, document_title)
        self.save_to_file(output, file_path)
        return output
