#!/usr/bin/env python3
# Run a command every N seconds unconditionally.

from dataclasses import dataclass
import shutil
import signal
import subprocess
import sys
import time
from typing import NoReturn

# Flag set by the signal handlers; checked in the loop for a clean exit.
STOP = False

USAGE = """\
usage: repeat_every <interval> [--sep|--compact-sep] [--end-after N] <cmd...>

Run a command every N seconds unconditionally.

options:
  --sep             print a separator between runs
  --compact-sep     like --sep but without the surrounding blank lines
  --end-after N     stop after N seconds (e.g. 0.5, 1.3)
  -h, --help        show this help message and exit
"""


@dataclass(frozen=True)
class Opts:
    """Parsed options and command for a repeat_every run."""

    interval: float
    cmd: list[str]
    use_separator: bool = False
    use_compact_separator: bool = False
    end_after: float | None = None


def handle_stop(*_) -> None:
    """Set a flag the loop checks, so the process exits cleanly on signal."""
    global STOP
    STOP = True


def print_err(*args, **kwargs) -> None:
    print(*args, **kwargs, file=sys.stderr)


def usage_and_exit(exit_code: int, message: str | None = None) -> NoReturn:
    """Print an optional error message and the usage to stderr, then exit."""
    if message is not None:
        print_err(f"ERROR: {message}")
    print_err(USAGE, end="")
    sys.exit(exit_code)


def parse_seconds(value: str) -> float | None:
    """Parse a seconds value, returning None if it is not a valid number."""
    try:
        return float(value)
    except ValueError:
        return None


def print_separator(run_count: int, interval: float) -> None:
    """Print the separator line, hiding the interval's trailing ".0"."""
    now = time.strftime("%H:%M:%S")
    print(f"--- [repeat_every {now}] Run #{run_count}, next in {interval:g}s ---")


def resolve_cmd(cmd: list[str]) -> list[str]:
    """Return the command to run, wrapping a lone spaced argument in sh -c.

    A single argument containing spaces is not a valid executable name, so
    treat it as a shell command line and run it through sh instead.
    """
    if len(cmd) == 1 and " " in cmd[0] and shutil.which(cmd[0]) is None:
        return ["sh", "-c", cmd[0]]
    return cmd


def parse_args(argv: list[str]) -> Opts:
    """Parse CLI arguments into an Opts, exiting on usage errors."""
    if not argv:
        usage_and_exit(1, "no arguments provided")

    interval = parse_seconds(argv[0])
    if interval is None:
        usage_and_exit(1, f"invalid interval: {argv[0]}")

    # Parse flags manually instead of using argparse: the command may contain
    # arbitrary flags, and argparse's REMAINDER greedily swallows our own
    # options (e.g. --sep) into the command.
    arg_idx = 1
    use_separator = False
    use_compact_separator = False
    end_after = None
    while arg_idx < len(argv) and argv[arg_idx].startswith("-"):
        flag = argv[arg_idx]
        if flag == "--":
            arg_idx += 1
            break
        if flag == "--sep":
            use_separator = True
        elif flag == "--compact-sep":
            use_separator = True
            use_compact_separator = True
        elif flag == "--end-after":
            arg_idx += 1
            if arg_idx >= len(argv):
                usage_and_exit(1, "--end-after requires a value")
            end_after = parse_seconds(argv[arg_idx])
            if end_after is None:
                usage_and_exit(1, f"invalid --end-after value: {argv[arg_idx]}")
        else:
            usage_and_exit(1, f"unknown option: {flag}")
        arg_idx += 1

    cmd = argv[arg_idx:]
    if not cmd:
        usage_and_exit(1, "missing command")

    return Opts(
        interval=interval,
        cmd=cmd,
        use_separator=use_separator,
        use_compact_separator=use_compact_separator,
        end_after=end_after,
    )


def main() -> bool:
    args = sys.argv[1:]

    if args and args[0] in ("--help", "-h"):
        usage_and_exit(0)

    opts = parse_args(args)
    cmd = resolve_cmd(opts.cmd)

    # Handle interupt signals
    signal.signal(signal.SIGINT, handle_stop)
    # note: also handle SIGTERM, it's used in tests because SIGINT is not received by bg jobs
    # started in a shell (e.g. in bats test file).
    signal.signal(signal.SIGTERM, handle_stop)

    start = time.monotonic()
    run_count = 0
    while not STOP:
        elapsed = time.monotonic() - start
        if opts.end_after is not None and elapsed >= opts.end_after:
            break
        run_count += 1
        if opts.use_separator:
            if not opts.use_compact_separator:
                print()
            print_separator(run_count, opts.interval)
            if not opts.use_compact_separator:
                print()
        try:
            subprocess.run(cmd)
        except FileNotFoundError:
            print_err(f"ERROR: command not found: {cmd[0]}")
            return False
        time.sleep(opts.interval)

    return True


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