#!/usr/bin/env bash
# color-tool — pick, convert, and format colors
# Supports: hex → RGB/RGBA, KDE Plasma color picker, clipboard copy, JSON output, color names
set -euo pipefail

# ── Configuration ─────────────────────────────────────────────────────────────

# Resolve the real directory of this script so we can find bundled helpers
SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
PICKER_SCRIPT="$SCRIPT_DIR/wl-colorpicker-plasma.py"
CONFIG_FILE="$HOME/.config/color-tool/config.toml"

# ── Mode flags (toggled by CLI arguments or config file) ──────────────────────

json_mode=0    # --json:    output as JSON
alpha_mode=0   # --alpha:   include alpha channel (8-digit hex)
name_mode=0    # --name:    fetch color name via thecolorapi.com
copy_mode=0    # --copy:    copy result to clipboard
desktop_mode=0 # --desktop: silent GUI mode (implies pick + copy + notify)
notify_mode=0  # internal:  show desktop notification after copy
config_pick=0  # config:    auto-launch picker when invoked with no arguments

# Desktop-mode defaults (overridden by [desktop] config section)
desktop_json=0
desktop_alpha=0
desktop_name=0
desktop_notify=1

# ── Config ────────────────────────────────────────────────────────────────────

# Parse ~/.config/color-tool/config.toml and apply [defaults] and [desktop] values.
# Only boolean true/false keys are supported; unknown keys are silently ignored.
load_config() {
  [[ ! -f "$CONFIG_FILE" ]] && return 0

  local section="" key val
  while IFS= read -r line; do
    line="${line%%#*}"   # strip inline comments
    if [[ "$line" =~ ^[[:space:]]*$ ]]; then continue; fi

    # Section header
    if [[ "$line" =~ ^\[([A-Za-z_-]+)\]$ ]]; then
      section="${BASH_REMATCH[1]}"
      continue
    fi

    # key = value — use if/then/fi so each branch always exits 0 (safe under set -e)
    if [[ "$line" =~ ^[[:space:]]*([A-Za-z_]+)[[:space:]]*=[[:space:]]*([^[:space:]]+) ]]; then
      key="${BASH_REMATCH[1]}"
      val="${BASH_REMATCH[2],,}"
      val="${val#\"}" ; val="${val%\"}"
      case "$section:$key" in
        defaults:json)  if [[ "$val" == "true" ]]; then json_mode=1;    fi ;;
        defaults:alpha) if [[ "$val" == "true" ]]; then alpha_mode=1;   fi ;;
        defaults:name)  if [[ "$val" == "true" ]]; then name_mode=1;    fi ;;
        defaults:copy)  if [[ "$val" == "true" ]]; then copy_mode=1;    fi ;;
        defaults:pick)  if [[ "$val" == "true" ]]; then config_pick=1;  fi ;;
        desktop:json)   if [[ "$val" == "true" ]]; then desktop_json=1;   else desktop_json=0;   fi ;;
        desktop:alpha)  if [[ "$val" == "true" ]]; then desktop_alpha=1;  else desktop_alpha=0;  fi ;;
        desktop:name)   if [[ "$val" == "true" ]]; then desktop_name=1;   else desktop_name=0;   fi ;;
        desktop:notify) if [[ "$val" == "true" ]]; then desktop_notify=1; else desktop_notify=0; fi ;;
      esac
    fi
  done < "$CONFIG_FILE"
}

# ── Help ──────────────────────────────────────────────────────────────────────

