#!/bin/bash
# Candura — Setup Script
# Run: ./setup.sh
# Installs hooks into Claude Code. Daemon auto-starts on first prompt.

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
CANDURA_DIR="$HOME/.candura"
CLAUDE_SETTINGS="$HOME/.claude/settings.json"

echo ""
echo "  Candura v1.0 — Cost Intelligence for AI Coding"
echo "  ═══════════════════════════════════════════════════"
echo ""

# 1. Install dependencies
echo "  [1/4] Installing dependencies..."
cd "$SCRIPT_DIR"
npm install --silent 2>/dev/null
echo "        ✓ Done"

# 2. Build TypeScript packages
echo "  [2/4] Building..."
npx tsc --build packages/core packages/hooks packages/daemon --force 2>/dev/null
echo "        ✓ Done"

# 3. Create config
mkdir -p "$CANDURA_DIR/live" "$CANDURA_DIR/sessions" "$CANDURA_DIR/cache"

if [ ! -f "$CANDURA_DIR/config.json" ]; then
  cat > "$CANDURA_DIR/config.json" << 'EOF'
{
  "thresholds": {
    "warn_above": 2.0,
    "block_above": 6.0,
    "daily_budget": 50.0,
    "monthly_budget": 500.0
  },
  "display": {
    "show_breakdown": true,
    "show_suggestions": true,
    "max_suggestions": 4,
    "compact_mode": false
  },
  "daemon": {
    "port": 7483,
    "auto_start": true,
    "idle_timeout": 1800
  },
  "telemetry": {
    "enabled": true,
    "endpoint": "https://candura.candura-telemetry.workers.dev/v1/session",
    "retention_days": 90
  }
}
EOF
  echo "  [3/4] Config created at $CANDURA_DIR/config.json"
else
  echo "  [3/4] Config exists ✓"
fi

# 4. Register hooks in Claude Code settings
echo "  [4/4] Registering hooks..."
mkdir -p "$HOME/.claude"

if [ ! -f "$CLAUDE_SETTINGS" ]; then
  echo '{}' > "$CLAUDE_SETTINGS"
fi

node -e "
const fs = require('fs');
const settings = JSON.parse(fs.readFileSync('$CLAUDE_SETTINGS', 'utf-8'));
const dir = '$SCRIPT_DIR/packages/hooks/src';

if (!settings.hooks) settings.hooks = {};

// Remove old candura hooks
for (const event of ['UserPromptSubmit', 'PostToolUse', 'Stop']) {
  if (settings.hooks[event]) {
    settings.hooks[event] = settings.hooks[event].filter(
      h => !JSON.stringify(h).includes('candura')
    );
    if (settings.hooks[event].length === 0) delete settings.hooks[event];
  }
}

// Pre-prompt: predicts cost, injects behavioral guidance
if (!settings.hooks.UserPromptSubmit) settings.hooks.UserPromptSubmit = [];
settings.hooks.UserPromptSubmit.push({
  hooks: [{
    type: 'command',
    command: 'node \"' + dir + '/pre-prompt-fast.mjs\"',
    timeout: 10
  }]
});

// Post-tool: tracks live session progress (async, never blocks)
if (!settings.hooks.PostToolUse) settings.hooks.PostToolUse = [];
settings.hooks.PostToolUse.push({
  hooks: [{
    type: 'command',
    command: 'node \"' + dir + '/post-tool-fast.mjs\"',
    timeout: 3
  }]
});

// Session end: records actual cost for calibration
if (!settings.hooks.Stop) settings.hooks.Stop = [];
settings.hooks.Stop.push({
  hooks: [{
    type: 'command',
    command: 'node \"' + dir + '/session-end-fast.mjs\"',
    timeout: 5
  }]
});

// Statusline: real-time cost display
var rootDir = dir.replace('/packages/hooks/src', '');
if (!settings.statusLine || !settings.statusLine.includes('candura')) {
  settings.statusLine = 'cd \"' + rootDir + '\" && npx tsx packages/hooks/src/statusline.ts';
}

fs.writeFileSync('$CLAUDE_SETTINGS', JSON.stringify(settings, null, 2));
"

echo "        ✓ Hooks registered"

echo ""
echo "  ═══════════════════════════════════════════════════"
echo "  ✓ Setup complete! Candura is now active."
echo "  ═══════════════════════════════════════════════════"
echo ""
echo "  How it works:"
echo "    • Predictions appear automatically before expensive prompts"
echo "    • Daemon starts on first prompt (no separate terminal needed)"
echo "    • Session costs recorded for accuracy improvement over time"
echo ""
echo "  Commands:"
echo "    npx candura predict \"your prompt\"   — test a prediction"
echo "    npx candura stats                   — see accuracy data"
echo "    npx candura history                 — recent session costs"
echo "    npx tsx packages/tui/src/index.ts   — live dashboard"
echo ""
echo "  Config: $CANDURA_DIR/config.json"
echo "  Uninstall: npx candura uninstall"
echo ""
