#!/usr/bin/env bash
# Diogenes Gateway - 1-Line IDE MCP Installer
# Installs the 100% Free Developer Tier (21 Context, AST & Guardrail Tools)
# Supports optional prepaid GRLC session key: --key grlc_sec_...
# Repository: https://github.com/stand-out-of-my-sun/diogenes-micro-gateway

set -e

GATEWAY_MCP_URL="https://diogenesgateway.com/mcp/context-code-solver"
SERVER_KEY="diogenes-context-code-solver"
SESSION_KEY=""

# Parse command line flags (--key <key>, --key=<key>, or key as argument)
while [[ $# -gt 0 ]]; do
  case "$1" in
    --key=*)
      SESSION_KEY="${1#*=}"
      shift
      ;;
    --key|-k)
      SESSION_KEY="$2"
      shift 2
      ;;
    grlc_sec_*)
      SESSION_KEY="$1"
      shift
      ;;
    *)
      shift
      ;;
  esac
done

echo ""
echo "=========================================================="
echo "  Diogenes Gateway - IDE MCP Installer"
echo "  Free Developer Tier (Context, AST, Patch & Guardrails)"
if [ -n "$SESSION_KEY" ]; then
  echo "  Prepaid Session Key: [Active - Authenticated]"
fi
echo "=========================================================="
echo ""

OS_TYPE="$(uname -s 2>/dev/null || echo 'Unknown')"
CONFIGS_UPDATED=0

merge_json_mcp() {
  local target_file="$1"
  local root_key="$2"
  local is_zed="$3"

  local target_dir
  target_dir="$(dirname "$target_file")"
  mkdir -p "$target_dir" 2>/dev/null || true

  if [ -f "$target_file" ]; then
    cp "$target_file" "${target_file}.bak"
    echo "  -> Backed up existing config to ${target_file}.bak"
  fi

  python3 -c "
import json, os, sys

path = sys.argv[1]
root_key = sys.argv[2]
server_key = sys.argv[3]
mcp_url = sys.argv[4]
session_key = sys.argv[5]
is_zed = sys.argv[6] == 'true'

data = {}
if os.path.exists(path):
    try:
        with open(path, 'r', encoding='utf-8') as f:
            content = f.read().strip()
            if content:
                data = json.loads(content)
    except Exception as e:
        print(f'     Note: Could not parse existing JSON ({e}), creating fresh backup.')
        data = {}

if not isinstance(data, dict):
    data = {}

if root_key not in data or not isinstance(data[root_key], dict):
    data[root_key] = {}

entry = {}
if is_zed:
    final_url = f'{mcp_url}?key={session_key}' if session_key else mcp_url
    entry = {'url': final_url}
else:
    entry = {'url': mcp_url}
    if session_key:
        entry['headers'] = {'Authorization': f'Bearer {session_key}'}

data[root_key][server_key] = entry

with open(path, 'w', encoding='utf-8') as f:
    json.dump(data, f, indent=2)
" "$target_file" "$root_key" "$SERVER_KEY" "$GATEWAY_MCP_URL" "$SESSION_KEY" "$is_zed" 2>/dev/null || \
  node -e "
const fs = require('fs');
const path = process.argv[1];
const rootKey = process.argv[2];
const serverKey = process.argv[3];
const mcpUrl = process.argv[4];
const sessionKey = process.argv[5];
const isZed = process.argv[6] === 'true';

let data = {};
if (fs.existsSync(path)) {
  try {
    const raw = fs.readFileSync(path, 'utf8').trim();
    if (raw) data = JSON.parse(raw);
  } catch (err) {
    data = {};
  }
}
if (typeof data !== 'object' || data === null) data = {};
if (!data[rootKey] || typeof data[rootKey] !== 'object') data[rootKey] = {};

let entry = {};
if (isZed) {
  entry.url = sessionKey ? (mcpUrl + '?key=' + sessionKey) : mcpUrl;
} else {
  entry.url = mcpUrl;
  if (sessionKey) {
    entry.headers = { 'Authorization': 'Bearer ' + sessionKey };
  }
}
data[rootKey][serverKey] = entry;

fs.writeFileSync(path, JSON.stringify(data, null, 2) + '\n', 'utf8');
" "$target_file" "$root_key" "$SERVER_KEY" "$GATEWAY_MCP_URL" "$SESSION_KEY" "$is_zed" 2>/dev/null || true

  echo "  [OK] Configured: $target_file"
  CONFIGS_UPDATED=$((CONFIGS_UPDATED + 1))
}

