"""One actual fictional task connects all five topics; no live model selection."""
import argparse, copy, json, os, platform, sqlite3, sys, time
from pathlib import Path
ROOT=Path(__file__).resolve().parent
sys.path.insert(0,str(ROOT/'project'))
from common import LabError, MerchantClient, canonical, write_json
from agent import Agent
from store import Store
from runtime import Runtime, load_student
from workflow import Workflow
from fallback import ScriptedModel, route
from settlement_reference import decide_settlement
from support import service, fresh, launch, collect, expiry, payload, expect_code
from acceptance import sources, inspect, verify
TASK='journey-return'
SCENARIOS=['lost_response','fair_queue','replay_conflict','migration_rollback','stale_worker','fallback_blocked','evidence_missing','forged_receipt']

def event(status,seq): return {'event_id':TASK+'-'+status,'seq':seq,'status':status,'source':'executor'}
def save_report(work,result):
    result.update({'format':'harness-journey-run-v1','provider_calls':0,'model_source':'authored offline fixtures','python':platform.python_version(),'sqlite':sqlite3.sqlite_version,'pid':os.getpid(),'sources':sources(),'limitations':['single host; runtime and merchant share one SQLite authority','synthetic execution units, no tokens or money','fixture reviewer, no actual human approval','public authored diagnostics, not unseen learner assessment']})
    write_json(Path(work)/'report.json',result)
    return result

def prepare(work,url,w,scenario,notes):
    s=Store(work/'tasks'/(TASK+'.sqlite'))
    try:
        model=ScriptedModel(w,TASK); a=Agent(s,MerchantClient(url,'alice-token'),model)
        a.submit('o-100','Return my unused ordinary item; it does not fit.',TASK)
        if scenario=='evidence_missing':
            a.run(TASK,rounds=2)
            lease=s.claim(TASK)
            try:
                notes['missing_evidence']=expect_code(lambda:a.tool(TASK,{'name':'propose_return','call_id':'bad-policy','arguments':canonical({'order_id':'o-100','quantity':1,'reason':'does not fit','policy_ids':['d-general']})},lease),'missing_policy_evidence')
                assert s.get(TASK)['proposal'] is None
            finally:s.release(TASK,lease)
        task=a.run(TASK)
        assert task['status']=='awaiting_approval'
        task=Agent(s,MerchantClient(url,'reviewer-token')).approve(TASK,1,task['proposal_hash'])
        w.enqueue(TASK,task['tenant'],task['owner'],task['operation_key'])
        w.create(TASK,task['tenant'],{'state':'waiting','approval':'approved','approval_epoch':task['approval']['proposal_version'],'operation_key':task['operation_key'],'budget_used':0,'extensions':{'reason':'does not fit'}})
        w.apply(TASK,'acme',event('ready',1))
        return {'task_id':TASK,'operation_key':task['operation_key'],'proposal_hash':task['proposal_hash'],'approval':task['approval'],'status':task['status'],'fixture_reviewer':True}
    finally:s.close()

def fair_diagnostic(work):
    import merchant_runtime
    path=work/'fair-fixture.sqlite'; merchant_runtime.init(path,global_limit=1)
    w=Workflow(path)
    try:
        for tid,tenant,owner in [('a1','acme','alice'),('a2','acme','alice'),('b1','other','other'),('b2','other','other')]: w.enqueue(tid,tenant,owner,'return:'+tid+':v1')
        order=[]; rounds=[]
        def snapshot():
            return {'cursor':w.db.execute('SELECT cursor FROM journey_scheduler WHERE id=1').fetchone()[0],'runtime':Runtime.snapshot(w)}
        for i in range(4):
            before=snapshot()
            claim=w.acquire_next('fair-'+str(i)); order.append(claim['task_id'])
            held=snapshot()
            blocked=expect_code(lambda:w.acquire_next('blocked'),'no_admissible_task')
            w.settle(claim,'confirmed_absent')
            settled=snapshot()
            w.close(); w=Workflow(path)
            rounds.append({'round':i+1,'before':before,'claim':claim,'held':held,'blocked':blocked,'settled':settled,'reopened':snapshot()})
        assert order==['a1','b1','a2','b2']
        return {'actual_admission_order':order,'rounds':rounds,'cursor_survives_reopen':all(r['held']['cursor']==r['reopened']['cursor'] for r in rounds),'scope':'separate scheduler fixture; main task uses this same atomic acquire_next implementation'}
    finally:w.close()

