#!/usr/bin/python3
# blob:summary=Show connected controllers, keyboards and mice, and switch game mode on or off
# blob:args=[status|on|off|toggle]
# blob:group=games

from __future__ import annotations

import json
import os
import re
import shutil
import subprocess
import sys
from pathlib import Path
from typing import Any

INPUT_DEVICES_FILE = Path("/proc/bus/input/devices")
POWER_SUPPLY_DIRECTORY = Path("/sys/class/power_supply")
STATE_DIRECTORY = Path(os.environ.get("XDG_STATE_HOME", str(Path.home() / ".local" / "state"))) / "blob"
GAME_MODE_FILE = STATE_DIRECTORY / "game-mode.json"
STAY_AWAKE_FILE = STATE_DIRECTORY / "indicators" / "stay-awake"
EV_REPEAT_BIT = 0x100000
BUS_NAMES = {"0003": "usb", "0005": "bluetooth"}
IGNORED_KEYBOARD_WORDS = ("consumer control", "system control", "power button", "video bus", "virtual", "hotkeys", "controller", "gamepad")
IGNORED_MOUSE_WORDS = ("touchpad", "controller", "gamepad", "motion sensors", "virtual")


def run(command: list[str]) -> str:
  try:
    result = subprocess.run(command, capture_output=True, text=True, timeout=5)
  except (OSError, subprocess.TimeoutExpired):
    return ""
  return result.stdout.strip() if result.returncode == 0 else ""


def read_input_devices() -> list[dict[str, str]]:
  try:
    text = INPUT_DEVICES_FILE.read_text(encoding="utf-8", errors="replace")
  except OSError:
    return []
  devices = []
  for block in text.strip().split("\n\n"):
    device = {"name": "", "handlers": "", "bus": "", "uniq": "", "ev": "0"}
    for line in block.splitlines():
      if line.startswith("N: Name="):
        device["name"] = line.split("=", 1)[1].strip().strip('"')
      elif line.startswith("H: Handlers="):
        device["handlers"] = line.split("=", 1)[1].strip()
      elif line.startswith("I: "):
        match = re.search(r"Bus=([0-9a-fA-F]{4})", line)
        device["bus"] = match.group(1).lower() if match else ""
      elif line.startswith("U: Uniq="):
        device["uniq"] = line.split("=", 1)[1].strip().lower()
      elif line.startswith("B: EV="):
        device["ev"] = line.split("=", 1)[1].strip()
    devices.append(device)
  return devices


def has_handler(device: dict[str, str], prefix: str) -> bool:
  return any(handler.startswith(prefix) for handler in device["handlers"].split())


def name_has(device: dict[str, str], words: tuple[str, ...]) -> bool:
  lowered = device["name"].lower()
  return any(word in lowered for word in words)


def battery_for(uniq: str) -> dict[str, Any]:
  if not uniq or not POWER_SUPPLY_DIRECTORY.is_dir():
    return {"battery": None, "charging": False}
  compact = uniq.replace(":", "")
  for supply in POWER_SUPPLY_DIRECTORY.iterdir():
    lowered = supply.name.lower()
    if uniq not in lowered and compact not in lowered.replace(":", "").replace("_", "").replace("-", ""):
      continue
    try:
      capacity = int((supply / "capacity").read_text().strip())
    except (OSError, ValueError):
      continue
    status = ""
    try:
      status = (supply / "status").read_text().strip().lower()
    except OSError:
      pass
    return {"battery": capacity, "charging": status in ("charging", "full")}
  return {"battery": None, "charging": False}


def controller_kind(name: str) -> str:
  lowered = name.lower()
  if any(word in lowered for word in ("xbox", "x-box", "xinput")):
    return "xbox"
  if any(word in lowered for word in ("dualsense", "dualshock", "playstation", "sony", "wireless controller")):
    return "playstation"
  if any(word in lowered for word in ("nintendo", "pro controller", "joy-con")):
    return "nintendo"
  if "steam" in lowered:
    return "steam"
  return "generic"


