#!/usr/bin/env bash
#
# deeptide installer — fetches the latest macOS build from r.paean.ai,
# detects arch (arm64 / x86_64), verifies sha256, drops `deeptide` and a
# `tide` symlink into ~/.local/bin (or $DEEPTIDE_BIN_DIR), then runs
# `--version` to confirm the binary launches under Gatekeeper.
#
#   curl -fsSL https://deeptide.sh | sh
#
# Env overrides:
#   DEEPTIDE_BIN_DIR=/usr/local/bin            install dir (default ~/.local/bin)
#   DEEPTIDE_VERSION=v0.6.61                   pin a specific version
#   DEEPTIDE_RELEASE_BASE=https://example.com  alternate CDN (testing)

set -euo pipefail

RELEASE_BASE="${DEEPTIDE_RELEASE_BASE:-https://r.paean.ai/deeptide}"
BIN_DIR="${DEEPTIDE_BIN_DIR:-$HOME/.local/bin}"
PIN_VERSION="${DEEPTIDE_VERSION:-}"

# ANSI colors when stdout is a TTY.
if [ -t 1 ]; then
  BOLD=$'\033[1m'; DIM=$'\033[2m'; CYAN=$'\033[36m'; GREEN=$'\033[32m'
  YELLOW=$'\033[33m'; RED=$'\033[31m'; RESET=$'\033[0m'
else
  BOLD=""; DIM=""; CYAN=""; GREEN=""; YELLOW=""; RED=""; RESET=""
fi

say()  { printf "%s\n" "$*"; }
note() { printf "%s\n" "${DIM}$*${RESET}"; }
err()  { printf "%s\n" "${RED}error:${RESET} $*" >&2; }

# --- Platform check: macOS only -----------------------------------------
case "$(uname -s)" in
  Darwin) ;;
  *)
    err "deeptide is currently macOS-only."
    note "For Linux / Windows, use the cross-platform sibling:"
    note "  https://github.com/paean-ai/zero-cli"
    exit 1
    ;;
esac

case "$(uname -m)" in
  arm64)  ARCH="arm64" ;;
  x86_64) ARCH="x86_64" ;;
  *)
    err "Unrecognised arch: $(uname -m). Expected arm64 or x86_64."
    exit 1
    ;;
esac
PLATFORM="darwin-$ARCH"

# --- Resolve manifest URL ------------------------------------------------
# Versioned: r.paean.ai/deeptide/v0.6.61/release.json
# Latest:    r.paean.ai/deeptide/release.json
if [ -n "$PIN_VERSION" ]; then
  MANIFEST_URL="$RELEASE_BASE/$PIN_VERSION/release.json"
  note "Pinned to $PIN_VERSION"
else
  MANIFEST_URL="$RELEASE_BASE/release.json"
fi

TMP=$(mktemp -d)
trap "rm -rf '$TMP'" EXIT

# --- Fetch manifest ------------------------------------------------------
if ! curl -fsSL "$MANIFEST_URL" -o "$TMP/release.json"; then
  err "Could not fetch release manifest from"
  note "  $MANIFEST_URL"
  note "Network down? CDN issue? Verify https://r.paean.ai/deeptide/release.json"
  exit 1
fi

# --- Parse manifest (shell-only, no python3 dependency) -----------------
# Pull out the per-platform sub-object then grep its url + sha256. Brittle
# if the JSON format drifts but we author both ends, so the layout is
# fixed: { platforms: { "darwin-arm64": { url, sha256, size }, ... } }
PLATFORM_BLOCK=$(sed -n "/\"$PLATFORM\"[[:space:]]*:[[:space:]]*{/,/^[[:space:]]*}/p" "$TMP/release.json")

if [ -z "$PLATFORM_BLOCK" ]; then
  err "No build for $PLATFORM in the release manifest."
  note "Available platforms can be inspected at:"
  note "  $MANIFEST_URL"
  exit 1
fi

extract() {
  # $1 = field name; reads from $PLATFORM_BLOCK
  printf "%s" "$PLATFORM_BLOCK" \
    | grep -E "\"$1\"[[:space:]]*:" \
    | head -1 \
    | sed -E 's/.*"'"$1"'"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/'
}

URL=$(extract url)
SHA=$(extract sha256)

# When DEEPTIDE_RELEASE_BASE points away from production (testing against a
# local server, mirror, or staging CDN), rewrite the manifest's URL prefix
# to match. The manifest always names production absolute URLs so other
# consumers (a future Homebrew formula, third-party tooling) can read the
# same file directly — but a single env override makes local end-to-end
# `python3 -m http.server` in dist/ a one-liner.
PROD_BASE="https://r.paean.ai/deeptide"
if [ "$RELEASE_BASE" != "$PROD_BASE" ]; then
  URL="${URL/$PROD_BASE/$RELEASE_BASE}"
fi

