#!/bin/bash
# ══════════════════════════════════════════════════════════════
#  BAS-More Ecosystem — Device Setup Wizard
#  Run on any new computer to connect to the ecosystem.
#
#  Usage:
#    curl -sL https://raw.githubusercontent.com/BAS-More/infrastructure/master/setup-device.sh | bash
#    — or —
#    bash setup-device.sh
# ══════════════════════════════════════════════════════════════

set -e

BLUE='\033[0;34m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'
BOLD='\033[1m'

TR_URL="https://recall.aidev.com.au"
CLAUDE_DIR="$HOME/.claude"
HOOKS_DIR="$CLAUDE_DIR/hooks"

step() { echo -e "\n${BLUE}[$1/7]${NC} ${BOLD}$2${NC}"; }
ok()   { echo -e "  ${GREEN}✓${NC} $1"; }
warn() { echo -e "  ${YELLOW}!${NC} $1"; }
fail() { echo -e "  ${RED}✗${NC} $1"; }

echo -e "${BOLD}"
echo "══════════════════════════════════════════════"
echo "  BAS-More Ecosystem — Device Setup"
echo "══════════════════════════════════════════════"
echo -e "${NC}"
echo "This will configure this computer to connect"
echo "to the BAS-More AI ecosystem at aidev.com.au."
echo ""

# ── Pre-flight ────────────────────────────────────────────────
step 1 "Checking prerequisites..."

if ! command -v node &>/dev/null; then
  fail "Node.js not found. Install from https://nodejs.org"
  exit 1
fi
ok "Node.js $(node --version)"

if ! command -v git &>/dev/null; then
  fail "Git not found. Install from https://git-scm.com"
  exit 1
fi
ok "Git $(git --version | cut -d' ' -f3)"

# Check connectivity to ecosystem
HTTP_CODE=$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 "$TR_URL/" 2>/dev/null || echo "000")
if [ "$HTTP_CODE" = "200" ]; then
  ok "Ecosystem reachable at aidev.com.au"
else
  fail "Cannot reach $TR_URL (HTTP $HTTP_CODE)"
  echo "  Check your internet connection and try again."
  exit 1
fi

# ── Total Recall MCP Server ───────────────────────────────────
step 2 "Installing Total Recall MCP server..."

TR_DIR="$HOME/.total-recall-server"
if [ -d "$TR_DIR" ]; then
  cd "$TR_DIR" && git pull --ff-only 2>/dev/null
  ok "Total Recall updated"
else
  git clone --depth 1 https://github.com/BAS-More/Total-Recall.git "$TR_DIR" 2>/dev/null
  ok "Total Recall cloned"
fi

cd "$TR_DIR" && npm install --omit=dev --silent 2>/dev/null
ok "Dependencies installed"

# ── MCP Config ────────────────────────────────────────────────
step 3 "Configuring MCP server..."

mkdir -p "$CLAUDE_DIR"
MCP_FILE="$CLAUDE_DIR/.mcp.json"

if [ -f "$MCP_FILE" ]; then
  # Merge — add total-recall if not present
  if grep -q "total-recall" "$MCP_FILE" 2>/dev/null; then
    ok "MCP server already configured"
  else
    # Add to existing config using node
    node -e "
      const fs = require('fs');
      const config = JSON.parse(fs.readFileSync('$MCP_FILE', 'utf8'));
      config.mcpServers = config.mcpServers || {};
      config.mcpServers['total-recall'] = {
        command: 'node',
        args: ['$TR_DIR/src/index.js'],
        env: { TOTAL_RECALL_DATA_DIR: '$HOME/.total-recall' }
      };
      fs.writeFileSync('$MCP_FILE', JSON.stringify(config, null, 2));
    "
    ok "Total Recall added to existing MCP config"
  fi
else
  cat > "$MCP_FILE" << MCPEOF
{
  "mcpServers": {
    "total-recall": {
      "command": "node",
      "args": ["$TR_DIR/src/index.js"],
      "env": {
        "TOTAL_RECALL_DATA_DIR": "$HOME/.total-recall"
      }
    }
  }
}
MCPEOF
  ok "MCP config created"
fi

mkdir -p "$HOME/.total-recall"
ok "Data directory ready"

# ── Auto-Capture Hooks ────────────────────────────────────────
step 4 "Installing auto-capture hooks..."

mkdir -p "$HOOKS_DIR"
HOOKS_URL="https://raw.githubusercontent.com/BAS-More/infrastructure/master"

# Download hook files
for hook in tr-user-capture.js tr-tool-capture.js tr-stop-capture.js tr-session-end.js tr-transcript-miner.js tr-broadcast.js; do
  if curl -sL "$HOOKS_URL/hetzner/$hook" -o "$HOOKS_DIR/$hook" 2>/dev/null; then
    ok "$hook"
  else
    # Fallback: generate minimal hook
    warn "$hook — download failed, will retry on next setup"
  fi
