#!/usr/bin/env bash
# Kartā installer fetcher.
#
#   curl -fsSL https://kartaa.pages.dev/install.sh | bash
#
# Downloads the matching macOS binary into ~/.local/bin/kartaa-install,
# marks it executable, and launches the full-screen TUI. Plain bash —
# inspect the source at https://kartaa.pages.dev/install.sh before
# piping if you'd rather. Linux is not yet supported via the script
# (the installer runs on your Mac and provisions a Linux host).

set -euo pipefail

# ── Ember palette (matches the TUI tokens in cmd/kartaa-install). ──
# Truecolor escapes; degrade gracefully on terminals without 24-bit.
EMBER=$'\033[38;2;255;140;79m'
INK=$'\033[38;2;232;217;201m'
DIM=$'\033[38;2;168;150;133m'
BOLD=$'\033[1m'
ITALIC=$'\033[3m'
RESET=$'\033[0m'

step() { printf '  %s▸%s %s%s%s\n'   "$EMBER" "$RESET" "$INK"  "$1" "$RESET"; }
note() { printf '    %s%s%s%s\n'      "$DIM"   "$ITALIC"        "$1" "$RESET"; }
warn() { printf '  %s!%s %s%s%s\n'    "$EMBER" "$RESET" "$DIM"  "$1" "$RESET"; }
fail() { printf '\n  %s✗%s %s%s%s\n\n' "$EMBER" "$RESET" "$INK"  "$1" "$RESET" >&2; exit 1; }

# ── Header ────────────────────────────────────────────────────
printf '\n'
printf '  %s%sKARTĀ%s  %s%s— self-hosted Codex cockpit%s\n' \
  "$EMBER" "$BOLD" "$RESET" "$DIM" "$ITALIC" "$RESET"
printf '\n'

# ── Platform check ────────────────────────────────────────────
os="$(uname -s)"
if [[ "$os" != "Darwin" ]]; then
  fail "only macOS is supported via the install script today (got $os). Track Linux at https://kartaa.pages.dev/getting-started/"
fi

case "$(uname -m)" in
  arm64|aarch64) arch="arm64" ;;
  x86_64)        arch="amd64" ;;
  *) fail "unsupported macOS arch: $(uname -m)" ;;
esac

target_dir="$HOME/.local/bin"
target="$target_dir/kartaa-install"
url="https://kartaa.pages.dev/binaries/darwin-$arch"

# ── Fetch + install ───────────────────────────────────────────
step "fetching darwin/$arch"
note "$url"
mkdir -p "$target_dir"
curl -fsSL -o "$target" "$url"
chmod +x "$target"

step "installed at $target"

# ── PATH hint ─────────────────────────────────────────────────
case ":$PATH:" in
  *":$target_dir:"*) ;;
  *)
    warn "$target_dir is not on your PATH yet"
    note "add to your shell rc to enable bare 'kartaa-install':"
    # shellcheck disable=SC2016
    printf '      %sexport PATH="$HOME/.local/bin:$PATH"%s\n' "$INK" "$RESET"
    ;;
esac

# ── Launch ────────────────────────────────────────────────────
step 'launching…'
printf '\n'

# Pipes-from-curl steal stdin; reattach to the controlling tty so the
# TUI can read keystrokes. </dev/tty is the standard curl|bash idiom
# for handing an interactive program back to the user's keyboard.
exec "$target" </dev/tty
