"""保存済み集計だけを読む。API・学習モデルは不要。"""
import argparse
import pandas as pd
import plotly.express as px
from gp_common import Run, checked_run

def plot(folder, root="outputs/gp_runs"):
    folder, meta = checked_run(folder)
    run = Run("saved-plots", folder / "metadata.json", {"source_run": meta["run_id"], "offline_html": True}, root)
    specs = [("month.csv", "month", "review_count", "date_basis", "取得CSV内の月別レビュー件数"),
             ("day.csv", "day", "mean_score", "date_basis", "有効評価の平均（0点補完なし）"),
             ("stars.csv", "score_valid", "count", None, "有効な星評価の件数"),
             ("versions.csv", "version", "review_count", None, "取得CSV内のバージョン別件数"),
             ("daily_stars.csv", "day", "ratio", "score_valid", "日別の有効評価構成比（分母を確認）"),
             ("monthly_stars.csv", "month", "ratio", "score_valid", "月別の有効評価構成比（分母を確認）"),
             ("version_stars.csv", "version", "ratio", "score_valid", "バージョン別の有効評価構成比"),
             ("sentiment_monthly.csv", "month", "count", "label", "辞書判定の月別件数"),
             ("term_frequency.csv", "term", "occurrences", None, "単語の延べ出現回数"),
             ("lda_monthly.csv", "month", "count", "topic_id", "LDA月別割当件数"),
             ("bertopic_monthly.csv", "month", "count", "topic_id", "BERTopic月別割当件数（外れ値除外）")]
    for name, x, y, color, title in specs:
        if name not in meta["files"]:
            continue
        d = pd.read_csv(folder / name, dtype={x: str}, keep_default_na=False)
        if d.empty:
            run.meta["skipped"][name] = "集計対象0件"
            continue
        d[y] = pd.to_numeric(d[y], errors="coerce")
        if color:
            d[color] = d[color].astype(str)
        if "date_basis" in d:
            d["date_basis"] = d["date_basis"].replace({"timezone_unknown_wall_clock": "時刻帯不明"})
        fig = px.bar(d, x=x, y=y, color=color, title=title,
                     facet_row="date_basis" if "date_basis" in d and color != "date_basis" else None,
                     hover_data=[c for c in d.columns if c not in [x, y, color]])
        fig.update_layout(barmode="stack" if y == "ratio" else "group",
                          legend=dict(orientation="h", y=-0.3, x=0), legend_title_text="",
                          title_font_size=13)
        fig.update_xaxes(type="category", title_text={"month": "投稿日（月）", "day": "投稿日", "version": "バージョン", "term": "語", "score_valid": "星評価"}.get(x,x))
        fig.update_yaxes(title_text={"count": "件数", "review_count": "件数", "mean_score": "平均評価", "ratio": "構成比", "occurrences": "出現回数"}.get(y,y))
        if y == "ratio":
            fig.update_yaxes(tickformat=".0%")
        run.figure(name.replace(".csv", ".html"), fig)
    return run.finish()

if __name__ == "__main__":
    p = argparse.ArgumentParser(); p.add_argument("run_folder"); plot(p.parse_args().run_folder)
