#!/usr/bin/env bash
#
# coa-db — tiny CLI over the public db.exil.es JSON API.
# No auth required. Pretty-prints with jq when available.
#
# Usage:
#   coa-db search <text...>     # search items/spells/npcs/quests
#   coa-db item   <id>
#   coa-db spell  <id>
#   coa-db npc    <id>
#   coa-db quest  <id>
#   coa-db spells <key=val>...  # filter catalogue, e.g. mechanic=15 limit=1000
#   coa-db changes
#   coa-db url <item|spell|npc|quest> <id>
#
# Env: COADB_BASE (default https://db.exil.es)

set -euo pipefail
BASE="${COADB_BASE:-https://db.exil.es}"
API="$BASE/api/v1"

_get() { curl -fsS --max-time 20 "$1"; }

_pretty() {
    if command -v jq >/dev/null 2>&1; then jq .
    else python3 -m json.tool 2>/dev/null || cat
    fi
}

# URL-encode a string (spaces, &, etc.) without external deps.
_enc() {
    python3 -c 'import sys,urllib.parse as u; print(u.quote(" ".join(sys.argv[1:])))' "$@"
}

cmd="${1:-}"; shift || true
case "$cmd" in
    search)
        [ "$#" -ge 1 ] || { echo "usage: coa-db search <text...>" >&2; exit 2; }
        _get "$API/search?q=$(_enc "$@")" | _pretty
        ;;
    item)   _get "$API/items/${1:?item id}"  | _pretty ;;
    spell)  _get "$API/spells/${1:?spell id}" | _pretty ;;
    npc)    _get "$API/npcs/${1:?npc id}"    | _pretty ;;
    quest)  _get "$API/quests/${1:?quest id}" | _pretty ;;
    spells)
        q=""; for kv in "$@"; do q="${q:+$q&}$kv"; done
        _get "$API/spells${q:+?$q}" | _pretty
        ;;
    changes) _get "$API/changes" | _pretty ;;
    health)  _get "$API/health"  | _pretty ;;
    url)
        kind="${1:?kind (item|spell|npc|quest)}"; id="${2:?id}"
        echo "$BASE/$kind/$id"
        ;;
    *)
        sed -n '2,20p' "$0" | sed 's/^# \{0,1\}//'
        exit 2
        ;;
esac
