#!/usr/bin/env bash

set -euo pipefail

PUBLIC_URL='https://api.omnirouter.ru'
SET_AUTH_TOKEN=0

usage() {
  cat <<'EOF'
OmniRouter Claude Code installer.

Usage:
  bash -s -- [--launch] [omni_api_key] [-- claude_args...]

Behavior:
  - Prompts for Omni API key if not provided
  - Pre-approves the key in Claude Code
  - Writes ANTHROPIC_* vars to a user env file
  - Adds source lines to common shell rc files
  - Optionally launches `claude`

Examples:
  curl -fsSL "https://api.omnirouter.ru/install/claude.sh" | bash
  curl -fsSL "https://api.omnirouter.ru/install/claude.sh" | bash -s -- omni_xxx
  curl -fsSL "https://api.omnirouter.ru/install/claude.sh?auth=oauth" | bash
  curl -fsSL "https://api.omnirouter.ru/install/claude.sh" | bash -s -- --launch -- -p "Hello"

Security:
  - Prefer interactive prompt mode. Passing the key as an argument may leak into shell history.
EOF
}

config_suffix() {
  if [[ -n "${CLAUDE_CODE_CUSTOM_OAUTH_URL:-}" ]]; then
    printf '%s' '-custom-oauth'
    return
  fi

  if [[ "${USER_TYPE:-}" == "ant" ]]; then
    case "${USE_LOCAL_OAUTH:-}" in
      1|true|TRUE|yes|YES|on|ON)
        printf '%s' '-local-oauth'
        return
        ;;
    esac
    case "${USE_STAGING_OAUTH:-}" in
      1|true|TRUE|yes|YES|on|ON)
        printf '%s' '-staging-oauth'
        return
        ;;
    esac
  fi

  printf '%s' ''
}

resolve_claude_config_path() {
  local config_dir home_base suffix
  config_dir="${CLAUDE_CONFIG_DIR:-$HOME/.claude}"
  if [[ -f "$config_dir/.config.json" ]]; then
    printf '%s\n' "$config_dir/.config.json"
    return
  fi

  home_base="${CLAUDE_CONFIG_DIR:-$HOME}"
  suffix="$(config_suffix)"
  printf '%s\n' "$home_base/.claude${suffix}.json"
}

ensure_source_line() {
  local rc_file source_line
  source_line='[ -f "${XDG_CONFIG_HOME:-$HOME/.config}/omnirouter/claude-env.sh" ] && . "${XDG_CONFIG_HOME:-$HOME/.config}/omnirouter/claude-env.sh"'

  for rc_file in "$HOME/.zshrc" "$HOME/.bashrc" "$HOME/.bash_profile" "$HOME/.profile"; do
    touch "$rc_file"
    if ! grep -Fqx "$source_line" "$rc_file"; then
      printf '\n%s\n' "$source_line" >> "$rc_file"
    fi
  done
}

write_env_file() {
  local env_dir env_file
  env_dir="${XDG_CONFIG_HOME:-$HOME/.config}/omnirouter"
  env_file="$env_dir/claude-env.sh"
  mkdir -p "$env_dir"

  {
    printf 'export ANTHROPIC_BASE_URL=%q\n' "$PUBLIC_URL"
    printf 'export ANTHROPIC_API_KEY=%q\n' "$omni_api_key"
    if [[ "$SET_AUTH_TOKEN" == "1" ]]; then
      printf 'export ANTHROPIC_AUTH_TOKEN=%q\n' "$omni_api_key"
    fi
  } > "$env_file"

  chmod 600 "$env_file"
  ensure_source_line
}

prompt_for_key() {
  if [[ -t 0 ]]; then
    read -r -s -p "Enter Omni API key: " omni_api_key
    printf '\n'
    return
  fi

  if [[ -r /dev/tty ]]; then
    read -r -s -p "Enter Omni API key: " omni_api_key < /dev/tty
    printf '\n' > /dev/tty
    return
  fi

  printf 'Omni API key is required.\n' >&2
  printf 'Pass it directly, for example:\n' >&2
  printf '  curl -fsSL "%s/install/claude.sh" | bash -s -- omni_xxx\n' "https://api.omnirouter.ru" >&2
  exit 1
}

launch=0
key_arg=''
declare -a claude_args=()

while (($# > 0)); do
  case "$1" in
    --help|-h)
      usage
      exit 0
      ;;
    --launch)
      launch=1
      shift
      ;;
    --)
      shift
      claude_args=("$@")
      break
      ;;
    -*)
      printf 'Unknown option: %s\n\n' "$1" >&2
      usage >&2
      exit 1
      ;;
    *)
      if [[ -n "$key_arg" ]]; then
        printf 'Unexpected extra argument: %s\n\n' "$1" >&2
        usage >&2
        exit 1
      fi
      key_arg="$1"
      shift
      ;;
  esac
done

if [[ -n "$key_arg" ]]; then
  omni_api_key="$key_arg"
else
  prompt_for_key
fi

if [[ -z "$omni_api_key" ]]; then
  printf 'Omni API key is required.\n' >&2
  exit 1
fi

config_path="$(resolve_claude_config_path)"
mkdir -p "$(dirname "$config_path")"

OMNI_API_KEY="$omni_api_key" CLAUDE_CONFIG_PATH="$config_path" python3 <<'PY'
import json
import os
import pathlib
import sys

key = os.environ["OMNI_API_KEY"]
config_path = pathlib.Path(os.environ["CLAUDE_CONFIG_PATH"])
suffix = key[-20:]

data = {}
if config_path.exists():
    try:
        data = json.loads(config_path.read_text())
    except json.JSONDecodeError as exc:
        print(f"Failed to parse Claude config {config_path}: {exc}", file=sys.stderr)
        sys.exit(1)

resp = data.setdefault("customApiKeyResponses", {})
approved = [value for value in resp.get("approved", []) if value != suffix]
rejected = [value for value in resp.get("rejected", []) if value != suffix]
approved.append(suffix)

resp["approved"] = approved
resp["rejected"] = rejected

config_path.write_text(json.dumps(data, indent=2) + "\n")
PY

write_env_file

export ANTHROPIC_BASE_URL="$PUBLIC_URL"
export ANTHROPIC_API_KEY="$omni_api_key"
if [[ "$SET_AUTH_TOKEN" == "1" ]]; then
  export ANTHROPIC_AUTH_TOKEN="$omni_api_key"
fi

printf 'Claude Code configured for OmniRouter.\n'
printf 'Saved env vars to %s\n' "${XDG_CONFIG_HOME:-$HOME/.config}/omnirouter/claude-env.sh"
printf 'Updated shell startup files: ~/.zshrc, ~/.bashrc, ~/.bash_profile, ~/.profile\n'

if ((launch)); then
  exec claude "${claude_args[@]}"
fi

printf 'Open a new shell or run: source ~/.zshrc\n'
