#!/usr/bin/env python3
"""Reproduce published descriptive statistics from aggregate inputs (stdlib only).

Save this script with weekly.json and daily.json, then run python3 reproduce.py.
To reaggregate raw FTC inputs, use ftc-recompute.py and the input manifest.
No record-level information is emitted here.
"""
import json
from pathlib import Path
import statistics
from datetime import date

ROOT = Path(__file__).resolve().parent
def pearson(xs, ys):
    if len(xs) < 3 or len(xs) != len(ys): return None
    a,b = statistics.fmean(xs),statistics.fmean(ys)
    denominator = sum((x-a)**2 for x in xs)**0.5 * sum((y-b)**2 for y in ys)**0.5
    return round(sum((x-a)*(y-b) for x,y in zip(xs,ys))/denominator,4) if denominator else None

def main():
    series = json.loads((ROOT/'weekly.json').read_text())
    daily = json.loads((ROOT/'daily.json').read_text())
    weeks = series['weeks']; paired = [w for w in weeks if w['fcc'] is not None]
    shares = {'ftc': [[] for _ in range(7)], 'fcc': [[] for _ in range(7)]}
    for week in paired:
        for agency in shares:
            days = daily[agency][week['week_start']]
            assert len(days) == 7 and sum(days.values()) == week[agency]
            for iso,count in days.items(): shares[agency][date.fromisoformat(iso).weekday()].append(count/week[agency])
    means = {agency: [round(statistics.fmean(day),5) for day in values] for agency,values in shares.items()}
    checks = {'week_count':len(weeks), 'paired_week_count':len(paired), 'weekday_correlation_points':7,
              'ftc_median':int(statistics.median(w['ftc'] for w in weeks)),
              'fcc_median':int(statistics.median(w['fcc'] for w in paired)),
              'weekly_correlation':pearson([w['ftc'] for w in paired],[w['fcc'] for w in paired]),
              'weekday_shape_correlation':pearson(means['ftc'],means['fcc']),
              'volume_ratio':round(statistics.fmean(w['ftc'] for w in paired)/statistics.fmean(w['fcc'] for w in paired),1)}
    for key,value in checks.items(): assert series['stats'][key] == value, (key,value,series['stats'][key])
    for index,row in enumerate(series['weekday_shape']):
        for agency in means: assert row[agency+'_share'] == means[agency][index]
    print(json.dumps({'status':'pass','reproduced':checks},indent=2))
if __name__ == '__main__': main()
