from __future__ import annotations

import ctypes
import os
import time
from typing import Any, Dict


class ProcessRemediation:
    """Simple, audited process control for confirmed malicious or dangerous processes."""

    def __init__(self, logger=None):
        self.logger = logger

    @staticmethod
    def _open_process(pid: int, desired_access: int):
        if os.name != "nt":
            return None
        if pid <= 0:
            return None
        handle = ctypes.windll.kernel32.OpenProcess(desired_access, False, pid)
        return handle

    def terminate(self, pid: int, *, force: bool = False) -> Dict[str, Any]:
        if pid <= 0:
            return {"pid": pid, "status": "invalid_pid", "force": force}

        if os.name != "nt":
            return {"pid": pid, "status": "unsupported_platform", "force": force}

        handle = self._open_process(pid, 0x0001)
        if not handle:
            return {"pid": pid, "status": "missing", "force": force}

        try:
            result = ctypes.windll.kernel32.TerminateProcess(handle, 1)
            if not result:
                return {"pid": pid, "status": "permission_denied", "force": force}
            return {"pid": pid, "status": "terminated", "force": force}
        finally:
            ctypes.windll.kernel32.CloseHandle(handle)

    def verify_stopped(self, pid: int) -> bool:
        if os.name != "nt":
            return True
        if pid <= 0:
            return True

        sync_access = 0x00100000  # SYNCHRONIZE
        for _ in range(10):
            handle = self._open_process(pid, sync_access)
            if not handle:
                return True
            try:
                wait_result = ctypes.windll.kernel32.WaitForSingleObject(handle, 0)
                if wait_result == 0:
                    return True
            finally:
                ctypes.windll.kernel32.CloseHandle(handle)
            time.sleep(0.05)
        return False