echo "Detecting installed IDE and agent configurations..."

# 1. Cursor IDE
CURSOR_DIRS=(
  "$HOME/.cursor"
  "$HOME/Library/Application Support/Cursor/User/globalStorage/cursor.mcp"
  "$HOME/.config/Cursor/User/globalStorage/cursor.mcp"
  "$APPDATA/Cursor/User/globalStorage/cursor.mcp"
)

CURSOR_CONFIG=""
for dir in "${CURSOR_DIRS[@]}"; do
  if [ -d "$dir" ] || [ "$dir" = "$HOME/.cursor" ]; then
    CURSOR_CONFIG="$dir/mcp.json"
    break
  fi
done

if [ -z "$CURSOR_CONFIG" ]; then
  CURSOR_CONFIG="$HOME/.cursor/mcp.json"
fi

echo "Installing to Cursor IDE..."
merge_json_mcp "$CURSOR_CONFIG" "mcpServers" "false"

# 2. Claude Desktop
CLAUDE_CONFIG=""
case "$OS_TYPE" in
  Darwin*)
    CLAUDE_CONFIG="$HOME/Library/Application Support/Claude/claude_desktop_config.json"
    ;;
  Linux*)
    CLAUDE_CONFIG="$HOME/.config/Claude/claude_desktop_config.json"
    ;;
  MINGW*|MSYS*|CYGWIN*)
    CLAUDE_CONFIG="$APPDATA/Claude/claude_desktop_config.json"
    ;;
  *)
    CLAUDE_CONFIG="$HOME/.config/Claude/claude_desktop_config.json"
    ;;
esac

echo "Installing to Claude Desktop..."
merge_json_mcp "$CLAUDE_CONFIG" "mcpServers" "false"

# 3. Zed Editor
ZED_CONFIG=""
case "$OS_TYPE" in
  Darwin*)
    ZED_CONFIG="$HOME/Library/Application Support/Zed/settings.json"
    ;;
  *)
    ZED_CONFIG="$HOME/.config/zed/settings.json"
    ;;
esac

if [ -f "$ZED_CONFIG" ] || [ -d "$(dirname "$ZED_CONFIG")" ]; then
  echo "Installing to Zed Editor..."
  merge_json_mcp "$ZED_CONFIG" "context_servers" "true"
fi

# 4. Project-local .cursor/mcp.json if current working directory has .git
if [ -d ".git" ]; then
  echo "Detected git project in current directory: adding local .cursor/mcp.json..."
  merge_json_mcp "./.cursor/mcp.json" "mcpServers" "false"
fi

echo ""
echo "=========================================================="
echo "  Installation Complete! ($CONFIGS_UPDATED configuration files updated)"
echo "=========================================================="
echo ""
echo "Diogenes Context & Code Solver MCP is now connected:"
echo "  URL: $GATEWAY_MCP_URL"
if [ -n "$SESSION_KEY" ]; then
  echo "  Prepaid Session Key: Active"
fi
echo ""
echo "Included Free Tools (100% Free Forever):"
echo "  * prune_context_skeleton     - Compress verbose files by 60%+ without losing symbols"
echo "  * plan_context_token_budget  - Analyze BPE tokens and prevent attention trough loss"
echo "  * apply_fuzzy_code_patch     - Apply fuzzy diff patches with self-healing match"
echo "  * analyze_ast_symbol_graph   - Extract AST functions, classes, and complexity metrics"
echo "  * heal_malformed_json        - Repair broken JSON with unquoted keys and trailing commas"
echo "  * guardrail_verify           - Pre-flight command and prompt injection gatekeeper"
echo "  * regex_oracle               - Synthesize ReDoS-safe regular expressions"
echo ""
echo "Restart Cursor or Claude Desktop to activate your new tools."
echo "Need help? Visit https://diogenesgateway.com"
echo ""
