#!/usr/bin/env python3
"""Display one phase's current ATM BD console snapshot.

Usage: bead-queues --phase <phase>

This command is deliberately a viewer, not an orchestration loop.  The
console owns reading the snapshot, judging staleness, and rendering it; this
wrapper simply preserves the console's output and status.
"""
from __future__ import annotations

import argparse
import re
import shutil
import subprocess
import sys


FAILED = 2
CONSOLE = "atm-bd"
REQUIRED_CONSOLE_VERSION = (0, 1, 0)
REQUIRED_CONSOLE_VERSION_TEXT = ".".join(map(str, REQUIRED_CONSOLE_VERSION))
CONSOLE_INSTALL = "{{ console_install }}"
VERSION_PATTERN = re.compile(r"\b([0-9]+)\.([0-9]+)\.([0-9]+)\b")


def _console_version_error(console: str) -> str | None:
    probe = subprocess.run([console, "--version"], capture_output=True, text=True, check=False)
    reported = (probe.stdout or probe.stderr).strip()
    match = VERSION_PATTERN.search(reported)
    fix = f"install or upgrade it with: {CONSOLE_INSTALL}"
    if probe.returncode != 0 or match is None:
        return (
            f"CONSOLE_VERSION_UNAVAILABLE: bead-queues requires {CONSOLE} >= "
            f"{REQUIRED_CONSOLE_VERSION_TEXT}; {CONSOLE} --version reported "
            f"{reported or 'no semantic version'}; {fix}"
        )
    actual = tuple(int(part) for part in match.groups())
    if actual < REQUIRED_CONSOLE_VERSION:
        found = ".".join(map(str, actual))
        return (
            f"CONSOLE_VERSION_TOO_OLD: bead-queues requires {CONSOLE} >= "
            f"{REQUIRED_CONSOLE_VERSION_TEXT}, found {found}; {fix}"
        )
    return None


def main(argv: list[str]) -> int:
    parser = argparse.ArgumentParser(prog="bead-queues", description=__doc__)
    parser.add_argument("--phase", required=True, help="phase to display")
    args = parser.parse_args(argv)

    console = shutil.which(CONSOLE)
    if console is None:
        print(f"bead-queues: {CONSOLE} is not on PATH; install it with: {CONSOLE_INSTALL}", file=sys.stderr)
        return FAILED

    version_error = _console_version_error(console)
    if version_error is not None:
        print(f"bead-queues: {version_error}", file=sys.stderr)
        return FAILED

    completed = subprocess.run([console, "show", "--phase", args.phase])
    return completed.returncode


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
