#!/usr/bin/env python3
"""Compare a rewritten AOT SQLite ELF with its original and the native C API shell."""

import argparse
from contextlib import closing
import os
from pathlib import Path
import runpy
import sqlite3
import subprocess
import tempfile


ROOT = Path(__file__).resolve().parents[1]
FIXTURES = runpy.run_path(str(ROOT / "scripts/check-shell"))


def native_shell(source, output):
    compiler = os.environ.get("CC", "cc")
    subprocess.run([
        compiler, "-std=c11", "-O2", "-pthread", "-DSQLITE_ENABLE_FTS5",
        "-DSQLITE_ENABLE_RTREE", "-DSQLITE_ENABLE_MATH_FUNCTIONS",
        f"-I{source}", str(ROOT / "c/api-shell.c"), str(source / "sqlite3.c"),
        "-lm", "-ldl", "-o", str(output),
    ], check=True)
    return output


def database_contents(path):
    uri = path.as_uri() + "?mode=ro"
    with closing(sqlite3.connect(uri, uri=True)) as connection:
        integrity = connection.execute("PRAGMA integrity_check").fetchall()
        if integrity != [("ok",)]:
            raise ValueError(f"database integrity check failed: {integrity!r}")
        return (
            connection.execute("PRAGMA journal_mode").fetchone(),
            connection.execute("PRAGMA user_version").fetchone(),
            connection.execute("SELECT type, name, tbl_name, sql FROM sqlite_schema "
                               "ORDER BY type,name").fetchall(),
            connection.execute("SELECT rowid, i, r, s, b, n FROM items ORDER BY rowid").fetchall(),
        )


def contract(command, directory, interpret, lookups):
    directory.mkdir()
    database = directory / "database with spaces.db"
    cases = [
        ("version", ["--version"], b"", 0),
        ("help", ["--help"], b"", 0),
        ("usage exit", ["extra", "argument"], b"", 2),
        ("source ID and CRLF input", [":memory:"], b"source-id\r\nversion\r\n", 0),
        ("WAL, typed bindings and rollback", [str(database)], FIXTURES["INSERT"].encode(), 0),
        ("persistent index and version", [str(database)],
         b"exec CREATE INDEX items_i ON items(i); PRAGMA user_version=37;\n", 0),
        ("error and rollback on close", [str(database)],
         b"exec BEGIN; DELETE FROM items;\nprepare SELECT no_such_column FROM items;\n", 1),
        ("reopen, typed reads and empty blob", [str(database)], FIXTURES["READ"].encode(), 0),
        ("reject several statements", [str(database)], b"prepare SELECT 1; SELECT 2;\nchanges\n", 1),
        ("reject invalid blob", [str(database)], b"prepare SELECT ?1;\nbind-blob 1 z1\nstep\n", 1),
        ("reject NUL input", [":memory:"], b"version\nexec SELECT \x00;\n", 1),
    ]
    if lookups:
        setup = (b"exec CREATE TABLE kv(id INTEGER PRIMARY KEY, value INTEGER NOT NULL); "
                 b"INSERT INTO kv VALUES(42,1729);\nprepare SELECT value FROM kv WHERE id = ?1;\n")
        iteration = b"bind-int 1 42\nstep\nstep\nreset\n"
        cases.append(("prepared lookup loop", [":memory:"], setup + iteration * lookups + b"finalize\n", 0))

    results = {}
    env = dict(os.environ, LC_ALL="C", TZ="UTC", CGRAAL_TRACE="0",
               CGRAAL_INTERPRET="1" if interpret else "0")
    for name, args, stdin, expected in cases:
        result = subprocess.run([*command, *args], input=stdin, capture_output=True,
                                cwd=directory, env=env, timeout=60)
        if result.returncode != expected:
            raise ValueError(f"{name}: exit {result.returncode}, expected {expected}\n"
                             f"stdout={result.stdout[:500]!r}\nstderr={result.stderr[:500]!r}")
        results[name] = (result.returncode, result.stdout, result.stderr)
    return results, database_contents(database)


def compare(reference, candidate, label):
    reference_tests, reference_database = reference
    candidate_tests, candidate_database = candidate
    for name, expected in reference_tests.items():
        actual = candidate_tests[name]
        for observation, left, right in zip(("exit status", "stdout", "stderr"), expected, actual):
            if left != right:
                expected_excerpt = left[:500] if isinstance(left, bytes) else left
                actual_excerpt = right[:500] if isinstance(right, bytes) else right
                raise ValueError(f"{label}, {name}: {observation} differs\n"
                                 f"native={expected_excerpt!r}\nactual={actual_excerpt!r}")
    if reference_database != candidate_database:
        raise ValueError(f"{label}: persistent database schema or rows differ from native C")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("candidate", type=Path, help="rewritten executable ELF")
    parser.add_argument("--original", type=Path,
                        default=ROOT / "dist/libexec/sqlite-api-shell-image")
    parser.add_argument("--native", type=Path, help="prebuilt C API shell from the same SQLite source")
    parser.add_argument("--amalgamation", type=Path, default=ROOT / "vendor/sqlite-amalgamation-3540100")
    parser.add_argument("--module", type=Path, help="API shell bitcode module for both Graal images")
    parser.add_argument("--lookups", type=int, default=0, help="repeat bound rowid lookups in one process")
    parser.add_argument("--interpreter-only", action="store_true",
                        help="test only the interpreter execution mode")
    args = parser.parse_args()
    if args.lookups < 0:
        parser.error("--lookups must be nonnegative")

    with tempfile.TemporaryDirectory(prefix="sqlite-binary-parity-") as temporary:
        work = Path(temporary)
        native = (args.native.resolve(strict=True) if args.native else
                  native_shell(args.amalgamation.resolve(strict=True), work / "native"))
        reference = contract([str(native)], work / "native-work", False, args.lookups)
        guest_args = ["--run-module", str(args.module.resolve(strict=True))] if args.module else []
        modes = [("interpreter", True)]
        if not args.interpreter_only:
            modes.append(("JIT enabled", False))
        for image_name, image in (("original", args.original), ("rewritten", args.candidate)):
            for mode, interpret in modes:
                label = f"{image_name} {mode}"
                command = [str(image.resolve(strict=True)), *guest_args]
                result = contract(command, work / label, interpret, args.lookups)
                compare(reference, result, label)
                print(f"{label}: {len(result[0])} command contracts and persistent database matched native C")


if __name__ == "__main__":
    try:
        main()
    except (OSError, sqlite3.Error, subprocess.SubprocessError, ValueError) as error:
        raise SystemExit(f"check-binary-parity: {error}") from error
