#!/usr/bin/env bash
set -euo pipefail

# Resolve the real script path even when invoked through a symlink (e.g. the
# npm global `bin/unieai` shim), so ROOT_DIR points at the package dir and not
# the node prefix. Without this, `bun ./src/entrypoints/cli.tsx` is not found.
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do
  DIR="$(cd -P "$(dirname "$SOURCE")" >/dev/null 2>&1 && pwd)"
  SOURCE="$(readlink "$SOURCE")"
  [ "${SOURCE#/}" = "$SOURCE" ] && SOURCE="$DIR/$SOURCE"
done
ROOT_DIR="$(cd -P "$(dirname "$SOURCE")/.." >/dev/null 2>&1 && pwd)"
#Get your current working directory and export it as an environment variable.
export CALLER_DIR="${CALLER_DIR:-$(pwd -W 2>/dev/null || pwd)}"

# UnieAI Code: keep state (sessions / plugins / skills / MCP / login / theme)
# isolated from the upstream Claude Code install. Honors a user-set
# CLAUDE_CONFIG_DIR or an explicit UNIEAI_CONFIG_DIR; otherwise defaults to
# ~/.unieai. Anyone who wants to share state with ~/.claude can opt in by
# setting CLAUDE_CONFIG_DIR="$HOME/.claude" before launching.
if [[ -z "${CLAUDE_CONFIG_DIR:-}" ]]; then
  export CLAUDE_CONFIG_DIR="${UNIEAI_CONFIG_DIR:-$HOME/.unieai}"
fi
mkdir -p "$CLAUDE_CONFIG_DIR"

cd "$ROOT_DIR"

# When spawned by the desktop/web server as a child CLI process,
# skip .env loading — the server has already set the correct env
# via cc-haha/settings.json. Loading .env would re-inject stale
# provider keys (e.g., a MiniMax key as ANTHROPIC_API_KEY) that
# override the active provider config.
if [[ "${CC_HAHA_SKIP_DOTENV:-0}" == "1" ]]; then
  # Bun auto-loads .env by default; explicitly point to /dev/null to suppress.
  ENV_FILE_FLAG="--env-file=/dev/null"
elif [[ -f .env ]]; then
  ENV_FILE_FLAG="--env-file=.env"
else
  ENV_FILE_FLAG=""
fi

# Force recovery CLI (simple readline REPL, no Ink TUI)
if [[ "${CLAUDE_CODE_FORCE_RECOVERY_CLI:-0}" == "1" ]]; then
  exec bun $ENV_FILE_FLAG ./src/localRecoveryCli.ts "$@"
fi

# Default: full CLI with Ink TUI
exec bun $ENV_FILE_FLAG ./src/entrypoints/cli.tsx "$@"
