#!/usr/bin/env bash
set -euo pipefail

usage() {
  cat <<'USAGE'
BRZ HealthOS web shortcut manager

Usage:
  brz-web-shortcut add "Name" https://example.com [icon-name]
  brz-web-shortcut set-icon "Name" /absolute/path/to/icon.png
  brz-web-shortcut remove "Name"
  brz-web-shortcut list
  brz-web-shortcut gui

Only HTTPS URLs are accepted by default.
USAGE
}

slugify() {
  printf '%s' "$1" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9]+/-/g; s/^-+//; s/-+$//' | cut -c1-60
}

safe_name() {
  printf '%s' "$1" | tr '\r\n' '  ' | sed -E 's/[[:cntrl:]]//g' | cut -c1-100
}

validate_url() {
  [[ "$1" =~ ^https://[^[:space:]]+$ ]]
}

install_shortcut() {
  local raw_name="$1" url="$2" icon="${3:-brz-healthos}" quiet="${4:-false}"
  local name slug desktop_dir app_dir desktop_file app_file
  name="$(safe_name "$raw_name")"
  [[ -n "$name" ]] || { echo "Shortcut name cannot be empty." >&2; exit 2; }
  validate_url "$url" || { echo "Only valid HTTPS URLs are allowed: $url" >&2; exit 2; }
  slug="$(slugify "$name")"
  [[ -n "$slug" ]] || slug="web-shortcut"

  if [[ $EUID -eq 0 ]]; then
    desktop_dir=""
    app_dir="/usr/local/share/applications"
  else
    desktop_dir="${XDG_DESKTOP_DIR:-$HOME/Desktop}"
    app_dir="${XDG_DATA_HOME:-$HOME/.local/share}/applications"
  fi
  mkdir -p "$app_dir"
  app_file="$app_dir/brz-web-${slug}.desktop"

  local -a targets=("$app_file")
  if [[ -n "$desktop_dir" ]]; then
    mkdir -p "$desktop_dir"
    desktop_file="$desktop_dir/${name}.desktop"
    targets+=("$desktop_file")
  fi
  for target in "${targets[@]}"; do
    cat > "$target" <<DESKTOP
[Desktop Entry]
Version=1.0
Type=Application
Name=$name
Comment=BRZ HealthOS managed web shortcut
Exec=xdg-open $url
Icon=$icon
Terminal=false
Categories=Network;Utility;
StartupNotify=true
X-BRZ-Managed=true
X-BRZ-URL=$url
DESKTOP
    chmod 0755 "$target"
    if command -v gio >/dev/null 2>&1; then
      gio set "$target" metadata::trusted true >/dev/null 2>&1 || true
    fi
  done

  if command -v update-desktop-database >/dev/null 2>&1; then
    update-desktop-database "$app_dir" >/dev/null 2>&1 || true
  fi
  if [[ "$quiet" != "true" ]]; then
    echo "Created BRZ web shortcut: $name -> $url"
  fi
}

remove_shortcut() {
  local raw_name="$1" name slug desktop_dir app_dir
  name="$(safe_name "$raw_name")"
  slug="$(slugify "$name")"
  desktop_dir="${XDG_DESKTOP_DIR:-$HOME/Desktop}"
  app_dir="${XDG_DATA_HOME:-$HOME/.local/share}/applications"
  rm -f "$desktop_dir/${name}.desktop" "$app_dir/brz-web-${slug}.desktop"
  if [[ $EUID -eq 0 ]]; then rm -f "/usr/local/share/applications/brz-web-${slug}.desktop"; fi
  echo "Removed BRZ web shortcut: $name"
}

set_icon() {
  local raw_name="$1" icon="$2" name slug app_file changed=0
  name="$(safe_name "$raw_name")"
  slug="$(slugify "$name")"
  [[ "$icon" = /* && -r "$icon" ]] || { echo "Icon must be a readable absolute path." >&2; exit 2; }
  local -a files=("${XDG_DATA_HOME:-$HOME/.local/share}/applications/brz-web-${slug}.desktop" "${XDG_DESKTOP_DIR:-$HOME/Desktop}/${name}.desktop")
  if [[ $EUID -eq 0 ]]; then files=("/usr/local/share/applications/brz-web-${slug}.desktop"); fi
  for app_file in "${files[@]}"; do
    [[ -f "$app_file" ]] || continue
    sed -i "s|^Icon=.*$|Icon=$icon|" "$app_file"
    changed=1
  done
  (( changed == 1 )) || { echo "Managed shortcut not found: $name" >&2; exit 3; }
  update-desktop-database "$(dirname "${files[0]}")" >/dev/null 2>&1 || true
  echo "Updated managed icon: $name"
}

list_shortcuts() {
  local app_dir="${XDG_DATA_HOME:-$HOME/.local/share}/applications"
  shopt -s nullglob
  local f name url
  for f in "$app_dir"/brz-web-*.desktop; do
    name="$(sed -n 's/^Name=//p' "$f" | head -n1)"
    url="$(sed -n 's/^X-BRZ-URL=//p' "$f" | head -n1)"
    printf '%s\t%s\n' "$name" "$url"
  done
}

gui_add() {
  command -v zenity >/dev/null 2>&1 || { echo "zenity is not installed." >&2; exit 1; }
  local result name url
  result="$(zenity --forms \
    --title='BRZ HealthOS — Add Web Shortcut' \
    --text='Create a secure HTTPS shortcut on this desktop.' \
    --add-entry='Name' \
    --add-entry='HTTPS URL' \
    --separator='|' 2>/dev/null)" || exit 0
  IFS='|' read -r name url <<< "$result"
  if ! validate_url "$url"; then
    zenity --error --title='BRZ HealthOS' --text='Please enter a valid HTTPS URL.' 2>/dev/null || true
    exit 2
  fi
  install_shortcut "$name" "$url" "brz-healthos" true
  zenity --info --title='BRZ HealthOS' --text="Shortcut '$name' was added to the desktop." 2>/dev/null || true
}

case "${1:-}" in
  add)
    [[ $# -ge 3 ]] || { usage; exit 2; }
    install_shortcut "$2" "$3" "${4:-brz-healthos}" false
    ;;
  remove)
    [[ $# -eq 2 ]] || { usage; exit 2; }
    remove_shortcut "$2"
    ;;
  set-icon)
    [[ $# -eq 3 ]] || { usage; exit 2; }
    set_icon "$2" "$3"
    ;;
  list)
    list_shortcuts
    ;;
  gui)
    gui_add
    ;;
  *)
    usage
    exit 2
    ;;
esac
