#!/bin/sh
# Gephyra shim for claudeCode.claudeProcessWrapper.
# Contract (verified, ext 2.1.220): the Claude extension launches THIS
# executable with the real CLI as argv[1] — the bundled native-binary path,
# or [node, cli.js] when that fallback is in play — followed by the CLI
# flags. Fail OPEN: on any doubt, exec the real CLI untouched so Claude Code
# keeps working.

set -u

# Resolve the config directory the same way the extension does: the current
# name wins, the pre-rename directory is used while it is the only one present.
# The two MUST agree — the extension writes state.json and this shim reads it.
CONFIG_DIR="${HOME}/.config/gephyra"
if [ ! -d "${CONFIG_DIR}" ] && [ -d "${HOME}/.config/cc-gg-bridgy" ]; then  # allow-published-string: former config dir, migration path
  CONFIG_DIR="${HOME}/.config/cc-gg-bridgy"  # allow-published-string
fi
STATE_FILE="${CONFIG_DIR}/state.json"
DEBUG_LOG="${CONFIG_DIR}/debug.log"
# The extension's spawn env is not injectable from outside, so a flag FILE
# also enables debug; an explicit env value (even 0) still wins.
if [ -z "${GEPHYRA_DEBUG:-}" ] && [ -f "${CONFIG_DIR}/debug-on" ]; then
  GEPHYRA_DEBUG=1
fi
# Extension stores realpath'd project keys; compare against the physical cwd.
PWD_REAL="$(pwd -P)"

debug() {
  [ "${GEPHYRA_DEBUG:-0}" = "1" ] || return 0
  mkdir -p "$CONFIG_DIR"
  if [ -f "$DEBUG_LOG" ] && [ "$(wc -c <"$DEBUG_LOG")" -gt 524288 ]; then
    : >"$DEBUG_LOG"
  fi
  printf '%s | cwd=%s | %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$PWD_REAL" "$*" >>"$DEBUG_LOG"
}

# Provider for this project from state.json. A provider is any name with an
# env profile at ${CONFIG_DIR}/<name>.env; "anthropic" is reserved for the
# clean-env passthrough. The quoted key is matched as a FIXED string (both
# quotes included, so one path can never prefix-match another) and the value
# is whatever quoted token follows its colon — pretty-printed and compact
# separators both parse. The value charset is restricted; a missing or
# malformed project value falls through to "default" (mirroring the
# extension's readState), and anything still unresolved fails closed to
# anthropic.
value_for_key() {
  line="$(grep -F "$1" "$STATE_FILE" | head -n 1)"
  [ -n "$line" ] || return 0
  rest="${line#*"$1"}"
  printf '%s\n' "$rest" | sed -n 's/^[[:space:]]*:[[:space:]]*"\([A-Za-z0-9_-]*\)".*/\1/p'
}

provider() {
  [ -f "$STATE_FILE" ] || { echo anthropic; return; }
  value="$(value_for_key "\"$PWD_REAL\"")"
  if [ -z "$value" ]; then
    value="$(value_for_key '"default"')"
  fi
  if [ -n "$value" ]; then
    echo "$value"
  else
    echo anthropic
  fi
}

# Vision proxy URL folded into state.json (formerly a standalone vision-proxy.url
# file). Unlike provider(), the value is a URL (colon/slash/dot), so capture
# everything between the quotes after the "visionProxyUrl" key — not the
# [A-Za-z0-9_-] charset provider() uses.
proxy_url() {
  [ -f "$STATE_FILE" ] || return 0
  line="$(grep -F '"visionProxyUrl"' "$STATE_FILE" | head -n 1)"
  [ -n "$line" ] || return 0
  printf '%s\n' "$line" | sed -n 's/.*"visionProxyUrl"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p'
}

# KEY=value lines only — parsed, never sourced, so a malformed value can't
# execute shell or half-apply the env.
load_env_file() {
  while IFS= read -r line || [ -n "$line" ]; do
    case "$line" in
    '' | \#*) continue ;;
    [A-Za-z_]*=*) export "${line?}" ;;
    *) debug "$1: skipped malformed line" ;;
    esac
  done <"$1"
}

