#!/usr/bin/env python3
"""Run: python3 m27-lab.py rollout|schema|drain|migration. Keep m27-core.py beside it."""
import concurrent.futures
import http.client
import importlib.util
import json
from pathlib import Path
import tempfile
import threading

spec=importlib.util.spec_from_file_location('m27core',Path(__file__).with_name('m27-core.py'))
c=importlib.util.module_from_spec(spec);spec.loader.exec_module(c)


def edit(op,base,status):return {'operation':op,'base':base,'status':status}


def refused(call):
    try:call()
    except c.Refusal as exc:return f'{exc.status} {exc.reason}'
    raise AssertionError('expected refusal')


class Calls:
    def __init__(self):self.results=[];self.lock=threading.Lock()
    def __call__(self,*args,**kwargs):
        try:
            result=c.request(*args,**kwargs)
            with self.lock:self.results.append(str(result[0]))
            return result
        except http.client.RemoteDisconnected:
            with self.lock:self.results.append('lost_reply')
            raise
    def totals(self):return {key:self.results.count(key) for key in sorted(set(self.results))}


def pause_read(adapter,port,call):
    adapter.hold_enter=threading.Event();adapter.hold_release=threading.Event()
    pool=concurrent.futures.ThreadPoolExecutor(1)
    future=pool.submit(call,port,'GET','/orders/o1')
    c.require(adapter.hold_enter.wait(5),503,'read_did_not_enter')
    return pool,future


def release_read(adapter,pool,future):
    adapter.hold_release.set();result=future.result(5);pool.shutdown()
    adapter.hold_enter=None;adapter.hold_release=None
    return result


def rollout(path):
    store=c.Store(path);old=c.Adapter(store,'old');new=c.Adapter(store,'new');call=Calls()
    with c.serve(old) as a,c.serve(new) as b:
        initial=[call(a,'GET','/orders/o1'),call(b,'GET','/orders/o1')]
        print('compatible reads:',','.join(f'{r[0]} {r[1]["state"]}' for r in initial))
        write=call(b,'POST','/orders/o1',edit('upgrade',1,1));retry=call(a,'POST','/orders/o1',edit('upgrade',1,1))
        c.require(write[1]==retry[1],500,'receipt_changed')
        print(f'new accepted={write[0]}; old identical retry={retry[0]}; same receipt=true')
        new.fault_reads=True
        print('faulty version readiness:',call(b,'GET','/ready')[0])
        print('chosen canary order read:',call(b,'GET','/orders/o1')[0])
        restored=call(a,'GET','/orders/o1')
        print(f'routing rollback: {restored[0]} {restored[1]["state"]} version={restored[1]["version"]}')
        pool,future=pause_read(old,a,call)
        with old.lock:old.ready=False
        rejected=call(a,'GET','/orders/o1')
        print(f'drain admission: {rejected[0]}; old in-flight={old.inflight}')
        done=release_read(old,pool,future)
        print(f'already admitted request: {done[0]}; old in-flight={old.inflight}')
    print('HTTP outcomes:',c.encoded(call.totals()))
    print('retained source:',c.encoded(store.counts()))


