# Generated by hardening step 5 (check runner)
from __future__ import annotations

import argparse
from pathlib import Path
import os


def _scalpel_env_flag(name: str) -> bool:
    """Return True if env var is set to a truthy value."""
    v = os.environ.get(name, "")
    return v.strip().lower() in ("1", "true", "yes", "y", "on")



def _call(mod: str, argv: list[str]) -> int:
    m = __import__(f"scalpel.tools.{mod}", fromlist=["main"])
    fn = getattr(m, "main", None)
    if not callable(fn):
        raise RuntimeError(f"scalpel.tools.{mod} missing main()")
    try:
        rc = fn(argv)
    except TypeError:
        rc = fn()
    return 0 if rc is None else int(rc)


def main(argv: list[str] | None = None) -> int:
    ap = argparse.ArgumentParser(prog="scalpel-check", description="Run optional preflight (doctor/smoke build) and validate.")
    ap.add_argument("--out", default="build/scalpel_smoke.html", help="Smoke HTML output path")
    ap.add_argument("--skip-validate", action="store_true", help="Skip smoke_validate")
    ap.add_argument("--skip-doctor", action="store_true", help="Skip doctor preflight")
    ap.add_argument("--skip-smoke", action="store_true", help="Skip smoke build preflight")

    ns = ap.parse_args(argv)

    out = Path(ns.out)
    out.parent.mkdir(parents=True, exist_ok=True)

    skip_doctor = bool(getattr(ns, "skip_doctor", False)) or _scalpel_env_flag("SCALPEL_SKIP_DOCTOR")
    skip_smoke  = bool(getattr(ns, "skip_smoke",  False)) or _scalpel_env_flag("SCALPEL_SKIP_SMOKE")
    if not skip_doctor:
        rc = _call("doctor", [])
        if rc != 0:
            return rc
    if not skip_smoke:
        rc = _call("smoke_build", ["--out", str(out)])
        if rc != 0:
            return rc
    if not ns.skip_validate:
        try:
            rc = _call("smoke_validate", [str(out)])
        except ModuleNotFoundError:
            rc = 0
        if rc != 0:
            return rc

    print(f"[scalpel-check] OK: {out}")
    return 0


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