#!/usr/bin/env bash
# CodeRAG MCP launcher — Rust rmcp only (fail-closed, no TS fallback).
# Resolves platform-matched native via optionalDependencies, staged bin/native, or local cargo target.
set -euo pipefail

PACKAGE_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
REPO_ROOT="$(cd "$PACKAGE_ROOT/../.." && pwd)"

host_platform_key() {
	local os arch
	os="$(uname -s 2>/dev/null || echo unknown)"
	arch="$(uname -m 2>/dev/null || echo unknown)"
	case "$os" in
		Darwin) os="darwin" ;;
		Linux) os="linux" ;;
		MINGW*|MSYS*|CYGWIN*|Windows_NT) os="win32" ;;
		*) os="$(printf '%s' "$os" | tr '[:upper:]' '[:lower:]')" ;;
	esac
	case "$arch" in
		x86_64|amd64) arch="x64" ;;
		aarch64|arm64) arch="arm64" ;;
		armv7l) arch="arm" ;;
		i386|i686) arch="ia32" ;;
	esac
	printf '%s-%s\n' "$os" "$arch"
}

platform_package_name() {
	case "$(host_platform_key)" in
		darwin-arm64) printf '%s\n' '@sylphx/locus-darwin-arm64' ;;
		darwin-x64) printf '%s\n' '@sylphx/locus-darwin-x64' ;;
		linux-x64) printf '%s\n' '@sylphx/locus-linux-x64-gnu' ;;
		linux-arm64) printf '%s\n' '@sylphx/locus-linux-arm64-gnu' ;;
		*) return 1 ;;
	esac
}

is_runnable_native() {
	local candidate="$1"
	[[ -n "$candidate" && -f "$candidate" && -x "$candidate" ]] || return 1

	if command -v file >/dev/null 2>&1; then
		local info
		info="$(file -b "$candidate" 2>/dev/null || true)"
		case "$(host_platform_key)" in
			darwin-arm64)
				[[ "$info" == *"Mach-O"* && ( "$info" == *"arm64"* || "$info" == *"aarch64"* ) ]] || return 1
				;;
			darwin-x64)
				[[ "$info" == *"Mach-O"* && ( "$info" == *"x86_64"* || "$info" == *"x86-64"* ) ]] || return 1
				;;
			linux-x64)
				[[ "$info" == *"ELF"* && ( "$info" == *"x86-64"* || "$info" == *"x86_64"* ) ]] || return 1
				;;
			linux-arm64)
				[[ "$info" == *"ELF"* && ( "$info" == *"aarch64"* || "$info" == *"ARM aarch64"* || "$info" == *"arm64"* ) ]] || return 1
				;;
		esac
	fi
	return 0
}

resolve_from_optional_dep() {
	local pkg_name pkg_dir candidate
	pkg_name="$(platform_package_name 2>/dev/null || true)"
	[[ -n "$pkg_name" ]] || return 1

	local search_roots=(
		"$PACKAGE_ROOT/node_modules"
		"$REPO_ROOT/node_modules"
		"$PACKAGE_ROOT/../node_modules"
		"$PACKAGE_ROOT/../../node_modules"
		"$PACKAGE_ROOT/../../../node_modules"
	)

	for root in "${search_roots[@]}"; do
		pkg_dir="$root/$pkg_name"
		candidate="$pkg_dir/locus-mcp-server"
		if is_runnable_native "$candidate"; then
			printf '%s\n' "$candidate"
			return 0
		fi
	done

	if command -v node >/dev/null 2>&1; then
		candidate="$(
			node -e "
        try {
          const p = require('node:path');
          const { createRequire } = require('node:module');
          const r = createRequire(p.join('$PACKAGE_ROOT', 'package.json'));
          const pkg = r.resolve('$pkg_name/package.json');
          process.stdout.write(p.join(p.dirname(pkg), 'locus-mcp-server'));
        } catch {
          process.exit(1);
        }
      " 2>/dev/null || true
		)"
		if is_runnable_native "${candidate:-}"; then
			printf '%s\n' "$candidate"
			return 0
		fi
	fi

	return 1
}

resolve_rust_bin() {
	if [[ -n "${LOCUS_RUST_BIN:-}" ]]; then
		if is_runnable_native "${LOCUS_RUST_BIN}"; then
			printf '%s\n' "${LOCUS_RUST_BIN}"
			return 0
		fi
		echo "[locus] LOCUS_RUST_BIN is set but not a runnable native for $(host_platform_key): ${LOCUS_RUST_BIN}" >&2
		return 1
	fi

	local candidate
	if candidate="$(resolve_from_optional_dep)"; then
		printf '%s\n' "$candidate"
		return 0
	fi

	for candidate in \
		"$PACKAGE_ROOT/bin/native/locus-mcp-server" \
		"$REPO_ROOT/bin/native/locus-mcp-server" \
		"$REPO_ROOT/target/release/locus-mcp-server" \
		"$REPO_ROOT/target/debug/locus-mcp-server"; do
		if is_runnable_native "$candidate"; then
			printf '%s\n' "$candidate"
			return 0
		fi
	done

	return 1
}

resolve_transport() {
	if [[ -n "${CODERAG_MCP_TRANSPORT:-}" ]]; then
		printf '%s\n' "${CODERAG_MCP_TRANSPORT}"
		return 0
	fi
	if [[ -n "${MCP_TRANSPORT:-}" ]]; then
		printf '%s\n' "${MCP_TRANSPORT}"
		return 0
	fi
	printf '%s\n' "stdio"
}

if bin="$(resolve_rust_bin)"; then
	transport="$(resolve_transport)"
	if [[ "$transport" == "http" ]]; then
		export MCP_TRANSPORT=http
		export CODERAG_MCP_TRANSPORT=http
	fi
	exec "$bin" "$@"
fi

host="$(host_platform_key)"
pkg="$(platform_package_name 2>/dev/null || true)"
echo "[locus] No runnable Rust MCP server for host platform: ${host}" >&2
if [[ -n "${pkg:-}" ]]; then
	echo "[locus] Expected optionalDependency package: ${pkg} (locus-mcp-server binary)." >&2
	echo "[locus] Reinstall with optional deps enabled, or run: bun run build:rust" >&2
else
	echo "[locus] Unsupported platform for published natives. Supported: darwin-arm64, darwin-x64, linux-x64, linux-arm64." >&2
	echo "[locus] Build from source: bun run build:rust" >&2
fi
exit 1
