"""One actual implementation call, including an optional abrupt test-only stop."""
from pathlib import Path
import argparse,hashlib,inspect,json,os,sqlite3,sys
import importer
BASE=Path(__file__).resolve().parent

def main():
    p=argparse.ArgumentParser();p.add_argument('--variant',choices=['baseline','corrected','no-op'],required=True);p.add_argument('--db',required=True);p.add_argument('--trace',required=True);p.add_argument('--stop-marker');a=p.parse_args()
    source=json.loads((BASE/'source.json').read_text());public={'baseline':importer.baseline_import,'corrected':importer.corrected_import,'no-op':importer.no_op_import}[a.variant]
    trace=open(a.trace,'w');before=sys.getprofile()
    names={'baseline_import','corrected_import','no_op_import','_apply','connect'}
    def profile(frame,event,arg):
        code=frame.f_code
        if Path(code.co_filename).resolve()!=BASE/'importer.py' or code.co_name not in names or event not in ['call','return']:return
        values={k:frame.f_locals[k] for k in ['path','source_revision','items','ignore_existing'] if k in frame.f_locals}
        row={'event':event,'function':code.co_name,'sourceFile':'importer.py','sourceLine':code.co_firstlineno,'fileSha256':hashlib.sha256((BASE/'importer.py').read_bytes()).hexdigest(),'functionSourceSha256':hashlib.sha256(inspect.getsource(code).encode()).hexdigest(),'arguments':values}
        if event=='return':
            if code.co_name=='connect':row['returnConnectionSettings']=importer.settings(arg)
            else:row['return']=arg
        trace.write(json.dumps(row)+'\n');trace.flush()
    def stop(index,item):
        if index==0:
            Path(a.stop_marker).write_text(json.dumps({'phase':'after_first_row_COMMIT_before_checkpoint','index':index,'item':item,'exitCode':86})+'\n')
            os._exit(86)
    sys.setprofile(profile)
    try:response=public(a.db,source['source_revision'],source['items'],stop if a.stop_marker else None)
    finally:sys.setprofile(before);trace.close()
    print(json.dumps({'response':response,'python':sys.version,'sqlite':sqlite3.sqlite_version,'sourceSha256':hashlib.sha256((BASE/'source.json').read_bytes()).hexdigest()}))
    return 0
if __name__=='__main__':raise SystemExit(main())
