#!/bin/sh

set -eu
umask 077

PARADAILY_URL="https://paradaily.com"
MCP_URL="$PARADAILY_URL/mcp"
TEMP_DIR=""

say() {
  printf '%s\n' "$1"
}

fail() {
  printf 'ParaDaily install stopped: %s\n' "$1" >&2
  exit 1
}

cleanup() {
  if [ -n "${TEMP_DIR:-}" ] && [ -d "$TEMP_DIR" ]; then
    rm -rf "$TEMP_DIR"
  fi
}

trap cleanup EXIT HUP INT TERM

command -v curl >/dev/null 2>&1 || fail "curl is required."

OS="$(uname -s)"
case "$OS" in
  Darwin|Linux) ;;
  *) fail "only macOS and Linux are supported." ;;
esac

CODEX_BIN="$(command -v codex 2>/dev/null || true)"
if [ -z "$CODEX_BIN" ] && [ "$OS" = "Darwin" ] && [ -x "/Applications/ChatGPT.app/Contents/Resources/codex" ]; then
  CODEX_BIN="/Applications/ChatGPT.app/Contents/Resources/codex"
fi
CLAUDE_BIN="$(command -v claude 2>/dev/null || true)"

if [ -z "$CODEX_BIN" ] && [ -z "$CLAUDE_BIN" ]; then
  fail "install Codex or Claude Code first, then run this command again. See https://paradaily.com/evidence-console/manual"
fi

TEMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/paradaily-install.XXXXXX")"
INITIALIZE_FILE="$TEMP_DIR/initialize.json"
TOOLS_FILE="$TEMP_DIR/tools.json"

curl -fsS --max-time 30 "$PARADAILY_URL/api/v2/health" >/dev/null \
  || fail "the ParaDaily evidence service is not ready."

if [ -n "$CODEX_BIN" ]; then
  "$CODEX_BIN" mcp remove paradaily >/dev/null 2>&1 || true
  "$CODEX_BIN" mcp add paradaily --url "$MCP_URL" >/dev/null \
    || fail "Codex MCP configuration failed."
fi

if [ -n "$CLAUDE_BIN" ]; then
  "$CLAUDE_BIN" mcp remove paradaily --scope user >/dev/null 2>&1 || true
  "$CLAUDE_BIN" mcp add --scope user --transport http paradaily "$MCP_URL" >/dev/null \
    || fail "Claude Code MCP configuration failed."
fi

curl -fsS --max-time 30 "$MCP_URL" \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"paradaily-installer","version":"2.0"}}}' \
  > "$INITIALIZE_FILE" \
  || fail "MCP initialization failed."

grep -q 'paradaily-evidence' "$INITIALIZE_FILE" \
  || fail "MCP initialization returned an unexpected response."

curl -fsS --max-time 30 "$MCP_URL" \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}' \
  > "$TOOLS_FILE" \
  || fail "MCP tool discovery failed."

grep -q 'search_evidence' "$TOOLS_FILE" \
  || fail "MCP tool discovery returned an unexpected response."

say "ParaDaily connected."
say "MCP: ready"
say "Evidence search: ready"
say "No API key is required. Restart an already-running Codex or Claude Code session to load the connection."
