#!/usr/bin/env python3
"""森林×太陽光環境性能——図1〜14を生成する。

入力: data/assumptions.csv
出力: results/figures/*.png、results/summary.json、results/figures/captions.md
"""
from __future__ import annotations

import csv
import json
from pathlib import Path

from co2_balance import Co2Inputs, cumulative_timeseries, simple_annual_comparison
from economics import EconInputs, evaluate
from runoff_simple import compare
from water_balance import as_table, default_bundle

ROOT = Path(__file__).resolve().parents[1]
DATA = ROOT / "data" / "assumptions.csv"
FIG = ROOT / "results" / "figures"
RESULTS = ROOT / "results"

C_FOREST = "#2f7a4d"
C_GRASS = "#7a9e4a"
C_PV = "#1f5fbf"
C_SHEET = "#5a6a7a"
C_BARE = "#b54a3c"
C_MUTED = "#8a8f98"
C_INK = "#1a1d21"
C_WARN = "#b54a3c"
C_OK = "#2f7a4d"


def load() -> dict[str, float]:
    out: dict[str, float] = {}
    with DATA.open(encoding="utf-8") as f:
        for row in csv.DictReader(f):
            out[row["key"]] = float(row["base"])
    return out


def setup_plt():
    import matplotlib

    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    from matplotlib import font_manager
    from matplotlib.patches import FancyBboxPatch, Rectangle

    for cand in ("Hiragino Sans", "Hiragino Kaku Gothic ProN", "Noto Sans CJK JP", "IPAexGothic"):
        if any(cand in f.name for f in font_manager.fontManager.ttflist):
            plt.rcParams["font.family"] = cand
            break
    plt.rcParams.update(
        {
            "axes.unicode_minus": False,
            "figure.facecolor": "white",
            "axes.facecolor": "white",
            "axes.edgecolor": "#d0d4da",
            "axes.labelcolor": C_INK,
            "xtick.color": C_INK,
            "ytick.color": C_INK,
            "text.color": C_INK,
            "axes.titleweight": "semibold",
            "axes.titlesize": 11,
            "font.size": 10,
        }
    )
    plt.Rectangle = Rectangle
    plt.FancyBboxPatch = FancyBboxPatch
    return plt


def _footer(fig, text: str) -> None:
    fig.text(0.5, -0.02, text, ha="center", va="top", fontsize=8, color="#4a5560")


def fig01_surface_types(plt) -> str:
    fig, ax = plt.subplots(figsize=(10, 4.2))
    labels = ["健全な林床", "裸地化した\n人工林", "草地型PV", "防草シート型PV", "裸地化したPV"]
    colors = [C_FOREST, C_BARE, C_GRASS, C_SHEET, C_BARE]
    cover = [90, 15, 85, 95, 10]
    bars = ax.bar(labels, cover, color=colors, edgecolor="#d0d4da")
    ax.set_ylabel("地表面被覆率の説明用目安（%）")
    ax.set_ylim(0, 110)
    ax.set_title("図1　土地利用ごとの地表面被覆（説明用の目安。写真比較の補助）")
    for b, v in zip(bars, cover):
        ax.text(b.get_x() + b.get_width() / 2, v + 2, f"{v}%", ha="center", fontsize=9)
    _footer(fig, "実測の被覆率はサイト依存。図は類型の対比のための説明用。写真は別途掲載。")
    path = FIG / "fig01_surface_cover.png"
    fig.tight_layout()
    fig.savefig(path, dpi=200, bbox_inches="tight")
    plt.close(fig)
    return path.name


def fig02_cross_section(plt) -> str:
    fig, axes = plt.subplots(1, 3, figsize=(10, 3.6), sharey=True)
    titles = ["森林（下層あり）", "草地型PV", "防草シート型PV"]
    colors = [C_FOREST, C_GRASS, C_SHEET]
    notes = ["樹冠・落葉・細根", "パネル＋密な草本", "シートが雨滴を遮断"]
    for ax, t, c, n in zip(axes, titles, colors, notes):
        ax.set_xlim(0, 1)
        ax.set_ylim(0, 1)
        ax.add_patch(plt.Rectangle((0, 0), 1, 0.25, color="#c4a574"))
        ax.add_patch(plt.Rectangle((0, 0.25), 1, 0.12, color=c, alpha=0.85))
        ax.text(0.5, 0.55, n, ha="center", fontsize=10)
        ax.set_title(t)
        ax.axis("off")
    fig.suptitle("図2　断面の模式図（説明図。実測写真ではない）", y=1.02)
    _footer(fig, "模式図。根系深さ・浸透経路は簡略化している。")
    path = FIG / "fig02_cross_section.png"
    fig.tight_layout()
    fig.savefig(path, dpi=200, bbox_inches="tight")
    plt.close(fig)
    return path.name


