#!/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 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"

  desktop_dir="${XDG_DESKTOP_DIR:-$HOME/Desktop}"
  app_dir="${XDG_DATA_HOME:-$HOME/.local/share}/applications"
  mkdir -p "$desktop_dir" "$app_dir"
  desktop_file="$desktop_dir/${name}.desktop"
  app_file="$app_dir/brz-web-${slug}.desktop"

  for target in "$desktop_file" "$app_file"; 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"
  echo "Removed BRZ web shortcut: $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"
    ;;
  list)
    list_shortcuts
    ;;
  gui)
    gui_add
    ;;
  *)
    usage
    exit 2
    ;;
esac
