#!/usr/bin/python3
# blob:summary=Set up a drawing tablet: screen mapping, active area, rotation and relative mode
# blob:args=[status|area <x> <y> <width> <height>|preset full|large|medium|small|ratio|rotation 0|90|180|270|relative on|off|reset|apply]
# blob:group=tablet

from __future__ import annotations

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

STATE_FILE = Path.home() / ".local" / "state" / "blob" / "tablet.conf"
DEFAULT_NAME = "hanvon-ugee-6-inch-pentablet-pen"
TABLET_WORDS = ("ugee", "xp-pen", "xppen", "hanvon", "star-g", "deco")
TABLET_WIDTH_MM = 152.4
TABLET_HEIGHT_MM = 101.6
MODEL = "XPPen Star G640"
ROTATIONS = {"0": 0, "90": 1, "180": 2, "270": 3}
NAME_PATTERN = re.compile(r"[a-z0-9:._-]+")
PRESETS = {"full": 1.0, "large": 0.75, "medium": 0.5, "small": 0.35}


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 if result.returncode == 0 else ""


def default_settings() -> dict[str, Any]:
  return {"name": DEFAULT_NAME, "x": 0.0, "y": 0.0, "width": TABLET_WIDTH_MM, "height": TABLET_HEIGHT_MM, "rotation": "0", "relative": False}


def load() -> dict[str, Any]:
  settings = default_settings()
  try:
    lines = STATE_FILE.read_text(encoding="utf-8").splitlines()
  except OSError:
    return settings
  for line in lines:
    key, _, value = line.partition("=")
    key, value = key.strip(), value.strip()
    if key == "name" and NAME_PATTERN.fullmatch(value):
      settings["name"] = value
    elif key in ("x", "y", "width", "height"):
      try:
        settings[key] = float(value)
      except ValueError:
        pass
    elif key == "transform":
      settings["rotation"] = {str(index): degrees for degrees, index in ROTATIONS.items()}.get(value, "0")
    elif key == "relative":
      settings["relative"] = value == "true"
  return clamp(settings)


def clamp(settings: dict[str, Any]) -> dict[str, Any]:
  settings["width"] = min(TABLET_WIDTH_MM, max(10.0, settings["width"]))
  settings["height"] = min(TABLET_HEIGHT_MM, max(10.0, settings["height"]))
  settings["x"] = min(TABLET_WIDTH_MM - settings["width"], max(0.0, settings["x"]))
  settings["y"] = min(TABLET_HEIGHT_MM - settings["height"], max(0.0, settings["y"]))
  return settings


def save(settings: dict[str, Any]) -> None:
  STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
  lines = [
    f"name={settings['name']}",
    f"x={settings['x']:.1f}",
    f"y={settings['y']:.1f}",
    f"width={settings['width']:.1f}",
    f"height={settings['height']:.1f}",
    f"transform={ROTATIONS[settings['rotation']]}",
    f"relative={'true' if settings['relative'] else 'false'}",
  ]
  temporary = STATE_FILE.with_suffix(".tmp")
  temporary.write_text("\n".join(lines) + "\n", encoding="utf-8")
  temporary.replace(STATE_FILE)


def connected_tablets() -> list[str]:
  try:
    devices = json.loads(run(["hyprctl", "devices", "-j"]) or "{}")
  except ValueError:
    return []
  return [str(tablet.get("name", "")) for tablet in devices.get("tablets", []) if tablet.get("name")]


def detect(settings: dict[str, Any]) -> bool:
  for name in connected_tablets():
    if any(word in name.lower() for word in TABLET_WORDS) and NAME_PATTERN.fullmatch(name):
      if settings["name"] != name:
        settings["name"] = name
        save(settings)
      return True
  return settings["name"] in connected_tablets()


