"""Independently check the tutorial CSV: python3 check-rates.py pilot.csv.
Reads only the named file and writes no files. Uses exact rational arithmetic.
"""
import csv
from fractions import Fraction
import json
import sys
with open(sys.argv[1], newline='') as source:
    reader = csv.DictReader(source)
    if reader.fieldnames != ['week', 'requests', 'within_one_day']:
        raise SystemExit('Expected week,requests,within_one_day columns')
    rows = list(reader)
if len(rows) != 2:
    raise SystemExit('This example compares exactly two weeks')
rates = []
total = answered = 0
for row in rows:
    try:
        count, within = int(row['requests']), int(row['within_one_day'])
    except (ValueError, TypeError):
        raise SystemExit('Counts must be integers')
    if count <= 0 or not 0 <= within <= count:
        raise SystemExit('Counts require requests > 0 and 0 <= within_one_day <= requests')
    total += count
    answered += within
    rates.append(Fraction(within, count))
print(json.dumps({'weekly_percent': [float(rate * 100) for rate in rates],
                  'change_percentage_points': float((rates[1] - rates[0]) * 100),
                  'combined_fraction': f'{answered}/{total}',
                  'combined_percent': float(Fraction(answered, total) * 100)}, indent=2))
