main
Drew Owens Publish Microgoose Rev A full-stack hardware, CAD, datasheet, and 7-stage RL stack e843249
"""Command-line interface for Microgoose onboard 50 Hz multi-daemon runtime (goosectl)."""

from __future__ import annotations

import argparse
import json
import os
import re
import signal
import subprocess
import sys
import time
from pathlib import Path
from typing import Any, Dict

from goosectl.config import (
    DEFAULT_SOCK_DIR,
    POLICY_PID_NAME,
    POLICY_SOCK_NAME,
    SPINE_PID_NAME,
    SPINE_SOCK_NAME,
)
from goosectl.protocol import unix_rpc_call

_GREEN = "\x1b[32m"
_RED = "\x1b[31m"
_CYAN = "\x1b[36m"
_BOLD = "\x1b[1m"
_DIM = "\x1b[2m"
_RESET = "\x1b[0m"

_ANSI_RE = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")


def strip_ansi(text: str) -> str:
    return _ANSI_RE.sub("", text)


def emit_ok(msg: str) -> None:
    if sys.stdout.isatty():
        print(f"{_GREEN}{_BOLD}OK:{_RESET} {msg}")
    else:
        print(f"OK: {strip_ansi(msg)}")


def emit_err(msg: str, hint: str | None = None) -> None:
    if sys.stderr.isatty():
        print(f"{_RED}{_BOLD}ERROR:{_RESET} {msg}", file=sys.stderr)
        if hint:
            print(f"{_DIM}Hint:{_RESET} {hint}", file=sys.stderr)
    else:
        print(f"ERROR: {strip_ansi(msg)}", file=sys.stderr)
        if hint:
            print(f"Hint: {strip_ansi(hint)}", file=sys.stderr)


def emit_json(payload: Dict[str, Any]) -> None:
    print(json.dumps(payload, indent=2))


def _paths(sock_dir: str) -> Dict[str, Path]:
    base = Path(sock_dir)
    return {
        "base": base,
        "spine_sock": base / SPINE_SOCK_NAME,
        "policy_sock": base / POLICY_SOCK_NAME,
        "spine_pid": base / SPINE_PID_NAME,
        "policy_pid": base / POLICY_PID_NAME,
        "spine_log": base / "microgoose-spine.log",
        "policy_log": base / "microgoose-policy.log",
    }


def _wait_socket_ping(sock_path: Path, timeout_sec: float = 4.0) -> bool:
    deadline = time.perf_counter() + timeout_sec
    while time.perf_counter() < deadline:
        if sock_path.exists():
            try:
                resp = unix_rpc_call(sock_path, {"cmd": "ping"}, timeout_sec=0.4)
                if resp.get("ok"):
                    return True
            except OSError:
                pass
        time.sleep(0.04)
    return False


def _stop_pid_file(pid_path: Path) -> bool:
    if not pid_path.is_file():
        return False
    try:
        pid = int(pid_path.read_text(encoding="utf-8").strip())
    except ValueError:
        pid_path.unlink(missing_ok=True)
        return False

    try:
        os.kill(pid, signal.SIGTERM)
    except ProcessLookupError:
        pid_path.unlink(missing_ok=True)
        return False

    for _ in range(40):
        try:
            os.kill(pid, 0)
            time.sleep(0.03)
        except ProcessLookupError:
            pid_path.unlink(missing_ok=True)
            return True

    try:
        os.kill(pid, signal.SIGKILL)
    except ProcessLookupError:
        pass
    pid_path.unlink(missing_ok=True)
    return True


