#!/usr/bin/env python3
"""
Tab3内容生成器 - 整体结构理解
包含：整体解构（节点基础信息、整体实质×形式、纵向逻辑流）、段落解构
"""
import html as html_module
from typing import Dict, Any, List


def render_overall_deconstruction_card(overall: Dict[str, Any]) -> str:
    """渲染整体解构卡片"""
    card_id = "overall-deconstruction"
    
    html = f'<div class="point-card overall-card" data-card-id="{card_id}">\n'
    html += f'<div class="point-card-header" onclick="toggleCardDetails(\'{card_id}\')">\n'
    html += '<span class="point-text">整体解构</span>\n'
    html += '<span class="toggle-icon">▼</span>\n'
    html += '</div>\n'
    
    html += f'<div class="point-card-details" id="{card_id}-details">\n'
    
    # 节点基础信息
    basic_info = overall.get("节点基础信息", "")
    if basic_info:
        html += '<div class="detail-section">\n'
        html += '<strong>节点基础信息：</strong>\n'
        html += f'<div class="detail-text">{html_module.escape(basic_info)}</div>\n'
        html += '</div>\n'
    
    # 整体实质×形式
    substance_form = overall.get("整体实质×形式", {})
    if substance_form:
        html += '<div class="detail-section">\n'
        html += '<strong>整体实质×形式：</strong>\n'
        
        # 处理可能是字符串或字典的情况
        if isinstance(substance_form, dict):
            if substance_form.get("抽象概念"):
                html += f'<div class="form-item"><strong>抽象概念：</strong>{html_module.escape(substance_form["抽象概念"])}</div>\n'
            if substance_form.get("画面形式"):
                html += f'<div class="form-item"><strong>画面形式：</strong>{html_module.escape(substance_form["画面形式"])}</div>\n'
            if substance_form.get("文案形式"):
                html += f'<div class="form-item"><strong>文案形式：</strong>{html_module.escape(substance_form["文案形式"])}</div>\n'
            if substance_form.get("声音形式"):
                html += f'<div class="form-item"><strong>声音形式：</strong>{html_module.escape(substance_form["声音形式"])}</div>\n'
        elif isinstance(substance_form, str):
            html += f'<div class="form-item">{html_module.escape(substance_form)}</div>\n'
        
        html += '</div>\n'
    
    # 纵向逻辑流
    logic_flow = overall.get("纵向逻辑流", [])
    if logic_flow:
        html += '<div class="detail-section">\n'
        html += '<strong>纵向逻辑流：</strong>\n'
        html += '<div class="logic-flow">\n'
        for stage in logic_flow:
            stage_num = stage.get("阶段编号", "")
            stage_name = stage.get("阶段逻辑名称", "")
            stage_desc = stage.get("阶段逻辑描述", "")
            
            html += '<div class="logic-stage">\n'
            if stage_num:
                html += f'<div class="stage-number">阶段 {stage_num}</div>\n'
            if stage_name:
                html += f'<div class="stage-name">{html_module.escape(stage_name)}</div>\n'
            if stage_desc:
                html += f'<div class="stage-desc">{html_module.escape(stage_desc)}</div>\n'
            html += '</div>\n'
        html += '</div>\n'
        html += '</div>\n'
    
    html += '</div>\n'
    html += '</div>\n'
    return html


