#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Orphan pulse process cleanup for swarm stop."""
from __future__ import annotations

import os
import subprocess

from pulse.tasks.task_ops import kill_process


def kill_orphan_pulse_processes() -> int:
    """Find and kill orphaned pulse worker processes not in the PID registry.

    After tree-killing tracked PIDs, stragglers can remain if the registry
    was cleared by a previous `swarm stop` while children were still alive.
    """
    killed = 0
    markers = ("pulse_worker", "cmd_swarm", "pulse.cli.cmd_swarm",
               "pulse.workers.pulse_worker")
    if os.name == "nt":
        try:
            out = subprocess.check_output(
                ["wmic", "process", "where",
                 "Name='python.exe' or Name='python3.exe'",
                 "get", "ProcessId,CommandLine"],
                stderr=subprocess.DEVNULL, text=True,
                encoding="utf-8", errors="replace",
                creationflags=0x08000000,
            )
            my_pid = os.getpid()
            for line in out.splitlines():
                if not any(m in line for m in markers):
                    continue
                parts = line.strip().rsplit(None, 1)
                if not parts:
                    continue
                try:
                    pid = int(parts[-1])
                except ValueError:
                    continue
                if pid == my_pid:
                    continue
                try:
                    kill_process(pid)
                    killed += 1
                except Exception:
                    pass
        except Exception:
            pass
    else:
        import signal
        try:
            out = subprocess.check_output(
                ["ps", "aux"], text=True, encoding="utf-8", errors="replace",
            )
            my_pid = os.getpid()
            for line in out.splitlines():
                if not any(m in line for m in markers):
                    continue
                parts = line.split()
                if len(parts) < 2:
                    continue
                try:
                    pid = int(parts[1])
                except ValueError:
                    continue
                if pid == my_pid:
                    continue
                try:
                    os.kill(pid, signal.SIGKILL)
                    killed += 1
                except (ProcessLookupError, PermissionError):
                    pass
        except Exception:
            pass
    return killed
