#!/usr/bin/env bash
# wdv-px CLI launcher and live controller (macOS 14+, Apple Silicon, GNU Bash)
set -euo pipefail

APP_DIR="$HOME/Applications/wdv-px.app"
SANDBOX_PLIST="$HOME/Library/Containers/com.wdv.wdv-px/Data/Library/Preferences/com.wdv.wdv-px.plist"

usage() {
  cat <<'USAGE'
Usage: wdv-px [options] [WxH]

Launch or live-control ~/Applications/wdv-px.app (all units in pixels).

Options:
  WxH             Set capture frame output size in pixels (e.g. wdv-px 800x600)
  --1x            Switch capture resolution to 1X
  --2x            Switch capture resolution to 2X (default)
  --lock          Lock fixed template dimensions
  --free          Unlock template dimensions
  --grid          Enable click-through crosshair grid
  --nogrid        Disable crosshair grid
  --clip          Enable auto-copy PNG to clipboard
  --noclip        Disable auto-copy PNG to clipboard
  --shot, --now   Trigger an immediate capture of the current frame
  --folder        Open Save Folder chooser dialog
  --cfg, --config Print current wdv-px preferences and exit
  -q, --quit      Quit wdv-px cleanly
  -h, --help      Show this help message
USAGE
}

if [[ ! -d "$APP_DIR" ]]; then
  echo "Error: $APP_DIR not found. Run /Users/van/Dropbox/public_html/wdv-px/build.sh first." >&2
  exit 1
fi

PARAMS=()
CMD="open"

while [[ $# -gt 0 ]]; do
  case "$1" in
    -h|--help)
      usage
      exit 0
      ;;
    --cfg|--config)
      if [[ -f "$SANDBOX_PLIST" ]]; then
        plutil -p "$SANDBOX_PLIST"
      else
        defaults read com.wdv.wdv-px 2>/dev/null || echo "No preferences saved yet (launch wdv-px once)."
      fi
      exit 0
      ;;
    -q|--quit)
      open "wdv-px://quit" 2>/dev/null || osascript -e 'tell application "wdv-px" to quit' 2>/dev/null || true
      exit 0
      ;;
    --folder)
      open "wdv-px://folder"
      exit 0
      ;;
    --1x)     CMD="set"; PARAMS+=("res=1") ;;
    --2x)     CMD="set"; PARAMS+=("res=2") ;;
    --lock)   CMD="set"; PARAMS+=("lock=1") ;;
    --free)   CMD="set"; PARAMS+=("lock=0") ;;
    --grid)   CMD="set"; PARAMS+=("grid=1") ;;
    --nogrid) CMD="set"; PARAMS+=("grid=0") ;;
    --clip)   CMD="set"; PARAMS+=("clip=1") ;;
    --noclip) CMD="set"; PARAMS+=("clip=0") ;;
    --shot|--now)
      if [[ "$CMD" == "open" ]]; then
        CMD="shot"
      else
        PARAMS+=("shot=1")
      fi
      ;;
    [0-9]*x[0-9]*|[0-9]*X[0-9]*)
      CMD="set"
      low="${1,,}"
      PARAMS+=("w=${low%x*}" "h=${low#*x}")
      ;;
    *)
      echo "Unknown option: $1" >&2
      usage >&2
      exit 1
      ;;
  esac
  shift
done

if [[ "$CMD" == "open" ]]; then
  open -a "$APP_DIR"
elif [[ "$CMD" == "shot" ]]; then
  open "wdv-px://shot"
else
  IFS='&'
  qs="${PARAMS[*]}"
  unset IFS
  open "wdv-px://set?${qs}"
fi
