#!/usr/bin/env python3
from __future__ import annotations

import os
import subprocess
import sys
from pathlib import Path

import remote_dispatch
from command_router import (
    HEALTH_STALE_SECONDS,
    CodexAdapter,
    CommandRouter,
    detect_project_name,
    load_health as _load_health,
    parse_account_override,
)
from health_client import AccountSnapshot, HealthStatus


def load_health(path: Path | None = None) -> dict[str, AccountSnapshot]:
    return _load_health(
        path,
        stale_after_s=HEALTH_STALE_SECONDS,
        tool_name="cdx",
        health_snapshot_tool="codex",
    )


def main(argv: list[str]) -> int:
    return CommandRouter(
        CodexAdapter(),
        detect_project_name=detect_project_name,
        parse_account_override=parse_account_override,
    ).main(argv)


def _deny_headless_local_dispatch() -> None:
    """No agent compute on the workstation. A terminal on any std fd means the owner is
    driving this and it proceeds untouched; a headless caller exits 97. Inside a sandbox
    container the machine already is the execution plane, so the run proceeds."""
    if remote_dispatch.in_container():
        return
    guard = Path.home() / ".claude" / "bin" / "local-dispatch-guard"
    if os.access(guard, os.X_OK):
        rc = subprocess.run([str(guard), "cdx"]).returncode
        if rc != 0:
            raise SystemExit(rc)
        return
    if not any(os.isatty(fd) for fd in (0, 1, 2)):
        print(f"cdx: local-dispatch-guard missing at {guard} — refusing headless dispatch", file=sys.stderr)
        raise SystemExit(97)


if __name__ == "__main__":
    _deny_headless_local_dispatch()
    os.environ.setdefault("STALL_GUARD_NOTIFY", "1")
    raise SystemExit(main(sys.argv))
