#!/usr/bin/env python3
"""
セミナー集客データを分析してグラフ画像を生成するスクリプト

【使い方】
1. このスクリプトと同じフォルダに以下の CSV を配置:
   - 年次データ.csv
   - 月別データ.csv

2. 実行:
     Mac:     python3 analyze_seminar_data.py
     Windows: python analyze_seminar_data.py

3. charts/ フォルダに以下のグラフ画像が生成される:
   - chart_trend.png       ... 年次トレンド（参加者+売上の複合）
   - chart_yoy.png         ... 前年比の推移
   - chart_monthly.png     ... 月別参加者（季節性）
   - chart_content.png     ... コンテンツ別シェア（円グラフ）

【必要なライブラリ】
講座サイトの requirements.txt に同梱されています。
未インストールの場合は以下を実行：
    pip3 install matplotlib       # Mac
    pip install matplotlib        # Windows
（本スクリプトは標準ライブラリの csv モジュールを使うので pandas は不要）
"""
import sys
import csv
from pathlib import Path

try:
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    from matplotlib import font_manager
except ImportError:
    print("❌ matplotlib が必要です: pip3 install matplotlib")
    sys.exit(1)

# 日本語フォント設定（Mac/Windows両対応の試行）
JP_FONTS = [
    "/System/Library/Fonts/Supplemental/Arial Unicode.ttf",   # Mac
    "/System/Library/Fonts/Hiragino Sans GB.ttc",             # Mac
    "C:/Windows/Fonts/meiryo.ttc",                            # Windows
    "C:/Windows/Fonts/YuGothM.ttc",                           # Windows
]
for fp in JP_FONTS:
    if Path(fp).exists():
        font_manager.fontManager.addfont(fp)
        plt.rcParams["font.family"] = font_manager.FontProperties(fname=fp).get_name()
        break
plt.rcParams["axes.unicode_minus"] = False

# カラーパレット
NAVY = "#1E40AF"
TEAL = "#0F766E"
AMBER = "#F59E0B"
RED = "#DC2626"
GREEN = "#059669"


def read_csv(path):
    with open(path, encoding="utf-8") as f:
        return list(csv.DictReader(f))


def chart_trend(data, output):
    """年次トレンド：参加者（棒）+ 売上（折れ線）"""
    years = [int(r["年度"]) for r in data]
    participants = [int(r["参加者数"]) for r in data]
    sales = [int(r["売上(万円)"]) for r in data]

    fig, ax1 = plt.subplots(figsize=(10, 5.5), dpi=160)
    bars = ax1.bar(years, participants, color=NAVY, alpha=0.85, width=0.55, label="参加者(人)")
    ax1.set_ylabel("参加者数（人）", fontsize=12, color=NAVY, fontweight="bold")
    ax1.tick_params(axis="y", labelcolor=NAVY)
    ax1.set_xticks(years)
    ax1.spines[["top", "right"]].set_visible(False)
    ax1.grid(axis="y", color="#E2E8F0", alpha=0.7)
    ax1.set_axisbelow(True)
    for b, v in zip(bars, participants):
        ax1.text(b.get_x() + b.get_width()/2, v + 15, f"{v}",
                 ha="center", fontsize=10, fontweight="bold", color=NAVY)

    ax2 = ax1.twinx()
    ax2.plot(years, sales, color=AMBER, linewidth=3, marker="o", markersize=10,
             markerfacecolor="white", markeredgecolor=AMBER, markeredgewidth=2.5,
             label="売上(万円)")
    ax2.set_ylabel("売上（万円）", fontsize=12, color=AMBER, fontweight="bold")
    ax2.tick_params(axis="y", labelcolor=AMBER)
    for x, v in zip(years, sales):
        ax2.text(x, v + 100, f"{v:,}", ha="center", fontsize=9, fontweight="bold", color=AMBER)

    fig.suptitle("図1. 年次トレンド（参加者・売上）", fontsize=14, fontweight="bold", y=1.02)
    fig.tight_layout()
    plt.savefig(output, dpi=180, bbox_inches="tight", facecolor="white")
    plt.close()
    print(f"  ✓ {output.name}")


