#!/bin/bash
set -euo pipefail

if [[ "$(uname -s)" != "Darwin" ]]; then
  printf 'This setup helper is for Mac.\n' >&2
  exit 1
fi

if ! command -v node >/dev/null 2>&1 || ! command -v npm >/dev/null 2>&1; then
  printf 'Install Node.js from https://nodejs.org/en/download, then run this file again.\n' >&2
  exit 1
fi

config_dir="${LAWTTE_CLAUDE_CONFIG_DIR:-$HOME/Library/Application Support/Claude}"
bridge_dir="$config_dir/lawtte-mcp-bridge"
header_path="$config_dir/lawtte-mcp-headers.txt"
config_path="$config_dir/claude_desktop_config.json"
node_path="$(node -p 'process.execPath')"

umask 077
mkdir -p "$config_dir" "$bridge_dir"
chmod 700 "$bridge_dir"

printf 'Installing the Lawtte connection helper...\n'
npm install --prefix "$bridge_dir" --no-audit --no-fund --ignore-scripts --save-exact mcp-remote@0.14.3

proxy_path="$bridge_dir/node_modules/mcp-remote/dist/proxy.js"
if [[ ! -f "$proxy_path" ]]; then
  printf 'The connection helper did not install correctly. Please try again.\n' >&2
  exit 1
fi

printf '\nPaste the Studio API key from Lawtte, then press Return. Nothing will appear as you paste: '
IFS= read -r -s lawtte_key
printf '\n'
if [[ ! "$lawtte_key" =~ ^lawtte_sk_[A-Za-z0-9_-]{32}$ ]]; then
  printf 'That does not look like a Lawtte Studio key. Create a new key on the Connect Claude page and try again.\n' >&2
  exit 1
fi

printf 'Authorization: Bearer %s\n' "$lawtte_key" > "$header_path"
unset lawtte_key
chmod 600 "$header_path"

LAWTTE_NODE_PATH="$node_path" LAWTTE_PROXY_PATH="$proxy_path" \
  LAWTTE_HEADER_PATH="$header_path" LAWTTE_CONFIG_PATH="$config_path" node <<'NODE'
const fs = require("node:fs");
const path = require("node:path");
const crypto = require("node:crypto");

const configPath = process.env.LAWTTE_CONFIG_PATH;
let config = {};
if (fs.existsSync(configPath)) {
  try {
    config = JSON.parse(fs.readFileSync(configPath, "utf8"));
  } catch {
    console.error("Claude's config is not valid JSON. It was not changed. Please ask for setup help.");
    process.exit(1);
  }
}

if (!config || typeof config !== "object" || Array.isArray(config) ||
    (config.mcpServers !== undefined && (!config.mcpServers || typeof config.mcpServers !== "object" || Array.isArray(config.mcpServers)))) {
  console.error("Claude's config has an unexpected format. It was not changed. Please ask for setup help.");
  process.exit(1);
}

config.mcpServers ??= {};
config.mcpServers["lawtte-studio"] = {
  command: process.env.LAWTTE_NODE_PATH,
  args: [
    process.env.LAWTTE_PROXY_PATH,
    "https://www.lawtte.ai/api/mcp",
    "--header-file",
    process.env.LAWTTE_HEADER_PATH,
    "--transport",
    "http-only"
  ]
};

const tempPath = path.join(path.dirname(configPath), `.claude_desktop_config.${crypto.randomUUID()}.tmp`);
try {
  fs.writeFileSync(tempPath, JSON.stringify(config, null, 2) + "\n", { mode: 0o600, flag: "wx" });
  fs.renameSync(tempPath, configPath);
  fs.chmodSync(configPath, 0o600);
} finally {
  if (fs.existsSync(tempPath)) fs.unlinkSync(tempPath);
}
NODE

printf '\nLawtte is configured for Claude Desktop. Fully quit Claude Desktop, then reopen it.\n'
printf 'In Claude, ask: What tools are available from Lawtte Studio?\n'