def diagnostics_before(work,url,w,scenario,notes,claim):
    if scenario=='replay_conflict':
        before=w.snapshot(TASK); old=w.apply(TASK,'acme',event('ready',1)); assert w.snapshot(TASK)==before
        notes['replayed_ready_receipt']=old
        notes['conflict']=expect_code(lambda:w.apply(TASK,'acme',dict(event('ready',1),status='completed')),'event_conflict')
        notes['sequence_conflict']=expect_code(lambda:w.apply(TASK,'acme',dict(event('ready',1),event_id='different')),'sequence_conflict')
        notes['backward']=expect_code(lambda:w.apply(TASK,'acme',dict(event('ready',3),event_id='backward-new')),'status_transition')
    if scenario=='fallback_blocked':
        cases=[({'error':'permission_denied'},'fallback_forbidden'),({'error':'refusal'},'fallback_forbidden'),({'error':'400'},'fallback_forbidden'),({'caps':('json',)},'fallback_capability_missing'),({'used':True},'fallback_invalid_budget'),({'used':2},'fallback_budget_exhausted'),({'deadline':0},'fallback_deadline_exceeded')]
        notes['blocked_matrix']=[expect_code(lambda args=args:route(**args),code) for args,code in cases]
        assert route(unknown=True)=='reconcile_original_key'
    if scenario=='forged_receipt': notes['forgery']=expect_code(lambda:w.settle(claim,'confirmed_receipt',3,{'operation_key':w.task(TASK)['operation_key']}),'runtime_receipt_unconfirmed')
    notes['live_migration']=expect_code(lambda:w.migrate(TASK),'migration_live_worker')

def finish(work,url,w,notes,student=None):
    original=w.task(TASK); expiry(w,TASK)
    if notes.get('scenario')=='migration_rollback':
        before=w.snapshot(TASK); old_epoch=w.task(TASK)['epoch']
        w.db.execute("CREATE TRIGGER fail_migration BEFORE UPDATE OF workflow_schema ON journey_workflows BEGIN SELECT RAISE(ABORT,'authored_migration_abort'); END")
        try:
            try:w.migrate(TASK)
            except sqlite3.IntegrityError as exc:notes['migration_abort']=str(exc)
            else:raise AssertionError('migration must roll back')
            assert w.snapshot(TASK)==before and w.task(TASK)['epoch']==old_epoch
        finally:w.db.execute('DROP TRIGGER fail_migration')
        notes['migration_rollback_preserved']=before
    before=w.snapshot(TASK); migrated=w.migrate(TASK)
    for k in ['operation_key','approval_epoch','budget_used','extensions']: assert before[k]==migrated[k]
    assert w.task(TASK)['reservation_id']==original['reservation_id']
    assert w.migrate(TASK)==migrated
    notes['migration']={'before':before,'after':migrated,'reservation_preserved':original['reservation_id']}
    if notes.get('scenario')=='stale_worker':
        old=json.loads((work/'claim.json').read_text())
        notes['stale_http']=expect_code(lambda:MerchantClient(url,'alice-token').request('POST','/v1/returns',payload(work,TASK,old)),'runtime_stale_claim')
        notes['stale_settlement']=expect_code(lambda:w.settle(old,'unknown'),'runtime_stale_claim')
    child=launch(work,url,TASK,student=student,recover=True,lease=5)
    result=collect(child,expected=0); notes['recovery_worker']=result
    w.apply(TASK,'acme',event('completed',4))
    notes['final']=inspect(work)
    return notes

def run(work,scenario='lost_response',student=None,stop=False):
    work=fresh(work); notes={'scenario':scenario,'command':sys.argv,'started':time.time()}
    write_json(work/'run.json',{'sources':sources(),'task_ids':[TASK],'scenario':scenario})
    with service(work,global_limit=1) as url:
        w=Workflow(work/'shared.sqlite'); w.decision=load_student(student) if student else decide_settlement
        try:
            notes['prepared']=prepare(work,url,w,scenario,notes)
            if scenario=='fair_queue': notes['fair_queue']=fair_diagnostic(work)
            claim=w.acquire_next('initial-controller',seconds=1.5)
            write_json(work/'claim.json',claim)
            w.apply(TASK,'acme',event('executing',2))
            diagnostics_before(work,url,w,scenario,notes,claim)
            w.renew(claim,seconds=1.5)
            child=launch(work,url,TASK,command='execute',claim_file=work/'claim.json',fault='crash')
            notes['crash_worker']=collect(child,expected=75)
            w.observe_unknown(TASK)
            # Crash has no return path; supervisor invokes the exact learner hook for unknown.
            try: w.settle(claim,'unknown')
            except Exception as exc:
                notes['learner_error']={'type':type(exc).__name__,'message':str(exc),'boundary':'actual_unknown_settlement'}
                notes['before_restart']=inspect(work); return save_report(work,notes)
            notes['before_restart']=inspect(work)
            if w.task(TASK)['reservation_id']!=claim['reservation_id']:
                notes['learner_error']={'type':'IncorrectSettlement','message':'unknown_must_hold_original_reservation','boundary':'actual_unknown_settlement'}
                return save_report(work,notes)
            assert route(unknown=True)=='reconcile_original_key'
            notes['unknown_fallback']='reconcile_original_key; no model/write attempt'
            if stop: return save_report(work,notes)
            try: finish(work,url,w,notes,student)
            except Exception as exc:
                if not student: raise
                notes['learner_error']={'type':type(exc).__name__,'message':str(exc),'boundary':'actual_recovery_settlement'}
                return save_report(work,notes)
        finally:w.close()
    notes['verification']=verify(work)
    return save_report(work,notes)

