"""Serial fictional allocation control; no UBL, tax or provider validation."""
from pathlib import Path
from datetime import datetime, timezone
from hashlib import sha256
import json
import platform
from copy import deepcopy

HERE=Path(__file__).resolve().parent
def token(value):
 if not isinstance(value,str) or not value or value.strip()!=value:
  raise ValueError('Expected nonempty exact string without edge whitespace')
 return value
def positive(value):
 if type(value) is not int or value<=0:
  raise ValueError('Expected positive integer minor units')
 return value
def validate(row):
 if set(row)!={'identity','amount_minor','reference','currency','kind'}:
  raise ValueError('Unexpected or missing fields')
 token(row['identity']);positive(row['amount_minor']);token(row['currency'])
 if row['kind'] not in ('ordinary','volume'):raise ValueError('Unsupported local category')
 if row['reference'] is not None:token(row['reference'])
def run(invoice,receipts):
 token(invoice['identity']);token(invoice['currency']);positive(invoice['gross_minor'])
 seen={};allocated=0;out=[]
 for row in receipts:
  validate(row)
  identity=row['identity'];fingerprint=json.dumps(row,sort_keys=True,separators=(',',':'))
  if identity in seen:
   state='duplicate_receipt' if seen[identity]==fingerprint else 'hold_conflict'
  else:
   seen[identity]=fingerprint
   if row['currency']!=invoice['currency']:state='hold_currency'
   elif row['kind']=='volume':state='period_review' if row['reference'] is None else 'hold_volume_reference'
   elif row['reference'] is None:state='hold_missing_reference'
   elif row['reference']!=invoice['identity']:state='hold_unknown_reference'
   elif allocated+row['amount_minor']>invoice['gross_minor']:state='hold_capacity'
   else:state='allocated';allocated+=row['amount_minor']
  out.append(dict(identity=identity,state=state,allocated_minor=allocated,remaining_minor=invoice['gross_minor']-allocated))
 return dict(receipts=out,allocated_minor=allocated,remaining_minor=invoice['gross_minor']-allocated)
def main():
 data=json.loads((HERE/'fixture.json').read_text());results=[]
 for scenario in data['scenarios']:
  receipts=data['receipts']+[data['receipts'][i] for i in scenario['append_replays']]
  result=run(data['invoice'],receipts)
  assert [r['state'] for r in result['receipts']]==scenario['expected_states']
  assert result['allocated_minor']==scenario['expected_allocated_minor']
  assert result['remaining_minor']==scenario['expected_remaining_minor']
  results.append(dict(name=scenario['name'],**result))
 checks=[];invoice=data['invoice'];first=data['receipts'][0]
 def reject(name,edit):
  row=deepcopy(first);edit(row)
  try:run(invoice,[row])
  except ValueError:checks.append(name)
  else:raise AssertionError(name)
 for name,value in [('numeric_string','30000'),('float',30000.0),('boolean',True),('zero',0),('negative',-1)]:
  reject(name,lambda r,v=value:r.update(amount_minor=v))
 reject('blank_identity',lambda r:r.update(identity=''))
 reject('identity_whitespace',lambda r:r.update(identity=' DEMO-A'))
 reject('numeric_reference',lambda r:r.update(reference=1))
 reject('empty_reference',lambda r:r.update(reference=''))
 reject('missing_field',lambda r:r.pop('currency'))
 reject('extra_field',lambda r:r.update(unexpected='x'))
 reject('unknown_kind',lambda r:r.update(kind='other'))
 changed=dict(first,amount_minor=30001)
 result=run(invoice,[first,changed]);assert result['receipts'][-1]['state']=='hold_conflict' and result['allocated_minor']==30000;checks.append('changed_content_does_not_add_allocation')
 result=run(invoice,[dict(first,amount_minor=100000)]);assert result['remaining_minor']==0;checks.append('exact_capacity')
 result=run(invoice,[dict(first,amount_minor=100001)]);assert result['receipts'][0]['state']=='hold_capacity' and result['allocated_minor']==0;checks.append('one_unit_excess')
 result=run(invoice,[dict(first,kind='volume')]);assert result['receipts'][0]['state']=='hold_volume_reference';checks.append('referenced_volume_is_unsupported')
 # Identical content remains a replay even if JSON key order differs.
 result=run(invoice,[first,dict(reversed(list(first.items())))]);assert result['allocated_minor']==30000 and result['receipts'][1]['state']=='duplicate_receipt';checks.append('canonical_key_order')
 print(json.dumps(dict(status='Executed offline on fictional inputs',author='Anant Mishra',executed_at_utc=datetime.now(timezone.utc).isoformat(),python_version=platform.python_version(),sha256={name:sha256((HERE/name).read_bytes()).hexdigest() for name in ['fixture.json','reproduce.py']},results=results,boundary_checks=checks),indent=2))
if __name__=='__main__':main()
