"""Independent Python re-implementation of Leviathan's solar-storage-toy-v1 runner
(/clients/leviathan-engines.mjs, read 31 Oct 2026, 2811 bytes). Written from the
source, not executed from it. Run: /usr/bin/python3 -I notes/fixture_sim.py

Sections: (1) baseline vs store-surplus on the shipped fixture with hourly and
battery energy balances; (2) proof-by-exhaustion that no parameter inside the
runner's own space reverses the conclusion; (3) assumptions outside the runner
that do reverse it (export tariff, throughput wear); (4) a price-blind dispatch
counterexample where the greedy method leaves most of the saving on the table,
plus a price-aware alternative method."""
import itertools, random

FIX = dict(id='solar-storage-toy-v1', step_hours=1,
           load=[2,2,2,2,2,2], solar=[0,1,5,4,0,0], price=[.2,.2,.1,.1,.4,.4],
           cap=3.0, power=2.0, eta_c=0.9, eta_d=0.9)

def simulate(f, mode='store-surplus', export_price=0.0, wear=0.0):
    """Mirror of simulate() in the mjs. export_price/wear are NOT in the runner;
    they are only used in section 3 and default to the runner's behaviour."""
    soc = cost = grid = 0.0; rows = []
    for i in range(len(f['load'])):
        load, solar, price = f['load'][i], f['solar'][i], f['price'][i]
        direct = min(load, solar); surplus = solar - direct; deficit = load - direct
        charge = discharge = 0.0
        if mode == 'store-surplus':
            charge = min(surplus, f['power'], (f['cap'] - soc) / f['eta_c'])
            soc += charge * f['eta_c']; surplus -= charge
            discharge = min(deficit, f['power'], soc * f['eta_d'])
            soc -= discharge / f['eta_d']; deficit -= discharge
        elif mode == 'price-aware':
            # hold stored energy for the dearest remaining deficit hours (section 4)
            charge = min(surplus, f['power'], (f['cap'] - soc) / f['eta_c'])
            soc += charge * f['eta_c']; surplus -= charge
            later = [(f['price'][j], f['load'][j] - min(f['load'][j], f['solar'][j]))
                     for j in range(i + 1, len(f['load']))]
            # energy (output side) wanted by later hours priced above this hour
            dearer = sum(min(d, f['power']) for p, d in later if p > price)
            avail = max(0.0, soc * f['eta_d'] - dearer)
            discharge = min(deficit, f['power'], avail)
            soc -= discharge / f['eta_d']; deficit -= discharge
        loss = charge * (1 - f['eta_c']) + discharge * (1 / f['eta_d'] - 1)
        cost += deficit * price - surplus * export_price + wear * (charge + discharge)
        grid += deficit
        rows.append(dict(hour=i, load=load, solar=solar, direct=direct, charge=charge,
                         discharge=discharge, loss=loss, curtailed=surplus, grid=deficit, soc=soc))
    return dict(cost=cost, grid=grid, final_soc=soc, rows=rows)

def balances(res):
    worst_hour = 0.0
    for r in res['rows']:
        inflow = r['solar'] + r['grid'] + r['discharge']
        outflow = r['load'] + r['charge'] + r['curtailed']
        worst_hour = max(worst_hour, abs(inflow - outflow))
    S = lambda k: sum(r[k] for r in res['rows'])
    batt = S('charge') - S('discharge') - S('loss') - res['final_soc']
    system = S('solar') + S('grid') - S('load') - S('curtailed') - S('loss') - res['final_soc']
    return worst_hour, batt, system, {k: round(S(k), 6) for k in ('solar','load','direct','charge','discharge','loss','curtailed','grid')}

if __name__ == '__main__':
    print('== 1. shipped fixture')
    for mode in ('no-storage', 'store-surplus'):
        r = simulate(FIX, mode)
        print(f'{mode:14s} cost {r["cost"]:.4f} grid {r["grid"]:.4f} kWh final_soc {r["final_soc"]:.3e}')
        for row in r['rows']:
            print('   ', {k: round(v, 4) for k, v in row.items()})
        wh, b, s, tot = balances(r)
        print(f'    worst hourly |in-out| {wh:.1e}; battery balance {b:.1e}; system balance {s:.1e}')
        print('    totals', tot)
    b, c = simulate(FIX, 'no-storage'), simulate(FIX, 'store-surplus')
    print(f'saving {b["cost"]-c["cost"]:.4f} cost units on {sum(r["charge"] for r in c["rows"]):.4f} kWh charged; '
          f'grid import {b["grid"]:.3f} -> {c["grid"]:.3f} kWh')

    print('\n== 2. search for a reversal inside the runner parameter space')
    # The runner has no export price and no battery cost. Charge consumes only energy that
    # would otherwise be curtailed; discharge only displaces grid import at price >= 0.
    # Hence cost(store) <= cost(baseline) for every admissible input. Exhaustive check on a grid
    # plus random draws (lengths 1-12, prices incl. 0, efficiencies incl. 1, cap/power incl. 0).
    rng = random.Random(1); worst = -1.0; n = 0; ties = 0
    for _ in range(20000):
        L = rng.randint(1, 12)
        f = dict(load=[rng.choice([0,1,2,3,5]) for _ in range(L)], solar=[rng.choice([0,0,1,4,5,9]) for _ in range(L)],
                 price=[rng.choice([0,.05,.1,.2,.4,1.0]) for _ in range(L)], cap=rng.choice([0,1,3,6,100]),
                 power=rng.choice([0,.5,2,10]), eta_c=rng.choice([.3,.5,.9,1]), eta_d=rng.choice([.3,.5,.9,1]))
        d = simulate(f, 'no-storage')['cost'] - simulate(f, 'store-surplus')['cost']
        n += 1; worst = max(worst, -d); ties += (abs(d) < 1e-12)
    print(f'{n} random inputs: max (store - baseline) cost = {worst:.1e} (reversal needs > 0); ties {ties}')

    print('\n== 3. assumptions outside the runner that reverse it (shipped fixture)')
    bcost = simulate(FIX, 'no-storage')['cost']
    for px in (0.0, 0.1, 0.2, 0.3, 0.324, 0.33, 0.4):
        d = simulate(FIX, 'no-storage', export_price=px)['cost'] - simulate(FIX, 'store-surplus', export_price=px)['cost']
        print(f'  export tariff {px:.3f}/kWh: saving {d:+.4f}')
    for w in (0.0, 0.1, 0.15, 0.179, 0.18, 0.2):
        d = bcost - simulate(FIX, 'store-surplus', wear=w)['cost']
        print(f'  wear {w:.3f}/kWh throughput: saving {d:+.4f}')
    # closed forms: export break-even = eta_c*eta_d*p_evening (0.81*0.4 = 0.324);
    # wear break-even = saving / (charge+discharge) = 1.08 / (3.333+2.7) = 0.179

    print('\n== 4. price-blind dispatch counterexample (method, not conclusion)')
    f2 = dict(FIX, price=[.2,.2,.1,.1,.1,.4])
    for mode in ('no-storage', 'store-surplus', 'price-aware'):
        r = simulate(f2, mode)
        print(f'  {mode:14s} cost {r["cost"]:.4f} final_soc {r["final_soc"]:.3f} discharge by hour',
              [round(x['discharge'], 3) for x in r['rows']])
    print('  shipped fixture under price-aware:', round(simulate(FIX, 'price-aware')['cost'], 4))
