#!/usr/bin/env python3
"""Verify successful machine-code compilation of SQLite's VDBE entry point."""

import argparse
import os
from pathlib import Path
import re
import subprocess


ROOT = Path(__file__).resolve().parents[1]
ITERATIONS = 10000
COMPILATION = re.compile(
    r"opt done[^\n]*\bsqlite3VdbeExec\s+\|Tier[^\n]*\bCodeSize\s+([1-9]\d*)"
)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("exe", nargs="?", type=Path, default=ROOT / "dist" / "sqlite-api-shell")
    args = parser.parse_args()
    binary = args.exe.resolve(strict=True)
    command = [
        str(binary),
        "-Dpolyglot.engine.BackgroundCompilation=false",
        "-Dpolyglot.engine.CompileOnly=sqlite3VdbeExec",
        ":memory:",
    ]
    batch = "prepare SELECT 42;\n" + "step\nreset\n" * ITERATIONS + "finalize\n"
    env = dict(os.environ, CGRAAL_INTERPRET="0", CGRAAL_TRACE="1")
    result = subprocess.run(command, input=batch, text=True, capture_output=True,
                            env=env, timeout=120)
    expected = "OK\n" + "ROW\tINTEGER 42\nOK\n" * ITERATIONS + "OK\n"
    if result.returncode != 0 or result.stdout != expected:
        raise SystemExit(f"SQLite execution check failed (exit {result.returncode})\n{result.stderr}")
    compiled = COMPILATION.search(result.stderr)
    if not compiled:
        raise SystemExit(f"Graal did not compile the sqlite3VdbeExec entry point\n{result.stderr}")
    print(f"sqlite3VdbeExec JIT compiled to {compiled[1]} bytes. Verified {ITERATIONS} rows.")


if __name__ == "__main__":
    main()