def fig03_fcp_erosion(plt) -> str:
    # Approximate Miura relationship: relative TSS rises as FCP falls
    fcp = list(range(30, 95, 5))
    # normalized so FCP=80 → 1.0, each -10% FCP → ×1.66 on transportable sediment
    rel = []
    for x in fcp:
        # integrate roughly from 80 baseline
        steps = (80 - x) / 10.0
        rel.append((1.66**steps) if steps >= 0 else (1 / (1.66 ** (-steps))))
    fig, ax = plt.subplots(figsize=(8, 4.5))
    ax.plot(fcp, rel, color=C_BARE, marker="o")
    ax.axvline(80, color=C_OK, linestyle="--", label="目安 FCP 80%（三浦ら）")
    ax.set_xlabel("林床被覆率 FCP（%）")
    ax.set_ylabel("輸送可能土砂の相対量（FCP80%=1）")
    ax.set_title("図3　ヒノキ林の林床被覆率と土砂移動（三浦ら2015の関係の図示）")
    ax.legend()
    _footer(fig, "急傾斜ヒノキ林・飛散侵食が主。FCP10%低下でTSS約+66%（30–90%帯）。サイト外挿注意。")
    path = FIG / "fig03_fcp_erosion.png"
    fig.tight_layout()
    fig.savefig(path, dpi=200, bbox_inches="tight")
    plt.close(fig)
    return path.name


def fig04_throughfall(plt) -> str:
    fig, ax = plt.subplots(figsize=(8, 3.8))
    ax.axis("off")
    ax.set_xlim(0, 10)
    ax.set_ylim(0, 4)
    ax.text(5, 3.5, "図4　樹冠通過雨と林床保護（概念）", ha="center", fontsize=12, fontweight="semibold")
    ax.annotate("", xy=(5, 2.2), xytext=(5, 3.2), arrowprops=dict(arrowstyle="->", color=C_PV))
    ax.text(5.2, 2.7, "大きな滴が落下し得る", fontsize=9)
    ax.add_patch(plt.Rectangle((1, 0.4), 8, 0.8, color=C_FOREST, alpha=0.3))
    ax.text(5, 0.75, "下層植生・落葉が衝撃を緩和", ha="center")
    ax.text(5, 0.15, "樹冠があるだけでは地表面侵食が常に小さいとは限らない", ha="center", fontsize=9, color=C_WARN)
    path = FIG / "fig04_throughfall.png"
    fig.tight_layout()
    fig.savefig(path, dpi=200, bbox_inches="tight")
    plt.close(fig)
    return path.name


def fig05_water_vs_sediment(plt) -> str:
    fig, ax = plt.subplots(figsize=(8, 4.2))
    cats = ["裸地", "密な草地", "防草シート\n（被覆部）"]
    runoff = [1.0, 0.7, 1.1]
    sediment = [1.0, 0.25, 0.05]
    x = range(len(cats))
    w = 0.35
    ax.bar([i - w / 2 for i in x], runoff, width=w, label="雨水流出（相対）", color=C_PV)
    ax.bar([i + w / 2 for i in x], sediment, width=w, label="土砂流出（相対）", color=C_BARE)
    ax.set_xticks(list(x))
    ax.set_xticklabels(cats)
    ax.set_ylabel("相対量（裸地=1の説明用）")
    ax.set_title("図5　雨水流出と土砂流出は別の物理量")
    ax.legend()
    _footer(fig, "説明用。シート端部・排水先の侵食は別評価。流出が増えても土砂が減り得る。")
    path = FIG / "fig05_runoff_vs_sediment.png"
    fig.tight_layout()
    fig.savefig(path, dpi=200, bbox_inches="tight")
    plt.close(fig)
    return path.name


