"""Bounded top-level merge-patch and conditional-update model; no HTTP server."""
import copy,json
BASE={'phone':'020-example','note':'initial'}
def patch(current,p):
 result=copy.deepcopy(current)
 for key,value in p.items():
  if value is None:result.pop(key,None)
  else:result[key]=copy.deepcopy(value)
 return result
cases=[{'patch':p,'result':patch(BASE,p)} for p in [{},{'phone':''},{'phone':None}]]
assert cases[0]['result']==BASE and cases[1]['result']['phone']=='' and 'phone' not in cases[2]['result']
current={'version':8,'data':{'phone':'new-number','note':'initial'}}
def conditional_write(state,expected,p):
 if state['version']!=expected:return {'status':412,'state':copy.deepcopy(state)}
 state['data']=patch(state['data'],p);state['version']+=1
 return {'status':200,'state':copy.deepcopy(state)}
stale=conditional_write(current,7,{'note':'call afternoon'})
assert stale['status']==412 and current['version']==8
safe_rebase=all(BASE[k]==current['data'].get(k) for k in ['note'])
assert safe_rebase
rebased=conditional_write(current,8,{'note':'call afternoon'})
assert rebased['status']==200 and current['data']['phone']=='new-number'
conflict_current={'phone':'new-number','note':'do not call'}
conflict=BASE['note']!=conflict_current['note'];assert conflict
report={'topLevelSemantics':cases,'staleWrite':stale,'rebasePrecondition':'Only touched note field unchanged from saved base','rebasedWrite':rebased,'sameFieldConflict':{'current':conflict_current,'proposedNote':'call afternoon','mustResolve':conflict},'scope':'Top-level-only illustrative model; not complete recursive RFC7396 or HTTP conformance'}
if __name__=='__main__':print(json.dumps(report,indent=2))
