#!/usr/bin/env python3
"""Generate HTML report from wf-2026-data.json with clickable source file links."""
import json
import os
import urllib.parse
from collections import defaultdict

# Load data
with open("/data/www/files/wf-2026-data.json", "r", encoding="utf-8") as f:
    data = json.load(f)

# Base URL prefix for file links - files are in 2026-yjs-wf/ subdirectory
FILE_BASE = "2026-yjs-wf/"

# Keywords
KEYWORDS = [
    "党员教育", "干部教育", "干部培训", "教育培训",
    "人才", "党建", "党员", "干部",
    "网络", "信息化", "智慧",
    "平台", "系统", "运维", "维护",
    "视频", "会议"
]

# Aggregate stats
total_files = len(set(m["source_file"] for m in data))
total_matches = len(data)
total_amount = sum(m["amount"] for m in data if m["amount"])
amount_count = sum(1 for m in data if m["amount"])
cities_set = sorted(set(m["city"] for m in data))
counties_set = set()
for m in data:
    counties_set.add((m["city"], m["county"]))
total_counties = len(counties_set)

# Keyword stats
kw_stats = {}
for kw in KEYWORDS:
    matches = [m for m in data if m["keyword"] == kw]
    if matches:
        amount = sum(m["amount"] for m in matches if m["amount"])
        kw_stats[kw] = {"count": len(matches), "amount": amount}

# City stats
city_stats = {}
for city in cities_set:
    matches = [m for m in data if m["city"] == city]
    amount = sum(m["amount"] for m in matches if m["amount"])
    city_counties = set(m["county"] for m in matches)
    city_stats[city] = {
        "count": len(matches),
        "amount": amount,
        "counties": len(city_counties),
        "files": len(set(m["source_file"] for m in matches))
    }

# Group by city -> county -> unit_type -> keyword
hierarchy = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(list))))
for m in data:
    hierarchy[m["city"]][m["county"]][m["unit_type"]][m["keyword"]].append(m)

# Sort cities by match count descending
sorted_cities = sorted(cities_set, key=lambda c: -city_stats[c]["count"])

# Max keyword count for bar chart scaling
max_kw_count = max(v["count"] for v in kw_stats.values()) if kw_stats else 1

