"""Execute three current graded SQL plans against a fictional read-only SQLite fixture.
This checks parameter binding and result scope, not production SQL authorization.
"""
import argparse,hashlib,json,sqlite3
from pathlib import Path
ROOT=Path(__file__).resolve().parent
SHA=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest()
def run(report_path):
    report=json.loads(Path(report_path).read_text())
    spec=json.loads((ROOT/'cases/text-to-sql-guardrails.json').read_text())
    if report.get('course')!='text-to-sql-guardrails' or report.get('passed') is not True or report.get('runner_sha256')!=SHA(ROOT/'lab_runner.py') or report.get('cases_sha256')!=SHA(ROOT/'cases/text-to-sql-guardrails.json'):
        raise ValueError('current_complete_grade_required')
    ledger=[('acme','a1','CNY',100,500),('acme','a1','CNY',199,-50),('acme','a1','CNY',200,800),
            ('acme','a1','USD',150,900),('other','a1','CNY',150,10000),
            ('acme','a2','CNY',150,700),('acme',"x' OR 1=1 --",'CNY',120,250)]
    db=sqlite3.connect(':memory:')
    db.execute('CREATE TABLE return_ledger(tenant TEXT, account_id TEXT, currency TEXT, event_time INTEGER, amount_cents INTEGER)')
    db.executemany('INSERT INTO return_ledger VALUES(?,?,?,?,?)',ledger);db.commit()
    db.execute('PRAGMA query_only=ON')
    allowed_columns={'tenant','account_id','currency','event_time','amount_cents'}
    def authorize(action,a,b,_database,_trigger):
        if action==sqlite3.SQLITE_SELECT:return sqlite3.SQLITE_OK
        if action==sqlite3.SQLITE_READ and a=='return_ledger' and b in allowed_columns:return sqlite3.SQLITE_OK
        if action==sqlite3.SQLITE_FUNCTION and b in {'coalesce','sum'}:return sqlite3.SQLITE_OK
        return sqlite3.SQLITE_DENY
    db.set_authorizer(authorize)
    output=[]
    for name in ['single-account','sorted-two-accounts','quoted-id-is-value']:
        case=next(c for c in spec['checks'] if c['id']==name)
        row=next(c for c in report['checks'] if c['case_id']==name)
        if row.get('passed') is not True or row.get('input')!=case['input'] or row.get('actual')!=case['expected']:
            raise ValueError('grade_case_binding')
        plan=row['actual'];value=db.execute(plan['sql'],plan['params']).fetchone()[0]
        p=case['input'];intent=p['intent']
        independent=sum(amount for tenant,account,currency,time,amount in ledger
                        if tenant==p['principal']['tenant'] and account in intent['account_ids']
                        and currency==intent['currency'] and intent['start']<=time<intent['end'])
        if type(value) is not int or value!=independent:raise ValueError('query_scope_or_total')
        output.append({'case':name,'actual_cents':value,'independent_cents':independent,'passed':True})
    try:db.execute('DELETE FROM return_ledger')
    except sqlite3.DatabaseError:write_blocked=True
    else:write_blocked=False
    db.close()
    if not write_blocked:raise ValueError('write_not_blocked')
    return {'passed':True,'queries':output,'write_blocked':True,'sqlite':sqlite3.sqlite_version,
            'probe_sha256':SHA(__file__),'source_report_sha256':SHA(report_path),
            'scope':'Fictional SQLite fixture and graded plans; report records are not tamper-proof; no production database role, RLS, provider or workload claims. LIMIT limits output rows, not the rows SUM scans.'}
if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--report',required=True);parser.add_argument('--out',required=True)
    args=parser.parse_args();result=run(args.report)
    Path(args.out).write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(result,sort_keys=True))