def _cmd_daemon(args: argparse.Namespace) -> int:
    p = _paths(args.sock_dir)
    p["base"].mkdir(parents=True, exist_ok=True)

    if args.daemon_action == "start":
        # Stop any stale instances on the same sock_dir first
        _stop_daemon_pair(p)

        runtime_root = str(Path(__file__).resolve().parents[1])
        env = dict(os.environ)
        existing_pp = env.get("PYTHONPATH", "")
        env["PYTHONPATH"] = f"{runtime_root}:{existing_pp}" if existing_pp else runtime_root

        spine_cmd = [sys.executable, "-m", "goosectl.spine_daemon", "--sock-dir", str(p["base"])]
        if args.sim:
            spine_cmd.append("--sim")
        else:
            spine_cmd.extend(["--port", args.port, "--baud", str(args.baud)])

        with p["spine_log"].open("wb") as slog:
            spine_proc = subprocess.Popen(
                spine_cmd,
                stdout=slog,
                stderr=subprocess.STDOUT,
                env=env,
                start_new_session=True,
            )

        if not _wait_socket_ping(p["spine_sock"], timeout_sec=4.0):
            spine_proc.terminate()
            emit_err(
                f"spine_daemon failed to bind {p['spine_sock']}",
                f"Inspect log output at {p['spine_log']}",
            )
            return 1

        policy_cmd = [sys.executable, "-m", "goosectl.policy_daemon", "--sock-dir", str(p["base"])]
        with p["policy_log"].open("wb") as plog:
            policy_proc = subprocess.Popen(
                policy_cmd,
                stdout=plog,
                stderr=subprocess.STDOUT,
                env=env,
                start_new_session=True,
            )

        if not _wait_socket_ping(p["policy_sock"], timeout_sec=4.0):
            policy_proc.terminate()
            _stop_pid_file(p["spine_pid"])
            emit_err(
                f"policy_daemon failed to bind {p['policy_sock']}",
                f"Inspect log output at {p['policy_log']}",
            )
            return 1

        if args.json:
            emit_json(
                {
                    "status": "ok",
                    "spine_pid": spine_proc.pid,
                    "policy_pid": policy_proc.pid,
                    "spine_socket": str(p["spine_sock"]),
                    "policy_socket": str(p["policy_sock"]),
                    "backend": "sim" if args.sim else f"serial:{args.port}@{args.baud}",
                }
            )
        else:
            mode_label = "200 Hz sim plant" if args.sim else f"UART {args.port} @ {args.baud} bps"
            emit_ok(
                f"Started spine_daemon (pid {spine_proc.pid}, {mode_label}) and "
                f"policy_daemon (pid {policy_proc.pid}, 50 Hz) in {p['base']}."
            )
        return 0

    if args.daemon_action == "stop":
        stopped = _stop_daemon_pair(p)
        if args.json:
            emit_json({"status": "ok", "stopped": stopped, "sock_dir": str(p["base"])})
        else:
            emit_ok(f"Stopped goosectl daemons in {p['base']} (active_stopped={stopped}).")
        return 0

    emit_err(f"Unsupported daemon action '{args.daemon_action}'", "Use `goosectl daemon start` or `stop`.")
    return 1


def _stop_daemon_pair(p: Dict[str, Path]) -> bool:
    any_stopped = False
    for sock_key in ("policy_sock", "spine_sock"):
        sp = p[sock_key]
        if sp.exists():
            try:
                unix_rpc_call(sp, {"cmd": "shutdown"}, timeout_sec=0.5)
                any_stopped = True
            except OSError:
                pass
    time.sleep(0.06)
    if _stop_pid_file(p["policy_pid"]):
        any_stopped = True
    if _stop_pid_file(p["spine_pid"]):
        any_stopped = True
    p["policy_sock"].unlink(missing_ok=True)
    p["spine_sock"].unlink(missing_ok=True)
    return any_stopped


def _call_policy_or_fail(sock_dir: str, req: Dict[str, Any], timeout_sec: float = 4.0) -> Dict[str, Any] | None:
    p = _paths(sock_dir)
    if not p["policy_sock"].exists():
        emit_err(
            f"Policy daemon socket not found at {p['policy_sock']}.",
            "Start the runtime with `goosectl daemon start --sim` (or specify `--port /dev/ttyS3`).",
        )
        return None
    try:
        resp = unix_rpc_call(p["policy_sock"], req, timeout_sec=timeout_sec)
    except OSError as exc:
        emit_err(
            f"Cannot reach policy_daemon at {p['policy_sock']}: {exc}",
            "Restart daemons with `goosectl daemon start --sim`.",
        )
        return None
    if not resp.get("ok"):
        err_msg = str(resp.get("error", "Unknown daemon error"))
        hint = "Check `goosectl status` for active mode or latched faults."
        if "policy load" in err_msg:
            hint = "Load an ONNX policy first with `goosectl policy load <path.onnx>`."
        elif "stand ramp" in err_msg:
            hint = "Wait for stand readiness with `goosectl stand`."
        elif "ESTOP" in err_msg or "CROUCH_ROLLBACK" in err_msg:
            hint = "Clear fault and re-stand with `goosectl stand` once the robot is upright and VBAT >= 6.1 V."
        emit_err(err_msg, hint)
        return None
    return resp