show_help() {
  local bold='\033[1m'
  local dim='\033[2m'
  local reset='\033[0m'
  local cyan='\033[36m'
  local yellow='\033[33m'
  local mag='\033[35m'

  # Render an inline color swatch for a hex code
  swatch() {
    local h="${1#\#}"
    printf "\033[48;2;%d;%d;%dm  \033[0m" $((16#${h:0:2})) $((16#${h:2:2})) $((16#${h:4:2}))
  }

  printf "\n"
  # Title: "color" in a rainbow gradient, "-tool" in bold
  printf "  ${bold}\033[38;2;255;80;80mc\033[38;2;255;160;0mo\033[38;2;220;210;0ml\033[38;2;80;200;80mo\033[38;2;80;160;255mr${reset}${bold}-tool${reset}"
  printf "  ${dim}—  pick, convert, and format colors${reset}\n\n"

  printf "  ${bold}${yellow}Usage${reset}  ${cyan}${0##*/}${reset} ${dim}[OPTIONS]${reset} [HEX_COLOR ...]\n\n"

  printf "  ${bold}${yellow}Options${reset}\n"
  printf "  ${bold}${cyan}--pick${reset}         Open the KDE Plasma color picker ${dim}(requires KDE + Wayland)${reset}\n"
  printf "  ${bold}${cyan}--alpha${reset}        Interpret 8-digit hex codes ${dim}(RRGGBBAA)${reset} and include alpha channel\n"
  printf "  ${bold}${cyan}--json${reset}         Output in JSON format\n"
  printf "  ${bold}${cyan}--name${reset}         Fetch nearest color name from thecolorapi.com ${dim}(requires curl, jq)${reset}\n"
  printf "  ${bold}${cyan}--copy${reset}         Copy result to clipboard ${dim}(wl-copy preferred, xclip as fallback)${reset}\n"
  printf "  ${bold}${cyan}--desktop${reset}      GUI mode: pick → copy → notify ${dim}(for app menu / .desktop launcher)${reset}\n"
  printf "  ${bold}${cyan}--install${reset}      Install to ~/.local/share/color-tool/ and symlink into ~/.local/bin/\n"
  printf "  ${bold}${cyan}--help${reset}, ${bold}${cyan}-h${reset}     Show this help message\n\n"

  printf "  ${bold}${yellow}Examples${reset}\n"
  printf "  ${cyan}${0##*/}${reset} ${mag}\"#534145\"${reset} $(swatch "#534145") ${mag}\"#433f43\"${reset} $(swatch "#433f43")\n"
  printf "  ${dim}echo${reset} ${mag}\"#123456\"${reset} $(swatch "#123456") ${dim}|${reset} ${cyan}${0##*/}${reset}\n"
  printf "  ${cyan}${0##*/}${reset} ${bold}${cyan}--pick${reset} ${bold}${cyan}--json${reset} ${bold}${cyan}--copy${reset}\n"
  printf "  ${cyan}${0##*/}${reset} ${bold}${cyan}--pick${reset} ${bold}${cyan}--alpha${reset} ${bold}${cyan}--json${reset} ${bold}${cyan}--name${reset} ${bold}${cyan}--copy${reset}\n\n"

  printf "  ${bold}${yellow}Config${reset}  ${dim}~/.config/color-tool/config.toml${reset}\n"
  printf "  ${dim}[defaults]${reset} keys: ${cyan}json  alpha  name  copy  pick${reset}\n"
  printf "  ${dim}[desktop]${reset}  keys: ${cyan}json  alpha  name  notify${reset}  ${dim}(copy + pick always on)${reset}\n\n"
}

# ── Environment detection ─────────────────────────────────────────────────────

# Confirm the session is KDE Plasma on Wayland before invoking the color picker.
# KWin's ColorPicker DBus service is only present in this specific environment.
check_kde_wayland() {
  if [[ -z "${WAYLAND_DISPLAY:-}" ]]; then
    echo "Error: color picker requires a Wayland session (WAYLAND_DISPLAY is not set)" >&2
    return 1
  fi
  local desktop="${XDG_CURRENT_DESKTOP:-}"
  if [[ "$desktop" != *KDE* ]] && [[ -z "${KDE_FULL_SESSION:-}" ]]; then
    echo "Error: color picker requires KDE Plasma (current desktop: ${desktop:-unknown})" >&2
    return 1
  fi
}

# ── Clipboard ─────────────────────────────────────────────────────────────────

# Write text to the system clipboard.
# Prefers wl-copy (native Wayland); falls back to xclip (X11, often Wayland-bridged).
# Prints a warning and exits non-zero if neither tool is available.
copy_to_clipboard() {
  local text="$1"
  if command -v wl-copy &>/dev/null; then
    printf '%s' "$text" | wl-copy
  elif command -v xclip &>/dev/null; then
    printf '%s' "$text" | xclip -selection clipboard
  else
    echo "Warning: no clipboard utility found (install wl-copy or xclip)" >&2
    echo "  Value: $text" >&2
    return 1
  fi
}

# ── Color picker ──────────────────────────────────────────────────────────────

# Launch the bundled KDE Plasma color picker and echo the selected hex color.
# Validates the environment before invoking the Python/Qt DBus helper.
run_color_picker() {
  if [[ ! -f "$PICKER_SCRIPT" ]]; then
    echo "Error: picker script not found: $PICKER_SCRIPT" >&2
    return 1
  fi
  check_kde_wayland || return 1
  python3 "$PICKER_SCRIPT"
}

# ── Desktop mode ─────────────────────────────────────────────────────────────

# Apply [desktop] config values as active mode flags; always enable pick and copy.
apply_desktop_config() {
  json_mode=$desktop_json
  alpha_mode=$desktop_alpha
  name_mode=$desktop_name
  notify_mode=$desktop_notify
  copy_mode=1
  config_pick=1
}

# Show a desktop notification with the copied value (non-fatal if notify-send absent).
notify_result() {
  local value="$1"
  command -v notify-send &>/dev/null || return 0
  notify-send -i "color-picker" "color-tool" "Copied to clipboard: $value" || true
}

# ── PATH suggestion ───────────────────────────────────────────────────────────

# Print the appropriate "add to PATH" instruction for the user's current shell.
# Detects fish via $SHELL or the parent process; falls back to showing both syntaxes.
suggest_path_add() {
  local bin_dir="$1" is_fish=0
  [[ "${SHELL:-}" == */fish ]] && is_fish=1
  if [[ $is_fish -eq 0 ]]; then
    local parent
    parent=$(ps -p "$PPID" -o comm= 2>/dev/null || true)
    [[ "$parent" == *fish* ]] && is_fish=1
  fi
  if [[ $is_fish -eq 1 ]]; then
    printf "      Run:  fish_add_path %s\n" "$bin_dir"
  else
    printf "      For bash/zsh:  export PATH=\"%s:\$PATH\"\n" "$bin_dir"
    printf "      For fish:      fish_add_path %s\n" "$bin_dir"
  fi
}

# ── Installation ──────────────────────────────────────────────────────────────

# Copy the script and helper into ~/.local/share/color-tool/ and symlink only
# the main binary into ~/.local/bin/. The picker script stays out of PATH.
do_install() {
  local data_dir="$HOME/.local/share/color-tool"
  local bin_dir="$HOME/.local/bin"
  local bin_link="$bin_dir/color-tool"
  local src_script
  src_script="$(readlink -f "$0")"

  if [[ ! -f "$PICKER_SCRIPT" ]]; then
    echo "Error: helper script not found: $PICKER_SCRIPT" >&2
    echo "       Run --install from the directory containing wl-colorpicker-plasma.py" >&2
    exit 1
  fi

  mkdir -p "$data_dir" "$bin_dir"

  cp "$src_script" "$data_dir/color-tool"
  chmod +x "$data_dir/color-tool"
  cp "$PICKER_SCRIPT" "$data_dir/wl-colorpicker-plasma.py"

  # -f replaces any existing symlink or stale file without prompting
  ln -sf "$data_dir/color-tool" "$bin_link"

  # Seed a sample config only if one doesn't already exist (preserve user edits on reinstall)
  local config_dir="$HOME/.config/color-tool"
  local config_file="$config_dir/config.toml"
  mkdir -p "$config_dir"
  if [[ ! -f "$config_file" ]]; then
    cat > "$config_file" <<'EOF'
# color-tool configuration
# https://github.com/rootiest/color-tool

[defaults]
# Set any option to true to enable it by default when using the terminal
json  = false   # output in JSON format
alpha = false   # include alpha channel (8-digit hex)
name  = false   # fetch color name from thecolorapi.com
copy  = false   # copy result to clipboard
pick  = false   # auto-launch color picker when invoked with no arguments

[desktop]
# Defaults for --desktop mode (launched from the app menu; copy is always enabled)
json   = false  # copy JSON format instead of hex
alpha  = false  # include alpha channel
name   = false  # fetch color name (requires network)
notify = true   # show desktop notification with the copied value
EOF
    printf "  config  %s  (sample created)\n" "$config_file"
  else
    printf "  config  %s\n" "$config_file"
  fi

  generate_desktop_file

  printf "Installed:\n"
  printf "  data    %s/\n" "$data_dir"
  printf "  bin     %s -> %s\n" "$bin_link" "$data_dir/color-tool"

  # Warn when the bin dir is not yet on PATH so the user knows what to add
  if [[ ":$PATH:" != *":$bin_dir:"* ]]; then
    printf "\nNote: %s is not in your PATH.\n" "$bin_dir"
    suggest_path_add "$bin_dir"
  fi
}

# Write a .desktop entry so color-tool appears in the app menu.
generate_desktop_file() {
  local app_dir="$HOME/.local/share/applications"
  local desktop_file="$app_dir/color-tool.desktop"
  local bin_path="$HOME/.local/bin/color-tool"
  mkdir -p "$app_dir"
  cat > "$desktop_file" <<EOF
[Desktop Entry]
Version=1.1
Type=Application
Name=Color Tool
Comment=Pick a color and copy it to the clipboard
Exec=$bin_path --desktop
Icon=color-picker
Categories=Utility;Graphics;
Keywords=color;picker;hex;rgb;clipboard;
Terminal=false
NoDisplay=false
EOF
  printf "  app     %s\n" "$desktop_file"
}

# ── Color conversion ──────────────────────────────────────────────────────────

# Convert a hex color to RGB/RGBA and print the result.
# Also copies a clean (no ANSI) value to clipboard when copy_mode is enabled.
hex_to_rgba() {
  local hex="$1"
  local clean_hex="${hex#\#}"

  # Accept 6-digit (#RRGGBB) or 8-digit (#RRGGBBAA); pad 6-digit with full opacity
  if [[ "$clean_hex" =~ ^[0-9A-Fa-f]{6}$ ]]; then
    clean_hex="${clean_hex}FF"
  elif [[ "$clean_hex" =~ ^[0-9A-Fa-f]{8}$ ]]; then
    : # already RRGGBBAA
  else
    echo "Invalid hex color: $hex" >&2
    return 1
  fi

  local r=$((16#${clean_hex:0:2}))
  local g=$((16#${clean_hex:2:2}))
  local b=$((16#${clean_hex:4:2}))
  local a=$((16#${clean_hex:6:2}))
  local name="" clip_value=""

  # Optionally resolve a human-readable name via the public thecolorapi.com API
  if [[ $name_mode -eq 1 ]]; then
    name=$(curl -s "https://www.thecolorapi.com/id?hex=${clean_hex:0:6}" | jq -r '.name.value // empty')
  fi

  # Build clip_value (always; desktop mode needs it even without terminal output)
  if [[ $json_mode -eq 1 ]]; then
    if [[ $alpha_mode -eq 1 ]]; then
      clip_value=$(printf '{"hex":"#%s","rgba":[%d,%d,%d,%d]}' "$clean_hex" "$r" "$g" "$b" "$a")
    else
      clip_value=$(printf '{"hex":"#%s","rgb":[%d,%d,%d]}' "${clean_hex:0:6}" "$r" "$g" "$b")
    fi
    [[ -n "$name" ]] && clip_value="${clip_value%\}}$(printf ',"name":"%s"}' "$name")"
  elif [[ $alpha_mode -eq 1 ]]; then
    clip_value="#${clean_hex}"
  else
    clip_value="#${clean_hex:0:6}"
  fi

  # Terminal output — skipped in desktop mode (no terminal to write to)
  if [[ $desktop_mode -eq 0 ]]; then
    if [[ $json_mode -eq 1 ]]; then
      echo "$clip_value"
    else
      if [[ $alpha_mode -eq 1 ]]; then
        printf "\033[2mHEX:\033[0m #%s \033[2m→ RGBA(\033[0m%3d, %3d, %3d, %3d\033[2m)\033[0m → \033[48;2;%d;%d;%dm  \033[0m" \
          "$clean_hex" "$r" "$g" "$b" "$a" "$r" "$g" "$b"
      else
        printf "\033[2mHEX:\033[0m #%s \033[2m→ RGB(\033[0m%3d, %3d, %3d\033[2m)\033[0m → \033[48;2;%d;%d;%dm  \033[0m" \
          "${clean_hex:0:6}" "$r" "$g" "$b" "$r" "$g" "$b"
      fi
      [[ -n "$name" ]] && printf " \033[2m→ Name:\033[0m %s" "$name"
      echo
    fi
  fi

  # Non-fatal: warn if clipboard copy fails (e.g. no clipboard utility installed)
  [[ $copy_mode -eq 1 ]] && copy_to_clipboard "$clip_value" || true
  [[ $notify_mode -eq 1 ]] && notify_result "$clip_value" || true
}

# ── Argument parsing ──────────────────────────────────────────────────────────

# Apply config defaults before processing CLI args so flags can still override them
load_config

args=()
while [[ $# -gt 0 ]]; do
  case "$1" in
  --help | -h)
    show_help
    exit 0
    ;;
  --pick)
    # Run the picker immediately; its output (a hex string) is queued for conversion
    picked="$(run_color_picker)" || exit 1
    [[ -n "$picked" ]] && args+=("$picked")
    ;;
  --json)    json_mode=1  ;;
  --alpha)   alpha_mode=1 ;;
  --name)    name_mode=1  ;;
  --copy)    copy_mode=1  ;;
  --desktop) desktop_mode=1; apply_desktop_config ;;
  --install) do_install; exit 0 ;;
  -*)
    echo "Unknown option: $1" >&2
    exit 1
    ;;
  *)
    args+=("$1")
    ;;
  esac
  shift
done

# Collect any hex values piped via stdin
if [[ ! -t 0 ]]; then
  while read -r line; do
    [[ -n "$line" ]] && args+=("$line")
  done
fi

# No colors collected: auto-pick if config requests it, otherwise show help
if [[ ${#args[@]} -eq 0 ]]; then
  if [[ $config_pick -eq 1 ]]; then
    picked="$(run_color_picker)" || exit 1
    [[ -n "$picked" ]] && args+=("$picked")
  elif [[ -t 0 ]]; then
    show_help
    exit 0
  fi
fi

# ── Execution ─────────────────────────────────────────────────────────────────

for hex in "${args[@]}"; do
  hex_to_rgba "$hex"
done
