#!/bin/sh
# API Indonesia installer: connects the API Indonesia MCP server to the AI
# agents installed on this machine (Claude Code, Codex, Cursor, VS Code,
# opencode, Gemini CLI, Windsurf, Zed, Claude Desktop and more).
#
#   curl -fsSL https://apiindonesia.id/install.sh | sh -s -- --key aip_live_xxx
#   curl -fsSL https://apiindonesia.id/install.sh | API_INDONESIA_API_KEY=aip_live_xxx sh
#
# Options:
#   --key <key>      API key from https://dashboard.apiindonesia.id (or set API_INDONESIA_API_KEY)
#   --agent <name>   only this agent (repeatable): claude-code, codex, cursor, vscode,
#                    opencode, gemini-cli, windsurf, zed, claude-desktop, ...
#   --project        write project config in the current directory instead of user config
#
# The key check calls a path that 404s, and failed requests are not billed.
# Needs Node.js 18+. macOS and Linux only; on Windows add the MCP config by hand.

main() {
  set -eu
  MCP_URL="https://mcp.apiindonesia.id/mcp"
  API_URL="https://use.apiindonesia.id"
  KEY="${API_INDONESIA_API_KEY:-}"
  AGENTS=""
  PROJECT=""

  while [ $# -gt 0 ]; do
    case "$1" in
      --key) [ $# -ge 2 ] || die "--key needs a value"; KEY="$2"; shift 2 ;;
      --key=*) KEY="${1#--key=}"; shift ;;
      --agent|-a) [ $# -ge 2 ] || die "--agent needs a value"; AGENTS="$AGENTS $2"; shift 2 ;;
      --agent=*) AGENTS="$AGENTS ${1#--agent=}"; shift ;;
      --project) PROJECT=1; shift ;;
      -h|--help) usage; exit 0 ;;
      *) die "unknown option: $1 (see --help)" ;;
    esac
  done

  if [ -z "$KEY" ]; then
    say "API Indonesia needs an API key."
    say ""
    say "  1. Sign up at https://dashboard.apiindonesia.id/register (3,000 free credits, no card)"
    say "  2. Dashboard > API Keys > create a key (starts with aip_live_)"
    say "  3. Run again:"
    say "     curl -fsSL https://apiindonesia.id/install.sh | sh -s -- --key aip_live_xxx"
    exit 1
  fi
  case "$KEY" in
    aip_live_*|aip_test_*) ;;
    *) die "that does not look like an API Indonesia key (expected aip_live_...)" ;;
  esac
  command -v curl >/dev/null 2>&1 || die "curl is required"

  say "Checking the API key..."
  CODE=$(curl -s -o /dev/null -w '%{http_code}' --max-time 20 \
    -H "x-api-key: $KEY" "$API_URL/api/v1/wilayah/provinsi/00" </dev/null || true)
  case "$CODE" in
    401|403) die "the API key was rejected ($CODE). Copy it again from the dashboard (API Keys)." ;;
    000) die "could not reach $API_URL. A proxy or sandbox network policy is blocking apiindonesia.id." ;;
  esac
  MCP_CODE=$(curl -s -o /dev/null -w '%{http_code}' --max-time 20 -X POST "$MCP_URL" \
    -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
    -H 'Accept: application/json, text/event-stream' \
    -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' </dev/null || true)
  [ "$MCP_CODE" = "200" ] || die "the MCP server at $MCP_URL did not answer (HTTP $MCP_CODE). Try again in a minute."

  if ! have_node; then
    if command -v claude >/dev/null 2>&1; then
      say "Node.js 18+ not found, so only Claude Code can be set up."
      claude mcp remove --scope user api-indonesia >/dev/null 2>&1 </dev/null || true
      claude mcp add --transport http --scope user api-indonesia "$MCP_URL" \
        --header "Authorization: Bearer $KEY" </dev/null
      say "Done for Claude Code. Restart it to load API Indonesia."
      exit 0
    fi
    say "Node.js 18+ is required to set up your agents (https://nodejs.org)."
    say "Or add this to your agent's MCP config by hand:"
    say ""
    say "  {\"mcpServers\": {\"api-indonesia\": {\"url\": \"$MCP_URL\", \"headers\": {\"Authorization\": \"Bearer <your key>\"}}}}"
    exit 1
  fi

  TMPD=$(mktemp -d 2>/dev/null || mktemp -d -t apiindonesia)
  trap 'rm -rf "$TMPD"' EXIT INT TERM
  say "Preparing the installer..."
  npm install --prefix "$TMPD" --no-save --no-audit --no-fund --loglevel=error add-mcp@2 >"$TMPD/npm.log" 2>&1 </dev/null \
    || { cat "$TMPD/npm.log" >&2; die "could not download add-mcp from npm"; }
  write_setup "$TMPD/setup.mjs"
  API_INDONESIA_API_KEY="$KEY" AIP_AGENTS="$AGENTS" AIP_PROJECT="$PROJECT" AIP_MCP_URL="$MCP_URL" \
    AIP_NPX="$(command -v npx || true)" node "$TMPD/setup.mjs" </dev/null
}

