#!/usr/bin/env python3
"""Run backend layer pipelines. Scans layers/ so new ones are picked up automatically."""
import argparse
import importlib
import sys
import time
from pathlib import Path

_BACKEND_DIR = Path(__file__).resolve().parent.parent
if str(_BACKEND_DIR) not in sys.path:
    sys.path.insert(0, str(_BACKEND_DIR))

LAYERS_DIR = _BACKEND_DIR / "layers"


def discover_layers():
    return sorted(
        p.parent.name
        for p in LAYERS_DIR.glob("*/pipeline.py")
        if p.parent.name != "__pycache__"
    )


def run_layer(name):
    mod = importlib.import_module(f"layers.{name}.pipeline")
    t0 = time.monotonic()
    mod.main()
    return time.monotonic() - t0


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--layers", nargs="+", metavar="LAYER")
    args = parser.parse_args()

    available = discover_layers()
    if not available:
        print(f"no layers found in {LAYERS_DIR}", file=sys.stderr)
        sys.exit(1)

    targets = args.layers if args.layers else available

    unknown = set(targets) - set(available)
    if unknown:
        print(f"unknown: {', '.join(sorted(unknown))} (available: {', '.join(available)})", file=sys.stderr)
        sys.exit(1)

    results = {}
    for name in targets:
        print(f"\n[{name}]")
        try:
            elapsed = run_layer(name)
            results[name] = ("PASS", elapsed)
            print(f"  ok ({elapsed:.1f}s)")
        except Exception as exc:
            results[name] = ("FAIL", str(exc))
            print(f"  FAIL: {exc}", file=sys.stderr)

    failures = [n for n, (s, _) in results.items() if s == "FAIL"]
    print(f"\n{len(targets) - len(failures)}/{len(targets)} passed")
    if failures:
        sys.exit(1)


if __name__ == "__main__":
    main()
