#!/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}"
if [ -z "$CONFIG_PATH" ]; then CONFIG_PATH="$HOME/.codex/config.toml"; fi
if [ "$APPLY" -ne 1 ]; then
  echo "DRY RUN: would append ITHZ-MCP Codex config to $CONFIG_PATH"
  echo "Project: $PROJECT"
  echo "Launcher: $LAUNCHER"
  echo "Storage profile: $STORAGE_PROFILE"
  exit 0
fi
mkdir -p "$(dirname "$CONFIG_PATH")"
if [ -f "$CONFIG_PATH" ]; then cp "$CONFIG_PATH" "$CONFIG_PATH.bak"; fi
ITHZ_PROJECT="$PROJECT" ITHZ_LAUNCHER="$LAUNCHER" ITHZ_STORAGE_PROFILE="$STORAGE_PROFILE" "$PYTHON" - <<'PY' >> "$CONFIG_PATH"
import os
from pathlib import Path
from ithz_mcp.host_install import codex_toml_snippet
project = Path(os.environ["ITHZ_PROJECT"])
launcher = Path(os.environ["ITHZ_LAUNCHER"])
storage_profile = os.environ["ITHZ_STORAGE_PROFILE"]
print()
print(codex_toml_snippet(project, launcher if launcher.exists() else None, storage_profile=storage_profile))
PY
echo "Installed ITHZ-MCP Codex config: $CONFIG_PATH"
