"""Sixteen synthetic v86 arithmetic fixtures. No network, real-person data or business actions."""
import argparse,json
from decimal import Decimal
from pathlib import Path
D=Decimal
INPUTS={'balance-wellbeing--databases': {'total': 24, 'needed': 18, 'excessive': 4, 'unresolved': 2}, 'balance-wellbeing--programming': {'total': 20, 'urgent': 4, 'ordinary': 12, 'unresolved': 4}, 'balance-wellbeing--networks': {'total': 20, 'inWindow': 16, 'timelyInWindow': 12, 'outsideWindow': 4}, 'balance-wellbeing--cloud': {'total': 20, 'boundary': 16, 'owner': 15, 'both': 13}, 'balance-wellbeing--cybersecurity': {'total': 18, 'triaged': 12, 'untriaged': 6, 'assigned': [6, 4, 2]}, 'balance-wellbeing--software-engineering': {'requirements': 10, 'baseEffort': 2, 'capacity': 24, 'newRequests': 3, 'newEffort': 3}, 'balance-wellbeing--data-engineering': {'events': 40, 'repeats': 10, 'identities': 30, 'reviewed': 24, 'defects': 18, 'legitimate': 6, 'unresolved': 6}, 'balance-wellbeing--visualisation': {'invited': 50, 'responded': 30, 'positive': 18, 'unknown': 20}, 'balance-wellbeing--nlp': {'tp': 6, 'fp': 4, 'fn': 2, 'tn': 8}, 'balance-wellbeing--hci': {'total': 12, 'discovered': 10, 'completed': 8}, 'balance-wellbeing--devops': {'total': 16, 'technical': 14, 'support': 12, 'both': 11}, 'learning-retention--operating-systems': {'files': 12, 'available': 10, 'questions': 6, 'correct': 4, 'correctedAvailable': 11}, 'learning-retention--databases': {'learners': 8, 'attempts': 16, 'firstCorrect': 5, 'secondCorrect': 7, 'correctAttempts': 12, 'anyCorrect': 7}, 'learning-retention--programming': {'tests': 8, 'passed': 8, 'questions': 5, 'correct': 3, 'laterCorrect': 4}, 'learning-retention--networks': {'intentions': 10, 'transmissions': 12, 'confirmed': 8, 'unresolved': 2, 'delayedQuestions': 6, 'delayedCorrect': 4}, 'learning-retention--cloud': {'enrolled': 20, 'activated': 18, 'submitted': 15, 'correct': 12}}
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(not isinstance(v,(int,float,list)) for v in x.values()):raise ValueError('Fixture values must be numeric or the assigned-count list')
 if any(v<0 for v in x.values() if isinstance(v,(int,float))):raise ValueError('Negative fixture input')
 if id=='balance-wellbeing--databases':
  assert x['needed']+x['excessive']+x['unresolved']==x['total'],'Permission groups must reconcile'
  return dict(neededPercent=percent(x['needed'],x['total']),excessivePercent=percent(x['excessive'],x['total']),unresolvedPercent=percent(x['unresolved'],x['total']),decidedPercent=percent(x['needed']+x['excessive'],x['total']))
 if id=='balance-wellbeing--programming':
  assert x['urgent']+x['ordinary']+x['unresolved']==x['total'],'Message groups must reconcile'
  return dict(immediateReductionPercent=percent(x['total']-x['urgent'],x['total']),immediateCount=x['urgent'],digestItemCount=x['ordinary'],reviewQueueCount=x['unresolved'])
 if id=='balance-wellbeing--networks':
  assert x['inWindow']+x['outsideWindow']==x['total'] and x['timelyInWindow']<=x['inWindow'],'Request groups must reconcile'
  return dict(inWindowResponsePercent=percent(x['timelyInWindow'],x['inWindow']),allRequestTimelyPercent=percent(x['timelyInWindow'],x['total']),outsideWindowPercent=percent(x['outsideWindow'],x['total']))
 if id=='balance-wellbeing--cloud':return dict(**groups(x['total'],x['boundary'],x['owner'],x['both']),jointPercent=percent(x['both'],x['total']),boundaryPercent=percent(x['boundary'],x['total']),ownerPercent=percent(x['owner'],x['total']))
 if id=='balance-wellbeing--cybersecurity':
  assert x['triaged']+x['untriaged']==x['total'] and sum(x['assigned'])==x['triaged'],'Alert groups must reconcile'
  return dict(triagedPercent=percent(x['triaged'],x['total']),untriagedPercent=percent(x['untriaged'],x['total']),teamSharesPercent=[percent(n,x['triaged']) for n in x['assigned']])
 if id=='balance-wellbeing--software-engineering':
  base=x['requirements']*x['baseEffort'];added=x['newRequests']*x['newEffort'];changed=base+added
  return dict(baseUnits=base,slackUnits=x['capacity']-base,addedUnits=added,changedUnits=changed,gapUnits=changed-x['capacity'],baseUtilisationPercent=percent(base,x['capacity']),changedUtilisationPercent=percent(changed,x['capacity']))
 if id=='balance-wellbeing--data-engineering':
  assert x['events']-x['repeats']==x['identities'] and x['reviewed']+x['unresolved']==x['identities'] and x['defects']+x['legitimate']==x['reviewed'],'Flag groups must reconcile'
  return dict(eventsPerIdentity=None if not x['identities'] else D(str(x['events']))/D(str(x['identities'])),reviewCoveragePercent=percent(x['reviewed'],x['identities']),reviewedDefectPercent=percent(x['defects'],x['reviewed']),allIdentityDefectPercent=percent(x['defects'],x['identities']))
 if id=='balance-wellbeing--visualisation':
  assert x['responded']+x['unknown']==x['invited'] and x['positive']<=x['responded'],'Response groups must reconcile'
  return dict(responsePercent=percent(x['responded'],x['invited']),respondentPositivePercent=percent(x['positive'],x['responded']),lowerLogicalPercent=percent(x['positive'],x['invited']),upperLogicalPercent=percent(x['positive']+x['unknown'],x['invited']))
 if id=='balance-wellbeing--nlp':return dict(precisionPercent=percent(x['tp'],x['tp']+x['fp']),recallPercent=percent(x['tp'],x['tp']+x['fn']),accuracyPercent=percent(x['tp']+x['tn'],sum(x.values())),falsePositives=x['fp'],falseNegatives=x['fn'])
 if id=='balance-wellbeing--hci':
  assert x['completed']<=x['discovered']<=x['total'],'Task groups must be nested'
  return dict(discoveryPercent=percent(x['discovered'],x['total']),completionPercent=percent(x['completed'],x['total']),discovererCompletionPercent=percent(x['completed'],x['discovered']))
 if id=='balance-wellbeing--devops':return dict(**groups(x['total'],x['technical'],x['support'],x['both']),jointPercent=percent(x['both'],x['total']),technicalPercent=percent(x['technical'],x['total']),supportPercent=percent(x['support'],x['total']))
 if id=='learning-retention--operating-systems':return dict(availabilityPercent=percent(x['available'],x['files']),delayedCorrectPercent=percent(x['correct'],x['questions']),correctedAvailabilityPercent=percent(x['correctedAvailable'],x['files']))
 if id=='learning-retention--databases':return dict(attemptCorrectPercent=percent(x['correctAttempts'],x['attempts']),firstLearnerPercent=percent(x['firstCorrect'],x['learners']),secondLearnerPercent=percent(x['secondCorrect'],x['learners']),anyCorrectLearnerPercent=percent(x['anyCorrect'],x['learners']))
 if id=='learning-retention--programming':
  first=percent(x['correct'],x['questions']);later=percent(x['laterCorrect'],x['questions'])
  return dict(suppliedTestPercent=percent(x['passed'],x['tests']),explanationPercent=first,laterExplanationPercent=later,pointIncrease=None if first is None or later is None else later-first)
 if id=='learning-retention--networks':return dict(confirmedIntentionPercent=percent(x['confirmed'],x['intentions']),transmissionsPerIntention=None if not x['intentions'] else D(str(x['transmissions']))/D(str(x['intentions'])),extraTransmissions=x['transmissions']-x['intentions'],delayedCorrectPercent=percent(x['delayedCorrect'],x['delayedQuestions']))
 if id=='learning-retention--cloud':return dict(activationPercent=percent(x['activated'],x['enrolled']),submissionPercent=percent(x['submitted'],x['enrolled']),allLearnerCorrectPercent=percent(x['correct'],x['enrolled']),submittedCorrectPercent=percent(x['correct'],x['submitted']))
 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 groups(20,16,15,13)==dict(both=13,firstOnly=3,secondOnly=2,neither=2)
 try:groups(20,16,15,10)
 except ValueError:pass
 else:raise AssertionError('Impossible overlap accepted')
 assert calculate('balance-wellbeing--nlp',dict(tp=0,fp=0,fn=2,tn=3))['precisionPercent'] is None
 assert len(fixture_results())==16
 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))
