"""Constructed data only. Run from this directory: python3 visual_report_lab.py"""
from collections import defaultdict
from csv import DictReader
from pathlib import Path
import json

ROOT=Path(__file__).resolve().parent
with (ROOT/'dispatches.csv').open(newline='') as file:
    rows=list(DictReader(file))
assert len(rows)==6
assert len({r['Batch'] for r in rows})==6
months=defaultdict(lambda: {'orders':0,'late':0})
regions=defaultdict(lambda: {'orders':0,'late':0})
for row in rows:
    orders=int(row['Orders']);late=int(row['Late'])
    if not 0<=late<=orders or orders<=0:raise ValueError('Invalid dispatch count')
    month=row['Date'][:7]
    months[month]['orders']+=orders;months[month]['late']+=late
    regions[row['Region']]['orders']+=orders;regions[row['Region']]['late']+=late
assert dict(months)=={'2026-01':{'orders':35,'late':5},'2026-02':{'orders':65,'late':16}}
assert dict(regions)=={'North':{'orders':45,'late':8},'South':{'orders':55,'late':13}}
for item in months.values():item['rate']=item['late']/item['orders']
cedar={'old':{'routine':(81,90),'complex':(2,10)},
       'new':{'routine':(19,20),'complex':(24,80)}}
def observed(period):
    cells=cedar[period].values()
    return sum(y for y,n in cells)/sum(n for y,n in cedar[period].values())
def equal_mix(period):
    return sum(y/n for y,n in cedar[period].values())/2
assert abs(observed('old')-.83)<1e-12
assert abs(observed('new')-.43)<1e-12
assert abs(equal_mix('old')-.55)<1e-12
assert abs(equal_mix('new')-.625)<1e-12
report={'source':'constructed dispatches.csv','months':dict(months),'regions':dict(regions),
        'cedar_observed':{p:observed(p) for p in cedar},
        'cedar_equal_mix':{p:equal_mix(p) for p in cedar},
        'limits':['dispatch source coverage assumed','Cedar periods not randomised','no causal effect established']}
(ROOT/'observed_report.json').write_text(json.dumps(report,indent=2)+'\n')
print('JAN',months['2026-01'])
print('FEB',months['2026-02'])
print('CEDAR OBSERVED',report['cedar_observed'])
print('CEDAR EQUAL MIX',report['cedar_equal_mix'])
print('VISUAL REPORT CHECKS PASS')
