"""Run a trusted command with a fresh log and a timeout. Python 3.10+."""
import argparse
import math
from pathlib import Path
import subprocess
import sys


def run_logged(argv, log_path, *, timeout=60):
    """Keep stdout/stderr on disk; propagate launch, exit and timeout errors."""
    if isinstance(argv, (str, bytes)) or not argv:
        raise ValueError("argv must be a nonempty argument sequence")
    if not math.isfinite(timeout) or timeout <= 0:
        raise ValueError("timeout must be a finite positive number")
    # Exclusive creation prevents accidental replacement of an earlier log.
    with Path(log_path).open("xb") as log:
        return subprocess.run(
            argv,
            stdin=subprocess.DEVNULL,
            stdout=log,
            stderr=subprocess.STDOUT,
            shell=False,
            check=True,
            timeout=timeout,
        )


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("mode", choices=["ok", "fail", "timeout"])
    parser.add_argument("log", type=Path, help="new log path; parent must exist")
    args = parser.parse_args()
    programs = {
        "ok": "print('processed 3 records', flush=True)",
        "fail": "import sys; print('invalid input', file=sys.stderr, flush=True); sys.exit(2)",
        "timeout": "import time; print('started', flush=True); time.sleep(30)",
    }
    command = [sys.executable, "-u", "-c", programs[args.mode]]
    try:
        run_logged(command, args.log, timeout=1 if args.mode == "timeout" else 10)
    except subprocess.CalledProcessError as exc:
        print(f"FAILED: exit={exc.returncode}; log={args.log}", file=sys.stderr)
        return 1
    except subprocess.TimeoutExpired:
        print(f"TIMEOUT: log={args.log}", file=sys.stderr)
        return 1
    except (OSError, ValueError) as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        return 1
    print(f"OK: log={args.log}")
    return 0


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