#!/usr/bin/env python3
"""Reproduce Sweden EOR Review fictional cases. Save sweden-eor-review-worked-records.json beside
this file and run python3 sweden-eor-review-check-model.py --records sweden-eor-review-worked-records.json.
Use --regression only for the published baseline. No individual payroll/legal calculation.
"""
from decimal import Decimal,ROUND_HALF_UP
from pathlib import Path
from datetime import date
import json, argparse, copy
D=Decimal
q=lambda x:x.quantize(D('.01'),rounding=ROUND_HALF_UP)
def agency(record, receipt_key='receipt_on_time', second_extra=D('0')):
 """Dated GBP obligations; only a declared cleared receipt increases available cash.
 Same-day ordering is an explicit input, never an assumption about bank settlement.
 Negative balances identify unfunded obligations, not executed overdraft payments.
 """
 if not isinstance(record,dict):raise ValueError('agency must be an object')
 def money(key):
  if key not in record:raise ValueError('Missing agency input: '+key)
  try:value=D(str(record[key]))
  except Exception:raise ValueError('Invalid agency amount: '+key)
  if not value.is_finite() or value<0:raise ValueError('Agency amount must be finite and nonnegative: '+key)
  return value
 def day(key):
  if key not in record:raise ValueError('Missing agency date: '+key)
  raw=record[key]
  try:value=date.fromisoformat(raw)
  except Exception:raise ValueError('Invalid ISO agency date: '+key)
  if value.isoformat()!=raw:raise ValueError('Agency date must be YYYY-MM-DD: '+key)
  return raw
 cash=money('cash');reserve=money('reserve');deposit=money('deposit');first=money('cycle');second=money('second_cycle')+second_extra;receipt=money('receipt')
 start=day('cash_date');deposit_day=day('deposit_date');first_day=day('first_funding');second_day=day('second_funding');received=day(receipt_key)
 # Both advertised scenario dates must be present, even if only one is selected.
 day('receipt_on_time');day('receipt_late')
 if min(deposit_day,first_day,second_day,received)<start:raise ValueError('Agency event precedes available opening cash')
 if first_day>second_day:raise ValueError('Second funding precedes first funding')
 if not second.is_finite() or second<0:raise ValueError('Invalid second cycle amount')
 order=record.get('same_day_order')
 if order not in ['outflows_before_receipts','receipts_before_outflows']:raise ValueError('Explicit valid same_day_order required')
 status=record.get('receipt_status')
 if status not in ['cleared','expected']:raise ValueError('receipt_status must be cleared or expected')
 events=[{'date':deposit_day,'event':'deposit','amount':-deposit,'kind':'outflow'}, {'date':first_day,'event':'first_funding','amount':-first,'kind':'funding'}, {'date':second_day,'event':'second_funding','amount':-second,'kind':'funding'}, {'date':received,'event':'receipt','amount':receipt if status=='cleared' else D(0),'kind':'receipt','declared_amount':receipt,'receipt_status':status}]
 priorities={'deposit':0,'first_funding':1,'second_funding':2,'receipt':3} if order=='outflows_before_receipts' else {'receipt':0,'deposit':1,'first_funding':2,'second_funding':3}
 events.sort(key=lambda e:(e['date'],priorities[e['event']]))
 opening={'date':start,'event':'opening','balance':cash,'floor_shortfall':max(D(0),reserve-cash)}
 ledger=[opening];minimum=cash;failed_funding=None;failed_floor=opening if cash<reserve else None
 for event in events:
  cash+=event['amount'];row={**event,'balance':cash,'floor_shortfall':max(D(0),reserve-cash)};ledger.append(row);minimum=min(minimum,cash)
  if failed_funding is None and event['kind'] in ['funding','outflow'] and cash<0:failed_funding=row
  if failed_floor is None and cash<reserve:failed_floor=row
 return {'minimum_balance':minimum,'ending_balance':cash,'reserve':reserve,'first_failed_funding_event':failed_funding,'first_failed_floor_event':failed_floor,'funding_status':'FUNDED' if failed_funding is None else 'FUNDING_SHORTFALL','floor_status':'PASS' if failed_floor is None else 'FLOOR_SHORTFALL','decision':'APPROVE' if failed_funding is None and failed_floor is None else 'HOLD','same_day_order':order,'receipt_status':status,'ledger':ledger}

def salary_for_period(period,instructions):
 salary=D('50000');seen=set()
 for row in sorted(instructions,key=lambda x:x.get('effective') or '9999'):
  if not row.get('effective') or not row.get('authorised'):continue
  if row['id'] in seen:continue
  seen.add(row['id'])
  if row['effective']<=period:salary=D(row['amount'])
 return salary