# Top-level version field — same flat-grep dance, but on the whole manifest.
VERSION=$(grep -E '"version"[[:space:]]*:' "$TMP/release.json" \
  | head -1 \
  | sed -E 's/.*"version"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/')

if [ -z "$URL" ] || [ -z "$SHA" ]; then
  err "Manifest missing url or sha256 for $PLATFORM."
  exit 1
fi

TARBALL=$(basename "$URL")

# --- Download ------------------------------------------------------------
say "${CYAN}deeptide${RESET} ${BOLD}${VERSION:-?}${RESET}  ${DIM}(macOS $ARCH)${RESET}"
say "Downloading ${DIM}${URL}${RESET}"
if ! curl -fsSL --progress-bar "$URL" -o "$TMP/$TARBALL"; then
  err "Download failed. URL above; retry, or grab the asset manually from"
  note "  $RELEASE_BASE/"
  exit 1
fi

# --- Verify sha256 -------------------------------------------------------
# Use shasum (BSD/macOS native) — no extra deps.
if ! command -v shasum >/dev/null 2>&1; then
  err "shasum not found — cannot verify download integrity."
  exit 1
fi
ACTUAL=$(shasum -a 256 "$TMP/$TARBALL" | awk '{print $1}')
if [ "$ACTUAL" != "$SHA" ]; then
  err "sha256 mismatch — refusing to install."
  note "expected: $SHA"
  note "actual:   $ACTUAL"
  note "Tarball may be corrupt or tampered with. Retry; if it persists,"
  note "report the URL + actual hash at https://github.com/paean-ai/deeptide/issues"
  exit 1
fi

# --- Extract -------------------------------------------------------------
tar -xzf "$TMP/$TARBALL" -C "$TMP"

if [ ! -x "$TMP/deeptide" ]; then
  err "Tarball did not contain a 'deeptide' executable."
  exit 1
fi

# --- Install -------------------------------------------------------------
mkdir -p "$BIN_DIR"
install -m 0755 "$TMP/deeptide" "$BIN_DIR/deeptide"
ln -sf "$BIN_DIR/deeptide" "$BIN_DIR/tide"

# Defensive: if a quarantine xattr slipped in (browser-saved tarball,
# unusual curl flags, MDM policy), strip it. Signed+notarized binaries
# don't need this — Gatekeeper validates online — but the call is cheap
# and silences the "downloaded from internet" first-launch dialog when
# users re-install via a non-curl path.
xattr -dr com.apple.quarantine "$BIN_DIR/deeptide" 2>/dev/null || true
xattr -dr com.apple.quarantine "$BIN_DIR/tide"     2>/dev/null || true

# --- Verify binary launches ---------------------------------------------
# Catches Gatekeeper rejection of unsigned / unnotarized builds. The
# common failure mode is `killed: 9` with no further diagnostic — surface
# the actual stderr so the user has something to report.
if ! LAUNCH_OUT=$("$BIN_DIR/deeptide" --version 2>&1); then
  err "Binary installed but failed to launch."
  note "Output:"
  printf "%s\n" "$LAUNCH_OUT" | sed 's/^/  /'
  note ""
  note "If you see 'killed: 9' or 'cannot be opened because it is from an"
  note "unidentified developer', the build may not yet be notarized — try:"
  note "  xattr -dr com.apple.quarantine $BIN_DIR/deeptide"
  note "If that doesn't help, file an issue at"
  note "  https://github.com/paean-ai/deeptide/issues"
  exit 1
fi
INSTALLED_VERSION=$(printf "%s" "$LAUNCH_OUT" | head -1)

say ""
say "${GREEN}✓${RESET} ${BOLD}deeptide ${INSTALLED_VERSION}${RESET} installed"
say "  ${DIM}→ $BIN_DIR/deeptide${RESET}"
say "  ${DIM}→ $BIN_DIR/tide   (symlink)${RESET}"
say ""

# --- PATH check ----------------------------------------------------------
case ":$PATH:" in
  *":$BIN_DIR:"*) ;;
  *)
    say "${YELLOW}!${RESET} ${BOLD}$BIN_DIR${RESET} is not in your PATH yet."
    say "  Add this line to your shell rc (e.g. ~/.zshrc):"
    say "    ${CYAN}export PATH=\"$BIN_DIR:\$PATH\"${RESET}"
    say ""
    ;;
esac

# --- Get-started hint ----------------------------------------------------
say "${BOLD}Next:${RESET}"
say "  ${CYAN}tide auth login${RESET}   ${DIM}# Paean OAuth (multimodal-aware)${RESET}"
say "  ${CYAN}tide login${RESET}        ${DIM}# save a DeepSeek API key${RESET}"
say "  ${CYAN}tide${RESET}              ${DIM}# launch the REPL${RESET}"
say "  ${CYAN}tide doctor${RESET}       ${DIM}# diagnose install + network${RESET}"
