#!/usr/bin/env python3
"""Reproduce DN's synthetic case. Reads local files and pinned public UCP schemas only; makes no transactions."""
import argparse,copy,hashlib,importlib.metadata,json,sys,urllib.request
from datetime import datetime,timezone
from pathlib import Path
from jsonschema import Draft202012Validator,FormatChecker
from referencing import Registry,Resource
ROOT=Path(__file__).resolve().parent
SCHEMA='https://ucp.dev/2026-08-25/schemas/shopping/order.json'
PREFIX='https://ucp.dev/2026-08-25/schemas/'
def canonical(v):return json.dumps(v,sort_keys=True,separators=(',',':'))
def integer(v):
 if type(v) is not int:raise ValueError('Amounts and quantities must be integer minor units/whole items')
 return v
def unique(rows,key,ignore=('received_at',)):
 found={}
 for row in rows:
  id=row[key];body={k:v for k,v in row.items() if k not in ignore}
  if id in found and canonical(found[id])!=canonical(body):raise ValueError('Conflicting repeated identifier')
  found[id]=body
 return list(found.values())
def amount(totals,kind='total'):
 rows=[x for x in totals if x['type']==kind]
 if len(rows)!=1:raise ValueError('Expected one selected total')
 return integer(rows[0]['amount'])
def reconcile(f):
 receipts=unique(f['order_receipts'],'receipt_id');o=f['authoritative_get']['order'];currency=o['currency']
 if currency!='ZAR':raise ValueError('Fixed fixture uses ZAR')
 line_ids=[x['id'] for x in o['line_items']]
 if len(set(line_ids))!=len(line_ids):raise ValueError('Duplicate authoritative line identifier')
 lines={x['id']:x for x in o['line_items']}
 if set(lines)!={'A','B','C'}:raise ValueError('Fixed fixture requires A/B/C lines')
 for r in receipts:
  if r['order']['id']!=o['id'] or r['order']['checkout_id']!=o['checkout_id'] or r['order']['currency']!=currency:raise ValueError('Snapshot identity/currency mismatch')
 original=sum(integer(x['quantity']['original'])*integer(x['item']['price']) for x in lines.values())+1000
 if original!=10998 or amount(o['totals'])!=original:raise ValueError('Original fixed-order obligation mismatch')
 for x in lines.values():
  q=x['quantity'];[integer(q[k]) for k in ['original','total','fulfilled']]
  if q['total']!=q['original'] or not 0<=q['fulfilled']<=q['total']:raise ValueError('Unsupported quantity change')
 events=unique(o['fulfillment']['events'],'id',ignore=());packages={}
 for e in events:
  if e['type'] not in ['shipped','delivered']:raise ValueError('Unsupported fixture event')
  package=(e['carrier'],e['tracking_number']);parts={}
  for li in e['line_items']:
   if li['id'] not in lines or li['id'] in parts:raise ValueError('Unknown or repeated fulfillment line')
   parts[li['id']]=integer(li['quantity'])
   if parts[li['id']]<=0:raise ValueError('Nonpositive fulfillment quantity')
  if package in packages and packages[package]['parts']!=parts:raise ValueError('Package contents changed')
  p=packages.setdefault(package,{'parts':parts,'stages':set()});p['stages'].add(e['type'])
 delivered={k:0 for k in lines}
 for p in packages.values():
  if 'delivered' in p['stages']:
   for k,q in p['parts'].items():delivered[k]+=q
 for k,q in delivered.items():
  if q>lines[k]['quantity']['total']:raise ValueError('Overfulfilled quantity')
  if q!=lines[k]['quantity']['fulfilled']:raise ValueError('Fulfillment events disagree with line state')
 adjustments=unique(o.get('adjustments',[]),'id',ignore=());completed={}
 if len(adjustments)>1:raise ValueError('Fixed fixture supports one distinct concession only')
 for a in adjustments:
  if a['type']!='refund' or len(a.get('line_items',[]))!=1:raise ValueError('Unsupported adjustment')
  li=a['line_items'][0]
  if li['id']!='B' or integer(li['quantity'])!=0:raise ValueError('Fixed concession must retain B quantity')
  value=amount(a['totals'])
  if not -3500<=value<=0:raise ValueError('Refund exceeds referenced line')
  if a['status']=='completed':completed[a['id']]=-value
 refund=sum(completed.values());expected=original-refund
 payments=unique(f['payment_sidecar'],'id');capture=posted=0;holds={}
 for p in payments:
  if p['currency']!=currency:raise ValueError('Mixed-currency payment')
  a=integer(p['amount'])
  if a<0:raise ValueError('Negative sidecar magnitude')
  if p['kind']=='authorization_hold':holds[p['id']]=a
  elif p['kind']=='capture':capture+=a
  elif p['kind']=='refund':
   if p.get('adjustment_id') not in completed:raise ValueError('Unlinked posted refund')
   if a>completed[p['adjustment_id']]:raise ValueError('Posted refund exceeds linked concession')
   posted+=a
  elif p['kind']!='hold_release':raise ValueError('Unknown payment type')
 for p in payments:
  if p['kind']=='hold_release':
   h=p['authorization_id']
   if h not in holds:raise ValueError('Unknown authorization release')
   holds[h]-=p['amount']
   if holds[h]<0:raise ValueError('Excess authorization release')
 open_hold=sum(holds.values());net=capture-posted;gap=net-expected
 full_goods=all(delivered[k]==lines[k]['quantity']['total'] for k in lines)
 return {'currency':currency,'original_gross_cents':original,'completed_refund_cents':refund,'final_customer_obligation_cents':expected,'posted_capture_cents':capture,'posted_refund_cents':posted,'net_posted_debit_cents':net,'unreconciled_debit_cents':gap,'open_hold_cents':open_hold,'delivered_units':sum(delivered.values()),'delivered_by_line':delivered,'package_count':len(packages),'fulfillment_event_count':len(events),'unique_order_receipts':len(receipts),'order_retry_count':len(f['order_receipts'])-len(receipts),'payment_retry_count':len(f['payment_sidecar'])-len(payments),'balanced':full_goods and len(packages)==3 and capture==original and posted==refund and gap==0 and open_hold==0}