def schema(path):
    store=c.Store(path);old=c.Adapter(store,'old');new=c.Adapter(store,'new');call=Calls()
    with c.serve(old) as a,c.serve(new) as b:
        boundary,rows=store.expand();print(f'expanded snapshot: boundary={boundary} rows={rows}')
        waiting=threading.Event();resume=threading.Event()
        def delayed():
            waiting.set();c.require(resume.wait(5),503,'backfill_resume_timeout');return store.backfill()
        with concurrent.futures.ThreadPoolExecutor(1) as pool:
            task=pool.submit(delayed);c.require(waiting.wait(5),503,'backfill_did_not_pause')
            result=call(b,'POST','/orders/o1',edit('during-copy',1,1))
            print(f'new write while old snapshot waits: {result[0]} version={result[1]["version"]}')
            print('tail applied before old copy:',store.catchup())
            resume.set();print('first backfill outcomes:',c.encoded(task.result(5)))
        with c.connection(path,True) as db:
            repeat=[store.apply(db,json.loads(r[0])) for r in db.execute("SELECT body FROM snapshot_rows WHERE id IN('o1','o2') ORDER BY id").fetchall()]
        print('same captured batch again:',c.encoded(repeat))
        print('last batch interruption:',refused(lambda:store.backfill(fault=True)))
        store=c.Store(path)
        with c.connection(path) as db:
            print('reopened target rows/cursor:',db.execute('SELECT count(*) FROM orders_target').fetchone()[0],db.execute('SELECT cursor FROM migration').fetchone()[0])
        print('resumed final batch:',c.encoded(store.backfill()))
        print('validation:',c.encoded(store.validate()))
        with c.connection(path,True) as db:
            bad=json.loads(db.execute("SELECT body FROM orders_target WHERE id='o2'").fetchone()[0]);bad['state']='shipped'
            db.execute("UPDATE orders_target SET body=? WHERE id='o2'",(c.encoded(bad),))
        print('equal row counts but wrong value:',refused(store.validate))
        print('current-source rebuild rows:',store.rebuild())
        print('contraction before retirement:',refused(lambda:store.contract(old)))
        with old.lock:old.ready=False
        store.retire_old();store.contract(old)
        print('retired old reader/writer; legacy view removed')
        print('old direct write:',refused(lambda:store.update('Ada','o1',edit('retired',2,2),old=True)))
        print('new writer after contraction:',call(b,'POST','/orders/o1',edit('after-contract',2,2))[0])
        store.catchup();print('final validation:',c.encoded(store.validate()))


def drain(path):
    store=c.Store(path);store.expand();store.backfill(3);store.catchup()
    router=c.ReadRouter(store);writer=c.Adapter(store,'new');call=Calls()
    with c.serve(router) as reads,c.serve(writer) as writes:
        print('old served; shadow check:',call(reads,'GET','/orders/o1')[0],router.comparisons[-1])
        with c.connection(path,True) as db:db.execute("DELETE FROM orders_target WHERE id='o1'")
        call(reads,'GET','/orders/o1');print('missing shadow:',router.comparisons[-1]);store.rebuild()
        with c.connection(path,True) as db:
            bad=json.loads(db.execute("SELECT body FROM orders_target WHERE id='o1'").fetchone()[0]);bad['state']='shipped'
            db.execute("UPDATE orders_target SET body=? WHERE id='o1'",(c.encoded(bad),))
        call(reads,'GET','/orders/o1');print('wrong-value shadow:',router.comparisons[-1]);store.rebuild()
        router.switch(['Ada']);print('Ada cohort new read:',call(reads,'GET','/orders/o1')[0])
        call(writes,'POST','/orders/o1',edit('lag',1,1))
        answer=call(reads,'GET','/orders/o1');print('stale target fallback:',answer[0],answer[1]['state'],router.comparisons[-1])
        store.catchup();print('caught-up new read:',call(reads,'GET','/orders/o1')[0])
        with c.connection(path,True) as db:db.execute("DELETE FROM orders_target WHERE id='o1'")
        print('missing new fallback:',call(reads,'GET','/orders/o1')[0])
        router.allow_fallback=False;print('fallback disabled:',call(reads,'GET','/orders/o1')[0]);store.rebuild()
        print('Bo remains old cohort:',call(reads,'GET','/orders/o2',actor='Bo')[0])
        print('Bo reads Ada object:',call(reads,'GET','/orders/o1',actor='Bo')[0])
        with c.connection(path,True) as db:db.execute("UPDATE accounts SET active=0 WHERE id='Ada'")
        print('current Ada revocation:',call(reads,'GET','/orders/o1')[0])
        with c.connection(path,True) as db:db.execute("UPDATE accounts SET active=1 WHERE id='Ada'")
        print('write on read-only listener:',call(reads,'POST','/orders/o1',edit('wrong-route',2,2))[0])
        router.rollback();print('rollback cohort:',sorted(router.cohort))
    print('route work:',c.encoded(router.counts))
    print('shadow log fields: classification only; no response bodies')
    print('HTTP outcomes:',c.encoded(call.totals()))


