"""Twelve fictional negotiation arithmetic examples. No network, agreement or real system execution."""
import argparse,json
from decimal import Decimal,ROUND_CEILING
from pathlib import Path
D=Decimal
INPUTS={'negotiation-conclusion--operating-systems': {'total': 30, 'confirmed': 21, 'unresolved': 6, 'outside': 3}, 'negotiation-conclusion--databases': {'proposals': 12, 'revisions': 29}, 'negotiation-conclusion--programming': {'price': 120, 'variable': 75, 'fixed': 900, 'volume': 25}, 'negotiation-conclusion--networks': {'total': 50, 'acknowledged': 45, 'completed': 36}, 'negotiation-conclusion--cloud': {'total': 20, 'organisation': 11, 'provider': 5, 'unresolved': 4}, 'negotiation-conclusion--cybersecurity': {'total': 28, 'necessary': 19, 'excessive': 5, 'unresolved': 4}, 'negotiation-conclusion--software-engineering': {'total': 14, 'technical': 11, 'operational': 10, 'both': 9}, 'negotiation-conclusion--data-engineering': {'total': 48, 'accepted': 35, 'unresolved': 8, 'rejected': 5}, 'negotiation-conclusion--visualisation': {'a_cost': 8, 'a_service': 6, 'b_cost': 6, 'b_service': 9, 'cost_weight': 80}, 'negotiation-conclusion--nlp': {'tp': 7, 'fp': 3, 'fn': 2, 'tn': 12}, 'negotiation-conclusion--hci': {'total': 20, 'discovered': 17, 'reviewed': 14, 'interpreted': 11}, 'negotiation-conclusion--devops': {'total': 18, 'technical': 15, 'business': 13, 'both': 11}}
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 shares(total,*keys):
  if sum(x[k] for k in keys)!=x[total]:raise ValueError('Categories do not reconcile')
  return {k+'Percent':p(k,total) for k in keys}
 d=id.split('--')[1]
 if d=='operating-systems':return shares('total','confirmed','unresolved','outside')
 if d=='databases':
  nested('revisions','proposals');extra=x['revisions']-x['proposals'];return dict(extraRevisions=extra,inflationPercent=percent(extra,x['proposals']),revisionsPerProposal=None if x['proposals']==0 else D(x['revisions'])/x['proposals'])
 if d=='programming':
  c=x['price']-x['variable'];b=None if c<=0 else D(x['fixed'])/c
  return dict(contribution=c,continuousBreakEven=b,wholeUnitBreakEven=None if b is None else int(b.to_integral_value(rounding=ROUND_CEILING)),scenarioSurplus=x['volume']*c-x['fixed'])
 if d=='networks':
  nested('total','acknowledged','completed');return dict(acknowledgementPercent=p('acknowledged','total'),completionPercent=p('completed','total'),acknowledgedIncomplete=x['acknowledged']-x['completed'],unacknowledged=x['total']-x['acknowledged'],acknowledgedCompletionPercent=p('completed','acknowledged'))
 if d=='cloud':return dict(**shares('total','organisation','provider','unresolved'),assignedPercent=percent(x['organisation']+x['provider'],x['total']))
 if d=='cybersecurity':return dict(**shares('total','necessary','excessive','unresolved'),decidedPercent=percent(x['necessary']+x['excessive'],x['total']))
 if d=='software-engineering':return dict(**groups(x['total'],x['technical'],x['operational'],x['both']),technicalPercent=p('technical','total'),operationalPercent=p('operational','total'),jointPercent=p('both','total'))
 if d=='data-engineering':return shares('total','accepted','unresolved','rejected')
 if d=='visualisation':
  if x['cost_weight']>100:raise ValueError('Weight must be between zero and one hundred')
  w=D(x['cost_weight'])/100
  return dict(equalA=D(x['a_cost']+x['a_service'])/2,equalB=D(x['b_cost']+x['b_service'])/2,weightedA=D(x['a_cost'])*w+D(x['a_service'])*(1-w),weightedB=D(x['b_cost'])*w+D(x['b_service'])*(1-w))
 if d=='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 d=='hci':
  nested('total','discovered','reviewed','interpreted');return dict(discoveryPercent=p('discovered','total'),reviewPercent=p('reviewed','total'),interpretationPercent=p('interpreted','total'),reviewerInterpretationPercent=p('interpreted','reviewed'))
 if d=='devops':return dict(**groups(x['total'],x['technical'],x['business'],x['both']),technicalPercent=p('technical','total'),businessPercent=p('business','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())==12
 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))
