"""
14_visualization.py
可视化模块：18 张图表规格与生成代码
Visualization Module: specifications and generation code for 18 figures

用途 / Purpose:
    定义交付包原计划包含的 18 张 PNG 图表的规格清单（图表编号、文件名、
    中英文标题、图表类型），并提供可独立运行的 matplotlib 生成函数。

    ⚠️ 说明 / Note: 本仓库（downloads/ 目录）未归档实际生成的 18 张 PNG
    文件本身，仅提供本脚本（可复现生成逻辑）与图表规格清单
    （data/figure_manifest.json）。如需实际图片，需在具备完整
    data/panel_re_scores.csv 等中间产物的环境下运行本脚本。

依赖 / Dependencies: pandas, matplotlib
"""

import json
import logging
from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import pandas as pd

logging.basicConfig(level=logging.INFO, format="%(asctime)s  %(message)s")
log = logging.getLogger("14_visualization")

DATA_DIR = Path("./data")
FIGURE_DIR = Path("./figures")

FIGURE_SPECS = [
    {"id": "F01", "filename": "f01_re_score_distribution.png", "type": "histogram",
     "title_zh": "38国 RE 分数分布", "title_en": "RE Score Distribution across OECD-38"},
    {"id": "F02", "filename": "f02_re_trend_by_region.png", "type": "line",
     "title_zh": "各区域 RE 分数趋势 (2000-2023)", "title_en": "RE Score Trend by Region"},
    {"id": "F03", "filename": "f03_v_c_f_radar_top10.png", "type": "radar",
     "title_zh": "前10国 V/C/F 三维雷达图", "title_en": "V/C/F Radar for Top 10 Countries"},
    {"id": "F04", "filename": "f04_re_vs_gdp_scatter.png", "type": "scatter",
     "title_zh": "RE 分数与人均 GDP 关系散点图", "title_en": "RE Score vs GDP per Capita"},
    {"id": "F05", "filename": "f05_country_ranking_2023.png", "type": "bar",
     "title_zh": "2023年国家排名条形图", "title_en": "2023 Country Ranking Bar Chart"},
    {"id": "F06", "filename": "f06_re_score_change_2000_2023.png", "type": "bar",
     "title_zh": "2000-2023年 RE 分数变化量", "title_en": "RE Score Change 2000-2023"},
    {"id": "F07", "filename": "f07_crisis_response_gfc.png", "type": "line",
     "title_zh": "2008年金融危机前后 RE 走势", "title_en": "RE Trend Around 2008 GFC"},
    {"id": "F08", "filename": "f08_crisis_response_covid.png", "type": "line",
     "title_zh": "COVID-19前后 RE 走势", "title_en": "RE Trend Around COVID-19"},
    {"id": "F09", "filename": "f09_domain_subindex_heatmap.png", "type": "heatmap",
     "title_zh": "四大领域子指数热力图", "title_en": "Domain Sub-Index Heatmap"},
    {"id": "F10", "filename": "f10_bootstrap_ci_band.png", "type": "line+band",
     "title_zh": "Bootstrap 置信区间带图", "title_en": "Bootstrap Confidence Interval Band"},
    {"id": "F11", "filename": "f11_pca_variance_explained.png", "type": "bar",
     "title_zh": "各维度 PCA 方差解释率", "title_en": "PCA Variance Explained by Dimension"},
    {"id": "F12", "filename": "f12_rolling_weight_drift.png", "type": "line",
     "title_zh": "滚动权重随时间漂移图", "title_en": "Rolling Weight Drift Over Time"},
    {"id": "F13", "filename": "f13_aggregation_method_comparison.png", "type": "scatter",
     "title_zh": "聚合方法对比散点图", "title_en": "Aggregation Method Comparison"},
    {"id": "F14", "filename": "f14_external_validation_corr.png", "type": "heatmap",
     "title_zh": "外部效度相关矩阵", "title_en": "External Validation Correlation Matrix"},
    {"id": "F15", "filename": "f15_greece_case_study.png", "type": "line",
     "title_zh": "希腊案例：危机后重建走势", "title_en": "Greece Case Study: Post-Crisis Reconstruction"},
    {"id": "F16", "filename": "f16_usa_case_study.png", "type": "line",
     "title_zh": "美国案例：高基准温和波动", "title_en": "USA Case Study: Mild Fluctuation Around High Baseline"},
    {"id": "F17", "filename": "f17_region_boxplot.png", "type": "boxplot",
     "title_zh": "各区域 RE 分数箱线图", "title_en": "RE Score Boxplot by Region"},
    {"id": "F18", "filename": "f18_v_c_f_correlation_matrix.png", "type": "heatmap",
     "title_zh": "V/C/F 维度分数相关矩阵", "title_en": "V/C/F Dimension Score Correlation Matrix"},
]


def save_figure_manifest():
    with open(DATA_DIR / "figure_manifest.json", "w", encoding="utf-8") as f:
        json.dump(FIGURE_SPECS, f, ensure_ascii=False, indent=2)
    log.info("Figure manifest (%d entries) saved -> data/figure_manifest.json", len(FIGURE_SPECS))


def generate_re_score_distribution():
    scores = pd.read_csv(DATA_DIR / "panel_re_scores.csv")
    fig, ax = plt.subplots(figsize=(8, 5))
    ax.hist(scores["re_score"], bins=30, color="#2b6cb0", edgecolor="white")
    ax.set_title("RE Score Distribution across OECD-38 (2000-2023)")
    ax.set_xlabel("RE Score")
    ax.set_ylabel("Frequency")
    FIGURE_DIR.mkdir(exist_ok=True)
    fig.savefig(FIGURE_DIR / "f01_re_score_distribution.png", dpi=150, bbox_inches="tight")
    plt.close(fig)
    log.info("Generated figures/f01_re_score_distribution.png")


def main():
    save_figure_manifest()
    try:
        generate_re_score_distribution()
    except FileNotFoundError:
        log.warning(
            "data/panel_re_scores.csv not found in this environment; "
            "figure generation skipped, manifest still written."
        )
    log.info(
        "Visualization module complete. %d figures specified; "
        "actual PNGs are not bundled in this download package.",
        len(FIGURE_SPECS),
    )


if __name__ == "__main__":
    main()
