"""Reproducible AIP arithmetic audit. Scenarios are not validated forecasts."""
import json
from pathlib import Path

def calculate(m):
 y=m['year1']; a=m['accounts']; h=m['housing']
 spending=sum(y['spending_T'].values())
 other=y['payroll_revenue_T']+y['other_revenue_T']
 denom=y['taxable_receipts_T']*(1-y['evasion_fraction'])*y.get('credit_factor',1)
 if denom<=0: raise ValueError('No collectible tax base')
 rate=max(0,(spending-other)/denom)
 grt=denom*rate
 rev=grt+y['payroll_revenue_T']+y['other_revenue_T']; spend=sum(y['spending_T'].values())
 gross=a['seed_USD']*(1+a['annual_return'])**a['years']
 service=a['healthcare_repayment_USD']+a['education_repayment_USD']
 # External repayment case: the seed stays invested; worker payments are not account withdrawals.
 # This is conditional on payment source, not an adopted collection schedule.
 return dict(required_grt_rate=rate,new_deficit_borrowing_T=0,grt_T=grt,total_revenue_T=rev,total_spending_T=spend,balance_T=rev-spend,
 gross_account_USD=gross,illustrative_service_obligations_USD=service,
 conditional_account_after_services_USD=gross-service,
 working_life_capitalization_repayment_total_USD=a['working_life_repayment_USD'],
 additional_capitalization_deduction_at_65_USD=0,
 final_retirement_entitlement_USD=None,
 resident_savings_USD=h['monthly_payment_USD']*h['resident_share']*12*h['years'],
 annual_construction_USD=h['monthly_payment_USD']*(1-h['resident_share'])*12*h['occupied_residences'])

