#!/usr/bin/env python3
"""Reproducible accounting scenarios, frozen 2026-10-16. Standard library only.

Run from any directory. Outputs are planning calculations, not calibrated forecasts.
Historical observations keep their vintages; illustrative starting balances are J.
"""
import copy
import json
import math
from pathlib import Path

ROOT = Path(__file__).resolve().parent
PUBLIC = ROOT.parents[2] / 'public/downloads/world-ledger-2026'
SOURCES = {
    'KNBS': 'https://www.knbs.or.ke/wp-content/uploads/2026/09/Kenya-Consumer-Price-Indices-and-Inflation-Rates-September-2026.pdf',
    'MTDS': 'https://www.treasury.go.ke/sites/default/files/Latest%20updates/2026%20MTDS%20FINAL.pdf',
    'IMF': 'https://mediacenter.imf.org/news/imf-world-economic-output-press-briefing/s/85df82f1-2ffe-44b3-91c4-a7a0e01042ae',
    'CBK': 'https://www.centralbank.go.ke/2026/10/',
    'FAO': 'https://www.fao.org/newsroom/detail/fao-food-price-index-rises-in-september-amid-weather-concerns-and-transport-disruptions/en',
}


def p(value, unit, kind='J', vintage='Illustrative planning assumption', source=None):
    return dict(value=value, unit=unit, evidence=kind, vintage=vintage, source=source)


PARAMETERS = {
    'debt_ratio': p(.678, 'GDP fraction', 'O', 'End June 2025, not October 2026', 'MTDS'),
    'external_share': p(5488.46 / 11814.47, 'fraction of debt', 'O', 'End June 2025; external debt proxy for FX debt', 'MTDS'),
    'domestic_rate': p(.10, 'annual effective rate'),
    'foreign_rate': p(.05, 'annual effective rate'),
    'primary_surplus': p(.01, 'current-year GDP fraction'),
    'stock_flow_adjustment': p(0., 'current-year GDP fraction'),
    'real_growth': p(.05, 'annual fraction'),
    'gdp_deflator': p(.05, 'annual fraction; distinct from CPI'),
    'fx_depreciation': p(0., 'annual fraction increase in KES per foreign currency'),
    'food_weight': p(.45, 'illustrative household basket fraction'),
    'transport_weight': p(.15, 'illustrative household basket fraction'),
    'other_weight': p(.40, 'illustrative household basket fraction'),
    'food_inflation': p(.095, 'year-on-year fraction', 'O', 'September 2026 division, held constant only in scenario', 'KNBS'),
    'transport_inflation': p(.156, 'year-on-year fraction', 'O', 'September 2026 division, held constant only in scenario', 'KNBS'),
    'other_inflation': p(.032, 'annual fraction; assumed composite, not measured housing division'),
    'wage_growth': p(.05, 'annual nominal fraction'),
    'monthly_income': p(40000., 'KES/month'),
    'gross_produce_value': p(1000000., 'KES/month before losses'),
    'spoilage_before': p(.25, 'fraction of gross produce value'),
    'spoilage_after': p(.15, 'fraction of gross produce value'),
    'variable_cost_share': p(.20, 'fraction of recovered revenue'),
    'intervention_cost': p(60000., 'KES/month'),
    'health_arrivals': p(100., 'patients/day'),
    'staff_count': p(10., 'staff'),
    'capacity_per_staff': p(12., 'patients per staff per day'),
    'ai_tasks': p(10000., 'tasks/month'),
    'tokens_per_task': p(10000., 'billable tokens/task'),
    'token_price': p(2., 'USD per million blended tokens; hypothetical vendor price'),
    'task_failure_rate': p(.10, 'fraction requiring rework'),
    'review_minutes': p(2., 'minutes per task; every task reviewed'),
    'review_rate': p(6., 'USD/hour'),
    'rework_minutes': p(10., 'minutes per failed task, additional to review'),
    'power_kw': p(10., 'kW IT load'),
    'pue': p(1.4, 'total facility energy / IT energy'),
    'power_price': p(.15, 'USD/kWh'),
    'uptime': p(.95, 'fraction of monthly hours operating'),
    'hours_per_month': p(730., 'hours; 365-day-year monthly average'),
    'fx_kes_usd': p(130., 'KES/USD; rounded illustrative conversion'),
    'bond_duration': p(8., 'years, modified duration'),
    'bond_convexity': p(75., 'years squared'),
    'yield_shock': p(.01, 'yield fraction, 100 basis points'),
    'population_2025': p(57.53, 'million', 'J', 'User Vision 2060 rounded UN WPP anchor, not independently re-extracted'),
    'population_2060': p(91.57, 'million', 'J', 'User Vision 2060 rounded UN WPP projection, not independently re-extracted'),
    'vision_growth': p(.07, 'annual real fraction; ambition, not forecast'),
    'vision_years': p(35., 'years from 2025 to 2060'),
}