# Build keyword distribution bars
kw_bars_html = ""
for kw in KEYWORDS:
    if kw in kw_stats:
        s = kw_stats[kw]
        bar_width = int(s["count"] / max_kw_count * 100)
        kw_bars_html += 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: {bar_width}%"></div>
                <span class="kw-bar-count">{s['count']}</span>
            </div>
            <div class="kw-bar-amount">{s['amount']:.2f}万元</div>
        </div>"""

# Build city cards
city_cards_html = ""
for city in sorted_cities:
    s = city_stats[city]
    card_id = city.replace(" ", "_")
    city_cards_html += f"""
        <div class="city-card" onclick="toggleCity('{card_id}')">
            <div class="city-card-header">
                <div class="city-card-name">{city}</div>
                <div class="city-card-stats">
                    <span class="stat-chip">{s['files']}个文件</span>
                    <span class="stat-chip">{s['count']}条匹配</span>
                    <span class="stat-chip highlight">{s['amount']:.2f}万元</span>
                    <span class="stat-chip">{s['counties']}个区县</span>
                </div>
                <div class="city-card-toggle">▼</div>
            </div>
            <div class="city-card-body" id="{card_id}" style="display:none;">"""

    # Get counties for this city sorted by match count
    city_data = hierarchy[city]
    county_counts = {c: sum(len(ut) for ut in city_data[c].values()) for c in city_data}
    sorted_counties = sorted(city_data.keys(), key=lambda c: -county_counts[c])
    
    for county in sorted_counties:
        county_data = city_data[county]
        county_matches = sum(sum(len(kw_list) for kw_list in ut.values()) for ut in county_data.values())
        county_amount = sum(m["amount"] for ut in county_data.values() for kw_list in ut.values() for m in kw_list if m["amount"])
        
        city_cards_html += f"""
                <div class="county-section">
                    <div class="county-header" onclick="toggleCounty('{card_id}_{county}')">
                        <span class="county-name">📍 {county}</span>
                        <span class="stat-chip">{county_matches}条</span>
                        <span class="stat-chip highlight">{county_amount:.2f}万元</span>
                        <span class="toggle">▼</span>
                    </div>
                    <div class="county-body" id="{card_id}_{county}" style="display:none;">"""
        
        for unit_type, kw_data in sorted(county_data.items(), key=lambda x: -sum(len(v) for v in x[1].values())):
            unit_matches = sum(len(v) for v in kw_data.values())
            unit_amount = sum(m["amount"] for kw_list in kw_data.values() for m in kw_list if m["amount"])
            
            city_cards_html += f"""
                        <div class="unit-section">
                            <div class="unit-header">🏛️ {unit_type} <span class="stat-chip">{unit_matches}条</span> <span class="stat-chip">{unit_amount:.2f}万元</span></div>
                            <div class="unit-body">"""
            
            for kw, match_list in sorted(kw_data.items(), key=lambda x: -len(x[1])):
                # Merge entries with same keyword
                kw_amount = sum(m["amount"] for m in match_list if m["amount"])
                kw_locations = ", ".join(sorted(set(m["location"] for m in match_list)))
                # Get unique source files
                source_files = sorted(set(m["source_file"] for m in match_list))
                
                # Build clickable file links
                file_links_html = ""
                for sf in source_files:
                    encoded_path = urllib.parse.quote(FILE_BASE + sf)
                    display_name = os.path.basename(sf)
                    file_links_html += f'<a href="{encoded_path}" target="_blank" class="file-link" title="{sf}">📎 {display_name}</a>\n'
                
                city_cards_html += f"""
                                <div class="kw-row">
                                    <table class="kw-table">
                                        <thead>
                                            <tr>
                                                <th>关键字</th>
                                                <th>匹配内容</th>
                                                <th>文件位置</th>
                                                <th>预算金额</th>
                                                <th>来源文件</th>
                                            </tr>
                                        </thead>
                                        <tbody>"""
                
                # Show up to 5 sample matches
                shown = 0
                for m in match_list[:5]:
                    content = m["content"][:200].replace("<", "&lt;").replace(">", "&gt;")
                    amount_str = f"{m['amount']:.2f}万元" if m["amount"] else "—"
                    sf_encoded = urllib.parse.quote(FILE_BASE + m["source_file"])
                    sf_display = os.path.basename(m["source_file"])
                    city_cards_html += f"""
                                            <tr>
                                                <td class="kw-cell">{kw}</td>
                                                <td class="content-cell">{content}</td>
                                                <td class="loc-cell">{m['location']}</td>
                                                <td class="amount-cell">{amount_str}</td>
                                                <td class="file-cell"><a href="{sf_encoded}" target="_blank" class="file-link" title="{m['source_file']}">📎 {sf_display}</a></td>
                                            </tr>"""
                
                if len(match_list) > 5:
                    city_cards_html += f"""
                                            <tr class="more-row">
                                                <td colspan="5">... 还有 {len(match_list)-5} 条匹配</td>
                                            </tr>"""
                
                city_cards_html += """
                                        </tbody>
                                    </table>
                                </div>"""
            
            city_cards_html += """
                            </div>
                        </div>"""
        
        city_cards_html += """
                    </div>
                </div>"""
    
    city_cards_html += """
            </div>
        </div>"""

# Build city summary table rows
city_summary_rows = ""
for city in sorted_cities:
    s = city_stats[city]
    city_summary_rows += f"""
                    <tr>
                        <td class="city-name-cell">{city}</td>
                        <td>{s['files']}</td>
                        <td>{s['count']}</td>
                        <td class="amount-cell">{s['amount']:.2f}</td>
                        <td>{s['counties']}</td>
                    </tr>"""

# Get unique file list for file index section
all_files = sorted(set(m["source_file"] for m in data))
file_index_html = ""
for i, sf in enumerate(all_files, 1):
    encoded = urllib.parse.quote(FILE_BASE + sf)
    display = os.path.basename(sf)
    file_index_html += f'<a href="{encoded}" target="_blank" class="file-index-link">{i}. {display}</a>\n'

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; }}
body {{ background: #0f172a; color: #e2e8f0; font-family: 'Microsoft YaHei', sans-serif; padding: 20px; }}
.header {{ text-align: center; padding: 30px 0; border-bottom: 1px solid #334155; margin-bottom: 30px; }}
.header h1 {{ font-size: 28px; color: #38bdf8; margin-bottom: 8px; }}
.header p {{ color: #94a3b8; font-size: 14px; }}

.summary-board {{ display: grid; grid-template-columns: repeat(6, 1fr); gap: 16px; margin-bottom: 30px; }}
.summary-card {{ background: #1e293b; border: 1px solid #334155; border-radius: 12px; padding: 20px; text-align: center; }}
.summary-card .value {{ font-size: 28px; font-weight: bold; color: #38bdf8; }}
.summary-card .label {{ font-size: 13px; color: #94a3b8; margin-top: 6px; }}
.summary-card .unit {{ font-size: 14px; color: #64748b; }}

.section-title {{ font-size: 20px; color: #38bdf8; margin: 30px 0 16px; padding-bottom: 8px; border-bottom: 1px solid #334155; }}

.kw-bar-container {{ background: #1e293b; border-radius: 12px; padding: 20px; margin-bottom: 30px; }}
.kw-bar-item {{ display: grid; grid-template-columns: 100px 1fr 150px; gap: 12px; align-items: center; margin-bottom: 10px; }}
.kw-bar-label {{ text-align: right; color: #cbd5e1; font-size: 14px; }}
.kw-bar-track {{ position: relative; height: 28px; background: #0f172a; border-radius: 6px; overflow: hidden; }}
.kw-bar-fill {{ height: 100%; background: linear-gradient(90deg, #0ea5e9, #38bdf8); border-radius: 6px; }}
.kw-bar-count {{ position: absolute; right: 10px; top: 4px; color: #fff; font-size: 13px; line-height: 20px; }}
.kw-bar-amount {{ text-align: right; color: #fbbf24; font-size: 13px; }}

.city-table {{ width: 100%; border-collapse: collapse; margin-bottom: 30px; }}
.city-table th {{ background: #1e293b; color: #94a3b8; padding: 12px; text-align: left; font-size: 13px; border-bottom: 2px solid #334155; }}
.city-table td {{ padding: 10px 12px; border-bottom: 1px solid #1e293b; font-size: 14px; }}
.city-table tr:hover {{ background: #1e293b; }}
.city-name-cell {{ color: #38bdf8; font-weight: bold; }}
.amount-cell {{ color: #fbbf24; text-align: right; }}

.city-card {{ background: #1e293b; border: 1px solid #334155; border-radius: 12px; margin-bottom: 16px; overflow: hidden; }}
.city-card-header {{ display: flex; align-items: center; justify-content: space-between; padding: 16px 20px; cursor: pointer; transition: background 0.2s; }}
.city-card-header:hover {{ background: #334155; }}
.city-card-name {{ font-size: 18px; font-weight: bold; color: #38bdf8; }}
.city-card-stats {{ display: flex; gap: 8px; }}
.stat-chip {{ background: #0f172a; color: #94a3b8; padding: 4px 12px; border-radius: 20px; font-size: 12px; }}
.stat-chip.highlight {{ background: #134e4a; color: #5eead4; }}
.city-card-toggle {{ color: #38bdf8; font-size: 16px; }}
.city-card-body {{ padding: 0 20px 20px; }}

.county-section {{ margin-bottom: 16px; border: 1px solid #334155; border-radius: 8px; overflow: hidden; }}
.county-header {{ display: flex; align-items: center; justify-content: space-between; padding: 12px 16px; background: #0f172a; cursor: pointer; }}
.county-header:hover {{ background: #1e293b; }}
.county-name {{ color: #fbbf24; font-weight: bold; }}
.county-body {{ padding: 12px 16px; }}

.unit-section {{ margin-bottom: 12px; }}
.unit-header {{ color: #cbd5e1; font-weight: bold; margin-bottom: 8px; padding: 6px 10px; background: #0f172a; border-radius: 6px; }}
.unit-body {{ margin-left: 12px; }}

.kw-row {{ margin-bottom: 12px; }}
.kw-table {{ width: 100%; border-collapse: collapse; font-size: 12px; }}
.kw-table th {{ background: #0f172a; color: #64748b; padding: 6px 8px; text-align: left; border-bottom: 1px solid #334155; }}
.kw-table td {{ padding: 6px 8px; border-bottom: 1px solid #1e293b; vertical-align: top; }}
.kw-table tr:hover {{ background: #0f172a; }}
.kw-cell {{ color: #38bdf8; font-weight: bold; white-space: nowrap; }}
.content-cell {{ color: #cbd5e1; max-width: 300px; word-break: break-all; }}
.loc-cell {{ color: #64748b; white-space: nowrap; }}
.file-cell {{ white-space: nowrap; }}
.more-row td {{ color: #64748b; text-align: center; font-style: italic; padding: 8px; }}

.file-link {{ display: inline-block; color: #38bdf8; text-decoration: none; font-size: 12px; margin: 2px 4px; padding: 2px 8px; background: #0f172a; border: 1px solid #334155; border-radius: 4px; }}
.file-link:hover {{ background: #0ea5e9; color: #fff; }}

.file-index {{ background: #1e293b; border-radius: 12px; padding: 20px; margin-bottom: 30px; }}
.file-index-link {{ display: inline-block; color: #38bdf8; text-decoration: none; font-size: 12px; margin: 3px 6px; padding: 4px 10px; background: #0f172a; border: 1px solid #334155; border-radius: 4px; }}
.file-index-link:hover {{ background: #0ea5e9; color: #fff; }}

.footer {{ text-align: center; color: #475569; font-size: 12px; padding: 20px 0; border-top: 1px solid #334155; margin-top: 30px; }}

@media (max-width: 768px) {{
    .summary-board {{ grid-template-columns: repeat(2, 1fr); }}
    .kw-bar-item {{ grid-template-columns: 80px 1fr; }}
    .kw-bar-amount {{ display: none; }}
}}
</style>
</head>
<body>

<div class="header">
    <h1>2026年 王飞 负责市场区域预决算分析报告</h1>
    <p>数据来源：2026-yjs-wf 目录预算文件 | 生成日期：2026-07-22</p>
</div>

<div class="summary-board">
    <div class="summary-card">
        <div class="value">{total_files}</div>
        <div class="label">预算文件</div>
    </div>
    <div class="summary-card">
        <div class="value">{total_matches}</div>
        <div class="label">关键字匹配</div>
    </div>
    <div class="summary-card">
        <div class="value">{total_amount:.2f}<span class="unit">万元</span></div>
        <div class="label">预算金额合计</div>
    </div>
    <div class="summary-card">
        <div class="value">{len(cities_set)}</div>
        <div class="label">市州</div>
    </div>
    <div class="summary-card">
        <div class="value">{total_counties}</div>
        <div class="label">区县</div>
    </div>
    <div class="summary-card">
        <div class="value">{len(kw_stats)}</div>
        <div class="label">关键字</div>
    </div>
</div>

<div class="section-title">关键字分布</div>
<div class="kw-bar-container">
{kw_bars_html}
</div>

<div class="section-title">市州汇总</div>
<table class="city-table">
    <thead>
        <tr>
            <th>市州</th>
            <th>文件数</th>
            <th>匹配数</th>
            <th>预算金额（万元）</th>
            <th>区县数</th>
        </tr>
    </thead>
    <tbody>
{city_summary_rows}
    </tbody>
</table>

<div class="section-title">市州详情（点击展开）</div>
{city_cards_html}

<div class="section-title">来源文件索引（{len(all_files)}个文件）</div>
<div class="file-index">
{file_index_html}
</div>

<div class="footer">
    2026年 王飞 负责市场区域预决算分析报告 | 由 budget-keyword-analysis 技能自动生成
</div>

<script>
function toggleCity(id) {{
    var el = document.getElementById(id);
    if (el.style.display === 'none') {{
        el.style.display = 'block';
    }} else {{
        el.style.display = 'none';
    }}
}}
function toggleCounty(id) {{
    var el = document.getElementById(id);
    if (el.style.display === 'none') {{
        el.style.display = 'block';
    }} else {{
        el.style.display = 'none';
    }}
}}
</script>

</body>
</html>"""

output_path = "/data/www/files/wf-2026-report.html"
with open(output_path, "w", encoding="utf-8") as f:
    f.write(html)

print(f"HTML report generated: {output_path}")
print(f"File size: {os.path.getsize(output_path) / 1024:.1f} KB")
print(f"Total files: {total_files}")
print(f"Total matches: {total_matches}")
print(f"Total amount: {total_amount:.2f}万元")
print(f"Cities: {len(cities_set)}")
print(f"Counties: {total_counties}")
print(f"Keywords matched: {len(kw_stats)}")