def audit(m):
 rows=[]
 def add(key,formula,value,unit,status='Arithmetic checked; inputs are scenarios'):
  rows.append(dict(key=key,formula=formula,value=value,unit=unit,status=status))
 c=calculate(m)
 for k,v in c.items(): add(k,'See calculate() and aip-model.json',v,'fraction' if k.endswith('_rate') else ('USD T' if k.endswith('_T') else 'USD'), 'Not a defined entitlement' if v is None else 'Arithmetic checked; conditional inputs')
 for r in [.04,.05,.0688,.07,.08,.09]:
  g=25000*(1+r)**65
  add('account_gross_'+str(r),'25000*(1+r)^65',g,'USD')
  add('account_after_services_'+str(r),'gross - 400000 - 155000; working-life repayment external',g-555000,'USD')
 for age in [0,5,10,18,22,30,40,50,60,65]: add('account_age_'+str(age),'25000*1.0688^age',25000*1.0688**age,'USD')
 for inf in [.02,.034]:
  add('gross_real_age65_'+str(inf),'25000*1.0688^65/(1+inflation)^65',25000*1.0688**65/(1+inf)**65,'birth-year USD')
  for n in [30,100]:add('purchasing_power_loss_'+str(inf)+'_'+str(n),'1-1/(1+inflation)^years',1-1/(1+inf)**n,'fraction')
 for fee in [.0025,.01]: add('account_fee_'+str(fee),'25000*((1.0688)*(1-fee))^65',25000*(1.0688*(1-fee))**65,'USD')
 for e in [.04,.05,.06,.15,.20]:
  v=46*.132*(1-e);add('grt_evasion_'+str(e),'46*.132*(1-evasion)',v,'USD T');add('historical_fixed_rate_budget_balance_evasion_'+str(e),'GRT+2-8.07',v+2-8.07,'USD T')
 add('historical_fixed_rate_joint_stress_gap','8.07 + 2.02*.10 - (46*.99*.132*.8 + 2)',8.07+2.02*.1-(46*.99*.132*.8+2),'USD T')
 add('grt_one_point_evasion','46*.132*.01',46*.132*.01,'USD T')
 add('required_rate_no_credits','(8.07-2)/(46*.95)',(8.07-2)/(46*.95),'fraction; not a rate recommendation')
 for name,rate in [('additive',.132*(1-.105-.02-.02)),('sequential',.132*(1-.105)*.98*.98)]:
  add('credit_rate_'+name,'13.2% with relative discounts 10.5%,2%,2%',rate,'fraction')
  add('historical_fixed_rate_credit_gap_'+name,'8.07 - (46*discounted_rate*.95 + 2)',8.07-(46*rate*.95+2),'USD T')
 for rate in [.10,.15,.30]:add('penalty_'+str(rate),'0.132*(1+penalty)',.132*(1+rate),'fraction')
 add('asset_loan_gain','5*(10-1)/10',4.5,'USD M; distinct unadopted anti-avoidance example')
 add('asset_loan_tax','4.5*.132',4.5*.132,'USD M; not included in receipts base')
 add('year30_component_spending','4.5+1.8+.35+0+2.6+.1',4.5+1.8+.35+2.6+.1,'USD T; historical component sum')
 add('historical_fixed_rate_year30_component_balance','12.3-9.35',12.3-(4.5+1.8+.35+2.6+.1),'USD T; historical conditional difference')
 add('education_year1_scope_gap','.620+.240-.740',.620+.240-.740,'USD T')
 add('worker_support_cost','45000000000/1000000',45000,'USD per affected worker; cost adequacy unproven')
 add('historical_fixed_rate_gap_with_education_and_worker_if_additional','.3016+.120+.045',.3016+.120+.045,'USD T; only if both are additional')
 add('transition_sum_B','100+700+250+200+170+180',1600,'USD B')
 for age in [1,10,17]:add('child_seed_age_'+str(age),'25000*(65-age)/65',25000*(65-age)/65,'USD')
 add('minimum_70m_child_seed_T','70000000*25000*(65-17)/65/1e12',70000000*25000*48/65/1e12,'USD T; lower bound if all ages <=17')
 for births in [3600000,4000000,750000]:add('annual_birth_seeds_'+str(births),'births*25000',births*25000,'USD')
 add('regional_allocation_total_B','6.5+5+4+3+2+2+18.75',41.25,'USD B')
 add('regional_gap_B','41.25-26.8',14.45,'USD B')
 add('regional_programs_without_tax_reduction_B','41.25-6.5',34.75,'USD B')
 add('regional_gap_without_tax_reduction_B','34.75-26.8',7.95,'USD B; depends on surplus basis')
 add('alliance_population_M','564+49.4+25.8+143.5',782.7,'million; historical roster only')
 add('alliance_gdp_T','32+.301+.197+1.084',33.582,'USD T; mixed-date historical inputs')
 add('health_savings_B','450+100+150+80+100',880,'USD B; overlap not ruled out')
 add('mortality_multiplication','45000*30',1350000,'deaths; arithmetic only, not AIP causal effect')
 add('incarceration_cost_low','2100000*40000',84000000000,'USD; historical inputs')
 add('incarceration_cost_high','2100000*60000',126000000000,'USD; historical inputs')
 add('dropout_lifetime_cohort_cost_low','1200000*260000',312000000000,'USD; lifetime cost per annual cohort, not annual cash')
 add('dropout_lifetime_cohort_cost_high','1200000*450000',540000000000,'USD; lifetime cost per annual cohort, not annual cash')
 add('dropout_benefit_cost_low','260000/50000',5.2,'benefit-cost ratio; not proven intervention effect')
 add('dropout_benefit_cost_high','450000/50000',9,'benefit-cost ratio; not proven intervention effect')
 add('housing_36_months','900*36',32400,'USD resident savings')
 add('housing_construction_60_months','100*60',6000,'USD construction')
 add('housing_90pct_occupancy','500*.9*100*12',540000,'USD annual construction')
 add('housing_new_units','600000/200000',3,'units; hypothetical cost')
 return rows

if __name__=='__main__':
 m=json.loads(Path(__file__).with_suffix('.json').read_text())
 print(json.dumps({'reference':calculate(m),'checks':audit(m)},indent=2))
