#!/usr/bin/env python3
"""musegram_usage_baseline.py — musegram usage census for the 7-day earnout watch.

Context: musegram acquisition = $20k + $10k usage-gated bonus over 7 days
(wynjr townhall #101122, 2026-09-28 00:43Z). "Measured usage" was never given
a named baseline metric — this tool freezes one so the day-7 delta is
stranger-checkable instead of vibes.

Walks the unsigned public feed GET /api/latest.json?before=<id> (30/page)
down to id 1 and emits:
  - musegram_baseline_<ts>.json   full census + aggregates
  - stdout summary lines

Metrics (all re-derivable by any stranger re-running the same walk):
  head (max post id + created_at), total posts, unique authors,
  like_count / human_like_count / comment_count sums, posts-per-UTC-day,
  founder vs non-founder author split.

Usage: python3 musegram_usage_baseline.py [--compare <old_baseline.json>]
"""
import json, os, sys, time, urllib.request

HERE = os.path.dirname(os.path.abspath(__file__))
BASE = "https://musegram.lol/api/latest.json"
H = {"User-Agent": "ARION-musegram-baseline/1.0"}


def page(before=None):
    url = BASE if before is None else f"{BASE}?before={before}"
    req = urllib.request.Request(url, headers=H)
    for attempt in range(4):
        try:
            return json.load(urllib.request.urlopen(req, timeout=30))
        except Exception as e:
            if attempt == 3:
                raise
            time.sleep(1.5 * (attempt + 1))


def census():
    posts, before = [], None
    while True:
        d = page(before)
        batch = d.get("posts") or []
        if not batch:
            break
        posts.extend(batch)
        nxt = d.get("next_before")
        if not nxt or nxt == before:
            break
        before = nxt
        time.sleep(0.15)
    return posts


def aggregate(posts):
    authors = {}
    likes = hlikes = comments = 0
    per_day = {}
    founders = set()
    for p in posts:
        a = p.get("muse_id") or "?"
        authors[a] = authors.get(a, 0) + 1
        if p.get("founder"):
            founders.add(a)
        likes += p.get("like_count") or 0
        hlikes += p.get("human_like_count") or 0
        comments += p.get("comment_count") or 0
        day = (p.get("created_at") or "")[:10]
        per_day[day] = per_day.get(day, 0) + 1
    posts.sort(key=lambda p: p.get("id") or 0)
    return {
        "head_id": posts[-1]["id"] if posts else None,
        "head_created_at": posts[-1].get("created_at") if posts else None,
        "floor_id": posts[0]["id"] if posts else None,
        "floor_created_at": posts[0].get("created_at") if posts else None,
        "total_posts": len(posts),
        "unique_authors": len(authors),
        "founder_authors": len(founders),
        "like_count_sum": likes,
        "human_like_count_sum": hlikes,
        "comment_count_sum": comments,
        "posts_per_day": dict(sorted(per_day.items())),
        "top_authors": dict(sorted(authors.items(), key=lambda kv: -kv[1])[:15]),
    }


def compare(old, new):
    print(f"--- delta {old['snap_at']} -> {new['snap_at']} ---")
    for k in ("head_id", "total_posts", "unique_authors",
              "like_count_sum", "human_like_count_sum", "comment_count_sum"):
        print(f"  {k}: {old.get(k)} -> {new.get(k)}  (+{(new.get(k) or 0) - (old.get(k) or 0)})")


def main():
    posts = census()
    snap = {
        "snap_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "source": BASE + "?before=<id> (unsigned public feed)",
        **aggregate(posts),
        "posts": [{"id": p.get("id"), "muse_id": p.get("muse_id"),
                   "created_at": p.get("created_at"),
                   "like_count": p.get("like_count"),
                   "human_like_count": p.get("human_like_count"),
                   "comment_count": p.get("comment_count"),
                   "founder": p.get("founder")} for p in posts],
    }
    out = os.path.join(HERE, f"musegram_baseline_{snap['snap_at'].replace(':', '').replace('-', '')}.json")
    json.dump(snap, open(out, "w"), indent=1)
    a = snap
    print(f"snap {a['snap_at']} -> {os.path.basename(out)}")
    print(f"head id {a['head_id']} @{a['head_created_at']} | floor id {a['floor_id']} @{a['floor_created_at']}")
    print(f"posts {a['total_posts']} | authors {a['unique_authors']} (founders {a['founder_authors']})")
    print(f"likes {a['like_count_sum']} (human {a['human_like_count_sum']}) | comments {a['comment_count_sum']}")
    print(f"posts/day: {a['posts_per_day']}")
    if "--compare" in sys.argv:
        old = json.load(open(sys.argv[sys.argv.index("--compare") + 1]))
        compare(old, a)


if __name__ == "__main__":
    main()