# Joint scenarios are designed narratives. No probability weights are assigned.
SCENARIOS = {
    'reference': {},
    'adaptation': dict(real_growth=.06, gdp_deflator=.04, domestic_rate=.09,
                       foreign_rate=.045, primary_surplus=.015, fx_depreciation=-.02,
                       food_inflation=.06, transport_inflation=.08, wage_growth=.07,
                       health_arrivals=90., spoilage_after=.12, task_failure_rate=.07),
    'supply_shock': dict(real_growth=.03, gdp_deflator=.08, domestic_rate=.12,
                         foreign_rate=.06, fx_depreciation=.10, primary_surplus=0.,
                         food_inflation=.15, transport_inflation=.25, other_inflation=.06,
                         wage_growth=.04, health_arrivals=130., power_price=.20,
                         spoilage_after=.20),
    'credit_squeeze': dict(real_growth=.01, gdp_deflator=.04, domestic_rate=.15,
                           foreign_rate=.08, fx_depreciation=.15, primary_surplus=-.01,
                           wage_growth=0., health_arrivals=110.,
                           intervention_cost=80000., task_failure_rate=.15),
    'compound_disruption': dict(real_growth=-.02, gdp_deflator=.10,
                                domestic_rate=.17, foreign_rate=.09,
                                fx_depreciation=.25, primary_surplus=-.02,
                                food_inflation=.25, transport_inflation=.35,
                                other_inflation=.10, wage_growth=.02,
                                health_arrivals=170., staff_count=8.,
                                spoilage_after=.23, intervention_cost=90000.,
                                power_price=.25, uptime=.80, task_failure_rate=.25),
}


def evaluate(v):
    basket = sum(v[a] * v[b] for a, b in (
        ('food_weight', 'food_inflation'), ('transport_weight', 'transport_inflation'),
        ('other_weight', 'other_inflation')))
    nominal_growth = (1 + v['real_growth']) * (1 + v['gdp_deflator']) - 1
    # Exact within this simplified annual, end-period-FX accounting convention.
    d, ext = v['debt_ratio'], v['external_share']
    debt_path = []
    for year in range(1, 4):
        domestic = d * (1 - ext) * (1 + v['domestic_rate']) / (1 + nominal_growth)
        foreign = d * ext * (1 + v['foreign_rate']) * (1 + v['fx_depreciation']) / (1 + nominal_growth)
        d = domestic + foreign - v['primary_surplus'] + v['stock_flow_adjustment']
        # New financing follows last period's composition. This explicit assumption
        # is not a forecast of Treasury's issuance strategy.
        ext = foreign / (domestic + foreign)
        debt_path.append(dict(year=year, debt_to_gdp=d, external_share=ext))
    recovered = v['gross_produce_value'] * (v['spoilage_before'] - v['spoilage_after'])
    contribution = recovered * (1 - v['variable_cost_share'])
    ai_inference = v['ai_tasks'] * v['tokens_per_task'] / 1e6 * v['token_price']
    review = v['ai_tasks'] * v['review_minutes'] / 60 * v['review_rate']
    rework = v['ai_tasks'] * v['task_failure_rate'] * v['rework_minutes'] / 60 * v['review_rate']
    power_kwh = v['power_kw'] * v['pue'] * v['hours_per_month'] * v['uptime']
    return dict(
        basket_annual_inflation=basket,
        real_income_annual_change=(1 + v['wage_growth']) / (1 + basket) - 1,
        monthly_income_after_year_in_initial_kes=v['monthly_income'] * (1 + v['wage_growth']) / (1 + basket),
        nominal_gdp_annual_growth=nominal_growth,
        debt_path=debt_path,
        spoilage_recovered_revenue_kes_month=recovered,
        spoilage_net_benefit_kes_month=contribution - v['intervention_cost'],
        spoilage_break_even_gross_value=v['intervention_cost'] / ((v['spoilage_before'] - v['spoilage_after']) * (1 - v['variable_cost_share'])),
        clinic_capacity_patients_day=v['staff_count'] * v['capacity_per_staff'],
        clinic_utilization=v['health_arrivals'] / (v['staff_count'] * v['capacity_per_staff']),
        clinic_daily_backlog_addition=max(0, v['health_arrivals'] - v['staff_count'] * v['capacity_per_staff']),
        ai_inference_usd_month=ai_inference, ai_review_usd_month=review,
        ai_rework_usd_month=rework, ai_total_usd_month=ai_inference + review + rework,
        ai_usd_per_completed_task=(ai_inference + review + rework) / v['ai_tasks'],
        ai_kes_month=(ai_inference + review + rework) * v['fx_kes_usd'],
        # Task costs assume successful human rework; no extra autonomous retries.
        facility_kwh_month=power_kwh, facility_usd_month=power_kwh * v['power_price'],
        bond_price_change_approx=-v['bond_duration'] * v['yield_shock'] + .5 * v['bond_convexity'] * v['yield_shock'] ** 2,
        vision_output_multiple=(1 + v['vision_growth']) ** v['vision_years'],
        vision_per_capita_multiple=(1 + v['vision_growth']) ** v['vision_years'] / (v['population_2060'] / v['population_2025']),
    )


