import argparse
import json
from collections import Counter
import pandas as pd
from janome.tokenizer import Tokenizer
from gp_common import Run, load_reviews
from gp_text_analysis import tokenize

# 教材用の小さい辞書。課金・広告などを一律に負の語へ追加しない。
SENTIMENT = {"楽しい": 1, "良い": 1, "好き": 1, "重い": -1, "悪い": -1}

def analyze(path="outputs/google_play_reviews.csv", root="outputs/gp_runs", dictionary=SENTIMENT):
    df = load_reviews(path); tokenizer = Tokenizer()
    run = Run("sentiment", path, {"dictionary": dictionary, "method": "base-form exact token count; negation not resolved"}, root)
    results, terms = [], Counter()
    for _, row in df.iterrows():
        counts = Counter(tokenize(row["content_raw"], tokenizer))
        matched = [{"term": w, "weight": dictionary[w], "count": n} for w, n in counts.items() if w in dictionary]
        score = sum(m["weight"] * m["count"] for m in matched)
        label = "unmatched" if not matched else "positive" if score > 0 else "negative" if score < 0 else "balanced"
        terms.update({m["term"]: m["count"] for m in matched})
        results.append((json.dumps(matched, ensure_ascii=False), sum(m["count"] for m in matched), score if matched else None, label))
    for i, col in enumerate(["matched_terms", "matched_count", "sentiment_score", "label"]):
        df[col] = [r[i] for r in results]
    run.csv("review_sentiment.csv", df)
    valid = df[df["month"].ne("")]
    monthly = valid.groupby(["date_basis", "month", "label"]).size().reset_index(name="count")
    monthly["denominator"] = monthly.groupby(["date_basis", "month"])["count"].transform("sum")
    monthly["ratio"] = monthly["count"] / monthly["denominator"]
    run.csv("sentiment_monthly.csv", monthly)
    summary = valid.groupby(["date_basis", "month"]).agg(
        review_count=("row_id", "size"), scored_count=("sentiment_score", "count"),
        mean_matched_score=("sentiment_score", "mean"), unmatched_count=("label", lambda s: int(s.eq("unmatched").sum()))).reset_index()
    summary["unmatched_ratio"] = summary["unmatched_count"] / summary["review_count"]
    run.csv("sentiment_monthly_summary.csv", summary)
    run.csv("term_frequency.csv", pd.DataFrame(terms.most_common(), columns=["term", "occurrences"]))
    return run.finish(input_rows=len(df), date_excluded=len(df)-len(valid),
                      limitation="単語辞書の例。否定や文脈は解決せず、星評価も正解ラベルとして使用しない。")

if __name__ == "__main__":
    p = argparse.ArgumentParser(); p.add_argument("input", nargs="?", default="outputs/google_play_reviews.csv")
    analyze(p.parse_args().input)