def schema_registry(record_pins=False):
 pins_path=ROOT/'schema_pins.json';existing=json.loads(pins_path.read_text()) if pins_path.exists() else {'schemas':[]};pins={x['url']:x for x in existing['schemas']};used={}
 def retrieve(uri):
  uri=uri.split('#')[0]
  if not uri.startswith(PREFIX):raise ValueError('Schema outside reviewed UCP version')
  if not record_pins and uri not in pins:raise ValueError('Schema URL absent from reviewed pins; stop before retrieval')
  rel=uri.removeprefix(PREFIX)
  if '..' in Path(rel).parts or Path(rel).is_absolute():raise ValueError('Invalid schema cache path')
  file=ROOT/'source'/rel
  if not file.exists():
   with urllib.request.urlopen(uri,timeout=20) as r:data=r.read()
   file.parent.mkdir(parents=True,exist_ok=True);file.write_bytes(data)
  else:data=file.read_bytes()
  digest=hashlib.sha256(data).hexdigest()
  if not record_pins and (uri not in pins or pins[uri]['sha256']!=digest):raise ValueError('Schema hash is absent or changed; stop and review source version')
  used[uri]={'url':uri,'sha256':digest,'bytes':len(data),'reviewed_at':'2026-11-26'}
  return Resource.from_contents(json.loads(data))
 return Registry(retrieve=retrieve),retrieve,used

