"""Bounded fictional finance worksheets. No network calls or financial actions."""
import argparse,json
from pathlib import Path
from decimal import Decimal as D,ROUND_HALF_UP
INPUTS={'finance-value--workflow': {'face': 50000, 'discountPercent': 2, 'financing': 300, 'processing': 200}, 'finance-value--analytics': {'aUnits': 100, 'aPrice': 100, 'aVariable': 60, 'bUnits': 50, 'bPrice': 200, 'bVariable': 160}, 'finance-value--ai': {'tasks': 80, 'savedMinutes': 5, 'reviewMinutes': 2, 'hourValue': 600, 'toolCost': 1000}, 'finance-value--devices': {'expectedIntervals': 100, 'observedIntervals': 90, 'observedKwh': 180, 'tariff': 3}, 'finance-value--integration': {'uniqueEvents': 6, 'retryEvents': 2, 'uniqueAmount': 12000, 'retryAmount': 4000}, 'finance-value--governance': {'total': 20, 'approval': 16, 'support': 15, 'both': 12}, 'finance-value--learning-tools': {'invited': 24, 'attended': 20, 'immediate': 16, 'later': 12}, 'finance-value--operating-systems': {'minutes': 45, 'rate': 2, 'contribution': 30, 'recovered': 30}, 'finance-value--databases': {'a': 5000, 'b': 2000, 'transfer': 600}, 'finance-value--programming': {'unit': '0.335', 'lines': 3}, 'finance-value--networks': {'sent': 40, 'timeouts': 5, 'confirmed': 3, 'minutesEach': 6, 'amountEach': 500}, 'finance-value--cloud': {'budget': 1000, 'spend': 600, 'elapsedDays': 18, 'periodDays': 30}, 'finance-value--cybersecurity': {'beforeProbability': '0.1', 'afterProbability': '0.04', 'impact': 100000, 'annualCost': 3000}, 'finance-value--software-engineering': {'total': 20, 'arithmetic': 17, 'semantic': 14, 'both': 13}, 'finance-value--data-engineering': {'originals': 12, 'retransmissions': 3, 'reversals': 1, 'originalAmount': 12000, 'retransmittedAmount': 3000, 'reversalAmount': 1000}, 'finance-value--visualisation': {'aInvoices': 30, 'aAmount': 30000, 'aOverdue': 18000, 'bInvoices': 10, 'bAmount': 50000, 'bOverdue': 10000}}
def percent(n,d):return None if d==0 else n/d*100
def calculate(id,x):
 if id not in INPUTS or set(x)!=set(INPUTS[id]):raise ValueError('Unknown case or missing/unexpected fields')
 if any(type(v) not in (int,str) for v in x.values()):raise ValueError('Use exact integers or decimal strings')
 try:v={k:D(str(a)) for k,a in x.items()}
 except Exception as e:raise ValueError('Invalid decimal') from e
 if any(not a.is_finite() or a<0 for a in v.values()):raise ValueError('Use finite nonnegative inputs')
 d=id.split('--')[1]
 def nested(*ks):
  if any(v[a]<v[b] for a,b in zip(ks,ks[1:])):raise ValueError('Inconsistent nested quantities')
 def overlap(a,b):
  t=v['total'];z=v['both'];u=v[a];w=v[b]
  if not max(D(0),u+w-t)<=z<=min(u,w) or max(u,w)>t:raise ValueError('Inconsistent overlap')
  return dict(both=z,**{a+'Only':u-z,b+'Only':w-z},neither=t-u-w+z,jointPercent=percent(z,t))
 if d=='workflow':
  if v['discountPercent']>100:raise ValueError('Discount exceeds face value')
  z=v['face']*v['discountPercent']/100;return dict(discount=z,supplierPayment=v['face']-z,netBenefit=z-v['financing']-v['processing'],totalOutflow=v['face']-z+v['financing']+v['processing'])
 if d=='analytics':
  a=v['aUnits']*(v['aPrice']-v['aVariable']);b=v['bUnits']*(v['bPrice']-v['bVariable']);r=v['aUnits']*v['aPrice']+v['bUnits']*v['bPrice'];return dict(aContribution=a,bContribution=b,revenue=r,contribution=a+b,marginPercent=percent(a+b,r))
 if d=='ai':
  n=v['tasks']*(v['savedMinutes']-v['reviewMinutes']);h=n/60;z=h*v['hourValue'];return dict(netMinutes=n,netHours=h,scenarioValue=z,netValue=z-v['toolCost'])
 if d=='devices':
  nested('expectedIntervals','observedIntervals');est=None if v['observedIntervals']==0 else v['observedKwh']*v['expectedIntervals']/v['observedIntervals'];return dict(coveragePercent=percent(v['observedIntervals'],v['expectedIntervals']),observedCost=v['observedKwh']*v['tariff'],estimatedKwh=est,estimatedCost=None if est is None else est*v['tariff'])
 if d=='integration':
  t=v['uniqueEvents']+v['retryEvents'];z=v['uniqueAmount']+v['retryAmount'];return dict(receivedEvents=t,rawAmount=z,uniqueAmount=v['uniqueAmount'],retryEventPercent=percent(v['retryEvents'],t),retryAmountPercent=percent(v['retryAmount'],z))
 if d=='governance':return overlap('approval','support')
 if d=='learning-tools':
  nested('invited','attended','immediate','later');return dict(attendancePercent=percent(v['attended'],v['invited']),immediatePercent=percent(v['immediate'],v['invited']),laterPercent=percent(v['later'],v['invited']),laterAmongAttendeesPercent=percent(v['later'],v['attended']))
 if d=='operating-systems':
  n=v['minutes']*v['rate']
  if v['recovered']>n:raise ValueError('Recovered volume exceeds affected volume')
  return dict(affected=n,grossAtRisk=n*v['contribution'],unresolved=n-v['recovered'],unresolvedContribution=(n-v['recovered'])*v['contribution'])
 if d=='databases':
  if v['transfer']>v['a']:raise ValueError('Transfer exceeds source balance in this fixture')
  return dict(aAfter=v['a']-v['transfer'],bAfter=v['b']+v['transfer'],totalBefore=v['a']+v['b'],totalAfter=v['a']+v['b'],debitOnlyTotal=v['a']+v['b']-v['transfer'])
 if d=='programming':
  if v['lines']!=v['lines'].to_integral_value():raise ValueError('Line count must be integral')
  a=v['unit'].quantize(D('.01'),rounding=ROUND_HALF_UP);t=a*v['lines'];z=(v['unit']*v['lines']).quantize(D('.01'),rounding=ROUND_HALF_UP);return dict(lineRounded=a,lineTotal=t,aggregateRounded=z,difference=t-z)
 if d=='networks':
  nested('sent','timeouts','confirmed');u=v['timeouts']-v['confirmed'];return dict(unresolved=u,timeoutPercent=percent(v['timeouts'],v['sent']),unresolvedPercent=percent(u,v['sent']),investigationMinutes=u*v['minutesEach'],amountUnresolved=u*v['amountEach'])
 if d=='cloud':
  nested('periodDays','elapsedDays');z=None if v['elapsedDays']==0 else v['spend']*v['periodDays']/v['elapsedDays'];return dict(consumedPercent=percent(v['spend'],v['budget']),runRate=z,forecastHeadroom=None if z is None else v['budget']-z)
 if d=='cybersecurity':
  if max(v['beforeProbability'],v['afterProbability'])>1:raise ValueError('Probability outside unit interval')
  a=v['beforeProbability']*v['impact'];b=v['afterProbability']*v['impact'];return dict(beforeExpected=a,afterExpected=b,reduction=a-b,netExpectedBenefit=a-b-v['annualCost'])
 if d=='software-engineering':return overlap('arithmetic','semantic')
 if d=='data-engineering':
  return dict(rawEvents=v['originals']+v['retransmissions']+v['reversals'],naiveNet=v['originalAmount']+v['retransmittedAmount']-v['reversalAmount'],canonicalNet=v['originalAmount']-v['reversalAmount'],overstatement=v['retransmittedAmount'])
 if d=='visualisation':
  nested('aAmount','aOverdue');nested('bAmount','bOverdue');a=percent(v['aOverdue'],v['aAmount']);b=percent(v['bOverdue'],v['bAmount']);return dict(invoices=v['aInvoices']+v['bInvoices'],totalAmount=v['aAmount']+v['bAmount'],overdueAmount=v['aOverdue']+v['bOverdue'],aPercent=a,bPercent=b,pooledPercent=percent(v['aOverdue']+v['bOverdue'],v['aAmount']+v['bAmount']),unweightedPercent=None if a is None or b is None else (a+b)/2)
 raise ValueError('Unknown case')
if __name__=='__main__':
 p=argparse.ArgumentParser(description=__doc__);p.add_argument('--case',default='all',choices=['all',*INPUTS]);p.add_argument('--input-file');a=p.parse_args();data=json.loads(Path(a.input_file).read_text()) if a.input_file else INPUTS;ids=INPUTS if a.case=='all' else [a.case];print(json.dumps({id:calculate(id,data[id]) for id in ids},default=str,indent=2))
