"""Execute exact local source once; assess original and weakened bars separately."""
import argparse,copy,hashlib,importlib,inspect,json,platform,sqlite3,sys
from pathlib import Path
import storage

def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def textsha(s):return hashlib.sha256(s.encode()).hexdigest()
def typed_equal(a,e):
    if type(a) is not type(e):return False
    if type(e) is dict:return a.keys()==e.keys() and all(typed_equal(a[k],v) for k,v in e.items())
    if type(e) is list:return len(a)==len(e) and all(typed_equal(x,y) for x,y in zip(a,e))
    return a==e

def evaluate_full(observations,expected):
    checks=[]
    for state in observations['states']:
        wanted=expected['states'][state['phase']]
        checks.append({'name':'full rows:'+state['phase'],'passed':typed_equal(state['rows'],wanted),'actual':state['rows'],'expected':wanted})
    for item in observations['calls']:
        wanted=expected['returns'][item['input']['phase']]
        checks.append({'name':'typed reply:'+item['input']['phase'],'passed':typed_equal(item['response'],wanted),'actual':item['response'],'expected':wanted})
    checks.append({'name':'actual public entry count','passed':observations['public_entries']==3,'actual':observations['public_entries'],'expected':3})
    return {'passed':all(x['passed'] for x in checks),'checks':checks}

def evaluate_response_only(observations,expected):
    # UNAPPROVED authored draft: deliberately deletes every effect/state assertion.
    checks=[]
    for item in observations['calls']:
        wanted=expected['returns'][item['input']['phase']]
        checks.append({'name':'typed reply only:'+item['input']['phase'],'passed':typed_equal(item['response'],wanted),'actual':item['response'],'expected':wanted})
    return {'passed':all(x['passed'] for x in checks),'checks':checks,'authority':'Unapproved authored acceptance-bar change; not actual AI output or intent approval'}

def observe(path):
    c=sqlite3.connect(path,isolation_level=None,autocommit=sqlite3.LEGACY_TRANSACTION_CONTROL)
    try:return [list(r) for r in c.execute('SELECT subject,limit_value FROM quotas ORDER BY subject')]
    finally:c.close()

def run(variant,out):
    out.mkdir(parents=True,exist_ok=False);root=Path(__file__).resolve().parent
    module=importlib.import_module(variant);function=module.apply_quota
    inputs=json.loads((root/'inputs.json').read_text());expected=json.loads((root/'expected.json').read_text())
    path=out/'state.sqlite';setup=storage.initialize(path);trace=[];connections=[];sql=[];phase=None
    identity={'file':variant+'.py','file_sha256':sha(root/(variant+'.py')),'module':module.__name__,'qualname':function.__qualname__,'first_line':function.__code__.co_firstlineno,'function_source_sha256':textsha(inspect.getsource(function))}
    def profile(frame,event,arg):
        if event not in ('call','return') or frame.f_code not in (function.__code__,storage.connect.__code__):return
        if frame.f_code is storage.connect.__code__:
            if event=='return':
                connections.append({'phase':phase,'actual_settings':storage.settings(arg)})
                arg.set_trace_callback(lambda statement:sql.append({'phase':phase,'statement':statement}))
            return
        row={'phase':phase,'event':event,'identity':identity}
        if event=='call':row['arguments']={'path':Path(frame.f_locals['path']).name,'subject':frame.f_locals['subject'],'limit':frame.f_locals['limit']}
        else:row['actual_return']=copy.deepcopy(arg)
        trace.append(row)
    states=[{'phase':'setup','rows':observe(path)}];calls=[]
    for item in inputs['calls']:
        phase=item['phase'];sys.setprofile(profile)
        try:response=function(path,item['subject'],item['limit'])
        finally:sys.setprofile(None)
        calls.append({'input':item,'response':response});states.append({'phase':phase,'rows':observe(path)})
    observations={'variant':variant,'function_identity':identity,'runtime':{'python':sys.version,'implementation':platform.python_implementation(),'sqlite':sqlite3.sqlite_version,'__debug__':__debug__},'setup_connection_settings':setup,'actual_call_connection_settings':connections,'calls':calls,'states':states,'public_entries':sum(t['event']=='call' for t in trace),'normal_returns':sum(t['event']=='return' for t in trace),'sql_trace':sql,'profile_scope':'Exact function call/return/source/arguments; no branch coverage or native Proof grounding claim'}
    original=evaluate_full(observations,expected);weak=evaluate_response_only(observations,expected)
    common={'requirement_sha256':sha(root/'requirement-v1.json'),'task_sha256':sha(root/'task.json'),'implementation_sha256':identity['file_sha256'],'storage_helper_sha256':sha(root/'storage.py'),'inputs_sha256':sha(root/'inputs.json'),'literal_oracle_sha256':sha(root/'expected.json'),'harness_sha256':sha(root/'run.py')}
    records={}
    for name,gate,fn in [('original-full',original,evaluate_full),('unapproved-response-only',weak,evaluate_response_only)]:
        records[name]={'kind':'Actual local teaching evidence record, not native Proof','variant':variant,'claim_scope':name,'passed':gate['passed'],'binding':{**common,'acceptance_bar_sha256':textsha(inspect.getsource(fn))},'actual_recorded_calls':len(calls),'actual_human_or_Change_approval':False}
    report={'variant':variant,'original_full':original,'unapproved_response_only':weak,'evidence_records':records,'units':{'public_calls':observations['public_entries'],'normal_returns':observations['normal_returns'],'new_connection_snapshots':len(states),'full_checks':len(original['checks']),'full_failed_checks':sum(not c['passed'] for c in original['checks']),'weakened_checks':len(weak['checks'])}}
    for name,obj in [('observations.json',observations),('report.json',report),('evidence-records.json',records)]: (out/name).write_text(json.dumps(obj,indent=2)+'\n')
    (out/'profile.jsonl').write_text(''.join(json.dumps(x,sort_keys=True)+'\n' for x in trace))
    print(json.dumps(report,indent=2));return 0 if original['passed'] else 1
if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('--variant',choices=['old','candidate','corrected'],required=True);p.add_argument('--output',type=Path,required=True);a=p.parse_args();raise SystemExit(run(a.variant,a.output))
