"""Sixteen synthetic v87 arithmetic fixtures. No network, real-person data or business actions."""
import argparse,json
from decimal import Decimal
from pathlib import Path
D=Decimal
INPUTS={'learning-retention--cybersecurity': {'total': 30, 'authorised': 24, 'opened': 18, 'submitted': 12, 'correct': 9}, 'learning-retention--software-engineering': {'total': 10, 'firstCorrect': 8, 'laterCorrect': 7, 'common': 8, 'commonFirst': 7, 'commonLater': 6}, 'learning-retention--data-engineering': {'events': 18, 'firstAttempts': 12, 'retakes': 3, 'repeats': 3, 'learners': 12, 'rawCorrect': 12, 'latestCorrect': 9}, 'learning-retention--visualisation': {'total': 10, 'recall': 8, 'transfer': 5, 'both': 4}, 'learning-retention--nlp': {'tp': 9, 'fp': 3, 'fn': 1, 'tn': 3}, 'learning-retention--hci': {'total': 14, 'discovered': 11, 'interpreted': 8}, 'learning-retention--devops': {'total': 12, 'build': 11, 'editorial': 9, 'both': 8}, 'growth-prospecting--operating-systems': {'total': 15, 'readable': 12, 'currentReadable': 9}, 'growth-prospecting--databases': {'rows': 20, 'organisations': 14, 'extraEnquiries': 6, 'owned': 10}, 'growth-prospecting--programming': {'a': [8, 6, 5], 'b': [6, 9, 7], 'firstWeights': [0.5, 0.3, 0.2], 'secondWeights': [0.7, 0.2, 0.1]}, 'growth-prospecting--networks': {'intentions': 25, 'transmissions': 30, 'received': 22, 'owned': 18, 'responded': 15}, 'growth-prospecting--cloud': {'expected': 60, 'technical': 80, 'handling': 45, 'changedTechnical': 100}, 'growth-prospecting--cybersecurity': {'total': 30, 'needed': 21, 'excessive': 6, 'unresolved': 3}, 'growth-prospecting--software-engineering': {'total': 20, 'technical': 17, 'business': 16, 'both': 14}, 'growth-prospecting--data-engineering': {'total': 24, 'eligible': 18, 'later': 4, 'unknown': 2}, 'growth-prospecting--visualisation': {'sessions': 100, 'enquiries': 20, 'qualified': 8, 'customers': 4}}
def percent(n,d):return None if d==0 else D(str(n))/D(str(d))*100
def groups(total,a,b,both):
 if min(total,a,b,both)<0 or max(a,b)>total or not max(0,a+b-total)<=both<=min(a,b):raise ValueError('Inconsistent overlap')
 return dict(both=both,firstOnly=a-both,secondOnly=b-both,neither=total-a-b+both)
