#!/usr/bin/env python3
"""
生成预算关键字分析HTML报告
读取analysis_results.json，按市州→区县→组织部/党校分层
关键字合并：同一区县同一单位下相同关键字合并为一行，金额累加，位置全列出
"""
import json
import os
from collections import defaultdict, OrderedDict

BASE_DIR = "/data/www/files/2026-yjs-cyl"
JSON_PATH = os.path.join(BASE_DIR, "analysis_results.json")
OUTPUT_HTML = os.path.join(BASE_DIR, "2026年 曾耀龙 负责市场区域预决算分析报告.html")

# 关键字颜色映射
KW_COLORS = {
    "网络培训": "#FF6B6B",
    "培训": "#4ECDC4",
    "能力提升": "#45B7D1",
    "视频拍摄": "#FFA07A",
    "党员教育片": "#98D8C8",
    "课程制作": "#F7DC6F",
    "直播": "#BB8FCE",
    "视频": "#85C1E9",
    "课件": "#F8B88B",
    "系统": "#82E0AA",
    "信息化": "#F1948A",
    "网络": "#AED6F1",
    "数字": "#D7BDE2",
    "设备": "#A3E4D7",
    "平台": "#F9E79F",
    "维护": "#D5A6BD",
    "软件": "#A9CCE3",
}

def load_data():
    with open(JSON_PATH, 'r', encoding='utf-8') as f:
        return json.load(f)

def merge_keywords(data):
    """
    按市州→区县→单位类型分层
    同一区县同一单位下相同关键字合并为一行，金额累加，位置全列出
    """
    # 构建分层结构
    cities = OrderedDict()
    
    for key, val in data.items():
        city = val['city']
        district = val['district'] if val['district'] else "未分类"
        unit_type = val['unit_type'] if val['unit_type'] else "未分类"
        
        if city not in cities:
            cities[city] = OrderedDict()
        if district not in cities[city]:
            cities[city][district] = OrderedDict()
        if unit_type not in cities[city][district]:
            cities[city][district][unit_type] = {
                'files': [],
                'keywords_merged': OrderedDict()
            }
        
        unit = cities[city][district][unit_type]
        
        for file_info in val['files']:
            file_entry = {
                'filename': file_info['filename'],
                'rel_path': file_info['rel_path'],
                'match_count': len(file_info['matches'])
            }
            unit['files'].append(file_entry)
            
            # 合并关键字
            for m in file_info['matches']:
                kw = m['keyword']
                if kw not in unit['keywords_merged']:
                    unit['keywords_merged'][kw] = {
                        'keyword': kw,
                        'amount': 0.0,
                        'locations': [],
                        'contents': [],
                        'count': 0,
                        'files': set()
                    }
                
                entry = unit['keywords_merged'][kw]
                entry['amount'] += m['amount']
                entry['count'] += 1
                entry['locations'].append(m['location'])
                entry['contents'].append(m['content'])
                entry['files'].add(file_info['filename'])
    
    return cities

def calc_totals(cities):
    """计算汇总数据"""
    total_files = 0
    total_matches = 0
    total_amount = 0.0
    total_cities = len(cities)
    total_districts = 0
    total_units = 0
    kw_dist = defaultdict(lambda: {'count': 0, 'amount': 0.0})
    
    for city, districts in cities.items():
        total_districts += len(districts)
        for district, units in districts.items():
            for unit_type, unit_data in units.items():
                total_files += len(unit_data['files'])
                for kw, kw_data in unit_data['keywords_merged'].items():
                    total_matches += kw_data['count']
                    total_amount += kw_data['amount']
                    kw_dist[kw]['count'] += kw_data['count']
                    kw_dist[kw]['amount'] += kw_data['amount']
                total_units += 1
    
    return {
        'total_files': total_files,
        'total_matches': total_matches,
        'total_amount': total_amount,
        'total_cities': total_cities,
        'total_districts': total_districts,
        'total_units': total_units,
        'kw_dist': dict(sorted(kw_dist.items(), key=lambda x: x[1]['count'], reverse=True))
    }

