#!/usr/bin/env python3
"""Public prerequisite contracts and grader. Python 3.9+, standard library.

The scaffold intentionally contains no completed learner implementation.
The public, fixed cases are diagnostics, not unseen interview assessments.
Only run modules you trust: import/execution is not a security sandbox.
"""
import argparse
import concurrent.futures
import hashlib
import importlib.util
import json
import math
import pathlib
import sqlite3
import subprocess
import sys
import tempfile

TEMPLATE = '''"""Implement the four contracts in PREREQUISITES.md. Standard library only."""

def parse_quantity(value):
    raise NotImplementedError("quantity")

def find_visible(conn, tenant, ids):
    raise NotImplementedError("parameterized SQL")

def next_action(observation):
    raise NotImplementedError("HTTP outcome")

def claim_once(db_path, operation_key):
    raise NotImplementedError("durable unique claim")
'''

def report_value(value, depth=0):
    """Keep a failed learner return JSON-readable without executing its repr."""
    if depth > 8:
        return {'diagnostic':'maximum_report_depth'}
    if value is None or type(value) in (bool,int,str):
        return value
    if type(value) is float:
        return value if math.isfinite(value) else {'non_json_number':str(value)}
    if type(value) in (list,tuple):
        return [report_value(x,depth+1) for x in value]
    if type(value) is dict:
        if not all(type(k) is str for k in value):
            return {'invalid_mapping_keys':sorted({type(k).__name__ for k in value})}
        return {k:report_value(v,depth+1) for k,v in value.items()}
    return {'non_json_type':type(value).__name__}

def load_module(path):
    path = pathlib.Path(path).resolve()
    spec = importlib.util.spec_from_file_location('learner_prerequisite', path)
    module = importlib.util.module_from_spec(spec)
    sys.modules[spec.name] = module
    spec.loader.exec_module(module)
    return module

def quantity_cases(module):
    rows = []
    cases = [(1,1,None),(100,100,None),(7,7,None),(True,None,TypeError),
             (False,None,TypeError),('1',None,TypeError),(1.0,None,TypeError),
             (None,None,TypeError),([],None,TypeError),(0,None,ValueError),
             (-1,None,ValueError),(101,None,ValueError)]
    for i,(value,expected,error) in enumerate(cases):
        try:
            actual = module.parse_quantity(value)
            ok = error is None and type(actual) is int and actual == expected
            detail = {'actual':actual,'expected':expected,'expected_error':error.__name__ if error else None}
        except Exception as exc:
            ok = error is not None and type(exc) is error
            detail = {'actual_error':type(exc).__name__,'expected_error':error.__name__ if error else None}
        rows.append({'case':'quantity-'+str(i),'passed':ok,**detail})
    return rows

def sql_cases(module):
    rows = []
    fixtures = [
        ([('r1','t1','mine'),('r2','t2','private'),('r3','t1','other')],
         [('t1',['r2','r1'],['r1']),('t1',['r3','r1','r1'],['r1','r3']),
          ('t2',['r3','r2'],['r2']),('t1',[],[]),
          ("t1' OR 1=1 --",['r1','r2'],[]),('t1',["x') OR 1=1 --"],[])]),
        ([('z9','org-a','one'),('a4','org-a','two'),('b8','org-b','private')],
         [('org-a',['z9','b8','a4'],['a4','z9']),('org-a',['missing'],[])])]
    for f,(records,cases) in enumerate(fixtures):
        conn = sqlite3.connect(':memory:')
        conn.execute('CREATE TABLE resources(id TEXT PRIMARY KEY, tenant TEXT NOT NULL, body TEXT NOT NULL)')
        conn.executemany('INSERT INTO resources VALUES (?,?,?)',records)
        conn.commit()
        expected_state = conn.execute('SELECT * FROM resources ORDER BY id').fetchall()
        for i,(tenant,ids,expected) in enumerate(cases):
            try:
                actual = module.find_visible(conn,tenant,list(ids))
                after = conn.execute('SELECT * FROM resources ORDER BY id').fetchall()
                ok = type(actual) is list and all(type(x) is str for x in actual) and actual == expected and after == expected_state
                detail = {'actual':actual,'expected':expected,'database_unchanged':after==expected_state}
            except Exception as exc:
                ok = False;detail={'actual_error':type(exc).__name__}
            rows.append({'case':'sql-'+str(f)+'-'+str(i),'passed':ok,**detail})
        conn.close()
    return rows