def fig06_water_balance(plt) -> str:
    rows = as_table(default_bundle())
    names = [r["name"].replace("（説明用）", "") for r in rows]
    et = [r["ET_mm"] for r in rows]
    q = [r["Q_mm"] for r in rows]
    fig, ax = plt.subplots(figsize=(9, 4.8))
    ax.bar(names, et, label="ET（仮定）", color=C_FOREST)
    ax.bar(names, q, bottom=et, label="Q=P−ET（残差）", color=C_PV, alpha=0.75)
    ax.axhline(1600, color=C_MUTED, linestyle=":", label="P=1600 mm（仮定）")
    ax.set_ylabel("mm / 年")
    ax.set_title("図6　年間水収支の説明用比較（仮定値）")
    ax.legend()
    plt.setp(ax.get_xticklabels(), rotation=15, ha="right")
    _footer(fig, "すべて kind=assumption。実測と混同しない。涵養は残差解釈であり地下水測定ではない。")
    path = FIG / "fig06_water_balance.png"
    fig.tight_layout()
    fig.savefig(path, dpi=200, bbox_inches="tight")
    plt.close(fig)
    return path.name


def fig07_rainfall_runoff(plt) -> str:
    fig, ax = plt.subplots(figsize=(8, 4.5))
    intensities = [30, 50, 80, 100, 150, 200, 300]
    for name, color in [("森林258", C_FOREST), ("草地128", C_GRASS), ("裸地79", C_BARE)]:
        inf = {"森林258": 258, "草地128": 128, "裸地79": 79}[name]
        ys = [max(0, r - inf) for r in intensities]
        ax.plot(intensities, ys, marker="o", label=name, color=color)
    ax.set_xlabel("降雨強度（mm/h）・継続1hの簡易モデル")
    ax.set_ylabel("浸透超過流出（mm）")
    ax.set_title("図7　降雨強度と浸透超過（教育用・災害予測不可）")
    ax.legend()
    _footer(fig, "飽和超過・地形・局所集中・パネル端部は未考慮。村井・岩崎の浸透能を閾値に使用。")
    path = FIG / "fig07_rainfall_runoff.png"
    fig.tight_layout()
    fig.savefig(path, dpi=200, bbox_inches="tight")
    plt.close(fig)
    return path.name


def fig08_co2_annual(plt, a: dict) -> str:
    uptake = a["forest_annual_co2_uptake_t"]
    avoided = a["pv_vs_lng_avoided_t_co2_yr"]
    fig, ax = plt.subplots(figsize=(7, 4.5))
    bars = ax.bar(
        ["森林の年間吸収\n（スギ説明例）", "太陽光の年間回避\n（LNG複合差・簡易）"],
        [uptake, avoided],
        color=[C_FOREST, C_PV],
    )
    ax.set_ylabel("t-CO₂ / 年・1ha相当")
    ax.set_title("図8　同一面積・同一年のフロー比較")
    for b, v in zip(bars, [uptake, avoided]):
        ax.text(b.get_x() + b.get_width() / 2, v + 5, f"{v:.1f}", ha="center")
    ax.text(0.5, 0.92, f"比 ≈ {avoided/uptake:.0f} 倍（ストック損失は含まない）", transform=ax.transAxes, ha="center")
    _footer(fig, "林野庁説明例8.8 t と電中研Y06原単位。蓄積304 tは別会計（図9）。")
    path = FIG / "fig08_co2_annual.png"
    fig.tight_layout()
    fig.savefig(path, dpi=200, bbox_inches="tight")
    plt.close(fig)
    return path.name


def fig09_co2_cumulative(plt) -> str:
    series = cumulative_timeseries(Co2Inputs())["series"]
    ys = [r["year"] for r in series]
    cum = [r["cumulative_t"] for r in series]
    fig, ax = plt.subplots(figsize=(8, 4.5))
    ax.plot(ys, cum, color=C_PV, lw=2)
    ax.axhline(0, color=C_MUTED, lw=1)
    ax.set_xlabel("年（0=転換時）")
    ax.set_ylabel("累積CO₂収支（t）正=純削減")
    ax.set_title("図9　累積CO₂収支（蓄積損失→運用回避）")
    pay = next((r["year"] for r in series if r["year"] > 0 and r["cumulative_t"] >= 0), None)
    if pay:
        ax.axvline(pay, color=C_OK, linestyle="--", label=f"回収 ≈ {pay} 年")
        ax.legend()
    _footer(fig, "年0に蓄積304 tを損失として計上。以降は回避−吸収機会喪失。代替電源・劣化は前提変更可。")
    path = FIG / "fig09_co2_cumulative.png"
    fig.tight_layout()
    fig.savefig(path, dpi=200, bbox_inches="tight")
    plt.close(fig)
    return path.name