def main():
    base = {k: x['value'] for k, x in PARAMETERS.items()}
    assert math.isclose(sum(base[k] for k in ('food_weight', 'transport_weight', 'other_weight')), 1)
    results = {name: dict(overrides=changes, outputs=evaluate(base | changes)) for name, changes in SCENARIOS.items()}
    b = results['reference']['outputs']
    assert math.isclose(b['spoilage_net_benefit_kes_month'], 20000.)
    assert math.isclose(b['ai_total_usd_month'], 3200.)
    assert math.isclose(b['clinic_utilization'], 100 / 120)
    assert math.isclose(b['basket_annual_inflation'], .07895)
    # Independent direct identity for first-year sovereign balance sheet.
    interest = base['debt_ratio'] * ((1-base['external_share'])*base['domestic_rate'] + base['external_share']*base['foreign_rate'])
    direct = (base['debt_ratio'] + interest) / 1.1025 - .01
    assert math.isclose(b['debt_path'][0]['debt_to_gdp'], direct)
    # One-at-a-time perturbations in own units, no false common-importance score.
    perturbations = dict(real_growth=.01, gdp_deflator=.01, domestic_rate=.01,
                         foreign_rate=.01, fx_depreciation=.10, primary_surplus=.01,
                         food_inflation=.01, transport_inflation=.01,
                         other_inflation=.01, wage_growth=.01, spoilage_after=.01,
                         intervention_cost=10000., health_arrivals=10., staff_count=1.,
                         task_failure_rate=.05, review_minutes=1., token_price=1.,
                         power_price=.05, uptime=.01)
    sensitivity = []
    for k, delta in perturbations.items():
        alt = evaluate(base | {k: base[k] + delta})
        sensitivity.append(dict(parameter=k, increase=delta, unit=PARAMETERS[k]['unit'],
            debt_ratio_year3_change=alt['debt_path'][2]['debt_to_gdp']-b['debt_path'][2]['debt_to_gdp'],
            real_income_change=alt['real_income_annual_change']-b['real_income_annual_change'],
            spoilage_net_kes_change=alt['spoilage_net_benefit_kes_month']-b['spoilage_net_benefit_kes_month'],
            ai_usd_change=alt['ai_total_usd_month']-b['ai_total_usd_month'],
            clinic_utilization_change=alt['clinic_utilization']-b['clinic_utilization'],
            facility_usd_change=alt['facility_usd_month']-b['facility_usd_month']))
    output = dict(asOf='2026-10-16', parameterCount=len(PARAMETERS), sources=SOURCES,
        parameters=PARAMETERS, scenarios=results, sensitivity=sensitivity,
        evidenceBoundary='Conditional accounting illustrations, no fitted causal coefficients, scenario probabilities, confidence intervals, or demonstrated forecasting skill. Debt begins at a historical June 2025 balance sheet, NOT an October 2026 nowcast. Years1-3 are model steps, not calendar-year forecasts. Inflation and rates are constant within each designed scenario. GDP deflator differs from CPI. External debt proxies FX exposure. No epidemiological spread model or market-implied distribution is estimated.')
    PUBLIC.mkdir(parents=True, exist_ok=True)
    for path in (ROOT / 'model-results.json', PUBLIC / 'model-results.json'):
        path.write_text(json.dumps(output, indent=2, allow_nan=False) + '\n')
    (PUBLIC / 'scenario_model.py').write_text(Path(__file__).read_text())
    print(json.dumps(dict(parameters=len(PARAMETERS), reference=b, scenarios={k: [round(x['debt_to_gdp']*100,3) for x in v['outputs']['debt_path']] for k,v in results.items()}), indent=2))


if __name__ == '__main__':
    main()
