"""Pure authored single identity-coded representation model. No HTTP request."""
import hashlib,json,platform
def strong_tag(payload):return '"'+hashlib.sha256(payload).hexdigest()+'"'
def serve(payload,tag,start,if_range,range_supported=True):
 if if_range.startswith('W/'):raise ValueError('client must not send weak If-Range')
 if not range_supported or tag!=if_range:return {'status':200,'tag':tag,'body':payload,'range':None}
 if not 0<=start<len(payload):raise ValueError('start outside subset')
 return {'status':206,'tag':tag,'body':payload[start:],'range':(start,len(payload)-1,len(payload))}
def finish(prefix,stored_tag,response,expected_total,expected_prefix_sha):
 if response['status']==200:return response['body']
 if response['status']!=206 or response['tag']!=stored_tag:raise ValueError('status/tag')
 start,end,total=response['range'];body=response['body']
 if hashlib.sha256(prefix).hexdigest()!=expected_prefix_sha:raise ValueError('stored prefix changed')
 if start!=len(prefix) or total!=expected_total or end!=total-1 or len(body)!=end-start+1:raise ValueError('range boundaries')
 return prefix+body
def demo():
 old=b'OLD-0123456789-END';new=b'NEW-abcdefghij-END';prefix=old[:7];tag=strong_tag(old);ph=hashlib.sha256(prefix).hexdigest()
 matched=serve(old,tag,len(prefix),tag);assert finish(prefix,tag,matched,len(old),ph)==old
 changed=serve(new,strong_tag(new),len(prefix),tag);assert changed['status']==200 and finish(prefix,tag,changed,len(old),ph)==new
 wrong=prefix+changed['body'];assert wrong!=old and wrong!=new
 ignored=serve(old,tag,len(prefix),tag,False);assert ignored['status']==200 and finish(prefix,tag,ignored,len(old),ph)==old
 rejected=[]
 for name,p,resp,total,h in [('wrong-start',prefix,{**matched,'range':(6,16,17)},len(old),ph),('short-body',prefix,{**matched,'body':matched['body'][:-1]},len(old),ph),('wrong-total',prefix,matched,len(old)+1,ph),('changed-prefix',b'XXX'+prefix[3:],matched,len(old),ph),('wrong-tag',prefix,{**matched,'tag':'"other"'},len(old),ph)]:
  try:finish(p,tag,resp,total,h)
  except ValueError:rejected.append(name)
  else:raise AssertionError(name)
 try:serve(old,tag,7,'W/"weak"')
 except ValueError:rejected.append('weak-client-validator')
 else:raise AssertionError('weak')
 def out(r):return {**r,'body':r['body'].decode('ascii')}
 return {'runtime':platform.python_version(),'old':old.decode(),'new':new.decode(),'stored_prefix':prefix.decode(),'match_response':out(matched),'changed_response':out(changed),'range_ignored_response':out(ignored),'wrong_append_mixed_result':wrong.decode(),'rejected_cases':rejected,'dates_multipart_compressed_and_network_executed':False,'all_assertions_passed':True}
if __name__=='__main__':print(json.dumps(demo(),indent=2))