# The reference tier-label mapping is glm.env. A provider env that omits the
# ANTHROPIC_DEFAULT_*_MODEL tiers inherits them from glm.env so /model shows
# real names instead of falling through to built-in Anthropic ids. Only TIER
# vars are inherited — NEVER BASE_URL / AUTH_TOKEN (those stay the provider's
# own), and a var the provider DID set always wins.
GLM_ENV="${CONFIG_DIR}/glm.env"
glm_value() {
  while IFS= read -r line || [ -n "$line" ]; do
    case "$line" in
    "$1="*) printf '%s\n' "${line#"$1="}"; return ;;
    esac
  done <"$GLM_ENV"
}
inject_tier_fallback() {
  [ -f "$GLM_ENV" ] || return 0
  for var in ANTHROPIC_DEFAULT_FABLE_MODEL ANTHROPIC_DEFAULT_FABLE_MODEL_NAME \
             ANTHROPIC_DEFAULT_OPUS_MODEL ANTHROPIC_DEFAULT_OPUS_MODEL_NAME \
             ANTHROPIC_DEFAULT_SONNET_MODEL ANTHROPIC_DEFAULT_SONNET_MODEL_NAME \
             ANTHROPIC_DEFAULT_HAIKU_MODEL ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME; do
    eval "cur=\${$var:-}"
    if [ -z "$cur" ]; then
      val="$(glm_value "$var")"
      if [ -n "$val" ]; then
        export "$var=$val"
        debug "tier fallback $var=$val (from glm.env)"
      fi
    fi
  done
}

# Real CLI when argv doesn't carry one: newest (by mtime) bundled binary from
# any installed Claude extension, else the system claude.
find_cli() {
  newest=""
  for d in "${HOME}/.cursor/extensions"/anthropic.claude-code-*/resources/native-binary/claude \
    "${HOME}/.vscode/extensions"/anthropic.claude-code-*/resources/native-binary/claude; do
    [ -x "$d" ] || continue
    if [ -z "$newest" ] || [ "$d" -nt "$newest" ]; then
      newest="$d"
    fi
  done
  if [ -n "$newest" ]; then
    echo "$newest"
  else
    command -v claude || true
  fi
}

PROVIDER="$(provider)"
debug "provider=$PROVIDER argv=$*"

if [ "$PROVIDER" != "anthropic" ]; then
  ENV_FILE="${CONFIG_DIR}/${PROVIDER}.env"
  # GEPHYRA_GLM_ENV overrides the path of the glm profile.
  if [ "$PROVIDER" = "glm" ] && [ -n "${GEPHYRA_GLM_ENV:-}" ]; then
    ENV_FILE="$GEPHYRA_GLM_ENV"
  fi
  if [ -f "$ENV_FILE" ]; then
    load_env_file "$ENV_FILE"
    debug "provider env loaded from $ENV_FILE"
  else
    debug "no env profile at $ENV_FILE — running clean (anthropic)"
  fi
fi

# Vision proxy (opt-in): when a proxy URL is present in state.json (written by
# the extension's proxy host), route this non-Anthropic provider's traffic
# through it so image turns can be served by Anthropic while text/code stays on
# the provider. Its absence means the proxy is off or unreachable, and the
# provider's own ANTHROPIC_BASE_URL stays in place (fail-open). The provider
# name is appended as a path prefix so one shared proxy resolves the upstream.
if [ "$PROVIDER" != "anthropic" ]; then
  VP_URL="$(proxy_url)"
  if [ -n "$VP_URL" ]; then
    export ANTHROPIC_BASE_URL="${VP_URL}/${PROVIDER}"
    debug "vision proxy on: ANTHROPIC_BASE_URL -> ${VP_URL}/${PROVIDER}"
  fi
fi

if [ "$#" -ge 1 ]; then
  # Interpreter-style argv (bare "node" or a .js entry) — resolve, don't guess.
  case "$1" in
  node)
    NODE_BIN="$(command -v node || true)"
    if [ -n "$NODE_BIN" ]; then
      shift
      debug "exec node passthrough: $NODE_BIN"
      exec "$NODE_BIN" "$@"
    fi
    ;;
  *.js)
    NODE_BIN="$(command -v node || true)"
    if [ -n "$NODE_BIN" ]; then
      debug "exec node script passthrough: $NODE_BIN $1"
      exec "$NODE_BIN" "$@"
    fi
    ;;
  esac
  if [ -f "$1" ] && [ -x "$1" ]; then
    debug "exec passthrough: $1"
    exec "$@"
  fi
fi

CLI="$(find_cli)"
if [ -n "$CLI" ]; then
  debug "exec discovered CLI: $CLI"
  exec "$CLI" "$@"
fi

echo "gephyra-wrapper: no Claude CLI found" >&2
exit 127
