#!/usr/bin/env python3
"""Preflight check for abi-evals."""
from __future__ import annotations

import subprocess
import sys
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parent.parent

REQUIRED_FILES = [
    "README.md",
    "SECURITY.md",
    "pyproject.toml",
    "src/abi_evals/__init__.py",
    "src/abi_evals/runner.py",
    "src/abi_evals/comparators.py",
    "src/abi_evals/goldens.py",
    "src/abi_evals/cli.py",
    "goldens/v1/manifest.json",
    "tests/fixtures/sample_eval_suite.json",
]


def check_files() -> list[str]:
    errors = []
    for f in REQUIRED_FILES:
        if not (REPO_ROOT / f).exists():
            errors.append(f"Missing: {f}")
    return errors


def run_lint() -> int:
    print("=== Running ruff ===")
    return subprocess.run(
        [sys.executable, "-m", "ruff", "check", "src/", "tests/"],
        cwd=REPO_ROOT,
    ).returncode


def run_tests() -> int:
    print("=== Running pytest ===")
    return subprocess.run(
        [sys.executable, "-m", "pytest", "tests/", "-v", "--tb=short"],
        cwd=REPO_ROOT,
    ).returncode


def main() -> int:
    print("abi-evals preflight check")
    print("=" * 40)

    print("\n--- File presence ---")
    file_errors = check_files()
    for e in file_errors:
        print(f"  FAIL: {e}")
    if not file_errors:
        print("  OK: All required files present")

    print()
    lint_rc = run_lint()
    print()
    test_rc = run_tests()

    if file_errors or lint_rc != 0 or test_rc != 0:
        print("\n PREFLIGHT FAILED")
        return 1
    print("\n PREFLIGHT PASSED")
    return 0


if __name__ == "__main__":
    sys.exit(main())
