"""Check the published CSV snapshot: python verify-coffee-prices.py us-coffee-prices.csv.

Uses Python's standard library. This checks reproducibility, not freshness or a new BLS download.
"""
import csv
import hashlib
import json
from datetime import date
from decimal import Decimal
from pathlib import Path
import sys


def verify(path):
    rows = list(csv.DictReader(path.open(encoding='utf-8', newline='')))
    months = [r['month'] for r in rows]
    if not rows or months != sorted(set(months)):
        raise ValueError('Months must be unique and in ascending order.')
    base = Decimal(rows[-1]['cpi_u_all_items'])
    real_column = f"avg_price_usd_per_lb_in_{months[-1]}_dollars"
    checked = 0
    for row in rows:
        date.fromisoformat(row['month'] + '-01')
        if not row['avg_price_usd_per_lb']:
            if row[real_column] or row['cost_usd_per_8oz_cup_at_1_to_16']:
                raise ValueError('Missing prices must not become computed values.')
            continue
        price = Decimal(row['avg_price_usd_per_lb'])
        real = price * base / Decimal(row['cpi_u_all_items'])
        cup = price * (Decimal(8) * Decimal('29.5735295625') / 16) / Decimal('453.59237')
        for column, expected in [(real_column, real), ('cost_usd_per_8oz_cup_at_1_to_16', cup)]:
            if abs(Decimal(row[column]) - expected) > Decimal('0.00051'):
                raise ValueError(f"{row['month']}: {column} does not reproduce to published precision")
        checked += 1
    start = date.fromisoformat(months[0] + '-01')
    end = date.fromisoformat(months[-1] + '-01')
    absent = []
    while start <= end:
        month = start.strftime('%Y-%m')
        if month not in months:
            absent.append(month)
        start = date(start.year + (start.month == 12), start.month % 12 + 1, 1)
    return {'sha256_lf_utf8': hashlib.sha256(path.read_text(encoding='utf-8').encode('utf-8')).hexdigest(), 'rows': len(rows),
            'computed_rows_checked': checked, 'data_through': months[-1],
            'omitted_months': absent,
            'blank_price_months': [r['month'] for r in rows if not r['avg_price_usd_per_lb']],
            'scope': 'Internal arithmetic of the published snapshot; not a fresh source verification.'}


if __name__ == '__main__':
    print(json.dumps(verify(Path(sys.argv[1])), indent=2))
