"""Fifteen invented arithmetic examples; no network, deployment, model or real-user data."""
import argparse,json
from decimal import Decimal
from pathlib import Path
D=Decimal
INPUTS={'growth-prospecting--nlp': {'tp': 10, 'fp': 4, 'fn': 2, 'tn': 14}, 'growth-prospecting--hci': {'total': 20, 'discovered': 16, 'submitted': 12, 'interpreted': 9}, 'growth-prospecting--devops': {'total': 16, 'technical': 14, 'business': 13, 'both': 12}, 'markets-opportunities--operating-systems': {'total': 40, 'supported': 28}, 'markets-opportunities--databases': {'enquiries': 20, 'joined': 32}, 'markets-opportunities--programming': {'total': 36, 'matched': 18, 'rejected': 8, 'unresolved': 10}, 'markets-opportunities--networks': {'a_total': 20, 'a_met': 18, 'b_total': 20, 'b_met': 12}, 'markets-opportunities--cloud': {'fixed': 600, 'variable': 2, 'tasks': 150}, 'markets-opportunities--cybersecurity': {'total': 24, 'reviewed': 15, 'pending': 5, 'absent': 4}, 'markets-opportunities--software-engineering': {'scenarios': 12, 'passed': 9, 'participants': 8, 'completed': 5}, 'markets-opportunities--data-engineering': {'total': 60, 'accepted': 40, 'duplicates': 8, 'unresolved': 12}, 'markets-opportunities--visualisation': {'a_total': 30, 'a_matches': 12, 'b_total': 10, 'b_matches': 6}, 'markets-opportunities--nlp': {'total': 20, 'delivery': 8, 'price': 6, 'both': 3}, 'markets-opportunities--hci': {'total': 24, 'understood': 18, 'completed': 15, 'nextstep': 12}, 'markets-opportunities--devops': {'total': 10, 'technical': 8, 'observation': 7, 'both': 6}}
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 id not in INPUTS:raise ValueError('Unknown case')
 if set(x)!=set(INPUTS[id]):raise ValueError('Missing or unexpected fields')
 if any(type(v) is not int or v<0 for v in x.values()):raise ValueError('Use non-negative integer fixture values')
 p=lambda a,b:percent(x[a],x[b])
 def nested(*keys):
  if any(x[a]<x[b] for a,b in zip(keys,keys[1:])):raise ValueError('Inconsistent nested counts')
 def reconcile(total,*keys):
  if sum(x[k] for k in keys)!=x[total]:raise ValueError('Categories do not reconcile')
 if id=='growth-prospecting--nlp':
  t=sum(x.values());return dict(total=t,precisionPercent=percent(x['tp'],x['tp']+x['fp']),recallPercent=percent(x['tp'],x['tp']+x['fn']),agreementPercent=percent(x['tp']+x['tn'],t))
 if id=='growth-prospecting--hci':
  nested('total','discovered','submitted','interpreted');return dict(discoveryPercent=p('discovered','total'),submissionPercent=p('submitted','total'),interpretationPercent=p('interpreted','total'),submitterInterpretationPercent=p('interpreted','submitted'))
 if id=='growth-prospecting--devops':return dict(**groups(x['total'],x['technical'],x['business'],x['both']),technicalPercent=p('technical','total'),businessPercent=p('business','total'),jointPercent=p('both','total'))
 if id=='markets-opportunities--operating-systems':
  nested('total','supported');return dict(supportedPercent=p('supported','total'),unresolved=x['total']-x['supported'],unresolvedPercent=percent(x['total']-x['supported'],x['total']))
 if id=='markets-opportunities--databases':
  nested('joined','enquiries');return dict(extraRows=x['joined']-x['enquiries'],inflationPercent=percent(x['joined']-x['enquiries'],x['enquiries']),interestRowsPerEnquiry=None if x['enquiries']==0 else D(x['joined'])/x['enquiries'])
 if id=='markets-opportunities--programming':
  reconcile('total','matched','rejected','unresolved');return dict(matchPercent=p('matched','total'),unresolvedPercent=p('unresolved','total'),assessedMatchPercent=percent(x['matched'],x['matched']+x['rejected']))
 if id=='markets-opportunities--networks':
  nested('a_total','a_met');nested('b_total','b_met');a=p('a_met','a_total');b=p('b_met','b_total');return dict(aPercent=a,bPercent=b,pooledPercent=percent(x['a_met']+x['b_met'],x['a_total']+x['b_total']),percentagePointGap=None if a is None or b is None else a-b)
 if id=='markets-opportunities--cloud':
  total=x['fixed']+x['variable']*x['tasks'];return dict(totalCost=total,costPerTask=None if x['tasks']==0 else D(total)/x['tasks'])
 if id=='markets-opportunities--cybersecurity':
  reconcile('total','reviewed','pending','absent');return dict(reviewedPercent=p('reviewed','total'),pendingPercent=p('pending','total'),absentPercent=p('absent','total'))
 if id=='markets-opportunities--software-engineering':
  nested('scenarios','passed');nested('participants','completed');return dict(acceptancePercent=p('passed','scenarios'),taskPercent=p('completed','participants'))
 if id=='markets-opportunities--data-engineering':
  reconcile('total','accepted','duplicates','unresolved');return dict(acceptedPercent=p('accepted','total'),duplicatePercent=p('duplicates','total'),unresolvedPercent=p('unresolved','total'))
 if id=='markets-opportunities--visualisation':
  nested('a_total','a_matches');nested('b_total','b_matches');return dict(aPercent=p('a_matches','a_total'),bPercent=p('b_matches','b_total'),pooledPercent=percent(x['a_matches']+x['b_matches'],x['a_total']+x['b_total']))
 if id=='markets-opportunities--nlp':
  g=groups(x['total'],x['delivery'],x['price'],x['both']);u=x['delivery']+x['price']-x['both'];return dict(**g,union=u,unionPercent=percent(u,x['total']))
 if id=='markets-opportunities--hci':
  nested('total','understood','completed','nextstep');return dict(understandingPercent=p('understood','total'),completionPercent=p('completed','total'),nextStepPercent=p('nextstep','total'),completerNextStepPercent=p('nextstep','completed'))
 if id=='markets-opportunities--devops':return dict(**groups(x['total'],x['technical'],x['observation'],x['both']),technicalPercent=p('technical','total'),observationPercent=p('observation','total'),jointPercent=p('both','total'))
 raise ValueError('Unknown case')
def fixture_results():return {id:calculate(id,x) for id,x in INPUTS.items()}
def self_test():
 assert percent(0,0) is None
 try:groups(10,8,7,1)
 except ValueError:pass
 else:raise AssertionError('Impossible overlap accepted')
 assert len(fixture_results())==15
 return 'Bounded fixture checks passed; not independent expert validation.'
if __name__=='__main__':
 p=argparse.ArgumentParser(description=__doc__);p.add_argument('--case',default='all',choices=['all',*INPUTS]);p.add_argument('--input-file');p.add_argument('--self-test',action='store_true');a=p.parse_args()
 if a.self_test:print(self_test())
 else:
  source=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,source[id]) for id in ids},default=str,indent=2))
