#!/usr/bin/env python3
"""Summarize the notification recorder log: counts by app, urgency, hour, top summaries.

Usage: notif-analyze.py [hours]   (default: all)  -> reads ~/.local/state/notif-log.jsonl
"""
import json
import os
import sys
import time
from collections import Counter, defaultdict

LOG = os.path.join(
    os.environ.get("XDG_STATE_HOME") or os.path.expanduser("~/.local/state"),
    "notif-log.jsonl",
)
hours = float(sys.argv[1]) if len(sys.argv) > 1 else None
cutoff = (time.time() - hours * 3600) if hours else 0

by_app = Counter()
by_urg = Counter()
by_hour = Counter()
app_urg = defaultdict(Counter)
top_summary = defaultdict(Counter)
total = 0
try:
    with open(LOG) as f:
        for ln in f:
            ln = ln.strip()
            if not ln:
                continue
            try:
                r = json.loads(ln)
            except Exception:
                continue
            if r.get("ts") and r["ts"] < cutoff:
                continue
            total += 1
            app = r.get("app") or "?"
            urg = r.get("urgency") or "?"
            by_app[app] += 1
            by_urg[str(urg)] += 1
            app_urg[app][str(urg)] += 1
            top_summary[app][r.get("summary") or ""] += 1
            if r.get("ts"):
                hh = time.strftime("%H", time.localtime(r["ts"]))
                by_hour[hh] += 1
except FileNotFoundError:
    print("no log yet:", LOG)
    sys.exit(0)

span = f"last {hours}h" if hours else "all-time"
print(f"total notifications ({span}): {total}\n")
print("by app (worst first):")
for app, n in by_app.most_common():
    urg = " ".join(f"{k}:{v}" for k, v in app_urg[app].most_common())
    print(f"  {n:4d}  {app}   [{urg}]")
print("\nby urgency:", "  ".join(f"{k}={v}" for k, v in by_urg.most_common()))
if by_hour:
    busy = "  ".join(f"{h}:00={n}" for h, n in sorted(by_hour.items(), key=lambda x: -x[1])[:6])
    print("busiest hours:", busy)
print("\ntop repeated summaries per app (mute candidates):")
for app, n in by_app.most_common(8):
    reps = [f'"{s}"×{c}' for s, c in top_summary[app].most_common(3) if c > 1]
    if reps:
        print(f"  {app}: " + "  ".join(reps))