say() { printf '%s\n' "$*"; }
die() { printf 'api-indonesia: %s\n' "$*" >&2; exit 1; }
usage() {
  say "Usage: curl -fsSL https://apiindonesia.id/install.sh | sh -s -- --key aip_live_xxx [--agent <name>]... [--project]"
}
have_node() {
  command -v node >/dev/null 2>&1 && command -v npm >/dev/null 2>&1 \
    && node -e 'process.exit(+process.versions.node.split(".")[0] >= 18 ? 0 : 1)' >/dev/null 2>&1 </dev/null
}

write_setup() {
cat > "$1" <<'JS'
import { appendFileSync, existsSync, readFileSync } from 'node:fs';
import { dirname, join, relative } from 'node:path';
import { homedir } from 'node:os';
import { agents, detectGlobalAgents, detectProjectAgents, upsertServer } from './node_modules/add-mcp/dist/lib.js';

const KEY = process.env.API_INDONESIA_API_KEY;
const URL_ = process.env.AIP_MCP_URL;
const local = process.env.AIP_PROJECT === '1';
const NAME = 'api-indonesia';
const ALIASES = { claude: 'claude-code', gemini: 'gemini-cli', copilot: 'github-copilot-cli', kiro: 'kiro-cli', kimi: 'kimi-code', droid: 'factory-droid', grok: 'grok-build', kilo: 'kilo-code', 'claude-app': 'claude-desktop' };
const HINT = {
  'claude-code': 'restart Claude Code, then run /mcp to see api-indonesia',
  'claude-desktop': 'quit Claude Desktop completely (Cmd+Q) and open it again',
  codex: 'start a new Codex session',
  cursor: 'restart Cursor, then check Settings > MCP that api-indonesia is enabled',
  vscode: 'reload VS Code (Developer: Reload Window); Copilot agent mode lists the tools',
  windsurf: 'restart Windsurf (or refresh MCP servers in Cascade)',
  zed: 'restart Zed',
};
const label = (a) => agents[a]?.displayName ?? a;
const tilde = (p) => (p.startsWith(homedir()) ? '~' + p.slice(homedir().length) : p);

let targets;
const asked = (process.env.AIP_AGENTS || '').split(/\s+/).filter(Boolean).map((a) => ALIASES[a] ?? a);
if (asked.length) {
  const unknown = asked.filter((a) => !agents[a]);
  if (unknown.length) {
    console.error(`api-indonesia: unknown agent: ${unknown.join(', ')}\nSupported: ${Object.keys(agents).join(', ')}`);
    process.exit(1);
  }
  targets = [...new Set(asked)];
} else {
  targets = local ? detectProjectAgents(process.cwd()) : await detectGlobalAgents();
}
if (local) targets = targets.filter((a) => agents[a].localConfigPath);

if (!targets.length) {
  console.error(local
    ? 'api-indonesia: no agent config found in this directory. Run without --project, or pass --agent <name>.'
    : 'api-indonesia: no AI agent found on this machine.\nInstall one (Claude Code, Codex, Cursor, VS Code, opencode, ...) or name it: --agent <name>');
  process.exit(1);
}

// Claude Desktop reads only local (stdio) servers from its config file, so it
// gets the mcp-remote bridge. GUI apps on macOS start with a minimal PATH, so
// use absolute paths and pass PATH explicitly.
function stdioBridge() {
  const nodeDir = dirname(process.execPath);
  const npx = existsSync(join(nodeDir, 'npx')) ? join(nodeDir, 'npx') : (process.env.AIP_NPX || 'npx');
  return {
    command: npx,
    args: ['-y', 'mcp-remote@0.16', URL_, '--header', 'Authorization:${API_INDONESIA_AUTH}'],
    env: { API_INDONESIA_AUTH: `Bearer ${KEY}`, PATH: [nodeDir, '/usr/local/bin', '/opt/homebrew/bin', '/usr/bin', '/bin'].join(':') },
  };
}

const ok = [];
const failed = [];
for (const a of targets) {
  const http = agents[a].supportedTransports.includes('http');
  const cfg = http ? { type: 'http', url: URL_, headers: { Authorization: `Bearer ${KEY}` } } : stdioBridge();
  try {
    const r = upsertServer(a, NAME, cfg, local ? { local: true, cwd: process.cwd() } : {});
    if (!r.success) throw new Error(r.error || 'write failed');
    const text = existsSync(r.path) ? readFileSync(r.path, 'utf8') : '';
    if (!text.includes(http ? URL_ : 'mcp-remote')) throw new Error(`config written but ${tilde(r.path)} does not contain the server`);
    ok.push({ a, path: r.path });
  } catch (e) {
    failed.push({ a, err: e instanceof Error ? e.message : String(e) });
  }
}

// Project configs now hold the API key: keep them out of git.
if (local && ok.length && existsSync(join(process.cwd(), '.git'))) {
  const gi = join(process.cwd(), '.gitignore');
  const have = existsSync(gi) ? readFileSync(gi, 'utf8').split(/\r?\n/) : [];
  const add = [...new Set(ok.map(({ path }) => relative(process.cwd(), path)))].filter((f) => !have.includes(f));
  if (add.length) appendFileSync(gi, (have.length && have[have.length - 1] !== '' ? '\n' : '') + add.join('\n') + '\n');
}

console.log('');
for (const { a, path } of ok) console.log(`  ✓ ${label(a)}  ${tilde(path)}`);
for (const { a, err } of failed) console.log(`  ✗ ${label(a)}  ${err}`);
console.log('');
if (!ok.length) {
  console.error('api-indonesia: no agent was set up. Add the server by hand: url ' + URL_ + ', header Authorization: Bearer <your key>');
  process.exit(1);
}
console.log(`API Indonesia is connected to ${ok.length} agent${ok.length > 1 ? 's' : ''}: 80+ tools for Indonesian public data`);
console.log('(regions, postal codes, holidays, prayer times, BMKG, exchange rates, UMP, NIK/NPWP checks and more).');
console.log('');
console.log('Last step, the agent has to reload its MCP servers:');
for (const { a } of ok) {
  const hint = local && a === 'claude-code' ? 'open Claude Code in this folder and approve api-indonesia when it asks' : (HINT[a] ?? 'restart it');
  console.log(`  - ${label(a)}: ${hint}`);
}
if (local) console.log('\nThese project files contain your API key. Do not commit them (added to .gitignore if this is a git repo).');
console.log('');
console.log('Then ask it something like: "Pakai API Indonesia, kapan libur nasional berikutnya?"');
if (failed.length) process.exitCode = 2;
JS
}

main "$@"
