#!/usr/bin/env python3
"""Release-era descriptive statistics (music history / statistics / education example).

Standard library only. Run from the edition folder:  python3 examples/release_era_statistics.py

Denominators are stated for every share. The edition is the top-N recordings by October 2026 ListenBrainz
listeners, so shares describe that ranked set, not all recorded music. Release dates are MusicBrainz
release-event dates - not composition dates and not the listening period.
"""
import collections
import csv
import os

D = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
csv.field_size_limit(1 << 30)


def rows(*parts):
    with open(os.path.join(D, *parts), encoding="utf-8", newline="") as fh:
        yield from csv.DictReader(fh)


flat = list(rows("data", "music_recordings_flat.csv"))
n = len(flat)
print(f"Edition: {n:,} recordings\n")

print("1. Decade of first documented release (denominator: all recordings in the edition)")
dec, dec_l = collections.Counter(), collections.Counter()
for r in flat:
    k = f"{int(r['first_release_year']) // 10 * 10}s" if r["first_release_year"] else "no release date"
    dec[k] += 1
    dec_l[k] += int(r["oct_listen_count"] or 0)
tl = sum(dec_l.values())
print(f"   {'decade':16s} {'recordings':>11s} {'share':>7s} {'share of October listens':>26s}")
for k in sorted(dec):
    print(f"   {k:16s} {dec[k]:11,d} {dec[k] / n:7.1%} {dec_l[k] / tl:26.1%}")

print("\n2. Release formats by decade of each release's earliest event (denominator: releases with a date)")
fmt, tot = collections.defaultdict(collections.Counter), collections.Counter()
for r in rows("data", "release_history", "releases.csv"):
    if r["earliest_release_date"]:
        d = f"{int(r['earliest_release_date'][:4]) // 10 * 10}s"
        tot[d] += 1
        for f in (r["medium_formats"] or "unknown").split(";"):
            fmt[d][f] += 1
for d in sorted(tot):
    top = ", ".join(f"{f} {c / tot[d]:.0%}" for f, c in fmt[d].most_common(3))
    print(f"   {d}: {tot[d]:8,d} releases; {top}")

print("\n3. Concentration of October listens inside the edition (denominator: October listens in the edition)")
ls = sorted((int(r["oct_listen_count"]) for r in flat if r["oct_listen_count"]), reverse=True)
s = sum(ls)
for share in (0.01, 0.10):
    k = max(1, int(len(ls) * share))
    print(f"   top {share:.0%} of recordings: {sum(ls[:k]) / s:.1%} of listens")

print("\n4. Missingness (denominator in brackets)")
for col in ("length_ms", "first_release_year", "first_artist_country_code", "w47_listen_count"):
    miss = sum(1 for r in flat if not r[col])
    print(f"   {col:28s} empty in {miss:,} [{n:,}]")
print(f"   audio descriptors unavailable  {sum(1 for r in flat if r['ab_features_available'] != 'true'):,} [{n:,}]")
