"""Detect the path of PowerToys Keyboard Manager default.json config file."""

import os
import platform


def powertoys_config_path(user: str | None = None) -> str:
    """Return the path to PowerToys Keyboard Manager default.json.

    Supports three resolution modes (in priority order):
    1. POWERTOYS_CONFIG env var override.
    2. WSL: /mnt/c/Users/<user>/AppData/Local/Microsoft/PowerToys/Keyboard Manager/default.json
       where <user> is the `user` argument, then $USER env var.
    3. Native Windows: %LOCALAPPDATA%/Microsoft/PowerToys/Keyboard Manager/default.json

    Args:
        user: Windows username. If None, reads $USER from env. Only used in WSL mode.

    Returns:
        Absolute path string to default.json (file may or may not exist).
    """
    override = os.environ.get("POWERTOYS_CONFIG")
    if override:
        return override

    relative = "Microsoft/PowerToys/Keyboard Manager/default.json"

    # Detect WSL: check for /mnt/c mount or WSL-specific env vars
    is_wsl = (
        os.path.exists("/mnt/c")
        or "WSL_DISTRO_NAME" in os.environ
        or "WSLENV" in os.environ
    )

    if is_wsl:
        resolved_user = user or os.environ.get("USER") or os.environ.get("USERNAME")
        if not resolved_user:
            raise ValueError(
                "Cannot determine Windows username. Pass user= or set $USER env var."
            )
        return f"/mnt/c/Users/{resolved_user}/AppData/Local/{relative}"

    if platform.system() == "Windows":
        local_app_data = os.environ.get("LOCALAPPDATA", "")
        if not local_app_data:
            raise ValueError("$LOCALAPPDATA env var is not set on this Windows system.")
        return os.path.join(local_app_data, relative)

    # Fallback: assume WSL-style path with $USER
    resolved_user = user or os.environ.get("USER") or os.environ.get("USERNAME", "")
    return f"/mnt/c/Users/{resolved_user}/AppData/Local/{relative}"