def find_inputs() -> dict[str, Any]:
  devices = read_input_devices()
  controllers = []
  seen_controllers = set()
  controller_ids = set()
  for device in devices:
    if not has_handler(device, "js"):
      continue
    key = device["uniq"] or device["name"]
    if key in seen_controllers:
      continue
    seen_controllers.add(key)
    if device["uniq"]:
      controller_ids.add(device["uniq"])
    controller = {
      "name": device["name"] or "Controller",
      "kind": controller_kind(device["name"]),
      "connection": BUS_NAMES.get(device["bus"], "other"),
    }
    controller.update(battery_for(device["uniq"]))
    controllers.append(controller)

  keyboards = []
  mice = []
  for device in devices:
    if device["uniq"] and device["uniq"] in controller_ids:
      continue
    if has_handler(device, "js"):
      continue
    try:
      repeats = int(device["ev"], 16) & EV_REPEAT_BIT
    except ValueError:
      repeats = 0
    if has_handler(device, "kbd") and repeats and not name_has(device, IGNORED_KEYBOARD_WORDS):
      if device["name"] not in keyboards:
        keyboards.append(device["name"])
    if has_handler(device, "mouse") and not name_has(device, IGNORED_MOUSE_WORDS):
      if device["name"] not in mice:
        mice.append(device["name"])

  return {"controllers": controllers, "keyboards": keyboards, "mice": mice}


def read_game_mode() -> dict[str, Any] | None:
  try:
    return json.loads(GAME_MODE_FILE.read_text(encoding="utf-8"))
  except (OSError, ValueError):
    return None


def dnd_enabled() -> bool:
  return run(["blob-shell", "notifications", "dndState"]) == "on"


def power_profile() -> str:
  return run(["powerprofilesctl", "get"]) if shutil.which("powerprofilesctl") else ""


def set_power_profile(profile: str) -> None:
  if profile and shutil.which("powerprofilesctl"):
    run(["powerprofilesctl", "set", profile])


def performance_available() -> bool:
  return "performance" in run(["powerprofilesctl", "list"]) if shutil.which("powerprofilesctl") else False


def refresh_indicators() -> None:
  run(["blob-shell", "-q", "blob.indicators", "refresh"])


def game_mode_on() -> None:
  if read_game_mode() is not None:
    return
  saved = {
    "dnd": dnd_enabled(),
    "stayAwake": STAY_AWAKE_FILE.exists(),
    "powerProfile": power_profile(),
  }
  STATE_DIRECTORY.mkdir(parents=True, exist_ok=True)
  GAME_MODE_FILE.write_text(json.dumps(saved) + "\n", encoding="utf-8")
  run(["blob-shell", "notifications", "setDnd", "on"])
  run(["blob-toggle-idle", "stay-awake"])
  if performance_available():
    set_power_profile("performance")
  run(["blob-hypr-toggle", "game-mode", "on"])
  refresh_indicators()


def game_mode_off() -> None:
  saved = read_game_mode()
  if saved is None:
    return
  run(["blob-shell", "notifications", "setDnd", "on" if saved.get("dnd") else "off"])
  run(["blob-toggle-idle", "stay-awake" if saved.get("stayAwake") else "allow-idle"])
  set_power_profile(str(saved.get("powerProfile") or ""))
  run(["blob-hypr-toggle", "game-mode", "off"])
  try:
    GAME_MODE_FILE.unlink()
  except OSError:
    pass
  refresh_indicators()


def status() -> dict[str, Any]:
  inputs = find_inputs()
  inputs["input"] = "controller" if inputs["controllers"] else "keyboard-mouse"
  inputs["gameMode"] = read_game_mode() is not None
  inputs["powerProfile"] = power_profile()
  inputs["performanceAvailable"] = performance_available()
  return inputs


def main(arguments: list[str]) -> int:
  action = arguments[0] if arguments else "status"
  if action == "status":
    print(json.dumps(status()))
  elif action == "on":
    game_mode_on()
  elif action == "off":
    game_mode_off()
  elif action == "toggle":
    if read_game_mode() is None:
      game_mode_on()
    else:
      game_mode_off()
  else:
    print("Usage: blob-games-mode [status|on|off|toggle]", file=sys.stderr)
    return 1
  return 0


if __name__ == "__main__":
  sys.exit(main(sys.argv[1:]))
