#!/usr/bin/env bash
# pakt install script.
#
#   curl -fsSL https://usepakt.ai/install.sh | bash
#
# Adds Pakt's public Git marketplace and installs (or updates) the Pakt plugin
# for Claude Code and Codex. The plugin bundles the remote MCP connection and
# agent guidance. It installs no binary or secret; OAuth happens in the browser
# when an agent first calls Pakt.

set -euo pipefail

PAKT_MARKETPLACE_NAME="bob-collective"
PAKT_MARKETPLACE_SOURCE="bob-collective/pakt-plugins"
PAKT_PLUGIN_ID="pakt@$PAKT_MARKETPLACE_NAME"
PAKT_MCP_URL="https://api.usepakt.ai/mcp"

found_host=0

if command -v claude >/dev/null 2>&1; then
  found_host=1
  echo "==> Claude Code"
  if ! claude plugin --help >/dev/null 2>&1; then
    echo "warning: update Claude Code to a release with plugin support; skipping Claude Code" >&2
  else
    if claude plugin marketplace list --json | grep -Fq "\"name\": \"$PAKT_MARKETPLACE_NAME\""; then
      claude plugin marketplace update "$PAKT_MARKETPLACE_NAME"
    else
      claude plugin marketplace add "$PAKT_MARKETPLACE_SOURCE" --scope user
    fi
    if claude plugin list --json | grep -Fq "\"id\": \"$PAKT_PLUGIN_ID\""; then
      claude plugin update "$PAKT_PLUGIN_ID" --scope user
    else
      claude plugin install "$PAKT_PLUGIN_ID" --scope user
    fi
    echo "    installed $PAKT_PLUGIN_ID"
  fi
fi

if command -v codex >/dev/null 2>&1; then
  found_host=1
  echo "==> Codex"
  if ! codex plugin --help >/dev/null 2>&1; then
    echo "warning: update Codex to a release with plugin support; skipping Codex" >&2
  else
    if codex plugin marketplace list --json | grep -Eq "\"name\"[[:space:]]*:[[:space:]]*\"$PAKT_MARKETPLACE_NAME\""; then
      codex plugin marketplace upgrade "$PAKT_MARKETPLACE_NAME"
    else
      codex plugin marketplace add "$PAKT_MARKETPLACE_SOURCE" --ref main
    fi
    # Codex uses `add` for both first installation and refresh.
    codex plugin add "$PAKT_PLUGIN_ID"
    echo "    installed $PAKT_PLUGIN_ID"
  fi
fi

cat <<EOF

------------------------------------------------------------------
claude.ai (manual):
  Settings -> Connectors -> Add custom connector -> $PAKT_MCP_URL

ChatGPT:
  Install Pakt from the Plugins Directory once its public listing is approved.
  Until then, enable Developer mode and add $PAKT_MCP_URL as a custom connector.
------------------------------------------------------------------
EOF

if [ "$found_host" -eq 0 ]; then
  echo "No recognized agent CLI (claude, codex) found on PATH — nothing was installed."
fi