def calculate(id,x):
 if any(v<0 for v in x.values() if isinstance(v,(int,float))):raise ValueError('Negative fixture input')
 p=lambda a,b:percent(x[a],x[b])
 if id=='learning-retention--cybersecurity':
  assert x['correct']<=x['submitted']<=x['opened']<=x['authorised']<=x['total']
  return dict(authorisedPercent=p('authorised','total'),openedPercent=p('opened','total'),submittedPercent=p('submitted','total'),allLearnerCorrectPercent=p('correct','total'),submittedCorrectPercent=p('correct','submitted'))
 if id=='learning-retention--software-engineering':
  assert x['commonFirst']<=x['common']<=x['total'] and x['commonLater']<=x['common']
  return dict(firstPercent=p('firstCorrect','total'),laterPercent=p('laterCorrect','total'),commonFirstPercent=p('commonFirst','common'),commonLaterPercent=p('commonLater','common'),rawPointChange=p('laterCorrect','total')-p('firstCorrect','total'),commonPointChange=p('commonLater','common')-p('commonFirst','common'))
 if id=='learning-retention--data-engineering':
  assert x['firstAttempts']+x['retakes']+x['repeats']==x['events']
  return dict(legitimateAttempts=x['firstAttempts']+x['retakes'],rawCorrectPercent=p('rawCorrect','events'),latestLearnerCorrectPercent=p('latestCorrect','learners'))
 if id=='learning-retention--visualisation':return dict(**groups(x['total'],x['recall'],x['transfer'],x['both']),recallPercent=p('recall','total'),transferPercent=p('transfer','total'),jointPercent=p('both','total'))
 if id=='learning-retention--nlp':return dict(precisionPercent=percent(x['tp'],x['tp']+x['fp']),recallPercent=percent(x['tp'],x['tp']+x['fn']),agreementPercent=percent(x['tp']+x['tn'],sum(x.values())))
 if id=='learning-retention--hci':
  assert x['interpreted']<=x['discovered']<=x['total']
  return dict(discoveryPercent=p('discovered','total'),interpretationPercent=p('interpreted','total'),discovererInterpretationPercent=p('interpreted','discovered'))
 if id=='learning-retention--devops':return dict(**groups(x['total'],x['build'],x['editorial'],x['both']),jointPercent=p('both','total'),buildPercent=p('build','total'),editorialPercent=p('editorial','total'))
 if id=='growth-prospecting--operating-systems':
  assert x['currentReadable']<=x['readable']<=x['total']
  return dict(readablePercent=p('readable','total'),currentCoveragePercent=p('currentReadable','total'),readableCurrentPercent=p('currentReadable','readable'))
 if id=='growth-prospecting--databases':
  assert x['organisations']+x['extraEnquiries']==x['rows'] and x['owned']<=x['organisations']
  return dict(ownedOrganisationPercent=p('owned','organisations'),rowOverstatementPercent=p('extraEnquiries','organisations'))
 if id=='growth-prospecting--programming':
  def score(values,weights):
   assert len(values)==len(weights) and abs(sum(weights)-1)<1e-9
   return sum(D(str(v))*D(str(w)) for v,w in zip(values,weights))
  return dict(firstA=score(x['a'],x['firstWeights']),firstB=score(x['b'],x['firstWeights']),changedA=score(x['a'],x['secondWeights']),changedB=score(x['b'],x['secondWeights']))
 if id=='growth-prospecting--networks':
  assert x['responded']<=x['owned']<=x['received']<=x['intentions']<=x['transmissions']
  return dict(receivedPercent=p('received','intentions'),ownedPercent=p('owned','intentions'),respondedPercent=p('responded','intentions'),ownedResponsePercent=p('responded','owned'),transmissionsPerIntention=None if not x['intentions'] else D(x['transmissions'])/D(x['intentions']),unconfirmed=x['intentions']-x['received'],confirmedUnowned=x['received']-x['owned'],ownedUnresponded=x['owned']-x['responded'])
 if id=='growth-prospecting--cloud':return dict(technicalHeadroom=x['technical']-x['expected'],technicalLoadPercent=p('expected','technical'),handlingGap=x['expected']-x['handling'],handlingCoveragePercent=p('handling','expected'),changedTechnicalHeadroom=x['changedTechnical']-x['expected'],changedTechnicalLoadPercent=p('expected','changedTechnical'))
 if id=='growth-prospecting--cybersecurity':
  assert x['needed']+x['excessive']+x['unresolved']==x['total']
  return dict(neededPercent=p('needed','total'),excessivePercent=p('excessive','total'),unresolvedPercent=p('unresolved','total'),decidedPercent=percent(x['needed']+x['excessive'],x['total']))
 if id=='growth-prospecting--software-engineering':return dict(**groups(x['total'],x['technical'],x['business'],x['both']),jointPercent=p('both','total'),technicalPercent=p('technical','total'),businessPercent=p('business','total'))
 if id=='growth-prospecting--data-engineering':
  assert x['eligible']+x['later']+x['unknown']==x['total']
  return dict(eligiblePercent=p('eligible','total'),laterPercent=p('later','total'),unknownPercent=p('unknown','total'),excluded=x['later']+x['unknown'])
 if id=='growth-prospecting--visualisation':
  assert x['customers']<=x['qualified']<=x['enquiries']<=x['sessions']
  return dict(sessionEnquiryPercent=p('enquiries','sessions'),enquiryQualifiedPercent=p('qualified','enquiries'),qualifiedCustomerPercent=p('customers','qualified'),enquiryCustomerPercent=p('customers','enquiries'),sessionCustomerPercent=p('customers','sessions'))
 raise ValueError('Unknown fixture identity')
def fixture_results(inputs=None):return {id:calculate(id,x) for id,x in (INPUTS if inputs is None else inputs).items()}
def self_test():
 assert percent(0,0) is None
 assert len(fixture_results())==16
 try:groups(10,8,5,1)
 except ValueError:pass
 else:raise AssertionError('Impossible overlap accepted')
 return 'Bounded arithmetic checks passed; not independent validation or implementation of the fictional systems.'
if __name__=='__main__':
 p=argparse.ArgumentParser(description=__doc__);p.add_argument('--case',default='all');p.add_argument('--input-file',help='Optional local JSON of synthetic fixtures; no network fetching');p.add_argument('--self-test',action='store_true');a=p.parse_args()
 if a.self_test:print(self_test())
 else:
  inputs=INPUTS if not a.input_file else json.loads(Path(a.input_file).read_text())
  if a.case!='all':
   if a.case not in inputs:p.error('Unknown fixture identity')
   inputs={a.case:inputs[a.case]}
  try:r=fixture_results(inputs)
  except (AssertionError,ValueError,KeyError,TypeError) as e:p.error(str(e))
  print(json.dumps(r,ensure_ascii=False,indent=2,default=str))
