"""Local SQLite learning helper. No network, installs, saved database or grading."""
import argparse
import json
from contextlib import contextmanager
from pathlib import Path
import sqlite3
import sys

ROOT=Path(__file__).resolve().parent
FIXTURES=('base','independent','changed','empty')
PINNED_SQLITE='3.53.1'

@contextmanager
def load_fixture(name):
    if name not in FIXTURES: raise ValueError('Unknown fixture')
    db=sqlite3.connect(':memory:')
    try:
        db.executescript((ROOT/'data'/'schema.sql').read_text()+ '\n'+(ROOT/'data'/f'{name}.sql').read_text())
        if db.execute('PRAGMA foreign_keys').fetchone()[0] != 1:
            raise RuntimeError('Foreign-key enforcement must be on')
        yield db
    finally:
        db.close()

def execute(db,sql):
    allowed={sqlite3.SQLITE_SELECT,sqlite3.SQLITE_READ,sqlite3.SQLITE_FUNCTION,sqlite3.SQLITE_RECURSIVE}
    def authorize(action,arg1,arg2,db_name,trigger):
        return sqlite3.SQLITE_OK if action in allowed else sqlite3.SQLITE_DENY
    ticks=0
    def progress():
        nonlocal ticks
        ticks+=1
        return ticks>1000
    db.set_authorizer(authorize)
    db.set_progress_handler(progress,1000)
    try:
        cursor=db.execute(sql)
        if cursor.description is None: raise ValueError('Use one result-producing SELECT query')
        rows=cursor.fetchmany(2001)
        if len(rows)>2000: raise ValueError('Result exceeds 2,000 rows; narrow your learning query')
        if any(isinstance(v,bytes) for row in rows for v in row):
            raise ValueError('Binary results are outside the text lesson runner')
        return {'columns':[c[0] for c in cursor.description],'rows':[list(row) for row in rows]}
    finally:
        db.set_authorizer(None)
        db.set_progress_handler(None,0)

def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('fixture',choices=FIXTURES)
    group=parser.add_mutually_exclusive_group(required=True)
    group.add_argument('--query',choices=sorted(p.stem for p in (ROOT/'queries').glob('*.sql')))
    group.add_argument('--file',type=Path)
    parser.add_argument('--allow-other-version',action='store_true',help='Run locally with an unvalidated SQLite version; output explicitly labels the mismatch')
    args=parser.parse_args()
    matched=sqlite3.sqlite_version==PINNED_SQLITE
    if not matched and not args.allow_other_version:
        parser.exit(2,f'Validated SQLite is {PINNED_SQLITE}; yours is {sqlite3.sqlite_version}. No query run. Read README before opting into --allow-other-version.\n')
    try:
        sql=(ROOT/'queries'/f'{args.query}.sql').read_text() if args.query else args.file.read_text()
        with load_fixture(args.fixture) as db:
            result=execute(db,sql)
        print(json.dumps({'fixture':args.fixture,'python_version':sys.version.split()[0],
              'sqlite_version':sqlite3.sqlite_version,'pinned_sqlite':PINNED_SQLITE,
              'matches_validated_runtime':matched,**result},indent=2,allow_nan=False))
    except (sqlite3.Error,ValueError,OSError) as exc:
        parser.exit(2,f'Query not completed: {exc}\nNo persistent database was changed. Keep your SQL file and revise it.\n')

if __name__=='__main__': main()