def http_cases(module):
    rows=[]
    def obs(kind,status,key=None,receipt=None,attempts=1,limit=3):
        return {'kind':kind,'status':status,'operation_key':key,'receipt':receipt,'attempts':attempts,'max_attempts':limit}
    cases=[
        (obs('read','ok'),{'action':'complete','operation_key':None}),
        (obs('read','timeout'),{'action':'retry_read','operation_key':None}),
        (obs('read','rate_limited',attempts=2),{'action':'retry_read','operation_key':None}),
        (obs('read','timeout',attempts=3),{'action':'stop','operation_key':None}),
        (obs('read','forbidden'),{'action':'stop','operation_key':None}),
        (obs('write','invalid_arguments','op-a'),{'action':'stop','operation_key':'op-a'}),
        (obs('write','timeout','op-a'),{'action':'reconcile_original','operation_key':'op-a'}),
        (obs('write','rate_limited','op-b'),{'action':'reconcile_original','operation_key':'op-b'}),
        (obs('write','ok','op-c'),{'action':'reconcile_original','operation_key':'op-c'}),
        (obs('write','timeout','op-d',attempts=3),{'action':'reconcile_original','operation_key':'op-d'}),
        (obs('write','ok','op-e',{'operation_key':'op-e','return_id':'ret-1'}),{'action':'complete','operation_key':'op-e'}),
        (obs('write','forbidden','op-f'),{'action':'stop','operation_key':'op-f'})]
    for i,(value,expected) in enumerate(cases):
        before=json.dumps(value,sort_keys=True)
        try:
            actual=module.next_action(value)
            ok=type(actual) is dict and actual==expected and json.dumps(value,sort_keys=True)==before
            detail={'actual':actual,'expected':expected,'input_unchanged':json.dumps(value,sort_keys=True)==before}
        except Exception as exc:
            ok=False;detail={'actual_error':type(exc).__name__}
        rows.append({'case':'http-'+str(i),'passed':ok,**detail})
    conflict=obs('write','ok','op-real',{'operation_key':'op-other','return_id':'ret-2'})
    try:
        module.next_action(conflict);ok=False;detail={'actual_error':None,'expected_error':'ValueError'}
    except Exception as exc:
        ok=type(exc) is ValueError;detail={'actual_error':type(exc).__name__,'expected_error':'ValueError'}
    rows.append({'case':'http-receipt-binding','passed':ok,**detail})
    return rows

def worker_call(module_path,db,key):
    result=subprocess.run([sys.executable,str(pathlib.Path(__file__).resolve()),'_claim-worker',
                           '--module',str(module_path),'--db',str(db),'--key',key],
                          text=True,capture_output=True,timeout=15)
    if result.returncode:
        return {'worker_error':result.stderr.strip()[-600:] or result.stdout.strip()[-600:]}
    try:
        data=json.loads(result.stdout)
        return data
    except ValueError:
        return {'worker_error':'expected one JSON worker result'}