def _cmd_health(args: argparse.Namespace) -> int:
    p = _paths(args.sock_dir)
    try:
        sp = unix_rpc_call(p["spine_sock"], {"cmd": "ping"}, timeout_sec=0.8)
        pol = unix_rpc_call(p["policy_sock"], {"cmd": "ping"}, timeout_sec=0.8)
    except OSError as exc:
        emit_err(
            f"Runtime health check failed in {p['base']}: {exc}",
            "Run `goosectl daemon start --sim` to launch spine_daemon and policy_daemon.",
        )
        return 1

    if args.json:
        emit_json({"status": "ok", "spine": sp, "policy": pol})
    else:
        emit_ok(
            f"spine_daemon (tick {sp.get('tick')}) and policy_daemon "
            f"(tick {pol.get('tick')}, mode {pol.get('mode')}) healthy."
        )
    return 0


def _cmd_status(args: argparse.Namespace) -> int:
    resp = _call_policy_or_fail(args.sock_dir, {"cmd": "status"})
    if resp is None:
        return 1
    st = resp["status"]
    if args.json:
        emit_json({"status": "ok", **st})
    else:
        rpy = st["torso_rpy_rad"]
        emit_ok(
            f"mode={_CYAN if sys.stdout.isatty() else ''}{st['mode']}{_RESET if sys.stdout.isatty() else ''} "
            f"torque={st['torque_enabled']} stand_ready={st['stand_ready']} "
            f"tick={st['policy_tick']} (dt={st['last_loop_dt_ms']:.2f} ms, infer={st['last_infer_ms']:.2f} ms) "
            f"rpy=({rpy[0]:+.3f},{rpy[1]:+.3f},{rpy[2]:+.3f}) rad "
            f"vbat={st['vbat_v']:.2f} V ibus={st['bus_current_a']:.2f} A ({st['bus_watts']:.2f} W) "
            f"beak={st['beak_mode']}({st['beak_present_rad']:.3f} rad)"
        )
    return 0


def _cmd_stand(args: argparse.Namespace) -> int:
    wait_flag = not bool(args.no_wait)
    resp = _call_policy_or_fail(
        args.sock_dir,
        {"cmd": "stand", "wait": wait_flag},
        timeout_sec=5.0,
    )
    if resp is None:
        return 1
    st = resp["status"]
    if args.json:
        emit_json({"status": "ok", **st})
    else:
        emit_ok(
            f"Stand mode engaged (mode={st['mode']}, stand_ready={st['stand_ready']}, "
            f"torque={st['torque_enabled']}, vbat={st['vbat_v']:.2f} V)."
        )
    return 0


def _cmd_walk(args: argparse.Namespace) -> int:
    resp = _call_policy_or_fail(
        args.sock_dir,
        {
            "cmd": "walk",
            "vx": args.vx,
            "vy": args.vy,
            "wz": args.wz,
            "head_pitch": args.head_pitch,
            "head_yaw": args.head_yaw,
            "head_roll": args.head_roll,
        },
    )
    if resp is None:
        return 1
    st = resp["status"]
    if args.json:
        emit_json({"status": "ok", **st})
    else:
        v = st["velocity_cmd"]
        emit_ok(
            f"Walking at 50 Hz with vx={v[0]:+.3f} m/s, vy={v[1]:+.3f} m/s, wz={v[2]:+.3f} rad/s "
            f"(policy={st['policy_path']})."
        )
    return 0


def _cmd_policy(args: argparse.Namespace) -> int:
    if args.policy_action == "load":
        resp = _call_policy_or_fail(
            args.sock_dir,
            {"cmd": "policy_load", "path": args.onnx_path, "action_scale": args.action_scale},
        )
        if resp is None:
            return 1
        if args.json:
            emit_json({"status": "ok", **resp})
        else:
            emit_ok(
                f"Hot-loaded ONNX policy {resp['policy_path']} "
                f"({resp['input_name']} -> {resp['output_name']}, warmup={resp['warmup_ms']:.2f} ms, "
                f"torque_enabled={resp['torque_enabled']})."
            )
        return 0

    if args.policy_action == "reset":
        resp = _call_policy_or_fail(args.sock_dir, {"cmd": "policy_reset"})
        if resp is None:
            return 1
        st = resp["status"]
        if args.json:
            emit_json({"status": "ok", **st})
        else:
            emit_ok(
                f"Reset policy state (last_actions zeroed, gait phase reset, torque_enabled={st['torque_enabled']})."
            )
        return 0

    emit_err(f"Unknown policy subcommand '{args.policy_action}'", "Use `goosectl policy load <onnx>` or `reset`.")
    return 1