def migration(path):
    store=c.Store(path);old=c.Adapter(store,'old');new=c.Adapter(store,'new');router=c.ReadRouter(store);call=Calls()
    with c.serve(old) as a,c.serve(new) as b,c.serve(router) as r:
        print('snapshot boundary/rows:',store.expand())
        pause=threading.Event();resume=threading.Event()
        def backfill_wait():pause.set();c.require(resume.wait(5),503,'backfill_resume_timeout');return store.backfill(3)
        with concurrent.futures.ThreadPoolExecutor(3) as pool:
            worker=pool.submit(backfill_wait);c.require(pause.wait(5),503,'backfill_did_not_pause')
            print('old read during paused backfill:',call(r,'GET','/orders/o1')[0])
            barrier=threading.Barrier(2)
            def write(port,key,actor,op,status):barrier.wait();return call(port,'POST','/orders/'+key,edit(op,1,status),actor=actor)
            one=pool.submit(write,a,'o1','Ada','write-a',1);two=pool.submit(write,b,'o2','Bo','write-b',2)
            print('concurrent old/new writes:',sorted([one.result()[0],two.result()[0]]))
            print('tail interruption:',refused(lambda:store.catchup(fault=True)))
            with c.connection(path) as db:print('reopened tail boundary/target rows:',db.execute('SELECT through FROM migration').fetchone()[0],db.execute('SELECT count(*) FROM orders_target').fetchone()[0])
            resume.set();print('backfill outcomes:',c.encoded(worker.result(5)))
        store=c.Store(path);router.store=store;old.store=store;new.store=store
        print('reopened tail applied:',store.catchup());print('duplicate tail applied:',store.catchup())
        print('validated source/target:',c.encoded(store.validate()))
        with c.connection(path,True) as db:
            bad=json.loads(db.execute("SELECT body FROM orders_target WHERE id='o2'").fetchone()[0]);bad['state']='draft'
            db.execute("UPDATE orders_target SET body=? WHERE id='o2'",(c.encoded(bad),))
        print('switch with equal counts and wrong value:',refused(lambda:router.switch(['Ada','Bo'])))
        store.rebuild();router.switch(['Ada','Bo']);print('read cohort after repair:',','.join(sorted(router.cohort)))
        barrier=threading.Barrier(3)
        with concurrent.futures.ThreadPoolExecutor(3) as pool:
            def op(method,key,body=None,actor='Ada'):
                barrier.wait();return call(b if method=='POST' else r,method,'/orders/'+key,body,actor=actor)
            first=pool.submit(op,'GET','o1');second=pool.submit(op,'GET','o2',None,'Bo');write=pool.submit(op,'POST','o3',edit('after-switch',1,0))
            print('concurrent switched reads:',sorted([first.result()[0],second.result()[0]]),'; write:',write.result()[0])
        new.lose_reply=True
        try:call(b,'POST','/orders/o1',edit('lost',2,2))
        except http.client.RemoteDisconnected:print('new write reply lost after commit')
        retry=call(a,'POST','/orders/o1',edit('lost',2,2));print('old adapter retry:',retry[0],c.encoded(retry[1]))
        store.catchup();router.rollback();rolled=call(r,'GET','/orders/o1')
        print('read rollback preserves new writes:',rolled[0],rolled[1]['state'],rolled[1]['version'])
        router.switch(['Ada','Bo']);pool,future=pause_read(old,a,call)
        with old.lock:old.ready=False
        store.retire_old();print('contract while admitted request waits:',refused(lambda:store.contract(old)))
        print('drained old request:',release_read(old,pool,future)[0])
        store.contract(old);print('legacy view removed; source remains write authority')
        print('old read rollback after contraction:',refused(router.rollback))
        print('new write after contraction:',call(b,'POST','/orders/o1',edit('final',3,1))[0])
        print('lag after old fallback removed:',call(r,'GET','/orders/o1')[0])
        print('tail recovery changes:',store.catchup());print('recovered new read:',call(r,'GET','/orders/o1')[0])
        print('final exact reconciliation:',c.encoded(store.validate()))
        print('retained source:',c.encoded(store.counts()))
        store.available=False;print('unavailable authority:',call(r,'GET','/orders/o1')[0]);store.available=True
        before=store.counts();print('malformed requests:',c.encoded(c.framing_probes(b)));c.require(store.counts()==before,500,'malformed_request_changed_state')
    print('application HTTP outcomes:',c.encoded(call.totals()))


if __name__=='__main__':
    import argparse
    parser=argparse.ArgumentParser();parser.add_argument('mode',choices=('rollout','schema','drain','migration'));args=parser.parse_args()
    with tempfile.TemporaryDirectory(prefix='fanout-m27-') as folder:globals()[args.mode](Path(folder)/'source.sqlite')