def claim_cases(module_path):
    rows=[]
    with tempfile.TemporaryDirectory(prefix='agent-prerequisite-') as directory:
        db=pathlib.Path(directory)/'claims.sqlite'
        with sqlite3.connect(db) as conn:
            conn.execute("CREATE TABLE claims(operation_key TEXT PRIMARY KEY, created_tag TEXT NOT NULL DEFAULT 'claimed')")
        for i,key in enumerate(['op-a',"op-b'quoted"]):
            with concurrent.futures.ThreadPoolExecutor(max_workers=6) as pool:
                results=list(pool.map(lambda _:worker_call(module_path,db,key),range(6)))
            with sqlite3.connect(db) as conn:
                ledger=conn.execute('SELECT operation_key,created_tag FROM claims ORDER BY operation_key').fetchall()
            winners=sum(x.get('claimed') is True for x in results)
            types_ok=all(type(x.get('claimed')) is bool for x in results)
            expected=sorted([(k,'claimed') for k in ['op-a',"op-b'quoted"][:i+1]])
            ok=types_ok and winners==1 and ledger==expected
            rows.append({'case':'claim-concurrent-'+str(i),'passed':ok,'workers':6,'winners':winners,
                         'exact_boolean_results':types_ok,'ledger':[list(x) for x in ledger],
                         'worker_errors':[x['worker_error'] for x in results if 'worker_error' in x]})
        replay=worker_call(module_path,db,'op-a')
        with sqlite3.connect(db) as conn:
            ledger=conn.execute('SELECT operation_key,created_tag FROM claims ORDER BY operation_key').fetchall()
        rows.append({'case':'claim-reopen-replay','passed':replay.get('claimed') is False and len(ledger)==2,
                     'actual':replay,'ledger_rows':len(ledger)})
    return rows

def grade(module_path):
    module_path=pathlib.Path(module_path).resolve()
    module=load_module(module_path)
    groups={'quantity':quantity_cases(module),'sql':sql_cases(module),'http':http_cases(module),
            'claim':claim_cases(module_path)}
    summaries={name:{'passed':all(x['passed'] for x in cases),'passed_cases':sum(x['passed'] for x in cases),
                     'total_cases':len(cases)} for name,cases in groups.items()}
    return {'format':'agent-prerequisites/v1','source':'authored_fixed_local_cases',
            'passed':all(x['passed'] for x in summaries.values()),'skills_passed':sum(x['passed'] for x in summaries.values()),
            'skills_total':4,'skills':summaries,'cases':groups,
            'learner_module':str(module_path),'learner_module_sha256':hashlib.sha256(module_path.read_bytes()).hexdigest(),
            'grader_sha256':hashlib.sha256(pathlib.Path(__file__).read_bytes()).hexdigest(),
            'python':sys.version,'live_model_calls':0,
            'scope':'Local code execution, isolated SQLite and independent worker processes. Fixed public diagnostics; not unseen interview, external effect or hiring assessment.'}

def main():
    parser=argparse.ArgumentParser(description=__doc__)
    sub=parser.add_subparsers(dest='command',required=True)
    scaffold=sub.add_parser('scaffold');scaffold.add_argument('--out',required=True)
    grading=sub.add_parser('grade');grading.add_argument('--module',required=True);grading.add_argument('--out')
    worker=sub.add_parser('_claim-worker');worker.add_argument('--module',required=True);worker.add_argument('--db',required=True);worker.add_argument('--key',required=True)
    args=parser.parse_args()
    if args.command=='scaffold':
        path=pathlib.Path(args.out)
        with path.open('x') as handle:handle.write(TEMPLATE)
        print(json.dumps({'created':str(path),'complete_implementations':0}));return 0
    if args.command=='_claim-worker':
        value=load_module(args.module).claim_once(args.db,args.key)
        print(json.dumps({'claimed':value}));return 0
    try:
        result=grade(args.module)
    except Exception as exc:
        result={'passed':False,'grader_error':type(exc).__name__,'detail':str(exc),
                'scope':'Import or unsupported module error; not a learner pass.'}
    rendered=json.dumps(report_value(result),ensure_ascii=False,indent=2,allow_nan=False)
    if args.out:pathlib.Path(args.out).write_text(rendered+'\n')
    print(rendered)
    return 0 if result['passed'] else 1

if __name__=='__main__':
    raise SystemExit(main())