def generate_html(cities, totals):
    """生成完整HTML报告"""
    
    # 关键字分布条形图数据
    kw_dist = totals['kw_dist']
    max_kw_count = max([v['count'] for v in kw_dist.values()]) if kw_dist else 1
    
    kw_bars = ""
    for kw, data in kw_dist.items():
        pct = (data['count'] / max_kw_count * 100) if max_kw_count > 0 else 0
        color = KW_COLORS.get(kw, "#888")
        kw_bars += f'''
        <div class="kw-bar-item">
            <div class="kw-bar-label">{kw}</div>
            <div class="kw-bar-track">
                <div class="kw-bar-fill" style="width:{pct}%;background:{color}"></div>
                <span class="kw-bar-count">{data['count']}次</span>
            </div>
            <div class="kw-bar-amount">{data['amount']:.2f}万元</div>
        </div>'''
    
    # 市州导航卡片
    city_cards = ""
    city_sections = ""
    
    for city_idx, (city, districts) in enumerate(cities.items()):
        city_id = f"city_{city_idx}"
        city_amount = 0
        city_matches = 0
        city_files = 0
        for district, units in districts.items():
            for unit_type, unit_data in units.items():
                city_files += len(unit_data['files'])
                for kw, kw_data in unit_data['keywords_merged'].items():
                    city_matches += kw_data['count']
                    city_amount += kw_data['amount']
        
        city_cards += f'''
        <a href="#{city_id}" class="city-card">
            <div class="city-card-name">{city}</div>
            <div class="city-card-stats">
                <span>{len(districts)}区县</span>
                <span>{city_files}文件</span>
                <span>{city_amount:.2f}万元</span>
            </div>
        </a>'''
        
        # 市州详情区块
        district_blocks = ""
        for dist_idx, (district, units) in enumerate(districts.items()):
            dist_id = f"{city_id}_dist_{dist_idx}"
            
            # 组织部和党校分开展示
            unit_blocks = ""
            for unit_type, unit_data in units.items():
                unit_id = f"{dist_id}_unit_{unit_type}"
                
                # 汇总金额
                unit_amount = sum(kw_data['amount'] for kw_data in unit_data['keywords_merged'].values())
                unit_match_count = sum(kw_data['count'] for kw_data in unit_data['keywords_merged'].values())
                
                icon = "📋" if "组织部" in unit_type else ("🎓" if "党校" in unit_type else "📄")
                
                # 文件链接
                file_links = ""
                for fi in unit_data['files']:
                    safe_path = fi['rel_path'].replace("\\", "/")
                    file_links += f'<a href="{safe_path}" target="_blank" class="file-link">📂{fi["filename"]}</a>\n'
                
                # 关键字表格行
                table_rows = ""
                for kw, kw_data in unit_data['keywords_merged'].items():
                    color = KW_COLORS.get(kw, "#888")
                    # 位置合并显示（最多显示10个，超出显示...）
                    locs = kw_data['locations']
                    if len(locs) > 10:
                        loc_str = ', '.join(locs[:10]) + f' ...等{len(locs)}处'
                    else:
                        loc_str = ', '.join(locs)
                    
                    # 内容合并显示
                    contents = kw_data['contents']
                    unique_contents = list(dict.fromkeys(contents))  # 去重保持顺序
                    if len(unique_contents) > 3:
                        content_str = '<br>'.join(unique_contents[:3]) + f'<br><em>...等{len(unique_contents)}条内容</em>'
                    else:
                        content_str = '<br>'.join(unique_contents)
                    
                    # 文件列表
                    kw_files = sorted(kw_data['files'])
                    file_list = ', '.join(kw_files)
                    
                    table_rows += f'''
                    <tr>
                        <td><span class="kw-tag" style="background:{color}">{kw}</span></td>
                        <td>{content_str}</td>
                        <td class="loc-cell">{loc_str}</td>
                        <td class="amt-cell">{kw_data["amount"]:.2f}</td>
                        <td class="file-cell">{file_list}</td>
                    </tr>'''
                
                if not table_rows:
                    table_rows = '<tr><td colspan="5" class="no-data">无匹配数据</td></tr>'
                
                unit_blocks += f'''
                <div class="unit-block" id="{unit_id}">
                    <div class="unit-header">
                        <span class="unit-icon">{icon}</span>
                        <span class="unit-name">{unit_type}</span>
                        <span class="unit-summary">汇总：{unit_amount:.2f}万元 | {unit_match_count}条匹配</span>
                    </div>
                    <div class="unit-files">
                        {file_links}
                    </div>
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>关键字</th>
                                <th>匹配内容</th>
                                <th>文件位置</th>
                                <th>预算金额(万元)</th>
                                <th>来源文件</th>
                            </tr>
                        </thead>
                        <tbody>
                            {table_rows}
                        </tbody>
                    </table>
                </div>'''
            
            district_blocks += f'''
            <div class="district-block" id="{dist_id}">
                <div class="district-header" onclick="toggleDistrict('{dist_id}')">
                    <span class="district-arrow">▶</span>
                    <span class="district-name">{district}</span>
                </div>
                <div class="district-content" id="{dist_id}_content">
                    {unit_blocks}
                </div>
            </div>'''
        
        city_sections += f'''
        <div class="city-section" id="{city_id}">
            <div class="city-header" onclick="toggleCity('{city_id}')">
                <span class="city-arrow">▶</span>
                <span class="city-name">{city}</span>
                <span class="city-summary">{len(districts)}个区县 | {city_files}个文件 | {city_matches}条匹配 | {city_amount:.2f}万元</span>
            </div>
            <div class="city-content" id="{city_id}_content">
                {district_blocks}
            </div>
        </div>'''
    
    html = f'''<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>2026年 曾耀龙 负责市场区域预决算分析报告</title>
    <style>
        * {{ margin: 0; padding: 0; box-sizing: border-box; }}
        
        :root {{
            --bg-primary: #0f172a;
            --bg-secondary: #1e293b;
            --bg-card: #1e293b;
            --bg-hover: #334155;
            --text-primary: #f1f5f9;
            --text-secondary: #94a3b8;
            --text-muted: #64748b;
            --accent: #3b82f6;
            --accent-glow: rgba(59, 130, 246, 0.3);
            --border: #334155;
            --success: #10b981;
            --warning: #f59e0b;
            --danger: #ef4444;
        }}
        
        body {{
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
            background: var(--bg-primary);
            color: var(--text-primary);
            line-height: 1.6;
            min-height: 100vh;
        }}
        
        .header {{
            background: linear-gradient(135deg, #0f172a 0%, #1e293b 50%, #0f172a 100%);
            border-bottom: 2px solid var(--accent);
            padding: 30px 40px;
            position: sticky;
            top: 0;
            z-index: 100;
            box-shadow: 0 4px 20px rgba(0,0,0,0.3);
        }}
        
        .header h1 {{
            font-size: 24px;
            color: var(--text-primary);
            margin-bottom: 8px;
        }}
        
        .header .subtitle {{
            color: var(--text-secondary);
            font-size: 14px;
        }}
        
        .header .date {{
            color: var(--text-muted);
            font-size: 12px;
            margin-top: 4px;
        }}
        
        .container {{
            max-width: 1400px;
            margin: 0 auto;
            padding: 24px;
        }}
        
        /* 汇总卡片 */
        .summary-cards {{
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
            margin-bottom: 32px;
        }}
        
        .summary-card {{
            background: var(--bg-card);
            border: 1px solid var(--border);
            border-radius: 12px;
            padding: 20px;
            text-align: center;
            transition: all 0.3s;
        }}
        
        .summary-card:hover {{
            border-color: var(--accent);
            box-shadow: 0 0 20px var(--accent-glow);
            transform: translateY(-2px);
        }}
        
        .summary-card .value {{
            font-size: 32px;
            font-weight: 700;
            color: var(--accent);
            margin-bottom: 4px;
        }}
        
        .summary-card .label {{
            color: var(--text-secondary);
            font-size: 13px;
        }}
        
        .summary-card .unit {{
            font-size: 14px;
            color: var(--text-muted);
        }}
        
        /* 关键字分布 */
        .kw-distribution {{
            background: var(--bg-card);
            border: 1px solid var(--border);
            border-radius: 12px;
            padding: 24px;
            margin-bottom: 32px;
        }}
        
        .kw-distribution h2 {{
            font-size: 18px;
            margin-bottom: 20px;
            color: var(--text-primary);
            border-left: 4px solid var(--accent);
            padding-left: 12px;
        }}
        
        .kw-bar-item {{
            display: grid;
            grid-template-columns: 100px 1fr 120px;
            gap: 12px;
            align-items: center;
            margin-bottom: 10px;
        }}
        
        .kw-bar-label {{
            text-align: right;
            font-size: 13px;
            color: var(--text-secondary);
        }}
        
        .kw-bar-track {{
            position: relative;
            background: var(--bg-primary);
            border-radius: 6px;
            height: 28px;
            overflow: hidden;
        }}
        
        .kw-bar-fill {{
            height: 100%;
            border-radius: 6px;
            transition: width 0.5s ease;
            opacity: 0.8;
        }}
        
        .kw-bar-count {{
            position: absolute;
            right: 8px;
            top: 50%;
            transform: translateY(-50%);
            font-size: 12px;
            color: var(--text-primary);
            font-weight: 600;
        }}
        
        .kw-bar-amount {{
            text-align: right;
            font-size: 13px;
            color: var(--accent);
            font-weight: 600;
        }}
        
        /* 市州导航 */
        .city-nav {{
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            margin-bottom: 32px;
            justify-content: center;
        }}
        
        .city-card {{
            background: var(--bg-card);
            border: 1px solid var(--border);
            border-radius: 10px;
            padding: 16px 24px;
            text-decoration: none;
            color: var(--text-primary);
            transition: all 0.3s;
            text-align: center;
            min-width: 160px;
        }}
        
        .city-card:hover {{
            border-color: var(--accent);
            background: var(--bg-hover);
            transform: translateY(-2px);
            box-shadow: 0 4px 15px var(--accent-glow);
        }}
        
        .city-card-name {{
            font-size: 16px;
            font-weight: 700;
            margin-bottom: 6px;
        }}
        
        .city-card-stats {{
            display: flex;
            gap: 10px;
            justify-content: center;
            flex-wrap: wrap;
        }}
        
        .city-card-stats span {{
            font-size: 12px;
            color: var(--text-secondary);
        }}
        
        /* 搜索框 */
        .search-box {{
            margin-bottom: 24px;
        }}
        
        .search-box input {{
            width: 100%;
            padding: 12px 20px;
            background: var(--bg-card);
            border: 1px solid var(--border);
            border-radius: 8px;
            color: var(--text-primary);
            font-size: 14px;
            outline: none;
            transition: all 0.3s;
        }}
        
        .search-box input:focus {{
            border-color: var(--accent);
            box-shadow: 0 0 10px var(--accent-glow);
        }}
        
        /* 市州区块 */
        .city-section {{
            margin-bottom: 24px;
            background: var(--bg-card);
            border: 1px solid var(--border);
            border-radius: 12px;
            overflow: hidden;
        }}
        
        .city-header {{
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 16px 24px;
            cursor: pointer;
            background: var(--bg-secondary);
            transition: background 0.2s;
            user-select: none;
        }}
        
        .city-header:hover {{
            background: var(--bg-hover);
        }}
        
        .city-arrow {{
            font-size: 12px;
            color: var(--accent);
            transition: transform 0.3s;
        }}
        
        .city-arrow.expanded {{
            transform: rotate(90deg);
        }}
        
        .city-name {{
            font-size: 18px;
            font-weight: 700;
        }}
        
        .city-summary {{
            margin-left: auto;
            font-size: 13px;
            color: var(--text-secondary);
        }}
        
        .city-content {{
            display: none;
            padding: 16px;
        }}
        
        /* 区县区块 */
        .district-block {{
            margin-bottom: 16px;
            border: 1px solid var(--border);
            border-radius: 8px;
            overflow: hidden;
        }}
        
        .district-header {{
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 12px 20px;
            cursor: pointer;
            background: rgba(59, 130, 246, 0.05);
            transition: background 0.2s;
            user-select: none;
        }}
        
        .district-header:hover {{
            background: rgba(59, 130, 246, 0.12);
        }}
        
        .district-arrow {{
            font-size: 10px;
            color: var(--accent);
            transition: transform 0.3s;
        }}
        
        .district-arrow.expanded {{
            transform: rotate(90deg);
        }}
        
        .district-name {{
            font-size: 16px;
            font-weight: 600;
        }}
        
        .district-content {{
            display: none;
            padding: 12px;
        }}
        
        /* 单位区块 */
        .unit-block {{
            margin-bottom: 16px;
            background: var(--bg-primary);
            border: 1px solid var(--border);
            border-radius: 8px;
            padding: 16px;
        }}
        
        .unit-header {{
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 12px;
        }}
        
        .unit-icon {{
            font-size: 20px;
        }}
        
        .unit-name {{
            font-size: 15px;
            font-weight: 600;
            color: var(--text-primary);
        }}
        
        .unit-summary {{
            margin-left: auto;
            font-size: 13px;
            color: var(--accent);
            background: rgba(59, 130, 246, 0.1);
            padding: 4px 12px;
            border-radius: 20px;
        }}
        
        .unit-files {{
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
            margin-bottom: 12px;
        }}
        
        .file-link {{
            display: inline-flex;
            align-items: center;
            gap: 4px;
            padding: 4px 12px;
            background: var(--bg-secondary);
            border: 1px solid var(--border);
            border-radius: 6px;
            color: var(--text-secondary);
            text-decoration: none;
            font-size: 12px;
            transition: all 0.2s;
        }}
        
        .file-link:hover {{
            border-color: var(--accent);
            color: var(--text-primary);
        }}
        
        /* 数据表格 */
        .data-table {{
            width: 100%;
            border-collapse: collapse;
            font-size: 13px;
        }}
        
        .data-table th {{
            background: var(--bg-secondary);
            color: var(--text-secondary);
            padding: 10px 12px;
            text-align: left;
            font-weight: 600;
            border-bottom: 2px solid var(--border);
            position: sticky;
            top: 0;
        }}
        
        .data-table td {{
            padding: 8px 12px;
            border-bottom: 1px solid var(--border);
            color: var(--text-primary);
            vertical-align: top;
        }}
        
        .data-table tr:hover {{
            background: var(--bg-hover);
        }}
        
        .kw-tag {{
            display: inline-block;
            padding: 2px 10px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
            color: #fff;
            white-space: nowrap;
        }}
        
        .loc-cell {{
            font-family: 'Courier New', monospace;
            font-size: 12px;
            color: var(--text-secondary);
        }}
        
        .amt-cell {{
            font-weight: 700;
            color: var(--success);
            text-align: right;
        }}
        
        .file-cell {{
            font-size: 12px;
            color: var(--text-muted);
        }}
        
        .no-data {{
            text-align: center;
            color: var(--text-muted);
            padding: 20px;
        }}
        
        .footer {{
            text-align: center;
            padding: 24px;
            color: var(--text-muted);
            font-size: 12px;
            border-top: 1px solid var(--border);
            margin-top: 32px;
        }}
        
        @media (max-width: 768px) {{
            .summary-cards {{
                grid-template-columns: repeat(2, 1fr);
            }}
            .kw-bar-item {{
                grid-template-columns: 80px 1fr 100px;
            }}
            .data-table {{
                font-size: 11px;
            }}
        }}
    </style>
</head>
<body>
    <div class="header">
        <h1>2026年 曾耀龙 负责市场区域预决算分析报告</h1>
        <div class="subtitle">预算文件关键字分析 | 17项关键字全量匹配</div>
        <div class="date">生成时间：2026-07-22 | 分析范围：内江市、自贡市、成都市东部新区</div>
    </div>
    
    <div class="container">
        <!-- 汇总看板 -->
        <div class="summary-cards">
            <div class="summary-card">
                <div class="value">{totals['total_files']}</div>
                <div class="label">预算文件数</div>
            </div>
            <div class="summary-card">
                <div class="value">{totals['total_matches']}</div>
                <div class="label">总匹配项</div>
            </div>
            <div class="summary-card">
                <div class="value">{totals['total_amount']:.2f}<span class="unit">万元</span></div>
                <div class="label">预算总金额</div>
            </div>
            <div class="summary-card">
                <div class="value">{totals['total_cities']}</div>
                <div class="label">市州数</div>
            </div>
            <div class="summary-card">
                <div class="value">{totals['total_districts']}</div>
                <div class="label">区县数</div>
            </div>
            <div class="summary-card">
                <div class="value">{len(kw_dist)}</div>
                <div class="label">命中关键字数</div>
            </div>
        </div>
        
        <!-- 关键字分布 -->
        <div class="kw-distribution">
            <h2>关键字分布</h2>
            {kw_bars}
        </div>
        
        <!-- 市州导航 -->
        <div class="city-nav">
            {city_cards}
        </div>
        
        <!-- 搜索框 -->
        <div class="search-box">
            <input type="text" id="searchInput" placeholder="搜索区县、关键字、匹配内容..." oninput="filterContent()">
        </div>
        
        <!-- 市州详情 -->
        {city_sections}
        
        <div class="footer">
            2026年 曾耀龙 负责市场区域预决算分析报告 | 数据来源：政府预算公开文件 | 17项关键字全量匹配分析
        </div>
    </div>
    
    <script>
        function toggleCity(id) {{
            const content = document.getElementById(id + '_content');
            const arrow = document.querySelector(`#${{id}} .city-arrow`);
            if (content.style.display === 'none' || content.style.display === '') {{
                content.style.display = 'block';
                arrow.classList.add('expanded');
            }} else {{
                content.style.display = 'none';
                arrow.classList.remove('expanded');
            }}
        }}
        
        function toggleDistrict(id) {{
            const content = document.getElementById(id + '_content');
            const arrow = document.querySelector(`#${{id}} .district-arrow`);
            if (content.style.display === 'none' || content.style.display === '') {{
                content.style.display = 'block';
                arrow.classList.add('expanded');
            }} else {{
                content.style.display = 'none';
                arrow.classList.remove('expanded');
            }}
        }}
        
        function filterContent() {{
            const query = document.getElementById('searchInput').value.toLowerCase();
            const sections = document.querySelectorAll('.city-section');
            
            sections.forEach(section => {{
                let hasMatch = false;
                const rows = section.querySelectorAll('.data-table tbody tr');
                rows.forEach(row => {{
                    const text = row.textContent.toLowerCase();
                    if (query === '' || text.includes(query)) {{
                        row.style.display = '';
                        hasMatch = true;
                    }} else {{
                        row.style.display = 'none';
                    }}
                }});
                
                const blocks = section.querySelectorAll('.unit-block');
                blocks.forEach(block => {{
                    const visibleRows = block.querySelectorAll('.data-table tbody tr:not([style*="display: none"])');
                    block.style.display = visibleRows.length > 0 ? '' : 'none';
                }});
                
                const visibleBlocks = section.querySelectorAll('.unit-block:not([style*="display: none"])');
                
                if (query === '') {{
                    section.style.display = '';
                    const cityContent = section.querySelector('.city-content');
                    const cityArrow = section.querySelector('.city-arrow');
                    cityContent.style.display = 'none';
                    cityArrow.classList.remove('expanded');
                    
                    const distContents = section.querySelectorAll('.district-content');
                    const distArrows = section.querySelectorAll('.district-arrow');
                    distContents.forEach(c => c.style.display = 'none');
                    distArrows.forEach(a => a.classList.remove('expanded'));
                }} else {{
                    if (visibleBlocks.length > 0) {{
                        section.style.display = '';
                        hasMatch = true;
                        const cityContent = section.querySelector('.city-content');
                        const cityArrow = section.querySelector('.city-arrow');
                        cityContent.style.display = 'block';
                        cityArrow.classList.add('expanded');
                        
                        const distContents = section.querySelectorAll('.district-content');
                        const distArrows = section.querySelectorAll('.district-arrow');
                        distContents.forEach(c => c.style.display = 'block');
                        distArrows.forEach(a => a.classList.add('expanded'));
                    }} else {{
                        section.style.display = 'none';
                    }}
                }}
            }});
        }}
        
        // 默认展开第一个市州
        window.addEventListener('DOMContentLoaded', function() {{
            const firstCity = document.querySelector('.city-section');
            if (firstCity) {{
                const id = firstCity.id;
                toggleCity(id);
            }}
        }});
    </script>
</body>
</html>'''
    
    return html

def main():
    data = load_data()
    cities = merge_keywords(data)
    totals = calc_totals(cities)
    
    html = generate_html(cities, totals)
    
    with open(OUTPUT_HTML, 'w', encoding='utf-8') as f:
        f.write(html)
    
    print(f"报告已生成: {OUTPUT_HTML}")
    print(f"文件大小: {os.path.getsize(OUTPUT_HTML) / 1024:.1f} KB")
    
    # 打印汇总
    print(f"\n=== 汇总 ===")
    print(f"文件数: {totals['total_files']}")
    print(f"总匹配: {totals['total_matches']}")
    print(f"总金额: {totals['total_amount']:.2f}万元")
    print(f"市州数: {totals['total_cities']}")
    print(f"区县数: {totals['total_districts']}")
    print(f"单位数: {totals['total_units']}")
    print(f"\n关键字分布:")
    for kw, d in totals['kw_dist'].items():
        print(f"  {kw}: {d['count']}次, {d['amount']:.2f}万元")

if __name__ == '__main__':
    main()
