"""Restart PowerToys so it reloads its Keyboard Manager configuration."""

import os
import subprocess
import time


def powertoys_restart() -> None:
    """Kill PowerToys processes and relaunch the application.

    Kills PowerToys.exe and PowerToys.KeyboardManagerEngine.exe using taskkill.exe,
    waits 1 second for them to shut down cleanly, then relaunches PowerToys.exe via
    cmd.exe /c start. Works from WSL (invokes taskkill.exe and cmd.exe from the
    Windows system32 path).

    The PowerToys executable is resolved using the $USER env var to build the
    standard AppData path. To override the exe path, set $POWERTOYS_EXE.

    Raises:
        RuntimeError: If taskkill.exe or cmd.exe cannot be found/invoked.
        FileNotFoundError: If the PowerToys.exe path cannot be resolved.
    """
    user = os.environ.get("USER") or os.environ.get("USERNAME", "")
    powertoys_exe = os.environ.get(
        "POWERTOYS_EXE",
        f"/mnt/c/Users/{user}/AppData/Local/PowerToys/PowerToys.exe",
    )

    # Kill running instances (ignore errors if not running)
    for process_name in ("PowerToys.exe", "PowerToys.KeyboardManagerEngine.exe"):
        subprocess.run(
            ["taskkill.exe", "/IM", process_name, "/F"],
            capture_output=True,
        )

    time.sleep(1)

    # Relaunch via cmd.exe /c start to detach from the current process
    # Convert WSL path to Windows path for cmd.exe
    win_exe = powertoys_exe
    if powertoys_exe.startswith("/mnt/c/"):
        win_exe = "C:\\" + powertoys_exe[len("/mnt/c/"):].replace("/", "\\")

    subprocess.Popen(
        ["cmd.exe", "/c", "start", "", win_exe],
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )
