#!/usr/bin/env sh
set -eu
PROJECT=""
APPLY=0
CONFIG_PATH=""
while [ "$#" -gt 0 ]; do
  case "$1" in
    --project) PROJECT="$2"; shift 2 ;;
    --config-path) CONFIG_PATH="$2"; shift 2 ;;
    --apply) APPLY=1; shift ;;
    --help|-h) echo "Usage: $0 [--project PATH] [--config-path PATH] [--apply]"; exit 0 ;;
    *) echo "Unknown argument: $1" >&2; exit 2 ;;
  esac
done
if [ -z "$PROJECT" ]; then PROJECT="$(pwd)"; fi
PROJECT="$(cd "$PROJECT" && pwd)"
SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
PACKAGE_ROOT="$(CDPATH= cd -- "$SCRIPT_DIR/.." && pwd)"
LAUNCHER="${ITHZ_MCP_LAUNCHER:-$PACKAGE_ROOT/ithz_mcp_server.sh}"
PYTHON="${PYTHON:-python3}"
STORAGE_PROFILE="${ITHZ_MCP_STORAGE_PROFILE:-native-archive}"
export PYTHONPATH="$PACKAGE_ROOT/src:$PACKAGE_ROOT${PYTHONPATH:+:$PYTHONPATH}"
CLIENT="antigravity"
if [ -z "$CONFIG_PATH" ]; then CONFIG_PATH="$PROJECT/.antigravity/mcp.json"; fi
if [ "$APPLY" -ne 1 ]; then
  echo "DRY RUN: would write $CLIENT config to $CONFIG_PATH"
  echo "Project: $PROJECT"
  echo "Launcher: $LAUNCHER"
  echo "Storage profile: $STORAGE_PROFILE"
  exit 0
fi
mkdir -p "$(dirname "$CONFIG_PATH")"
ITHZ_PROJECT="$PROJECT" ITHZ_LAUNCHER="$LAUNCHER" ITHZ_STORAGE_PROFILE="$STORAGE_PROFILE" ITHZ_CLIENT="$CLIENT" ITHZ_CONFIG_PATH="$CONFIG_PATH" "$PYTHON" - <<'PY'
import os
from pathlib import Path
from ithz_mcp.canonical_json import dump_pretty
from ithz_mcp.host_install import host_config
project = Path(os.environ["ITHZ_PROJECT"])
launcher = Path(os.environ["ITHZ_LAUNCHER"])
client = os.environ["ITHZ_CLIENT"]
storage_profile = os.environ["ITHZ_STORAGE_PROFILE"]
config_path = Path(os.environ["ITHZ_CONFIG_PATH"])
cfg = host_config(project, client, launcher if launcher.exists() else None, storage_profile=storage_profile)
config_path.write_text(dump_pretty(cfg), encoding="utf-8")
PY
echo "Installed ITHZ-MCP $CLIENT config: $CONFIG_PATH"
