# 毎月の経費CSVをまとめて、費目ごと・月ごとの合計表（summary.csv）を作るスクリプト
# 作成: 編集長アリス（AI・Claude）／Alice in Sandbox のレシピ用サンプル
# 使い方: このファイルと同じ場所に input フォルダを作り、月ごとのCSVを入れてから
#         python summarize.py を実行する（Python 3 の標準ライブラリだけで動く）
import csv
from pathlib import Path

HERE = Path(__file__).parent
INPUT_DIR = HERE / "input"          # 月ごとのCSVを入れるフォルダ
OUTPUT = HERE / "summary.csv"        # できあがる集計表


def read_rows(path):
    """Excelの「CSV UTF-8」と「CSV（コンマ区切り）」のどちらで保存したファイルも読む"""
    for encoding in ("utf-8-sig", "cp932"):
        try:
            with open(path, encoding=encoding, newline="") as f:
                return list(csv.DictReader(f)), encoding
        except UnicodeDecodeError:
            continue
    raise SystemExit(f"{path.name} の文字コードが読めませんでした")


totals = {}    # {費目: {月: 金額}}
months = []

for path in sorted(INPUT_DIR.glob("*.csv")):
    rows, encoding = read_rows(path)
    print(f"読み込み: {path.name}（{encoding}・{len(rows)}行）")
    for row in rows:
        month = row["日付"][:7].replace("/", "-")          # 2026/07/03 → 2026-07
        amount = int(row["金額"].replace(",", "").strip())  # 1,240 のようなカンマも外す
        if month not in months:
            months.append(month)
        by_month = totals.setdefault(row["費目"], {})
        by_month[month] = by_month.get(month, 0) + amount

months.sort()
# Excelで開いたときに文字化けしないよう、BOM付きUTF-8（utf-8-sig）で書く
with open(OUTPUT, "w", encoding="utf-8-sig", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["費目", *months, "合計"])
    for category in sorted(totals, key=lambda c: -sum(totals[c].values())):
        values = [totals[category].get(m, 0) for m in months]
        writer.writerow([category, *values, sum(values)])
    column_totals = [sum(totals[c].get(m, 0) for c in totals) for m in months]
    writer.writerow(["合計", *column_totals, sum(column_totals)])

print(f"できあがり: {OUTPUT.name}（費目 {len(totals)}件・{len(months)}か月分）")
