#!/bin/sh
# Conway Terminal Installer
# curl -fsSL https://conway.tech/terminal.sh | sh
#
# Installs conway-terminal globally, creates a wallet, provisions an API key,
# and configures Claude Code / Claude Desktop if present.

set -e

# ─── ASCII Art ─────────────────────────────────────────────────────────────────

cat << 'BANNER'

   ██████╗ ██████╗ ███╗   ██╗██╗    ██╗ █████╗ ██╗   ██╗
  ██╔════╝██╔═══██╗████╗  ██║██║    ██║██╔══██╗╚██╗ ██╔╝
  ██║     ██║   ██║██╔██╗ ██║██║ █╗ ██║███████║ ╚████╔╝
  ██║     ██║   ██║██║╚██╗██║██║███╗██║██╔══██║  ╚██╔╝
  ╚██████╗╚██████╔╝██║ ╚████║╚███╔███╔╝██║  ██║   ██║
   ╚═════╝ ╚═════╝ ╚═╝  ╚═══╝ ╚══╝╚══╝ ╚═╝  ╚═╝   ╚═╝

  T E R M I N A L
  To exist, you must pay for your compute.

BANNER

# ─── Colors ────────────────────────────────────────────────────────────────────

if [ -t 1 ]; then
  BOLD='\033[1m'
  DIM='\033[2m'
  GREEN='\033[0;32m'
  YELLOW='\033[0;33m'
  RED='\033[0;31m'
  CYAN='\033[0;36m'
  RESET='\033[0m'
else
  BOLD='' DIM='' GREEN='' YELLOW='' RED='' CYAN='' RESET=''
fi

info()  { printf "${CYAN}[info]${RESET}  %s\n" "$1"; }
ok()    { printf "${GREEN}[ok]${RESET}    %s\n" "$1"; }
warn()  { printf "${YELLOW}[warn]${RESET}  %s\n" "$1"; }
fail()  { printf "${RED}[fail]${RESET}  %s\n" "$1"; exit 1; }

# ─── Preflight ─────────────────────────────────────────────────────────────────

info "Checking prerequisites..."

# Check Node.js
if ! command -v node >/dev/null 2>&1; then
  fail "Node.js is required but not found. Install it from https://nodejs.org"
fi

NODE_VERSION=$(node -v | sed 's/v//' | cut -d. -f1)
if [ "$NODE_VERSION" -lt 18 ]; then
  fail "Node.js >= 18 required (found v$(node -v | sed 's/v//')). Update at https://nodejs.org"
fi
ok "Node.js v$(node -v | sed 's/v//')"

# Check npm
if ! command -v npm >/dev/null 2>&1; then
  fail "npm is required but not found."
fi
ok "npm $(npm -v)"

# ─── Install ───────────────────────────────────────────────────────────────────

info "Installing conway-terminal..."
npm install -g conway-terminal@latest 2>&1 | tail -1
ok "conway-terminal installed ($(conway-terminal --version))"

# ─── Init Wallet ───────────────────────────────────────────────────────────────

info "Initializing wallet at ~/.conway/wallet.json..."
INIT_RESULT=$(conway-terminal --init)
WALLET_ADDRESS=$(echo "$INIT_RESULT" | grep -o '"address":"[^"]*"' | cut -d'"' -f4)
IS_NEW=$(echo "$INIT_RESULT" | grep -o '"isNew":[a-z]*' | cut -d: -f2)

if [ "$IS_NEW" = "true" ]; then
  ok "New wallet created: ${WALLET_ADDRESS}"
else
  ok "Existing wallet loaded: ${WALLET_ADDRESS}"
fi

# ─── Provision API Key ─────────────────────────────────────────────────────────

CONFIG_FILE="$HOME/.conway/config.json"
WALLET_FILE="$HOME/.conway/wallet.json"
API_KEY=""

if [ -f "$CONFIG_FILE" ]; then
  EXISTING_KEY=$(grep -o '"apiKey":"[^"]*"' "$CONFIG_FILE" 2>/dev/null | cut -d'"' -f4 || true)
  if [ -n "$EXISTING_KEY" ]; then
    API_KEY="$EXISTING_KEY"
    KEY_PREFIX=$(echo "$API_KEY" | cut -c1-12)
    ok "API key already configured: ${KEY_PREFIX}..."
  fi
