"""Local locked compare-and-write fixture, not HTTP endpoint or authentication."""
import threading,copy,re,json
class Resource:
    def __init__(self):self.body={'owner':'unassigned','note':'initial'};self.version=1;self.lock=threading.Lock()
    def read(self):
        with self.lock:return {'body':copy.deepcopy(self.body),'etag':'"v'+str(self.version)+'"'}
    def unsafe_write(self,body):
        with self.lock:self.body=copy.deepcopy(body);self.version+=1
    def write(self,expected,body):
        if not isinstance(expected,str)or not re.fullmatch(r'"v[1-9][0-9]*"',expected):raise ValueError('single authored strong v-tag only; weak/*/lists outside subset')
        with self.lock:
            # Compare and assignment are one critical section; not check then later write.
            if expected!='"v'+str(self.version)+'"':return {'status':412,'applied':False}
            self.body=copy.deepcopy(body);self.version+=1;return {'status':200,'applied':True,'etag':'"v'+str(self.version)+'"'}
def demo():
    unsafe=Resource();a=unsafe.read();b=unsafe.read();new_a={**a['body'],'owner':'agent-A'};new_b={**b['body'],'note':'agent-B edit'}
    unsafe.unsafe_write(new_a);unsafe.unsafe_write(new_b);lost=unsafe.read();assert lost['body']['owner']=='unassigned'
    guarded=Resource();a=guarded.read();b=guarded.read();first=guarded.write(a['etag'],{**a['body'],'owner':'agent-A'});before=guarded.read();second=guarded.write(b['etag'],{**b['body'],'note':'agent-B edit'});after=guarded.read();assert first['status']==200 and second['status']==412 and before==after and after['body']['owner']=='agent-A'
    # B explicitly refetches and chooses to keep A's owner while changing only note.
    refreshed=guarded.read();decision_body={**refreshed['body'],'note':'agent-B edit'};third=guarded.write(refreshed['etag'],decision_body);assert third['status']==200 and guarded.read()['body']=={'owner':'agent-A','note':'agent-B edit'}
    try:guarded.write('W/"v3"',decision_body)
    except ValueError:weak_rejected=True
    else:raise AssertionError('weak accepted')
    return {'authored_initial_two_editor_snapshots':[a,b],'without_precondition_lost_update':lost,'guarded_first_write':first,'stale_second_write':second,'state_before_rejection':before,'state_after_rejection':after,'explicit_refetch_then_deliberate_merge':{'snapshot':refreshed,'chosen_body':decision_body,'result':third,'final':guarded.read()},'weak_tag_rejected_by_local_subset':weak_rejected,'scope':'Single existing resource, unconditional unsafe illustration and single-strong-tag guarded endpoint policy, thread lock in one Python process. Sequential editor scenario, no actual concurrent network/HTTP/auth/DB transaction. Example rejects stale with412 and does not implement HTTP already-applied-success exception, wildcard/tag lists or general ETag grammar. Authorization/idempotency remain independent.'}
if __name__=='__main__':print(json.dumps(demo(),indent=2))
