#  @line_count 200
"""新格式适配器（需求树格式）"""
from typing import List, Dict, Any
from .base_adapter import BaseParserAdapter


class RequirementTreeAdapter(BaseParserAdapter):
    """处理新格式：需求树结构"""
    
    def extract_function_points(self) -> List[Dict[str, Any]]:
        """从需求树中提取功能点"""
        function_points = []
        requirement_content = self.data.get('需求内容', {})
        
        # 递归遍历章节
        self._traverse_requirements(requirement_content, [], function_points)
        
        return function_points
    
    def _traverse_requirements(self, sections: Dict, path: List[str], 
                               function_points: List[Dict]):
        """递归遍历章节，提取需求"""
        for section_key, section_data in sections.items():
            section_info = section_data.get('章节信息', {})
            section_title = section_info.get('章节标题', '')
            current_path = path + [section_title]
            
            # 如果有需求列表，提取需求
            if '需求列表' in section_data:
                requirements = section_data['需求列表']
                for req in requirements:
                    function_points.append({
                        'module_name': ' > '.join(current_path[:-1]) if len(current_path) > 1 else section_title,
                        'function_name': req.get('需求编号', ''),
                        'description': req.get('需求描述', ''),
                        'requirement_id': req.get('需求编号', ''),
                        'requirement_type': self._parse_requirement_type(
                            req.get('需求编号', '')
                        ),
                        'interface_info': {
                            k: v for k, v in req.items() 
                            if k in ['接口名称', '接口类型', '来源', '目的地']
                        } if any(k in req for k in ['接口名称', '接口类型']) else None
                    })
            
            # 递归处理子章节
            if '子章节' in section_data:
                self._traverse_requirements(
                    section_data['子章节'], 
                    current_path, 
                    function_points
                )
    
    def _parse_requirement_type(self, req_id: str) -> str:
        """从需求编号解析需求类型"""
        if req_id.startswith('FR-'):
            return '功能需求'
        elif req_id.startswith('IR-'):
            return '接口需求'
        elif req_id.startswith('OR-'):
            return '其他需求'
        return '未知'
    
    def get_document_info(self) -> Dict[str, Any]:
        """获取文档信息"""
        metadata = self.data.get('文档元数据', {})
        return {
            'title': metadata.get('标题', ''),
            'version': '',  # 新格式可能没有版本
            'date': metadata.get('生成时间', ''),
            'section_count': self._count_sections(self.data.get('需求内容', {}))
        }
    
    def _count_sections(self, sections: Dict) -> int:
        """递归统计章节数量"""
        count = 0
        for section_data in sections.values():
            count += 1
            if '子章节' in section_data:
                count += self._count_sections(section_data['子章节'])
        return count
    
    def get_sections(self) -> List[Dict[str, Any]]:
        """获取章节列表（转换为扁平结构）"""
        sections = []
        self._flatten_sections(self.data.get('需求内容', {}), sections)
        return sections
    
    def _flatten_sections(self, sections: Dict, result: List[Dict]):
        """递归扁平化章节结构"""
        for section_data in sections.values():
            section_info = section_data.get('章节信息', {})
            result.append({
                'title': section_info.get('章节标题', ''),
                'number': section_info.get('章节编号', ''),
                'level': section_info.get('章节级别', 0),
                'requirement_count': len(section_data.get('需求列表', []))
            })
            if '子章节' in section_data:
                self._flatten_sections(section_data['子章节'], result)
    
    def get_module_summary(self) -> List[Dict[str, Any]]:
        """获取模块摘要"""
        modules = []
        sections_dict = {}
        
        # 遍历需求内容，构建模块统计
        self._build_module_summary(self.data.get('需求内容', {}), sections_dict)
        
        for module_name, info in sections_dict.items():
            modules.append({
                'name': module_name,
                'function_count': info['requirement_count'],
                'description': info.get('description', '')
            })
        
        return modules
    
    def _build_module_summary(self, sections: Dict, result: Dict):
        """递归构建模块摘要"""
        for section_data in sections.values():
            section_info = section_data.get('章节信息', {})
            section_title = section_info.get('章节标题', '')
            
            if '需求列表' in section_data:
                if section_title not in result:
                    result[section_title] = {
                        'requirement_count': 0,
                        'description': ''
                    }
                result[section_title]['requirement_count'] += len(section_data['需求列表'])
            
            if '子章节' in section_data:
                self._build_module_summary(section_data['子章节'], result)
    
    @staticmethod
    def can_parse(data: Dict[str, Any]) -> bool:
        """检测是否为新格式"""
        return '需求内容' in data and '文档元数据' in data
