import json
import os
import sys
from typing import Dict, List, Optional, Sequence


def _extract_command(argv: Sequence[str]) -> List[str]:
    args = list(argv)
    if args and args[0] == "--":
        args = args[1:]
    if not args:
        raise SystemExit("worker command is required")
    return args


def _write_ready_payload(payload: Dict[str, object]) -> None:
    fd_value = os.environ.get("SANDAI_SUPERVISOR_READY_FD")
    if not fd_value:
        return

    try:
        fd = int(fd_value)
    except ValueError:
        return

    try:
        data = json.dumps(payload, separators=(",", ":")) + "\n"
        os.write(fd, data.encode("utf-8"))
    finally:
        try:
            os.close(fd)
        except OSError:
            pass


def _install_guard() -> str:
    if os.name != "posix":
        return "none"

    try:
        import caoe  # type: ignore
    except ImportError:
        os.setsid()
        return "setsid"

    caoe.install()
    return "caoe"


def main(argv: Optional[Sequence[str]] = None) -> int:
    command = _extract_command(sys.argv[1:] if argv is None else argv)
    guard = _install_guard()
    _write_ready_payload(
        {
            "pid": os.getpid(),
            "pgid": os.getpgrp() if os.name == "posix" else None,
            "guard": guard,
        }
    )
    os.execvpe(command[0], command, os.environ.copy())
    return 0


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