done

# ── Hook Registration ─────────────────────────────────────────
step 5 "Registering hooks in Claude Code..."

SETTINGS_FILE="$CLAUDE_DIR/settings.json"

# Use node to safely merge hooks into settings.json
node -e "
  const fs = require('fs');
  const path = '$SETTINGS_FILE';
  const hooksDir = '$HOOKS_DIR';

  let config = {};
  try { config = JSON.parse(fs.readFileSync(path, 'utf8')); } catch {}

  const hooks = {
    UserPromptSubmit: [{
      hooks: [{
        type: 'command',
        command: 'node ' + hooksDir + '/tr-user-capture.js',
        timeout: 5,
        async: true,
        statusMessage: 'Capturing knowledge...'
      }]
    }],
    PostToolUse: [
      { matcher: 'Edit', hooks: [{ type: 'command', command: 'node ' + hooksDir + '/tr-tool-capture.js', timeout: 5, async: true }] },
      { matcher: 'Write', hooks: [{ type: 'command', command: 'node ' + hooksDir + '/tr-tool-capture.js', timeout: 5, async: true }] },
      { matcher: 'Bash', hooks: [{ type: 'command', command: 'node ' + hooksDir + '/tr-tool-capture.js', timeout: 5, async: true }] }
    ],
    Stop: [{
      hooks: [{
        type: 'command',
        command: 'node ' + hooksDir + '/tr-stop-capture.js',
        timeout: 10,
        async: true
      }]
    }],
    SessionEnd: [{
      hooks: [{
        type: 'command',
        command: 'node ' + hooksDir + '/tr-session-end.js',
        timeout: 30,
        async: true
      }]
    }],
    SessionStart: [{
      hooks: [{
        type: 'command',
        command: 'node ' + hooksDir + '/tr-transcript-miner.js',
        timeout: 60,
        async: true
      }]
    }]
  };

  // Merge hooks (don't overwrite existing non-TR hooks)
  config.hooks = config.hooks || {};
  for (const [event, entries] of Object.entries(hooks)) {
    if (!config.hooks[event]) {
      config.hooks[event] = entries;
    } else {
      // Check if TR hooks already exist
      const hasTR = config.hooks[event].some(e =>
        e.hooks?.some(h => h.command?.includes('tr-'))
      );
      if (!hasTR) {
        config.hooks[event].push(...entries);
      }
    }
  }

  fs.writeFileSync(path, JSON.stringify(config, null, 2));
  console.log('done');
" 2>/dev/null && ok "Hooks registered" || warn "Could not auto-register hooks — add manually"

# ── Verify ────────────────────────────────────────────────────
step 6 "Verifying setup..."

# Test MCP server
TR_TEST=$(timeout 5 node "$TR_DIR/src/index.js" 2>&1 | head -1 || echo "failed")
if echo "$TR_TEST" | grep -q "config loaded\|DB ready\|tools registered"; then
  ok "MCP server starts correctly"
else
  warn "MCP server test inconclusive: $TR_TEST"
fi

# Test hook connectivity
node -e "
  const https = require('https');
  const req = https.get('$TR_URL/stats', res => {
    let d = '';
    res.on('data', c => d += c);
    res.on('end', () => {
      const s = JSON.parse(d);
      console.log('Knowledge: ' + s.data.knowledge + ' entries');
      process.exit(0);
    });
  });
  req.on('error', () => { console.log('failed'); process.exit(1); });
  req.setTimeout(5000, () => { console.log('timeout'); process.exit(1); });
" 2>/dev/null && ok "Connected to ecosystem memory" || warn "Could not verify — check connectivity"

# ── Summary ───────────────────────────────────────────────────
step 7 "Done!"

echo ""
echo -e "${GREEN}${BOLD}══════════════════════════════════════════════${NC}"
echo -e "${GREEN}${BOLD}  Setup complete!${NC}"
echo -e "${GREEN}${BOLD}══════════════════════════════════════════════${NC}"
echo ""
echo "  Services:"
echo "    Dashboard:    https://aidev.com.au"
echo "    Total Recall: https://recall.aidev.com.au"
echo "    LLM Council:  https://council.aidev.com.au"
echo "    MAH:          https://mah.aidev.com.au"
echo "    Agent-MVP:    https://agents.aidev.com.au"
echo ""
echo -e "  ${YELLOW}Restart Claude Code to activate.${NC}"
echo ""
echo "  Broadcast tool:"
echo "    node ~/.claude/hooks/tr-broadcast.js --list"
echo "    node ~/.claude/hooks/tr-broadcast.js \"Your message\""
echo ""
