"""Entry points for the perpetual-done, perpetual-fail, and perpetual-metric commands.

These are installed to $PATH when the package is pip-installed, so any
container — regardless of language — can signal workload completion or record
metrics:

    perpetual-done "All 1000 jobs processed"
    perpetual-fail "Out of memory" 137
    perpetual-metric epoch 42
    perpetual-metric loss 0.312

perpetual-done/fail write /run/pc-status/done.json and exit.
perpetual-metric writes to /run/pc-status/metrics.json (best-effort, no exit).
"""

from __future__ import annotations

import sys

from perpetual_compute._status import log_metric, write_status


def cmd_done() -> None:
    """perpetual-done [reason]

    Signal successful workload completion and exit 0.
    """
    reason = " ".join(sys.argv[1:]).strip() or None
    write_status("completed", reason=reason, exit_code=0)
    sys.exit(0)


def cmd_fail() -> None:
    """perpetual-fail [reason] [exit_code]

    Signal workload failure and exit with exit_code (default 1).

    The last argument is treated as exit_code if it is a plain integer,
    otherwise the entire argument list is the reason.

    Examples:
        perpetual-fail "Out of memory"
        perpetual-fail "Out of memory" 137
        perpetual-fail 1
    """
    args = sys.argv[1:]
    exit_code = 1
    reason: str | None = None

    if args:
        # If the last token is a plain integer, treat it as exit_code
        try:
            exit_code = int(args[-1])
            reason_parts = args[:-1]
        except ValueError:
            reason_parts = args

        reason = " ".join(reason_parts).strip() or None

    write_status("failed", reason=reason, exit_code=exit_code)
    sys.exit(exit_code)


def cmd_metric() -> None:
    """perpetual-metric <key> <value>

    Record a numeric metric visible in the Perpetual Compute portal.

    Writes to /run/pc-status/metrics.json immediately (does NOT exit).
    Safe to call multiple times; values for the same key are overwritten.

    Examples:
        perpetual-metric epoch 42
        perpetual-metric loss 0.312
        perpetual-metric throughput_samples_per_sec 1024
    """
    args = sys.argv[1:]
    if len(args) != 2:
        print(
            "Usage: perpetual-metric <key> <value>\n"
            "  key:   metric name (string)\n"
            "  value: numeric value (float or int)",
            file=sys.stderr,
        )
        sys.exit(1)

    key = args[0].strip()
    try:
        value = float(args[1])
    except ValueError:
        print(f"Error: value must be a number, got: {args[1]!r}", file=sys.stderr)
        sys.exit(1)

    log_metric(key, value)
