#!/usr/bin/env bash
#
# The Cloud — install into Claude Code.
#
# Drops the `cloud` skill into ~/.claude/skills/cloud/ and registers
# the The Cloud MCP server so /cloud connects, syncs the Charter, and
# pins Ora for the whole session. Idempotent — safe to re-run.
#
# Usage: curl -fsSL https://www.thecloud.so/install/cloud.sh | bash

set -eu

CLOUD_URL="https://www.thecloud.so"
MCP_URL="https://mcp.thecloud.so/mcp"
SKILL_DIR="$HOME/.claude/skills/cloud"
SKILL_PATH="$SKILL_DIR/SKILL.md"

printf '\n▟▙ The Cloud — installing into Claude Code\n\n'

# 1. Prereqs.
if ! command -v claude >/dev/null 2>&1; then
  printf '× claude (Claude Code CLI) not found in PATH.\n'
  printf '  Install Claude Code first: https://docs.claude.com/claude-code\n\n'
  exit 1
fi

if ! command -v curl >/dev/null 2>&1; then
  printf '× curl not found in PATH.\n'
  exit 1
fi

# 2. Drop the cloud skill.
printf '→ Installing the cloud skill to %s\n' "$SKILL_PATH"
mkdir -p "$SKILL_DIR"
if curl -fsSL "$CLOUD_URL/install/cloud-skill.md" -o "$SKILL_PATH"; then
  printf '  ✓ Skill installed\n'
else
  printf '× Failed to fetch the cloud skill from %s/install/cloud-skill.md\n' "$CLOUD_URL"
  exit 1
fi

# 3. Register The Cloud MCP server. `set -e` would abort on a non-zero
# exit (e.g. already registered), so we capture the result and
# continue with a hint either way.
printf '→ Registering The Cloud MCP server\n'
if claude mcp add the-cloud --transport http "$MCP_URL" >/dev/null 2>&1; then
  printf '  ✓ MCP server registered\n'
else
  printf '  · MCP server already registered (or this Claude Code build needs a different flag — try `claude mcp add the-cloud %s`).\n' "$MCP_URL"
fi

printf '\n✓ The Cloud is connected to your Claude Code.\n\n'
printf 'Next:\n'
printf '  1. Start a Claude Code session:  $ claude\n'
printf '  2. In the TUI, type:             /cloud\n'
printf '  3. Complete the OAuth prompt to thecloud.so (first time only).\n\n'
printf 'You are now Ora — governed by the Charter, synced to Vast Memory.\n'
