"""Read and list PowerToys Keyboard Manager shortcuts as human-readable dicts."""

import json
import os

# Windows Virtual Key codes → readable names
VK_CODES: dict[int, str] = {
    91: "lwin", 92: "rwin",
    160: "lshift", 161: "rshift",
    162: "lctrl", 163: "rctrl",
    164: "lalt", 165: "ralt",
    32: "space", 13: "enter", 9: "tab", 27: "esc",
    # F-keys
    112: "f1", 113: "f2", 114: "f3", 115: "f4",
    116: "f5", 117: "f6", 118: "f7", 119: "f8",
    120: "f9", 121: "f10", 122: "f11", 123: "f12",
    # Digits 0-9
    48: "0", 49: "1", 50: "2", 51: "3", 52: "4",
    53: "5", 54: "6", 55: "7", 56: "8", 57: "9",
}
# Letters A-Z (VK 65-90)
for _vk in range(65, 91):
    VK_CODES[_vk] = chr(_vk).lower()


def _vk_to_name(vk: int) -> str:
    """Convert a VK code integer to a readable key name."""
    return VK_CODES.get(vk, str(vk))


def _parse_keys(original_keys: str) -> list[str]:
    """Parse a semicolon-separated VK code string to a list of readable names."""
    if not original_keys:
        return []
    return [_vk_to_name(int(code)) for code in original_keys.split(";") if code]


def powertoys_shortcut_list(config_path: str | None = None) -> list[dict]:
    """Return all global shortcuts from PowerToys Keyboard Manager config.

    Reads the default.json file and returns the list of remapShortcuts.global entries
    with VK codes converted to human-readable key names.

    Args:
        config_path: Absolute path to default.json. If None, uses the POWERTOYS_CONFIG
                     env var or the default WSL path for the current $USER.

    Returns:
        List of dicts with keys: keys, target, args, elevated, exact_match, start_in_dir.
    """
    if config_path is None:
        config_path = os.environ.get("POWERTOYS_CONFIG")
    if config_path is None:
        user = os.environ.get("USER") or os.environ.get("USERNAME", "")
        config_path = (
            f"/mnt/c/Users/{user}/AppData/Local/Microsoft/PowerToys"
            f"/Keyboard Manager/default.json"
        )

    with open(config_path, "r", encoding="utf-8") as f:
        data = json.load(f)

    shortcuts = data.get("remapShortcuts", {}).get("global", [])
    result = []
    for entry in shortcuts:
        result.append({
            "keys": _parse_keys(entry.get("originalKeys", "")),
            "target": entry.get("runProgramFilePath", ""),
            "args": entry.get("runProgramArgs", ""),
            "elevated": entry.get("runProgramElevationLevel", 0) != 0,
            "exact_match": entry.get("exactMatch", False),
            "start_in_dir": entry.get("runProgramStartInDir", ""),
        })
    return result