fi

if [ -z "$API_KEY" ]; then
  info "Provisioning API key via SIWE..."
  if PROVISION_RESULT=$(conway-terminal --provision 2>/dev/null); then
    API_KEY=$(echo "$PROVISION_RESULT" | grep -o '"apiKey":"[^"]*"' | cut -d'"' -f4)
    KEY_PREFIX=$(echo "$API_KEY" | cut -c1-12)
    ok "API key provisioned: ${KEY_PREFIX}..."
  else
    warn "Auto-provisioning failed. You can get a key manually:"
    printf "  ${DIM}1. Visit https://app.conway.tech${RESET}\n"
    printf "  ${DIM}2. Sign in with wallet ${WALLET_ADDRESS}${RESET}\n"
    printf "  ${DIM}3. Create an API key and set: export CONWAY_API_KEY=cnwy_k_...${RESET}\n"
    printf "\n"
    printf "  Or retry: ${BOLD}conway-terminal --provision${RESET}\n"
  fi
fi

# ─── Claude Code Integration ──────────────────────────────────────────────────

if command -v claude >/dev/null 2>&1; then
  info "Configuring Claude Code..."

  # Add MCP server
  if [ -n "$API_KEY" ]; then
    claude mcp add conway conway-terminal -e "CONWAY_API_KEY=${API_KEY}" --scope user 2>/dev/null && \
      ok "MCP server added to Claude Code" || \
      warn "Could not add MCP server (may already exist)"
  else
    claude mcp add conway conway-terminal --scope user 2>/dev/null && \
      ok "MCP server added to Claude Code (no API key — set CONWAY_API_KEY later)" || \
      warn "Could not add MCP server (may already exist)"
  fi

  # Copy skill
  SKILL_DIR="$HOME/.claude/skills/conway-automaton"
  SKILL_SOURCE=$(npm root -g 2>/dev/null)/conway-terminal/plugin/skills/conway-automaton/SKILL.md
  if [ -f "$SKILL_SOURCE" ]; then
    mkdir -p "$SKILL_DIR"
    cp "$SKILL_SOURCE" "$SKILL_DIR/SKILL.md"
    ok "Automaton skill installed"
  fi

  # Copy commands
  COMMANDS_DIR="$HOME/.claude/commands"
  COMMANDS_SOURCE=$(npm root -g 2>/dev/null)/conway-terminal/plugin/commands
  if [ -d "$COMMANDS_SOURCE" ]; then
    mkdir -p "$COMMANDS_DIR"
    cp "$COMMANDS_SOURCE"/*.md "$COMMANDS_DIR/" 2>/dev/null
    ok "Slash commands installed (/conway, /conway-status, /conway-deploy)"
  fi
else
  info "Claude Code CLI not found — skipping Claude Code integration"
  printf "  ${DIM}Install Claude Code: https://claude.ai/claude-code${RESET}\n"
fi

# ─── OpenClaw Integration ─────────────────────────────────────────────────────

if command -v openclaw >/dev/null 2>&1 || [ -d "$HOME/.openclaw" ]; then
  info "Configuring OpenClaw..."

  # Install Conway skill for OpenClaw
  OPENCLAW_SKILL_DIR="$HOME/.openclaw/skills/conway"
  OPENCLAW_SKILL_SOURCE=$(npm root -g 2>/dev/null)/conway-terminal/plugin/skills/conway-openclaw/SKILL.md
  if [ -f "$OPENCLAW_SKILL_SOURCE" ]; then
    mkdir -p "$OPENCLAW_SKILL_DIR"
    cp "$OPENCLAW_SKILL_SOURCE" "$OPENCLAW_SKILL_DIR/SKILL.md"
    ok "Conway skill installed for OpenClaw"
  fi

  # Add Conway MCP to openclaw.json if it exists
  OPENCLAW_CONFIG="$HOME/.openclaw/openclaw.json"
  if [ -f "$OPENCLAW_CONFIG" ]; then
    if grep -q '"conway"' "$OPENCLAW_CONFIG" 2>/dev/null; then
      ok "Conway MCP already configured in OpenClaw"
    else
      ENV_VAL="${API_KEY:-}"
      node -e "
        const fs = require('fs');
        let raw = fs.readFileSync('$OPENCLAW_CONFIG', 'utf-8');
        // Strip JSON5 comments for parsing
        raw = raw.replace(/\/\/.*$/gm, '').replace(/\/\*[\s\S]*?\*\//g, '');
        const cfg = JSON.parse(raw);
        if (!cfg.mcpServers) cfg.mcpServers = {};
        cfg.mcpServers.conway = {
          command: 'conway-terminal',
          env: { CONWAY_API_KEY: process.env.ENV_VAL || '' }
        };
        fs.writeFileSync('$OPENCLAW_CONFIG', JSON.stringify(cfg, null, 2));
      " 2>/dev/null && ok "Conway MCP added to OpenClaw config" || \
        warn "Could not update openclaw.json automatically"
    fi
  fi
else
  info "OpenClaw not found — skipping OpenClaw integration"
  printf "  ${DIM}Install OpenClaw: curl -fsSL https://openclaw.ai/install.sh | bash${RESET}\n"
fi

# ─── Claude Desktop Integration ───────────────────────────────────────────────

CLAUDE_DESKTOP_CONFIG=""
if [ -f "$HOME/Library/Application Support/Claude/claude_desktop_config.json" ]; then
  CLAUDE_DESKTOP_CONFIG="$HOME/Library/Application Support/Claude/claude_desktop_config.json"
elif [ -f "$HOME/.config/Claude/claude_desktop_config.json" ]; then
  CLAUDE_DESKTOP_CONFIG="$HOME/.config/Claude/claude_desktop_config.json"
fi

if [ -n "$CLAUDE_DESKTOP_CONFIG" ]; then
  info "Found Claude Desktop config at: ${CLAUDE_DESKTOP_CONFIG}"

  # Check if conway is already configured
  if grep -q '"conway"' "$CLAUDE_DESKTOP_CONFIG" 2>/dev/null; then
    ok "Conway already configured in Claude Desktop"
  else
    # Use node to safely merge JSON
    ENV_VAL="${API_KEY:-}"
    node -e "
      const fs = require('fs');
      const cfg = JSON.parse(fs.readFileSync('$CLAUDE_DESKTOP_CONFIG', 'utf-8'));
      if (!cfg.mcpServers) cfg.mcpServers = {};
      cfg.mcpServers.conway = {
        command: 'npx',
        args: ['-y', 'conway-terminal'],
        env: { CONWAY_API_KEY: process.env.ENV_VAL || '' }
      };
      fs.writeFileSync('$CLAUDE_DESKTOP_CONFIG', JSON.stringify(cfg, null, 2));
    " 2>/dev/null && ok "Conway added to Claude Desktop config" || \
      warn "Could not update Claude Desktop config automatically"
  fi
fi

# ─── Summary ───────────────────────────────────────────────────────────────────

printf "\n"
printf "${BOLD}═══════════════════════════════════════════${RESET}\n"
printf "${BOLD}  Conway Terminal installed successfully${RESET}\n"
printf "${BOLD}═══════════════════════════════════════════${RESET}\n"
printf "\n"
printf "  Wallet:  ${CYAN}${WALLET_ADDRESS}${RESET}\n"
if [ -n "$API_KEY" ]; then
  printf "  API Key: ${CYAN}${KEY_PREFIX}...${RESET}\n"
fi
printf "  Config:  ${DIM}~/.conway/${RESET}\n"
printf "  Wallet File: ${DIM}${WALLET_FILE}${RESET}\n"
printf "  Chains: ${DIM}Base mainnet (eip155:8453), Base Sepolia (eip155:84532)${RESET}\n"
printf "\n"
if [ -z "$API_KEY" ] || [ "$IS_NEW" = "true" ]; then
  printf "  ${YELLOW}Fund your account:${RESET}\n"
  printf "  ${DIM}• Send USDC on Base mainnet to ${WALLET_ADDRESS}${RESET}\n"
  printf "  ${DIM}• For test usage, switch tools to Base Sepolia (eip155:84532)${RESET}\n"
  printf "  ${DIM}• Or buy credits at https://app.conway.tech${RESET}\n"
  printf "\n"
fi
printf "  ${GREEN}Claude Code:  Type /conway to get started${RESET}\n"
printf "  ${GREEN}OpenClaw:     Conway skill auto-activates when you need compute${RESET}\n"
printf "\n"
