import json
import os
import signal
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 _setsid_if_possible() -> Optional[int]:
    if os.name != "posix":
        return None
    try:
        os.setsid()
    except OSError:
        return None
    return os.getpgrp()


def _install_parent_death_signal() -> str:
    if not sys.platform.startswith("linux"):
        return "none"

    try:
        import ctypes
    except ImportError:
        return "none"

    libc = ctypes.CDLL(None, use_errno=True)
    prctl = getattr(libc, "prctl", None)
    if prctl is None:
        return "none"

    prctl.argtypes = [ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong]
    prctl.restype = ctypes.c_int

    PR_SET_PDEATHSIG = 1
    if prctl(PR_SET_PDEATHSIG, signal.SIGKILL, 0, 0, 0) != 0:
        return "none"
    return "pdeathsig"


def _install_guard() -> Dict[str, object]:
    pgid = _setsid_if_possible()
    guard = _install_parent_death_signal()
    if guard == "none" and pgid is not None:
        guard = "setsid"
    return {
        "pid": os.getpid(),
        "pgid": pgid,
        "guard": guard,
    }


def main(argv: Optional[Sequence[str]] = None) -> int:
    command = _extract_command(sys.argv[1:] if argv is None else argv)
    metadata = _install_guard()
    _write_ready_payload(metadata)
    os.execvpe(command[0], command, os.environ.copy())
    return 0


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