from __future__ import annotations

import argparse
import shutil
import sqlite3
import subprocess
import sys
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]


def run(label: str, command: list[str]) -> None:
    print(f"\n[{label}] {' '.join(command)}", flush=True)
    subprocess.run(command, cwd=ROOT, check=True)


def verify_database() -> None:
    database = ROOT / "data" / "review.db"
    if not database.exists():
        print("\n[database] skipped: data/review.db does not exist")
        return
    with sqlite3.connect(f"file:{database.as_posix()}?mode=ro", uri=True) as connection:
        result = connection.execute("PRAGMA integrity_check").fetchone()
    if not result or result[0] != "ok":
        raise RuntimeError(f"SQLite integrity check failed: {result}")
    print(f"\n[database] integrity_check=ok size={database.stat().st_size}")


def main() -> int:
    parser = argparse.ArgumentParser(description="Verify the governance regression baseline")
    parser.add_argument(
        "--e2e",
        action="store_true",
        help="also run the Playwright browser suite",
    )
    args = parser.parse_args()

    run("python", [sys.executable, "-m", "unittest", "discover", "-s", "tests"])
    node = shutil.which("node")
    if not node:
        raise RuntimeError("node is required for JavaScript syntax checks")
    for script in ("static/app.js", "static/heaven-loading-v2.js"):
        run("javascript", [node, "--check", script])
    run("patch", ["git", "diff", "--check"])
    verify_database()

    if args.e2e:
        npm = shutil.which("npm.cmd" if sys.platform == "win32" else "npm")
        if not npm:
            raise RuntimeError("npm is required for the Playwright suite")
        run("playwright", [npm, "run", "test:e2e"])
    print("\nBaseline verification passed.")
    return 0


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