"""River-only network: steady-state heat balance by cumulative river reach.
Run python river_model.py. No third-party dependencies.
Gauge flows are screening proxies. They are not measured flows at each site.
"""
import json
from pathlib import Path

RHO=1000.0
CP=4186.0
PUE=1.15
TARGET_DELTA_C=0.1  # illustrative control target, not a permit limit
DIVERSION=[0.0,0.8,0.9]

def delta_c(heat_mw,flow):
    if flow<=0 or heat_mw<0:raise ValueError('Positive flow and non-negative heat required')
    return heat_mw*1e6/(RHO*CP*flow)

def calculate(network,sources,diversion=0):
    if not 0<=diversion<=1:raise ValueError('Diversion fraction must lie in [0,1]')
    g={s['id']:s for s in sources['data']}
    capacities={s['name']:s['it_mw']for s in network['sites']}
    north=['Falstone','Bellingham','Wark','Barrasford','Chollerford']
    # Upstream cumulative additions are retained: downstream nodes do not reset warming.
    spec=[('Falstone','Upper North Tyne',['Falstone'],23022,'Downstream Kielder release proxy; confirm site intake flow.'),
          ('Bellingham','Upper North Tyne',north[:2],23022,'Upstream release-only sensitivity; tributary additions ignored. No local flow validation.'),
          ('Wark','North Tyne',north[:3],23022,'Upstream release-only sensitivity; tributary additions ignored. No local flow validation.'),
          ('Barrasford','Lower North Tyne',north[:4],23003,'Reaverhill downstream reference, not an exact site-flow measurement.'),
          ('Chollerford','Lower North Tyne',north,23003,'Reaverhill upstream proxy; local flow and additional inflows require survey.'),
          ('Haydon Bridge','South Tyne',['Haydon Bridge'],23004,'Haydon Bridge gauge reference; confirm intake/return locations.'),
          ('Hexham','Combined Tyne',north+['Haydon Bridge','Hexham'],23001,'Bywell is downstream of Hexham/Corbridge; not an exact local flow.'),
          ('Corbridge','Combined Tyne',list(capacities),23001,'Bywell downstream cumulative screening reference; local flow requires confirmation.')]
    rows=[]
    for name,reach,upstream,station_id,note in spec:
        s=g[station_id];it=sum(capacities[x]for x in upstream);heat=it*PUE*(1-diversion)
        max_heat=RHO*CP*s['gdf-q95-flow']*TARGET_DELTA_C/1e6
        rows.append(dict(community=name,river_reach=reach,upstream_sites=upstream,
                         local_it_mw=capacities[name],cumulative_it_mw=it,
                         diversion_fraction=diversion,residual_heat_mw=heat,
                         gauge=s['name'],station_id=station_id,mean_flow=s['gdf-mean-flow'],q95_flow=s['gdf-q95-flow'],
                         mean_delta_c=delta_c(heat,s['gdf-mean-flow']),
                         q95_delta_c=delta_c(heat,s['gdf-q95-flow']),
                         heat_budget_at_target_mw=max_heat,
                         required_diversion_at_q95=max(0,1-max_heat/(it*PUE)) if it else 0,
                         flow_status=note))
    return rows

def main():
    d=Path(__file__).resolve().parent
    n=json.loads((d/'network.json').read_text());s=json.loads((d/'river_flow_sources.json').read_text())
    r={str(int(f*100))+'pct_diverted':calculate(n,s,f)for f in DIVERSION}
    result={'rho_kg_m3':RHO,'cp_j_kg_k':CP,'full_load_pue':PUE,'illustrative_target_c':TARGET_DELTA_C,
            'network_it_mw':sum(x['it_mw']for x in n['sites']),
            'assumptions':['Full IT load; all facility electricity becomes potentially rejectable heat.',
             'Complete instantaneous river mixing, no heat loss to air, steady flow.',
             'Upstream heat is accumulated through the North/South Tyne confluence.',
             'Historical daily mean and Q95 values are proxies, not simultaneous local measurements.',
             'Q95 is not a guaranteed minimum. Short reservoir release pulses are omitted.',
             'Outfall plumes, ecology, absolute temperatures and permit limits require separate assessment.',
             'Diversion means reuse, storage, alternative cooling or load avoidance during that hour.',
             'The annual carbon heat-use fraction is different from instantaneous river heat diversion.'],
            'scenarios':r}
    (d/'river_results.json').write_text(json.dumps(result,indent=2)+'\n')
    for name,rows in r.items():
        print(name)
        for x in rows:print(x['community'],f"{x['cumulative_it_mw']:.1f} MW upstream IT",f"{x['mean_delta_c']:.3f} C mean",f"{x['q95_delta_c']:.3f} C Q95")

if __name__=='__main__':main()
