"""Exact theoretical On-Off fridge + solar model; W, minutes, kWh.
Coopernico hourly published forecasts include TAR, exclude VAT, are non-binding.
Missing 23:00 price stays missing; a separate estimate repeats the 22:00 price.
Run beside coopernico-prices.json. Standard Python library only.
"""
import json
from pathlib import Path
SOLAR=[(0,0),(465,0),(615,900),(810,1500),(1020,600),(1140,0),(1440,0)]
HERE=Path(__file__).resolve().parent
PRICES=json.loads((HERE/'coopernico-prices.json').read_text(encoding='utf-8'))
SELL=.05  # Hypothetical OTHER buyer, not Coopernico.

def solar_power(t,scale=1):
    for (a,pa),(b,pb) in zip(SOLAR,SOLAR[1:]):
        if a<=t<=b:return scale*(pa+(pb-pa)*(t-a)/(b-a))
    raise ValueError(t)

def simulate(on_w=115,off_w=1.5,on_minutes=20,off_minutes=30,peak_w=850,surge_seconds=.2,phase=0,scale=1):
    cycle=on_minutes+off_minutes
    assert on_minutes>0 and off_minutes>0 and 0<=surge_seconds/60<on_minutes
    edges={float(t) for t in range(0,1441,15)}|{float(t) for t,p in SOLAR}
    starts=[]
    for i in range(-2,int(1440/cycle)+3):
        start=phase+i*cycle
        if 0<=start<1440:starts.append(start)
        for t in (start,start+surge_seconds/60,start+on_minutes):
            if 0<t<1440:edges.add(t)
    edges=sorted(edges)
    keys=('solar','load','direct','physical_import','physical_export')
    quarters=[{k:0.0 for k in keys} for _ in range(96)]
    for a,b in zip(edges,edges[1:]):
        pos=((a+b)/2-phase)%cycle
        power=peak_w if pos<surge_seconds/60 else on_w if pos<on_minutes else off_w
        sa,sb=solar_power(a,scale),solar_power(b,scale);split=[a,b]
        if (sa-power)*(sb-power)<0:split.insert(1,a+(power-sa)*(b-a)/(sb-sa))
        for x,y in zip(split,split[1:]):
            sun=(solar_power(x,scale)+solar_power(y,scale))/2*(y-x)/60000
            load=power*(y-x)/60000;q=quarters[int((x+y)/2//15)]
            q['solar']+=sun;q['load']+=load;q['direct']+=min(sun,load)
            q['physical_import']+=max(load-sun,0);q['physical_export']+=max(sun-load,0)
    for i,q in enumerate(quarters):
        q['start']=f'{i//4:02d}:{i%4*15:02d}'
        q['import']=max(q['load']-q['solar'],0);q['export']=max(q['solar']-q['load'],0)
        q['credited_solar']=q['load']-q['import'];q['price_eur_kwh']=PRICES['prices_eur_kwh'][i//4]
    def total(first,last):
        rows=quarters[first:last]
        r={k:sum(q[k] for q in rows) for k in (*keys,'import','export','credited_solar')}
        known=[q for q in rows if q['price_eur_kwh'] is not None]
        missing=[q for q in rows if q['price_eur_kwh'] is None]
        subtotal=sum(q['import']*q['price_eur_kwh'] for q in known)
        baseline=sum(q['load']*q['price_eur_kwh'] for q in known)
        unpriced=sum(q['import'] for q in missing)
        estimated=subtotal+unpriced*PRICES['final_hour_estimate_eur_kwh'];revenue=r['export']*SELL
        r.update(known_purchase_cost=subtotal,unpriced_import_kwh=unpriced,
          complete_published_purchase_cost=subtotal if not missing else None,estimated_purchase_cost=estimated,
          estimated_no_solar_cost=baseline+sum(q['load'] for q in missing)*PRICES['final_hour_estimate_eur_kwh'],
          hypothetical_other_buyer_revenue=revenue,estimated_with_sale_net=estimated-revenue,
          estimate_if_missing_hour_at_observed_min=subtotal+unpriced*min(p for p in PRICES['prices_eur_kwh'] if p is not None),
          estimate_if_missing_hour_at_observed_max=subtotal+unpriced*max(p for p in PRICES['prices_eur_kwh'] if p is not None))
        return r
    return {'parameters':dict(on_w=on_w,off_w=off_w,on_minutes=on_minutes,off_minutes=off_minutes,peak_w=peak_w,surge_seconds=surge_seconds,phase=phase,scale=scale),
      'starts':starts,'high':total(40,68),'day':total(0,96),'quarters':quarters}

def validate(r):
    assert len(r['quarters'])==96
    for q in r['quarters']:
        assert abs(q['load']-q['direct']-q['physical_import'])<1e-9
        assert abs(q['solar']-q['direct']-q['physical_export'])<1e-9
        assert abs(q['solar']+q['import']-q['load']-q['export'])<1e-9
        assert not(q['import']>1e-9 and q['export']>1e-9)

def results():
    r=simulate();validate(r)
    assert abs(r['day']['solar']-9.3)<1e-9 and abs(r['high']['solar']-7.78875)<1e-9
    expected=(115*580+1.5*860)/60000+29*(850-115)*.2/3600000
    assert len(r['starts'])==29 and abs(r['day']['load']-expected)<1e-9
    without=simulate(surge_seconds=0);validate(without)
    r['surge_extra_kwh']=r['day']['load']-without['day']['load'];r['without_surges_day']=without['day']
    r['cycle_sensitivity']=[]
    for name,args in [('low',dict(on_w=80,off_w=1,on_minutes=15,off_minutes=40,peak_w=500)),('central',{}),('high',dict(on_w=150,off_w=2,on_minutes=25,off_minutes=20,peak_w=1200))]:
        row=simulate(**args);validate(row)
        r['cycle_sensitivity'].append({'scenario':name,'starts_count':len(row['starts']),'average_starts_per_hour':60/(row['parameters']['on_minutes']+row['parameters']['off_minutes']),'parameters':row['parameters'],'high':row['high'],'day':row['day']})
    r['alignment_sensitivity']=[]
    for phase in (0,7.5,15,25):
        row=simulate(phase=phase);validate(row);r['alignment_sensitivity'].append({'phase_minutes':phase,**row['day']})
    r['sale_sensitivity']=[{'hypothetical_other_buyer_eur_kwh':p,'revenue':r['day']['export']*p,'estimated_net':r['day']['estimated_purchase_cost']-r['day']['export']*p} for p in (0,.02,.05,.08)]
    return r

if __name__=='__main__':
    r=results();(HERE/'results.json').write_text(json.dumps(r,indent=2,ensure_ascii=False)+'\n',encoding='utf-8')
    print(json.dumps({k:r[k] for k in ('day','high','surge_extra_kwh')},indent=2))