def render_paragraph_card(paragraph: Dict[str, Any], idx: int) -> str:
    """渲染段落解构卡片"""
    para_num = paragraph.get("段落序号", idx)
    time_range = paragraph.get("时间范围", "")
    units = paragraph.get("包含单元", [])
    full_text = paragraph.get("段落完整文案", "")
    
    card_id = f'paragraph-{para_num}'
    
    html = f'<div class="point-card paragraph-card" data-card-id="{card_id}">\n'
    html += f'<div class="point-card-header" onclick="toggleCardDetails(\'{card_id}\')">\n'
    html += f'<span class="point-number">段落 #{para_num}</span>\n'
    if time_range:
        html += f'<span class="point-time">{html_module.escape(time_range)}</span>\n'
    if units:
        units_str = ", ".join([str(u) for u in units])
        html += f'<span class="point-units">包含单元: {units_str}</span>\n'
    html += '<span class="toggle-icon">▼</span>\n'
    html += '</div>\n'
    
    html += f'<div class="point-card-details" id="{card_id}-details">\n'
    
    # 段落完整文案
    if full_text:
        html += '<div class="detail-section">\n'
        html += '<strong>段落完整文案：</strong>\n'
        html += f'<div class="detail-text">{html_module.escape(full_text)}</div>\n'
        html += '</div>\n'
    
    # 具体元素实质和形式
    concrete_elements = paragraph.get("具体元素实质和形式", [])
    if concrete_elements:
        html += '<div class="detail-section">\n'
        html += '<strong>具体元素实质和形式：</strong>\n'
        for elem in concrete_elements:
            elem_name = elem.get("具体元素名称", "")
            html += '<div class="sub-section">\n'
            if elem_name:
                html += f'<div class="element-name"><strong>{html_module.escape(elem_name)}</strong></div>\n'
            if elem.get("对应形式-文案"):
                html += f'<div class="form-item"><strong>对应形式-文案：</strong>{html_module.escape(elem["对应形式-文案"])}</div>\n'
            if elem.get("对应形式-画面"):
                html += f'<div class="form-item"><strong>对应形式-画面：</strong>{html_module.escape(elem["对应形式-画面"])}</div>\n'
            if elem.get("对应形式-声音"):
                html += f'<div class="form-item"><strong>对应形式-声音：</strong>{html_module.escape(elem["对应形式-声音"])}</div>\n'
            html += '</div>\n'
        html += '</div>\n'
    
    # 具象概念实质和形式
    concrete_concepts = paragraph.get("具象概念实质和形式", [])
    if concrete_concepts:
        html += '<div class="detail-section">\n'
        html += '<strong>具象概念实质和形式：</strong>\n'
        for concept in concrete_concepts:
            concept_name = concept.get("具象概念名称", "")
            html += '<div class="sub-section">\n'
            if concept_name:
                html += f'<div class="element-name"><strong>{html_module.escape(concept_name)}</strong></div>\n'
            if concept.get("对应形式-文案"):
                html += f'<div class="form-item"><strong>对应形式-文案：</strong>{html_module.escape(concept["对应形式-文案"])}</div>\n'
            if concept.get("对应形式-画面"):
                html += f'<div class="form-item"><strong>对应形式-画面：</strong>{html_module.escape(concept["对应形式-画面"])}</div>\n'
            if concept.get("对应形式-声音"):
                html += f'<div class="form-item"><strong>对应形式-声音：</strong>{html_module.escape(concept["对应形式-声音"])}</div>\n'
            html += '</div>\n'
        html += '</div>\n'
    
    # 抽象概念实质和形式
    abstract_concepts = paragraph.get("抽象概念实质和形式", [])
    if abstract_concepts:
        html += '<div class="detail-section">\n'
        html += '<strong>抽象概念实质和形式：</strong>\n'
        for concept in abstract_concepts:
            concept_name = concept.get("抽象概念名称", "")
            html += '<div class="sub-section">\n'
            if concept_name:
                html += f'<div class="element-name"><strong>{html_module.escape(concept_name)}</strong></div>\n'
            if concept.get("对应形式-文案"):
                html += f'<div class="form-item"><strong>对应形式-文案：</strong>{html_module.escape(concept["对应形式-文案"])}</div>\n'
            if concept.get("对应形式-画面"):
                html += f'<div class="form-item"><strong>对应形式-画面：</strong>{html_module.escape(concept["对应形式-画面"])}</div>\n'
            if concept.get("对应形式-声音"):
                html += f'<div class="form-item"><strong>对应形式-声音：</strong>{html_module.escape(concept["对应形式-声音"])}</div>\n'
            html += '</div>\n'
        html += '</div>\n'
    
    html += '</div>\n'
    html += '</div>\n'
    return html


def generate_tab3_content(data: Dict[str, Any]) -> str:
    """生成Tab3内容：整体结构理解"""
    html = '<div class="tab-content" id="tab3" style="display: none;">\n'
    html += '<div class="section">\n'
    html += '<h3>整体结构理解</h3>\n'
    
    structure_understanding = data.get("整体结构理解", {})
    
    if not structure_understanding:
        html += '<p>暂无数据</p>\n'
    else:
        # 整体解构
        overall = structure_understanding.get("整体解构", {})
        if overall:
            html += render_overall_deconstruction_card(overall)
        
        # 段落解构
        paragraph_list = structure_understanding.get("段落解构", [])
        if paragraph_list:
            html += '<div class="section-divider"></div>\n'
            html += f'<div class="section-info">共 {len(paragraph_list)} 个段落</div>\n'
            for idx, paragraph in enumerate(paragraph_list, start=1):
                html += render_paragraph_card(paragraph, idx)
    
    html += '</div>\n'
    html += '</div>\n'
    return html