def _cmd_honk(args: argparse.Namespace) -> int:
    resp = _call_policy_or_fail(
        args.sock_dir,
        {"cmd": "beak", "style": args.style, "duration": args.duration},
    )
    if resp is None:
        return 1
    st = resp["status"]
    if args.json:
        emit_json({"status": "ok", "beak_mode": resp["beak_mode"], "status": st})
    else:
        emit_ok(
            f"Triggered 15th-DoF beak '{resp['beak_mode']}' alongside mode={st['mode']} "
            f"(locomotion joints unperturbed)."
        )
    return 0


def _cmd_estop(args: argparse.Namespace) -> int:
    resp = _call_policy_or_fail(args.sock_dir, {"cmd": "estop", "reason": args.reason})
    if resp is None:
        return 1
    st = resp["status"]
    if args.json:
        emit_json({"status": "ok", **st})
    else:
        emit_ok(
            f"Emergency stop latched (mode={st['mode']}, torque_enabled={st['torque_enabled']}, "
            f"reason={st['last_fault_reason']})."
        )
    return 0


def _cmd_monitor(args: argparse.Namespace) -> int:
    timeout = max(4.0, args.ticks * 0.05 + 2.5)
    resp = _call_policy_or_fail(args.sock_dir, {"cmd": "monitor", "ticks": args.ticks}, timeout_sec=timeout)
    if resp is None:
        return 1
    samples = resp["samples"]
    if args.json:
        emit_json({"status": "ok", "count": len(samples), "samples": samples})
    else:
        dts = [s["last_loop_dt_ms"] for s in samples] or [0.0]
        last = samples[-1] if samples else {}
        emit_ok(
            f"Captured {len(samples)} ticks @ 50 Hz "
            f"(mean_dt={sum(dts)/len(dts):.2f} ms, max_dt={max(dts):.2f} ms, "
            f"final_mode={last.get('mode')}, vbat={last.get('vbat_v', 0.0):.2f} V)."
        )
    return 0


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="goosectl",
        description="Onboard 50 Hz multi-daemon control CLI for the 15-DoF Microgoose biped",
    )
    parser.add_argument("--sock-dir", default=DEFAULT_SOCK_DIR, help="Socket directory (default: /tmp)")
    sub = parser.add_subparsers(dest="subcmd", required=True)

    # daemon start|stop
    p_daemon = sub.add_parser("daemon", help="Start or stop spine_daemon and policy_daemon")
    p_daemon.add_argument("daemon_action", choices=("start", "stop"), help="Lifecycle action")
    p_daemon.add_argument("--sim", action="store_true", help="Run simulated STM32G431 + XL330 plant")
    p_daemon.add_argument("--port", default="/dev/ttyS3", help="Serial UART port for STM32G431 spine")
    p_daemon.add_argument("--baud", type=int, default=1_000_000, help="Serial baud rate")
    p_daemon.add_argument("--sock-dir", default=DEFAULT_SOCK_DIR, help="Socket directory")
    p_daemon.add_argument("--json", action="store_true", help="Emit JSON output")
    p_daemon.set_defaults(func=_cmd_daemon)

    # health
    p_health = sub.add_parser("health", help="Check spine_daemon and policy_daemon IPC health")
    p_health.add_argument("--sock-dir", default=DEFAULT_SOCK_DIR, help="Socket directory")
    p_health.add_argument("--json", action="store_true", help="Emit JSON output")
    p_health.set_defaults(func=_cmd_health)

    # status
    p_status = sub.add_parser("status", help="Read current 50 Hz runtime and RobotState telemetry")
    p_status.add_argument("--sock-dir", default=DEFAULT_SOCK_DIR, help="Socket directory")
    p_status.add_argument("--json", action="store_true", help="Emit JSON output")
    p_status.set_defaults(func=_cmd_status)

    # stand
    p_stand = sub.add_parser("stand", help="Execute smooth 1.5 s minimum-jerk ramp to standing pose")
    p_stand.add_argument("--no-wait", action="store_true", help="Return immediately while ramp executes")
    p_stand.add_argument("--sock-dir", default=DEFAULT_SOCK_DIR, help="Socket directory")
    p_stand.add_argument("--json", action="store_true", help="Emit JSON output")
    p_stand.set_defaults(func=_cmd_stand)

    # walk
    p_walk = sub.add_parser("walk", help="Engage 50 Hz ONNX walking policy with velocity targets")
    p_walk.add_argument("--vx", type=float, default=0.15, help="Forward velocity [m/s]")
    p_walk.add_argument("--vy", type=float, default=0.0, help="Lateral velocity [m/s]")
    p_walk.add_argument("--wz", type=float, default=0.0, help="Yaw rate [rad/s]")
    p_walk.add_argument("--head-pitch", type=float, default=None, help="Head pitch command [rad]")
    p_walk.add_argument("--head-yaw", type=float, default=None, help="Head yaw command [rad]")
    p_walk.add_argument("--head-roll", type=float, default=None, help="Head roll command [rad]")
    p_walk.add_argument("--sock-dir", default=DEFAULT_SOCK_DIR, help="Socket directory")
    p_walk.add_argument("--json", action="store_true", help="Emit JSON output")
    p_walk.set_defaults(func=_cmd_walk)

    # policy load|reset
    p_pol = sub.add_parser("policy", help="Live-load or reset the 61 -> 14 ONNX locomotion policy")
    pol_sub = p_pol.add_subparsers(dest="policy_action", required=True)

    p_pload = pol_sub.add_parser("load", help="Hot-load ONNX policy without dropping servo torque")
    p_pload.add_argument("onnx_path", help="Path to 61 -> 14 ONNX policy file")
    p_pload.add_argument("--action-scale", type=float, default=None, help="Override ONNX metadata action scale")
    p_pload.add_argument("--sock-dir", default=DEFAULT_SOCK_DIR, help="Socket directory")
    p_pload.add_argument("--json", action="store_true", help="Emit JSON output")
    p_pload.set_defaults(func=_cmd_policy)

    p_preset = pol_sub.add_parser("reset", help="Zero last_actions and gait phase without torque drop")
    p_preset.add_argument("--sock-dir", default=DEFAULT_SOCK_DIR, help="Socket directory")
    p_preset.add_argument("--json", action="store_true", help="Emit JSON output")
    p_preset.set_defaults(func=_cmd_policy)

    # honk (15th-DoF beak controller)
    p_honk = sub.add_parser("honk", help="Drive 15th-DoF expressive beak (honk, chatter, open, close)")
    p_honk.add_argument(
        "--style",
        choices=("honk", "chatter", "open", "close"),
        default="honk",
        help="Beak motion profile (default: honk)",
    )
    p_honk.add_argument("--duration", type=float, default=None, help="Optional profile duration [s]")
    p_honk.add_argument("--sock-dir", default=DEFAULT_SOCK_DIR, help="Socket directory")
    p_honk.add_argument("--json", action="store_true", help="Emit JSON output")
    p_honk.set_defaults(func=_cmd_honk)

    # estop
    p_estop = sub.add_parser("estop", help="Latch immediate torque-safe emergency stop")
    p_estop.add_argument("--reason", default="operator_cli_estop", help="Reason recorded in telemetry")
    p_estop.add_argument("--sock-dir", default=DEFAULT_SOCK_DIR, help="Socket directory")
    p_estop.add_argument("--json", action="store_true", help="Emit JSON output")
    p_estop.set_defaults(func=_cmd_estop)

    # monitor
    p_mon = sub.add_parser("monitor", help="Stream N consecutive 50 Hz telemetry ticks")
    p_mon.add_argument("--ticks", type=int, default=10, help="Number of 50 Hz ticks to capture")
    p_mon.add_argument("--sock-dir", default=DEFAULT_SOCK_DIR, help="Socket directory")
    p_mon.add_argument("--json", action="store_true", help="Emit JSON output")
    p_mon.set_defaults(func=_cmd_monitor)

    return parser


def main(argv: list[str] | None = None) -> int:
    parser = build_parser()
    args = parser.parse_args(argv)
    return int(args.func(args))


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