def calculate(r):
 if 'agency' not in r:raise ValueError('Missing required agency object')
 agency_timely=agency(r['agency']);agency_late=agency(r['agency'],'receipt_late');agency_extra=agency(r['agency'],second_extra=D('500'))
 z=r['sek_routes']; wage=D(z['employment']);fee=D(z['fee']);out=D(z['treasury_SEK_per_USD']);into=D(z['payroll_SEK_per_USD']);bank=D(z['bank'])
 usd=q(wage/into);converted=usd*out+bank+fee
 s=r['sales'];commission=(D(s['collected'])-D(s['refunds']))*D(s['rate']);gross=D(s['base'])+commission
 f=r['six_person'];employment=sum(D(f[x]) for x in ['salary','employer','pension','insurance']);fees=D(f['fee_per_person'])*D(f['people']);rate=D(f['rate']);cash=D(f['cash']);security=D(f['salary']);b=D(f['bank'])
 monthly=employment/rate+fees;opening=monthly+security/rate+b
 adverse=q(employment/D('9.8'))+q(security/D('9.8'))+fees+b
 return {'agency':agency_timely,'agency_late':agency_late,'agency_second_extra500':agency_extra,'agency_timely_min':agency_timely['minimum_balance'],'agency_late_min':agency_late['minimum_balance'],'agency_second_extra500_min':agency_extra['minimum_balance'], 'direct_SEK_total':wage+fee,'two_conversion_total':converted,'two_conversion_extra':converted-wage-fee,'underfunded_SEK_shortfall':wage-D('35000')*into,'coordinator_B':q(D('42000')*18/31),'coordinator_total':D('40000')+q(D('42000')*18/31),'commission':commission,'sales_gross':gross,'sales_pension_base':D(s['base'])*D(s['pension_rate']),'sales_pension_full':gross*D(s['pension_rate']),'growth_3_EOR':D('60000')*3,'growth_3_own_first_year':D('150000')+D('12000')*3+D('90000'),'growth_15_EOR':D('60000')*15,'growth_15_own_first_year':D('150000')+D('12000')*15+D('90000'),'growth_first_year_crossover':D('240000')/D('48000'),'conversion_AB_opening':D('45000')+D('40000')+D('65000')+D('58000'),'conversion_AB_remaining':D('250000')-D('208000'),'status_remaining':D('220000')-D('65000')-D('50000')-D('75000'),'candidate_A_pension':D('55000')*D('.05'),'candidate_B_pension':D('70000')*D('.06'),'six_monthly':monthly,'six_opening':opening,'six_remaining':cash-opening,'six_adverse_opening':adverse,'six_adverse_shortfall':adverse-cash,'alternative_monthly':employment/rate+D('3000')+(employment/rate)*D('.0075'),'bonus_reconciliation':D('8000')/rate,'bonus_cash_remaining':cash-opening-D('8000')/rate}
def regressions(r,out):
 expected={'agency_timely_min':'15000','agency_late_min':'-8000','agency_second_extra500_min':'14500','direct_SEK_total':'375000','two_conversion_total':'382342.90','two_conversion_extra':'7342.90','underfunded_SEK_shortfall':'7000','coordinator_B':'24387.10','coordinator_total':'64387.10','commission':'10400','sales_gross':'55400','sales_pension_base':'2025','sales_pension_full':'2493','growth_3_EOR':'180000','growth_3_own_first_year':'276000','growth_15_EOR':'900000','growth_15_own_first_year':'420000','growth_first_year_crossover':'5','conversion_AB_opening':'208000','conversion_AB_remaining':'42000','status_remaining':'30000','candidate_A_pension':'2750','candidate_B_pension':'4200','six_monthly':'45094','six_opening':'75144','six_remaining':'856','six_adverse_opening':'76603.18','six_adverse_shortfall':'603.18','alternative_monthly':'44811.25','bonus_reconciliation':'800','bonus_cash_remaining':'56'}
 checks=0
 for k,v in expected.items():assert out[k]==D(v),(k,out[k],v);checks+=1
 instruction={'id':'E07-v2','effective':'2027-01-01','amount':'52000','authorised':True}
 for period,rows,want in [('2026-12-01',[instruction],'50000'),('2027-01-01',[instruction],'52000'),('2027-01-01',[instruction,instruction],'52000'),('2027-01-01',[{**instruction,'effective':None}],'50000'),('2027-01-01',[{**instruction,'authorised':False}],'50000')]:assert salary_for_period(period,rows)==D(want);checks+=1
 assert out['sales_pension_full']-out['sales_pension_base']==D('468');checks+=1
 assert out['six_monthly']-out['alternative_monthly']==D('282.75');checks+=1
 assert D('1400')+D('600')==D('2000');checks+=1
 assert D('50000')*D('0.8')==D('40000');checks+=1
 assert D('4400')-D('400')==D('4000');checks+=1
 return checks

def serialise(value):
 if isinstance(value,D):return str(q(value))
 if isinstance(value,dict):return {k:serialise(v) for k,v in value.items()}
 if isinstance(value,list):return [serialise(v) for v in value]
 return value
if __name__=='__main__':
 parser=argparse.ArgumentParser(description='Calculate the supplied fictional Sweden records. Agency, SEK, sales and six-person fields drive their scenarios; remaining illustrations are fixed reproduction examples.')
 parser.add_argument('--records',type=Path,default=Path(__file__).with_name('sweden-eor-review-worked-records.json'))
 parser.add_argument('--regression',action='store_true',help='Also assert the published baseline values; do not use this flag for changed scenarios.')
 args=parser.parse_args()
 try:
  r=json.loads(args.records.read_text());out=calculate(r)
  result={'result':'CALCULATED','outputs':serialise(out),'scope':'Agency dated inputs, SEK routes, sales and six-person fields are parameterised. Other named examples remain fixed reproductions.'}
  if args.regression:result.update(result='PASS',checks=regressions(r,out))
  print(json.dumps(result,indent=2))
 except (ValueError,KeyError,TypeError,ZeroDivisionError) as error:
  parser.exit(2,'Invalid scenario: '+str(error)+'\n')