def chart_yoy(data, output):
    """前年比の推移"""
    years = [int(r["年度"]) for r in data]
    participants = [int(r["参加者数"]) for r in data]
    sales = [int(r["売上(万円)"]) for r in data]
    yoy_p = [None] + [round((participants[i] - participants[i-1]) / participants[i-1] * 100, 1)
                      for i in range(1, len(participants))]
    yoy_s = [None] + [round((sales[i] - sales[i-1]) / sales[i-1] * 100, 1)
                      for i in range(1, len(sales))]

    fig, ax = plt.subplots(figsize=(10, 5), dpi=160)
    x = list(range(len(years)))
    w = 0.38
    bars_p = ax.bar([i - w/2 for i in x[1:]], yoy_p[1:], w, color=NAVY, label="参加者前年比")
    bars_s = ax.bar([i + w/2 for i in x[1:]], yoy_s[1:], w, color=AMBER, label="売上前年比")

    ax.set_xticks(x)
    ax.set_xticklabels(years)
    ax.axhline(y=0, color="#64748B", linewidth=0.8)
    ax.set_ylabel("前年比（%）", fontsize=12)
    ax.set_title("図2. 前年比の推移", fontsize=14, fontweight="bold", pad=14)
    ax.spines[["top", "right"]].set_visible(False)
    ax.grid(axis="y", color="#E2E8F0", alpha=0.7)
    ax.set_axisbelow(True)
    ax.legend(loc="lower right", framealpha=1)

    for b, v in zip(bars_p + bars_s, yoy_p[1:] + yoy_s[1:]):
        offset = 1.5 if v >= 0 else -3
        color = GREEN if v > 0 else RED
        ax.text(b.get_x() + b.get_width()/2, v + offset, f"{v:+.1f}%",
                ha="center", fontsize=9, fontweight="bold", color=color)

    fig.tight_layout()
    plt.savefig(output, dpi=180, bbox_inches="tight", facecolor="white")
    plt.close()
    print(f"  ✓ {output.name}")


def chart_monthly(data, output):
    """月別参加者（季節性発見）"""
    months = [r["月"] for r in data]
    parts = [int(r["参加者数"]) for r in data]
    sats = [float(r["満足度(5段階)"]) for r in data]

    fig, ax = plt.subplots(figsize=(11, 5.5), dpi=160)
    colors = [TEAL if p == max(parts) else NAVY if p >= 55 else "#94A3B8" for p in parts]
    bars = ax.bar(months, parts, color=colors, alpha=0.88, width=0.65)
    for b, v, s in zip(bars, parts, sats):
        ax.text(b.get_x() + b.get_width()/2, v + 1.5, f"{v}",
                ha="center", fontsize=10, fontweight="bold")
        ax.text(b.get_x() + b.get_width()/2, 3, f"⭐{s}",
                ha="center", fontsize=8, color="#475569")

    ax.set_ylabel("参加者（人）", fontsize=12, color=NAVY, fontweight="bold")
    ax.set_ylim(0, max(parts) + 12)
    ax.set_title("図3. 月別参加者数（2024年） — 棒色は規模別、下段は満足度",
                 fontsize=13, fontweight="bold", pad=14)
    ax.spines[["top", "right"]].set_visible(False)
    ax.grid(axis="y", color="#E2E8F0", alpha=0.7)
    ax.set_axisbelow(True)
    plt.setp(ax.get_xticklabels(), rotation=0, fontsize=10)
    fig.tight_layout()
    plt.savefig(output, dpi=180, bbox_inches="tight", facecolor="white")
    plt.close()
    print(f"  ✓ {output.name}")


def chart_content(data, output):
    """コンテンツ別シェア（円グラフ）"""
    by_content = {}
    for r in data:
        name = r["セミナー名"]
        p = int(r["参加者数"])
        by_content[name] = by_content.get(name, 0) + p
    labels = list(by_content.keys())
    sizes = list(by_content.values())
    colors = [NAVY, TEAL, AMBER, GREEN, RED, "#7C3AED", "#0891B2"][:len(labels)]

    fig, ax = plt.subplots(figsize=(9, 6), dpi=160)
    wedges, texts, autotexts = ax.pie(
        sizes, labels=labels, autopct="%1.1f%%",
        colors=colors, startangle=90,
        textprops={"fontsize": 11},
        wedgeprops={"edgecolor": "white", "linewidth": 2},
    )
    for at in autotexts:
        at.set_color("white")
        at.set_fontweight("bold")
        at.set_fontsize(11)
    ax.set_title("図4. コンテンツ別 参加者シェア（年間）", fontsize=14, fontweight="bold", pad=20)
    fig.tight_layout()
    plt.savefig(output, dpi=180, bbox_inches="tight", facecolor="white")
    plt.close()
    print(f"  ✓ {output.name}")


def main():
    script_dir = Path(__file__).parent
    year_csv = script_dir / "年次データ.csv"
    monthly_csv = script_dir / "月別データ.csv"
    out_dir = script_dir / "charts"
    out_dir.mkdir(exist_ok=True)

    if not year_csv.exists() or not monthly_csv.exists():
        print(f"❌ 入力 CSV が見つかりません")
        print(f"   必要: 年次データ.csv / 月別データ.csv")
        print(f"   サンプルは sample_data_raw/ にあります")
        sys.exit(1)

    print("📊 グラフ生成中...")
    year_data = read_csv(year_csv)
    monthly_data = read_csv(monthly_csv)

    chart_trend(year_data, out_dir / "chart_trend.png")
    chart_yoy(year_data, out_dir / "chart_yoy.png")
    chart_monthly(monthly_data, out_dir / "chart_monthly.png")
    chart_content(monthly_data, out_dir / "chart_content.png")

    print()
    print(f"✅ 完了。出力先: {out_dir}/")


if __name__ == "__main__":
    main()
