#!/bin/sh
set -eu

os_name="$(uname -s 2>/dev/null || printf '%s' unknown)"
case "$os_name" in
  Linux) system_name="Linux" ;;
  Darwin) system_name="macOS" ;;
  *) echo "This script supports macOS/Linux only. Use the Windows .cmd/.ps1 script on Windows."; exit 1 ;;
esac

if [ "${HOME:-}" = "" ]; then
  echo "Cannot determine home directory."
  exit 1
fi

home_dir="$HOME"

codex_dir="$home_dir/.codex"
config_path="$codex_dir/config.toml"
auth_path="$codex_dir/auth.json"

is_codex_running() {
  if command -v pgrep >/dev/null 2>&1; then
    pgrep -if '(^|/)(Codex|Code X)(\.app/Contents/MacOS/Codex)?([[:space:]]|$)' >/dev/null 2>&1
    return $?
  fi

  ps -ef 2>/dev/null | grep -Ei '(^|/)(Codex|Code X)(\.app/Contents/MacOS/Codex)?([[:space:]]|$)' | grep -v grep >/dev/null 2>&1
}

stop_codex_if_running() {
  if ! is_codex_running; then
    return 0
  fi

  echo "Detected running Code X/Codex. Stopping it before updating config..."

  if [ "$system_name" = "macOS" ] && command -v osascript >/dev/null 2>&1; then
    osascript -e 'tell application "Codex" to quit' >/dev/null 2>&1 || true
    sleep 2
  fi

  if is_codex_running; then
    if command -v pkill >/dev/null 2>&1; then
      pkill -if '(^|/)(Codex|Code X)(\.app/Contents/MacOS/Codex)?([[:space:]]|$)' >/dev/null 2>&1 || true
      sleep 1
    fi
  fi

  if is_codex_running; then
    echo "Unable to stop Code X/Codex automatically. Please close it manually and rerun."
    exit 1
  fi

  echo "Code X/Codex has exited."
}

mkdir -p "$codex_dir"
stop_codex_if_running

backup_file() {
  src="$1"
  if [ -f "$src" ]; then
    stamp="$(date +%Y%m%d-%H%M%S)"
    cp "$src" "$src.bak.$stamp"
    echo "Backed up $src -> $src.bak.$stamp"
  fi
}

backup_file "$config_path"
backup_file "$auth_path"

printf '%s\n' "Enter EveryGPT API key:"
if [ -t 0 ]; then
  old_stty="$(stty -g)"
  stty -echo
  IFS= read -r api_key
  stty "$old_stty"
  printf '\n'
else
  IFS= read -r api_key
fi

if [ -z "${api_key:-}" ]; then
  echo "API key cannot be empty."
  exit 1
fi

cat > "$config_path" <<EOF
model_provider = "custom"
model = "gpt-5.5"
review_model = "gpt-5.5"
model_reasoning_effort = "xhigh"
disable_response_storage = true
network_access = "enabled"

[model_providers.custom]
name = "EveryGPT"
base_url = "https://api.everygpt.site/v1"
wire_api = "responses"
requires_openai_auth = true

[features]
goals = true

EOF

api_key_escaped=$(printf '%s' "$api_key" | sed 's/\\/\\\\/g; s/"/\\"/g')
cat > "$auth_path" <<EOF
{
  "OPENAI_API_KEY": "$api_key_escaped"
}
EOF

chmod 600 "$config_path" "$auth_path" 2>/dev/null || true

echo "Wrote config: $config_path"
echo "Wrote auth:   $auth_path"
echo "Detected OS:  $system_name"