def apply(settings: dict[str, Any]) -> None:
  lua = (
    "hl.device({ name = \"%s\", active_area_position = { %.1f, %.1f }, active_area_size = { %.1f, %.1f }, "
    "transform = %d, relative_input = %s })"
  ) % (
    settings["name"], settings["x"], settings["y"], settings["width"], settings["height"],
    ROTATIONS[settings["rotation"]], "true" if settings["relative"] else "false",
  )
  run(["hyprctl", "eval", lua])


def mapping() -> dict[str, Any]:
  try:
    return json.loads(run(["blob-toggle-tablet", "status"]) or "{}")
  except ValueError:
    return {}


def monitors() -> list[dict[str, Any]]:
  try:
    raw = json.loads(run(["hyprctl", "monitors", "-j"]) or "[]")
  except ValueError:
    return []
  return [
    {"name": monitor["name"], "width": monitor["width"], "height": monitor["height"],
     "transform": monitor.get("transform", 0), "focused": bool(monitor.get("focused")),
     "description": monitor.get("description", "")}
    for monitor in raw
  ]


def target_ratio(settings: dict[str, Any]) -> float:
  screens = monitors()
  mode = mapping().get("mode", "all")
  chosen = [screen for screen in screens if screen["name"] == mode] or [screen for screen in screens if screen["focused"]]
  if mode == "all" and screens:
    left = sum(screen["width"] for screen in screens)
    ratio = left / max(screen["height"] for screen in screens)
  elif chosen:
    screen = chosen[0]
    width, height = (screen["height"], screen["width"]) if screen["transform"] % 2 else (screen["width"], screen["height"])
    ratio = width / height
  else:
    ratio = 16 / 9
  return 1 / ratio if settings["rotation"] in ("90", "270") else ratio


def preset(settings: dict[str, Any], name: str) -> None:
  if name == "ratio":
    ratio = target_ratio(settings)
    width, height = TABLET_WIDTH_MM, TABLET_WIDTH_MM / ratio
    if height > TABLET_HEIGHT_MM:
      width, height = TABLET_HEIGHT_MM * ratio, TABLET_HEIGHT_MM
  else:
    scale = PRESETS[name]
    width, height = TABLET_WIDTH_MM * scale, TABLET_HEIGHT_MM * scale
  settings.update(width=width, height=height, x=(TABLET_WIDTH_MM - width) / 2, y=(TABLET_HEIGHT_MM - height) / 2)


def status() -> dict[str, Any]:
  settings = load()
  is_connected = detect(settings)
  return {
    "model": MODEL,
    "name": settings["name"],
    "connected": is_connected,
    "tabletWidth": TABLET_WIDTH_MM,
    "tabletHeight": TABLET_HEIGHT_MM,
    "area": {"x": settings["x"], "y": settings["y"], "width": settings["width"], "height": settings["height"]},
    "rotation": settings["rotation"],
    "relative": settings["relative"],
    "mapping": mapping(),
    "monitors": monitors(),
    "screenRatio": round(target_ratio(settings), 4),
  }


def number(text: str) -> float:
  try:
    return float(text)
  except ValueError:
    print(f"Not a number: {text}", file=sys.stderr)
    raise SystemExit(2)


def main(arguments: list[str]) -> int:
  action = arguments[0] if arguments else "status"
  value = arguments[1] if len(arguments) > 1 else ""
  if action == "status":
    print(json.dumps(status()))
    return 0
  settings = load()
  detect(settings)
  if action == "area" and len(arguments) == 5:
    settings.update(x=number(arguments[1]), y=number(arguments[2]), width=number(arguments[3]), height=number(arguments[4]))
  elif action == "preset" and (value in PRESETS or value == "ratio"):
    preset(settings, value)
  elif action == "rotation" and value in ROTATIONS:
    settings["rotation"] = value
  elif action == "relative" and value in ("on", "off"):
    settings["relative"] = value == "on"
  elif action == "reset":
    settings = dict(default_settings(), name=settings["name"])
  elif action != "apply":
    print("blob-tablet does not understand: " + " ".join(arguments), file=sys.stderr)
    return 2
  save(clamp(settings))
  apply(settings)
  return 0


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