def fig10_revenue(plt, a: dict) -> str:
    from economics import tariff_table

    rows = tariff_table(a["pv_annual_generation_kwh"])
    fig, ax = plt.subplots(figsize=(8, 4.2))
    ax.bar([str(r["tariff"]) for r in rows], [r["revenue_yen"] / 1e4 for r in rows], color=C_PV)
    ax.set_xlabel("売電単価（円/kWh）")
    ax.set_ylabel("年間売上高（万円）")
    ax.set_title("図10　1ha・77万kWhの売上高（利益ではない）")
    _footer(fig, "借入返済・税・保険・O&M・更新を差し引く前。制度・契約で単価は異なる。")
    path = FIG / "fig10_revenue.png"
    fig.tight_layout()
    fig.savefig(path, dpi=200, bbox_inches="tight")
    plt.close(fig)
    return path.name


def fig11_disaster_incentive(plt) -> str:
    fig, ax = plt.subplots(figsize=(9, 3.8))
    ax.axis("off")
    steps = ["異常発生", "発見\n（点検・監視）", "発電影響\n／損失", "早期修復", "再開"]
    for i, s in enumerate(steps):
        x = 0.5 + i * 1.8
        ax.add_patch(plt.FancyBboxPatch((x, 1.2), 1.5, 1.2, boxstyle="round,pad=0.05", facecolor="#eef4fb", edgecolor=C_PV))
        ax.text(x + 0.75, 1.8, s, ha="center", va="center", fontsize=9)
        if i < len(steps) - 1:
            ax.annotate("", xy=(x + 1.55, 1.8), xytext=(x + 1.5, 1.8), arrowprops=dict(arrowstyle="->", color=C_MUTED))
    ax.set_xlim(0, 10)
    ax.set_ylim(0, 4)
    ax.text(5, 3.4, "図11　継続収益がある土地での復旧インセンティブ（概念）", ha="center", fontsize=12, fontweight="semibold")
    ax.text(5, 0.5, "収益が薄い土地では発見・修復の遅延と公的負担が増えやすい場合がある（仮説と実証を区別）", ha="center", fontsize=9)
    path = FIG / "fig11_recovery_incentive.png"
    fig.tight_layout()
    fig.savefig(path, dpi=200, bbox_inches="tight")
    plt.close(fig)
    return path.name


def fig12_recovery_placeholder(plt) -> str:
    fig, ax = plt.subplots(figsize=(8, 3.5))
    ax.axis("off")
    ax.text(0.5, 0.6, "図12　災害復旧の実例枠", ha="center", fontsize=14, transform=ax.transAxes)
    ax.text(
        0.5,
        0.35,
        "費用・工期・負担主体付きの写真は、許諾確認後に差し込む。\n撮影リストは photos/shoot_list.md。",
        ha="center",
        transform=ax.transAxes,
        fontsize=10,
        color=C_MUTED,
    )
    path = FIG / "fig12_recovery_case.png"
    fig.tight_layout()
    fig.savefig(path, dpi=200, bbox_inches="tight")
    plt.close(fig)
    return path.name


def fig13_risk_over_time(plt) -> str:
    import numpy as np

    t = np.linspace(0, 100, 50)
    early = 10 + 0.05 * t
    late = 10 + 0.35 * t + 0.002 * t**2
    fig, ax = plt.subplots(figsize=(8, 4.2))
    ax.plot(t, early, label="早期発見・復旧", color=C_OK)
    ax.plot(t, late, label="長期放置", color=C_BARE)
    ax.set_xlabel("時間（相対）")
    ax.set_ylabel("累積環境負荷（概念）")
    ax.set_title("図13　初期被害が同程度でも、放置で累積負荷が分岐する")
    ax.legend()
    _footer(fig, "概念図。縦軸は実測単位ではない。発生確率だけでは長期性能を測れない。")
    path = FIG / "fig13_risk_time.png"
    fig.tight_layout()
    fig.savefig(path, dpi=200, bbox_inches="tight")
    plt.close(fig)
    return path.name


