#!/bin/bash
# ==============================================================================
# X64 LIOS - Sovereign Hyprland Monitor Scaling Engine
# Supports Automatic EDID PPI Scaling ("auto") and Fractional Presets (1.0..2.0)
# ==============================================================================

export LC_ALL=C.UTF-8
export LC_NUMERIC=C
UID_NUM=$(id -u)
export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/${UID_NUM}}"
export DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-unix:path=${XDG_RUNTIME_DIR}/bus}"

notify_scale() {
  local title="$1"
  local body="$2"
  local dnd_val
  dnd_val=$(cat "${XDG_RUNTIME_DIR}/x64-shell/dnd" 2>/dev/null || echo "0")
  if [ "$dnd_val" != "1" ] && command -v notify-send >/dev/null 2>&1; then
    notify-send -a "Pantalla X64" "$title" "$body" 2>/dev/null || true
  fi
}

get_focused_info() {
  export HYPRLAND_INSTANCE_SIGNATURE=$(ls -t /run/user/$(id -u)/hypr/ 2>/dev/null | head -n1)
  local mon_info=$(hyprctl monitors -j 2>/dev/null | jq -e -c '.[] | select(.focused == true)' 2>/dev/null)
  if [ -z "$mon_info" ]; then
    mon_info=$(hyprctl monitors -j 2>/dev/null | jq -e -c '.[0]' 2>/dev/null)
  fi
  echo "$mon_info"
}

is_config_auto() {
  local lua_cfg="$HOME/.config/hypr/hyprland.lua"
  if [ -f "$lua_cfg" ] && grep -qE 'scale\s*=\s*"auto"' "$lua_cfg" 2>/dev/null; then
    echo "true"
  else
    echo "false"
  fi
}

case "$1" in
  "status")
    info=$(get_focused_info)
    name=$(echo "$info" | jq -r '.name // "Virtual-1"')
    scale=$(echo "$info" | jq -r '.scale // 1')
    auto_state=$(is_config_auto)
    echo "${name}|${scale}|${auto_state}"
    ;;
  "current"|"")
    info=$(get_focused_info)
    echo "$info" | jq -r '.scale // 1'
    ;;
  "monitor")
    info=$(get_focused_info)
    echo "$info" | jq -r '.name // "Virtual-1"'
    ;;
  "auto"|"AUTO")
    info=$(get_focused_info)
    name=$(echo "$info" | jq -r '.name // "Virtual-1"')
    height=$(echo "$info" | jq -r '.height // 1080')

    export HYPRLAND_INSTANCE_SIGNATURE=$(ls -t /run/user/$(id -u)/hypr/ 2>/dev/null | head -n1)
    mode="preferred"
    if [[ "$name" =~ ^(Virtual|XWAYLAND|qemu|vbox) ]] || [ "$height" -eq 1022 ]; then
      mode="1920x1080@60"
      if [ "$height" -eq 1022 ] || [ "$height" -ne 1080 ]; then
        hyprctl eval "hl.monitor({ output = \"$name\", mode = \"1920x1080@60\", position = \"auto\", scale = 1.0 })" >/dev/null 2>&1
        sleep 0.05
      fi
    fi

    hyprctl eval "hl.monitor({ output = \"$name\", mode = \"$mode\", position = \"auto\", scale = \"auto\" })" >/dev/null 2>&1

    lua_cfg="$HOME/.config/hypr/hyprland.lua"
    if [ -f "$lua_cfg" ]; then
      sed -i -E 's/scale\s*=\s*("auto"|[0-9.]+)/scale    = "auto"/' "$lua_cfg"
    fi

    if [ -f "/etc/skel/.config/hypr/hyprland.lua" ] && [ "$(id -u)" -eq 0 ]; then
      sed -i -E 's/scale\s*=\s*("auto"|[0-9.]+)/scale    = "auto"/' "/etc/skel/.config/hypr/hyprland.lua"
    fi

    notify_scale "Escalado Automático (AUTO)" "Monitor ${name} sincronizado por densidad EDID"
    echo "auto"
    ;;
  *)
    target_scale="$1"
    final_scale=$(awk -v s="$target_scale" 'BEGIN { printf "%g", s }')
    if [ -z "$final_scale" ] || [ "$final_scale" = "0" ]; then
      final_scale="1"
    fi

    info=$(get_focused_info)
    name=$(echo "$info" | jq -r '.name // "Virtual-1"')
    height=$(echo "$info" | jq -r '.height // 1080')

    export HYPRLAND_INSTANCE_SIGNATURE=$(ls -t /run/user/$(id -u)/hypr/ 2>/dev/null | head -n1)
    mode="preferred"
    if [[ "$name" =~ ^(Virtual|XWAYLAND|qemu|vbox) ]] || [ "$height" -eq 1022 ]; then
      mode="1920x1080@60"
      if [ "$height" -eq 1022 ] || [ "$height" -ne 1080 ]; then
        hyprctl eval "hl.monitor({ output = \"$name\", mode = \"1920x1080@60\", position = \"auto\", scale = 1.0 })" >/dev/null 2>&1
        sleep 0.05
      fi
    fi

    hyprctl eval "hl.monitor({ output = \"$name\", mode = \"$mode\", position = \"auto\", scale = $final_scale })" >/dev/null 2>&1

    lua_cfg="$HOME/.config/hypr/hyprland.lua"
    if [ -f "$lua_cfg" ]; then
      sed -i -E "s/scale\s*=\s*(\"auto\"|[0-9.]+)/scale    = $final_scale/" "$lua_cfg"
      if [ "$mode" != "preferred" ]; then
        sed -i -E "s/mode\s*=\s*\"[^\"]+\"/mode     = \"$mode\"/" "$lua_cfg"
      fi
    fi

    if [ -f "/etc/skel/.config/hypr/hyprland.lua" ] && [ "$(id -u)" -eq 0 ]; then
      sed -i -E "s/scale\s*=\s*(\"auto\"|[0-9.]+)/scale    = $final_scale/" "/etc/skel/.config/hypr/hyprland.lua"
      if [ "$mode" != "preferred" ]; then
        sed -i -E "s/mode\s*=\s*\"[^\"]+\"/mode     = \"$mode\"/" "/etc/skel/.config/hypr/hyprland.lua"
      fi
    fi

    pct_label=$(awk -v s="$final_scale" 'BEGIN { printf "%.0f%%", s * 100 }')
    notify_scale "Escala de Monitor: ${pct_label}" "Aplicada en vivo sobre ${name}"
    echo "$final_scale"
    ;;
esac