def resume(work,student=None):
    work=Path(work).resolve(); meta=json.loads((work/'run.json').read_text())
    if meta['sources']!=sources():raise LabError('source_changed_rerun_fresh')
    notes=json.loads((work/'report.json').read_text()); notes.pop('learner_error',None)
    with service(work,global_limit=1) as url:
        w=Workflow(work/'shared.sqlite'); w.decision=load_student(student) if student else decide_settlement
        try:
            state=w.task(TASK)
            if state['state']=='completed':raise LabError('already_completed_use_verify')
            # Failed learner implementation may have left its original hold leased.
            if not state['reservation_id']: raise LabError('unsafe_released_unknown_requires_fresh_run')
            expiry(w,TASK)
            if not any(json.loads(r['value_json'])['decision']['action']=='hold' for r in w.db.execute("SELECT value_json FROM rt_events WHERE task_id=? AND event='settlement'",(TASK,))):
                claim=w.acquire(TASK,'repair-unknown',seconds=.15,recover=True)
                w.settle(claim,'unknown'); expiry(w,TASK)
            finish(work,url,w,notes,student)
        finally:w.close()
    notes['verification']=verify(work); return save_report(work,notes)

def grade(work,student):
    notes=run(work,student=student); checks=[]
    fn=load_student(student)
    valid=[(5,None,'unknown',{'action':'hold','charge_units':0,'release_units':0}),(5,None,'confirmed_absent',{'action':'release','charge_units':0,'release_units':5}),(5,3,'confirmed_receipt',{'action':'settle','charge_units':3,'release_units':2}),(2,3,'confirmed_receipt',{'action':'overrun','charge_units':3,'release_units':0})]
    for i,(r,a,e,expected) in enumerate(valid):
        p={'reserved_units':r,'actual_units':a,'evidence':e}; before=copy.deepcopy(p)
        try:actual=fn(p); ok=actual==expected and p==before and all(type(actual[k]) is int for k in ['charge_units','release_units'])
        except Exception as exc:actual={'error':type(exc).__name__};ok=False
        checks.append({'id':'contract-'+str(i),'passed':ok,'expected':expected,'actual':actual})
    invalid=[None,{}, {'reserved_units':True,'actual_units':None,'evidence':'unknown'},{'reserved_units':5,'actual_units':True,'evidence':'confirmed_receipt'},{'reserved_units':5,'actual_units':0,'evidence':'unknown'},{'reserved_units':5,'actual_units':None,'evidence':[]}]
    for i,p in enumerate(invalid):
        try:fn(p);ok=False
        except ValueError as exc:ok=str(exc)=='invalid_settlement_input'
        except Exception:ok=False
        checks.append({'id':'invalid-'+str(i),'passed':ok})
    verdict=verify(work); checks.append({'id':'independent_actual_hook_verifier','passed':verdict['passed'],'detail':verdict})
    notes['grade']={'passed':all(c['passed'] for c in checks),'checks':checks,'student_sha256':__import__('hashlib').sha256(Path(student).read_bytes()).hexdigest(),'actual_hook_invoked':True}
    return save_report(work,notes)

def main():
    p=argparse.ArgumentParser(); p.add_argument('command',choices=['demo','scenario','resume','inspect','verify','grade']);p.add_argument('--work',required=True);p.add_argument('--name',choices=SCENARIOS,default='lost_response');p.add_argument('--student');p.add_argument('--task-id');p.add_argument('--stop-after-unknown',action='store_true');a=p.parse_args()
    try:
        if a.command=='inspect':result=inspect(a.work,a.task_id);code=0
        elif a.command=='verify':result=verify(a.work);code=0 if result['passed'] else 1
        elif a.command=='resume':result=resume(a.work,a.student);code=0 if result['verification']['passed'] else 1
        elif a.command=='grade':result=grade(a.work,a.student or str(ROOT/'settlement_student.py'));code=0 if result['grade']['passed'] else 1
        else:
            if a.stop_after_unknown and a.name!='lost_response':raise LabError('checkpoint_only_lost_response')
            result=run(a.work,a.name,a.student,a.stop_after_unknown);code=1 if 'learner_error' in result or result.get('verification',{}).get('passed') is False else 0
        if a.command in {'inspect','verify'}: print(json.dumps(result,ensure_ascii=False,indent=2))
        else: print(canonical({'command':a.command,'work':str(Path(a.work).resolve()),'report':str(Path(a.work).resolve()/'report.json'),'exit':code,'passed':result.get('grade',result.get('verification',{})).get('passed'),'learner_error':result.get('learner_error')}))
        return code
    except Exception as exc:print(canonical({'error':getattr(exc,'code',type(exc).__name__),'message':str(exc)}),file=sys.stderr);return 2
if __name__=='__main__':sys.exit(main())