def fig14_matrix(plt) -> str:
    metrics = [
        "表面侵食抑制",
        "雨水浸透",
        "蒸発散（水資源）",
        "洪水ピーク抑制",
        "CO₂フロー",
        "生物多様性",
        "維持管理資金",
        "復旧インセンティブ",
    ]
    # qualitative: 2=相対的に有利になりやすい条件あり, 1=条件依存, 0=不利になりやすい — NOT a score to sum
    data = {
        "健全森林": [2, 2, 0, 1, 1, 2, 1, 1],
        "過密人工林": [0, 1, 0, 1, 1, 1, 0, 0],
        "草地型PV": [2, 1, 1, 1, 2, 1, 2, 2],
        "シート型PV": [2, 0, 1, 1, 2, 0, 2, 2],
        "管理不良PV": [0, 0, 1, 0, 2, 0, 0, 1],
    }
    import numpy as np

    mat = np.array(list(data.values()))
    fig, ax = plt.subplots(figsize=(10, 4.8))
    im = ax.imshow(mat, cmap="RdYlGn", vmin=0, vmax=2, aspect="auto")
    ax.set_xticks(range(len(metrics)))
    ax.set_xticklabels(metrics, rotation=30, ha="right")
    ax.set_yticks(range(len(data)))
    ax.set_yticklabels(list(data.keys()))
    ax.set_title("図14　独立指標の条件付き傾向（加点して総合点にしない）")
    cbar = fig.colorbar(im, ax=ax, ticks=[0, 1, 2])
    cbar.ax.set_yticklabels(["不利側", "条件依存", "有利側"])
    _footer(fig, "色は議論の地図。サイト条件で逆転する。数値スコアの合計は行わない。")
    path = FIG / "fig14_indicator_matrix.png"
    fig.tight_layout()
    fig.savefig(path, dpi=200, bbox_inches="tight")
    plt.close(fig)
    return path.name


CAPTIONS = {
    "fig01_surface_cover.png": "土地利用類型ごとの地表面被覆の説明用目安。",
    "fig02_cross_section.png": "森林・草地型PV・シート型PVの断面模式図（説明図）。",
    "fig03_fcp_erosion.png": "ヒノキ林の林床被覆率と輸送土砂の相対関係（三浦ら2015に基づく図示）。",
    "fig04_throughfall.png": "樹冠通過雨と下層による衝撃緩和の概念図。",
    "fig05_runoff_vs_sediment.png": "雨水流出と土砂流出が独立しうることを示す説明用棒グラフ。",
    "fig06_water_balance.png": "年水収支の説明用スタック（仮定のET）。",
    "fig07_rainfall_runoff.png": "浸透超過の簡易比較（災害予測不可）。",
    "fig08_co2_annual.png": "森林年間吸収と太陽光回避排出のフロー比較。",
    "fig09_co2_cumulative.png": "蓄積損失を年0に載せた累積CO₂収支。",
    "fig10_revenue.png": "売電単価別の年間売上高（利益ではない）。",
    "fig11_recovery_incentive.png": "継続収益と復旧インセンティブの概念図。",
    "fig12_recovery_case.png": "実例写真の差し込み枠。",
    "fig13_risk_time.png": "早期復旧と放置の累積負荷分岐（概念）。",
    "fig14_indicator_matrix.png": "独立指標の条件付き傾向表（総合点なし）。",
}


def main() -> None:
    FIG.mkdir(parents=True, exist_ok=True)
    plt = setup_plt()
    a = load()
    names = [
        fig01_surface_types(plt),
        fig02_cross_section(plt),
        fig03_fcp_erosion(plt),
        fig04_throughfall(plt),
        fig05_water_vs_sediment(plt),
        fig06_water_balance(plt),
        fig07_rainfall_runoff(plt),
        fig08_co2_annual(plt, a),
        fig09_co2_cumulative(plt),
        fig10_revenue(plt, a),
        fig11_disaster_incentive(plt),
        fig12_recovery_placeholder(plt),
        fig13_risk_over_time(plt),
        fig14_matrix(plt),
    ]
    summary = {
        "figures": names,
        "co2_simple": simple_annual_comparison(Co2Inputs()),
        "co2_payback_year": cumulative_timeseries(Co2Inputs())["payback_year"],
        "runoff_at_100mmh": compare(100),
        "economics": evaluate(EconInputs()),
        "water_balance_assumption": as_table(default_bundle()),
    }
    (RESULTS / "summary.json").write_text(json.dumps(summary, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    cap = ["# 図キャプション\n"] + [f"- `{k}`: {v}" for k, v in CAPTIONS.items()]
    (FIG / "captions.md").write_text("\n".join(cap) + "\n", encoding="utf-8")
    print("wrote", len(names), "figures")


if __name__ == "__main__":
    main()
