"""Transparent daily reference balance, not an implementation of Source."""
from pathlib import Path
import csv
root=Path(__file__).resolve().parent
storage=30.0;capacity=40.0;minimum=10.0;delivery_limit=3.0
out=[]
with (root/'storage_daily.csv').open() as f:
 for row in csv.DictReader(f):
  before=storage
  inflow=float(row['inflow_ml_day'])
  demand=float(row['demand_ml_day'])
  area=float(row['area_ha'])
  rain=float(row['rain_mm_day'])*area*0.01
  available=before+inflow+rain
  evaporation=min(available,float(row['evap_mm_day'])*area*0.01)
  available-=evaporation
  supplied=min(demand,delivery_limit,max(0.0,available-minimum))
  available-=supplied
  spill=max(0.0,available-capacity)
  storage=available-spill
  residual=before+inflow+rain-evaporation-supplied-spill-storage
  if abs(residual)>1e-9:raise ValueError('Balance does not close')
  out.append([row['date'],before,inflow,evaporation,supplied,demand-supplied,spill,storage])
with (root/'storage_results.csv').open('w',newline='') as f:
 w=csv.writer(f);w.writerow(['date','start_ml','inflow_ml','evap_ml','supply_ml','shortfall_ml','spill_ml','end_ml']);w.writerows(out)
print('Final storage ML:',round(storage,4))
print('Total shortfall ML:',round(sum(r[5] for r in out),4))
print('Days with shortfall:',sum(r[5]>1e-9 for r in out))
print('Balance checked at every step')