def run(record_pins=False):
 f=json.loads((ROOT/'public_event_fixture.json').read_text());reg,retrieve,used=schema_registry(record_pins)
 schema=retrieve(SCHEMA).contents;validator=Draft202012Validator(schema,registry=reg,format_checker=FormatChecker())
 tests=[]
 def check(name,fn):fn();tests.append({'name':name,'passed':True})
 def expect_error(change):
  x=copy.deepcopy(f);change(x)
  try:reconcile(x)
  except (ValueError,KeyError):return
  raise AssertionError('Invalid case was accepted')
 def validate_all():
  bodies={canonical(x['order']):x['order'] for x in f['order_receipts']}
  for o in list(bodies.values())+[f['authoritative_get']['order']]:validator.validate(o)
  assert len(bodies)==9
 check('Nine distinct full snapshots and final GET validate against pinned official JSON Schemas',validate_all)
 r=reconcile(f)
 check('Integer-cent obligation equals 10998 minus1000 =9998',lambda:assertion(r['final_customer_obligation_cents']==9998 and r['net_posted_debit_cents']==9998 and r['balanced']))
 check('Three packages contain A2 B1 C1 despite six shipment-stage events',lambda:assertion(r['delivered_by_line']=={'A':2,'B':1,'C':1} and r['package_count']==3 and r['fulfillment_event_count']==6))
 check('Later retry receipts and duplicate capture have no repeated economic effect',lambda:assertion(r['order_retry_count']==1 and r['payment_retry_count']==1))
 def reversed_receipts():
  x=copy.deepcopy(f);x['order_receipts'].reverse();assert reconcile(x)==r
 check('Arrival order cannot overwrite explicit authoritative GET',reversed_receipts)
 check('Conflicting receipt identifier fails',lambda:expect_error(lambda x:x['order_receipts'][-2]['order'].update(currency='USD')))
 check('Unknown fulfillment line fails',lambda:expect_error(lambda x:x['authoritative_get']['order']['fulfillment']['events'][0]['line_items'][0].update(id='UNKNOWN')))
 check('Duplicate authoritative line identifier fails before dictionary construction',lambda:expect_error(lambda x:x['authoritative_get']['order']['line_items'].append(copy.deepcopy(x['authoritative_get']['order']['line_items'][0]))))
 def two_concessions(x,each,mislink=False):
  adjustments=x['authoritative_get']['order']['adjustments'];first=adjustments[0];first['totals'][0]['amount']=-each
  second=copy.deepcopy(first);second['id']=first['id']+'-second';adjustments.append(second)
  payments=x['payment_sidecar'];p=next(p for p in payments if p['kind']=='refund');p['amount']=each
  extra=copy.deepcopy(p);extra['id']=p['id']+'-second';extra['adjustment_id']=first['id'] if mislink else second['id'];payments.append(extra)
 check('Two R20 concessions on R35 line are rejected by the single-concession scope',lambda:expect_error(lambda x:two_concessions(x,2000)))
 check('Two concession IDs with both payment refunds linked to the first are rejected',lambda:expect_error(lambda x:two_concessions(x,1000,mislink=True)))
 def overfill(x):
  for e in x['authoritative_get']['order']['fulfillment']['events']:
   if e['tracking_number']=='P1':e['line_items'][0]['quantity']=3
 check('Overfulfilled quantities fail',lambda:expect_error(overfill))
 check('Mixed payment currency fails',lambda:expect_error(lambda x:x['payment_sidecar'][0].update(currency='USD')))
 check('Refund above line amount fails',lambda:expect_error(lambda x:x['authoritative_get']['order']['adjustments'][0]['totals'][0].update(amount=-3501)))
 check('Fractional-cent payment fails',lambda:expect_error(lambda x:x['payment_sidecar'][3].update(amount=1000.1)))
 check('Unlinked posted refund fails',lambda:expect_error(lambda x:x['payment_sidecar'][3].update(adjustment_id='UNKNOWN')))
 def pending():
  x=copy.deepcopy(f);x['payment_sidecar']=[p for p in x['payment_sidecar'] if p['kind']!='refund'];z=reconcile(x);assert z['unreconciled_debit_cents']==1000 and not z['balanced']
 check('Completed merchant concession without posted refund stays unresolved by1000c',pending)
 def hold():
  x=copy.deepcopy(f);x['payment_sidecar']=[p for p in x['payment_sidecar'] if p['kind']!='hold_release'];z=reconcile(x);assert z['net_posted_debit_cents']==9998 and z['open_hold_cents']==10998 and not z['balanced']
 check('Authorization hold remains distinct from posted debit',hold)
 def offset():
  x=copy.deepcopy(f);x['payment_sidecar']=[p for p in x['payment_sidecar'] if p['kind']!='refund'];
  for p in x['payment_sidecar']:
   if p['kind']=='capture':p['amount']=9998
  z=reconcile(x);assert z['unreconciled_debit_cents']==0 and not z['balanced']
 check('Offsetting undercapture and missing refund cannot create false closure',offset)
 if record_pins:(ROOT/'schema_pins.json').write_text(json.dumps({'schema_version':'2026-08-25','reviewed_at':'2026-11-26','verification':'Exact downloaded bytes pinned; version URL alone is not treated as immutable.','schemas':sorted(used.values(),key=lambda x:x['url'])},indent=2)+'\n')
 versions={'python':sys.version.split()[0],'jsonschema':importlib.metadata.version('jsonschema'),'referencing':importlib.metadata.version('referencing')}
 report={'suite':'DN200-091 synthetic fixture v1.0.0','executed_at':datetime.now(timezone.utc).isoformat(),'passed':len(tests),'failed':0,'schema_document_count':len(used),'schema_hash_verification':not record_pins,'tests':tests,'default_outputs':r,'runtime_versions':versions}
 (ROOT/'fixture_test_results.json').write_text(json.dumps(report,indent=2)+'\n');(ROOT/'runtime_versions.json').write_text(json.dumps(versions,indent=2)+'\n');print(json.dumps(report,indent=2))
def assertion(value):assert value
if __name__=='__main__':
 parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--record-schema-pins',action='store_true',help='Maintainer-only initial acquisition: deliberately accepts reviewed current bytes and writes pins. Do not use to bypass a hash mismatch.');args=parser.parse_args();run(args.record_schema_pins)
