#!/usr/bin/env bash
# Random Unsplash photo → Terminal Widget (--image).
# Config: ~/.config/terminal-widget/unsplash.env (see recipe).
#
# Usage:
#   unsplash-random.sh [TARGET] [KEYWORD|-] [ORIENTATION]
#
# Args override env defaults. Use "-" for KEYWORD to mean fully random.
# Duplicate a LaunchAgent and change TARGET + KEYWORD for multiple widgets.
#
# Tap refresh: set UNSPLASH_TAP_SHORTCUT in unsplash.env to a Shortcuts
# name that runs this script. Do not use run-command — the sandboxed app
# cannot exec ~/Scripts or Homebrew binaries.
set -euo pipefail

# launchd / fdautil often have a minimal PATH
export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin${PATH:+:$PATH}"

UNSPLASH_ENV="${UNSPLASH_ENV:-$HOME/.config/terminal-widget/unsplash.env}"
if [[ -f "$UNSPLASH_ENV" ]]; then
	# shellcheck source=/dev/null
	source "$UNSPLASH_ENV"
fi

if [[ -z "${TERMINAL_WIDGET:-}" ]]; then
	if [[ -x /opt/homebrew/bin/terminal-widget ]]; then
		TW=/opt/homebrew/bin/terminal-widget
	elif [[ -x /usr/local/bin/terminal-widget ]]; then
		TW=/usr/local/bin/terminal-widget
	else
		TW=terminal-widget
	fi
else
	TW="$TERMINAL_WIDGET"
fi

TARGET="${1:-${UNSPLASH_TARGET:-unsplash}}"
QUERY="${2:-${UNSPLASH_QUERY:--}}"
ORIENTATION="${3:-${UNSPLASH_ORIENTATION:-landscape}}"
[[ "$QUERY" == "-" ]] && QUERY=""
[[ "$ORIENTATION" == "-" ]] && ORIENTATION=""

widget_error() {
	local msg="$1"
	echo "Unsplash: $msg" >&2
	if command -v "$TW" >/dev/null 2>&1; then
		"$TW" --target "$TARGET" \
			--icon exclamationmark.triangle.fill \
			--background "#422006" \
			--foreground "#fde68a" \
			--text "Unsplash: $msg" || true
	fi
}

if [[ -z "${UNSPLASH_ACCESS_KEY:-}" ]]; then
	widget_error "UNSPLASH_ACCESS_KEY not set"
	exit 1
fi

for cmd in jq curl; do
	if ! command -v "$cmd" >/dev/null 2>&1; then
		widget_error "$cmd required"
		exit 1
	fi
done

if ! command -v "$TW" >/dev/null 2>&1; then
	widget_error "terminal-widget not found (set TERMINAL_WIDGET)"
	exit 1
fi

API="https://api.unsplash.com/photos/random"
PARAMS=()
[[ -n "$QUERY" ]] && PARAMS+=("query=$(printf %s "$QUERY" | jq -sRr @uri)")
[[ -n "$ORIENTATION" ]] && PARAMS+=("orientation=$(printf %s "$ORIENTATION" | jq -sRr @uri)")
if ((${#PARAMS[@]})); then
	API+="?$(IFS='&'; echo "${PARAMS[*]}")"
fi

if ! JSON=$(curl -fsS \
	-H "Authorization: Client-ID ${UNSPLASH_ACCESS_KEY}" \
	-H "Accept-Version: v1" \
	"$API"); then
	widget_error "API request failed"
	exit 1
fi

IMAGE_URL=$(echo "$JSON" | jq -r '.urls.regular // .urls.small // empty')
if [[ -z "$IMAGE_URL" || "$IMAGE_URL" == "null" ]]; then
	ERR=$(echo "$JSON" | jq -r '.errors[0] // .message // "no image url"' 2>/dev/null || echo "no image url")
	widget_error "$ERR"
	exit 1
fi

# Unsplash guideline: trigger download_location when displaying a photo
DOWNLOAD_LOC=$(echo "$JSON" | jq -r '.links.download_location // empty')
if [[ -n "$DOWNLOAD_LOC" && "$DOWNLOAD_LOC" != "null" ]]; then
	curl -fsS -H "Authorization: Client-ID ${UNSPLASH_ACCESS_KEY}" "$DOWNLOAD_LOC" >/dev/null || true
fi

ACTION_ARGS=()
if [[ -n "${UNSPLASH_TAP_SHORTCUT:-}" ]]; then
	ACTION_ARGS=(--action-kind run-shortcut --action-value "$UNSPLASH_TAP_SHORTCUT")
fi

"$TW" \
	--target "$TARGET" \
	--image "$IMAGE_URL" \
	--padding fill \
	"${ACTION_ARGS[@]}"