#!/usr/bin/env bash

# SPDX-FileCopyrightText: 2026 Jiri Vyskocil
# SPDX-FileCopyrightText: 2026 Andreas Knüpfer
# SPDX-License-Identifier: Apache-2.0
# terok:container — this file is deployed into task containers, not used on the host.

# Toad launcher wrapper.
# Seeds launcher.agents into toad.json before exec-ing the real binary.
# This runs on every invocation so the agent list survives toad's own
# config writes (which drop keys it doesn't manage internally).

set -euo pipefail

TOAD_CONFIG="${HOME}/.config/toad/toad.json"
TOAD_REAL="${HOME}/.local/share/uv/tools/batrachian-toad/bin/toad"

# Agents pre-installed in the container image (newline-separated identities).
LAUNCHER_AGENTS="claude.com
vibe.mistral.ai
openai.com
copilot.github.com
opencode.ai
blablador.helmholtz.de
kisski.academiccloud.de"

# Inject custom agent TOML for Blablador into Toad's package data.
# Toad only reads agents from its bundled data dir — no user override dir yet.
# Glob the python version to survive upgrades (e.g. 3.14 → 3.15).
TOAD_AGENTS_DIR=""
for _candidate in "${HOME}"/.local/share/uv/tools/batrachian-toad/lib/python*/site-packages/toad/data/agents; do
  if [[ -d "${_candidate}" ]]; then
    TOAD_AGENTS_DIR="${_candidate}"
    break
  fi
done
if [[ -z "${TOAD_AGENTS_DIR}" ]]; then
  echo "Warning: Toad agents dir not found; agent TOML injection skipped" >&2
fi

# Inject bundled agent TOML files from /usr/local/share/terok/toad-agents/
# into Toad's package data directory.  Each .toml file describes an ACP agent.
TEROK_TOAD_AGENTS="/usr/local/share/terok/toad-agents"
if [[ -n "${TOAD_AGENTS_DIR}" ]] && [[ -d "${TEROK_TOAD_AGENTS}" ]]; then
  for _toml_src in "${TEROK_TOAD_AGENTS}"/*.toml; do
    [[ -f "${_toml_src}" ]] || continue
    _toml_name="${_toml_src##*/}"
    _toml_dest="${TOAD_AGENTS_DIR}/${_toml_name}"
    if [[ ! -f "${_toml_dest}" ]]; then
      _toml_tmp=$(mktemp "${_toml_dest}.XXXXXX" 2>/dev/null) || continue
      if cp "${_toml_src}" "${_toml_tmp}" 2>/dev/null; then
        mv -f "${_toml_tmp}" "${_toml_dest}" 2>/dev/null \
          || { echo "Warning: could not install ${_toml_name}" >&2; rm -f "${_toml_tmp}"; }
      else
        echo "Warning: failed to copy ${_toml_name}" >&2
        rm -f "${_toml_tmp}"
      fi
    fi
  done
fi

# ---------------------------------------------------------------------------
# Patch agent TOMLs to use terok ACP wrappers.
#
# Toad launches ACP agents by exec-ing the command from run_command."*" in
# the agent's TOML file.  By default these point to the bare upstream
# adapters (claude-agent-acp, opencode acp, etc.) which bypass terok's
# per-agent git identity setup.
#
# We replace those commands with terok wrappers that configure the
# environment before exec-ing the real adapter.  Patching is idempotent.
# ---------------------------------------------------------------------------
_patch_run_command() {
  local file="$1" wrapper="$2"
  [[ -f "$file" ]] || return 0
  # Anchor the check to the run_command line to avoid false positives from
  # the wrapper name appearing in help text or comments.
  grep -qE '^run_command\.\"\*\"[[:space:]]*=[[:space:]]*\"'"${wrapper}"'\"' "$file" 2>/dev/null \
      && return 0
  sed -i '/^run_command\.\"\*\"/s|= .*|= "'"${wrapper}"'"|' "$file"
}

if [[ -n "${TOAD_AGENTS_DIR}" ]]; then
  _patch_run_command "${TOAD_AGENTS_DIR}/claude.com.toml"          "terok-claude-acp"
  _patch_run_command "${TOAD_AGENTS_DIR}/openai.com.toml"          "terok-codex-acp"
  _patch_run_command "${TOAD_AGENTS_DIR}/opencode.ai.toml"         "terok-opencode-acp"
  _patch_run_command "${TOAD_AGENTS_DIR}/copilot.github.com.toml"  "terok-copilot-acp"
  _patch_run_command "${TOAD_AGENTS_DIR}/vibe.mistral.ai.toml"     "terok-vibe-acp"
  # OpenCode-based providers (blablador-acp, kisski-acp) are symlinks to
  # opencode-provider-acp which already sources terok-acp-env.sh — no patching needed.
fi

if command -v jq >/dev/null 2>&1; then
  mkdir -p "$(dirname "${TOAD_CONFIG}")"
  existing='{}'
  if [[ -f "${TOAD_CONFIG}" ]]; then
    raw=$(cat "${TOAD_CONFIG}" 2>/dev/null || true)
    # Reset to empty object if file is corrupt / not valid JSON.
    existing=$(printf '%s' "${raw}" | jq -e '.' 2>/dev/null) || existing='{}'
  fi

  # Ensure all expected agents are in the launcher (append missing ones).
  current=$(printf '%s' "${existing}" | jq -r '.launcher.agents // ""' 2>/dev/null)
  missing=""
  while IFS= read -r agent; do
    [[ -z "${agent}" ]] && continue
    if ! printf '%s\n' "${current}" | grep -qxF -- "${agent}"; then
      missing="${missing:+${missing}
}${agent}"
    fi
  done <<< "${LAUNCHER_AGENTS}"

  if [[ -n "${missing}" ]]; then
    new_agents="${current:+${current}
}${missing}"
    updated=$(printf '%s' "${existing}" | jq --arg agents "${new_agents}" \
      '.launcher.agents = $agents' 2>/dev/null) || true
    if [[ -n "${updated}" ]]; then
      tmpfile=$(mktemp "${TOAD_CONFIG}.XXXXXX") || true
      if [[ -n "${tmpfile}" ]]; then
        printf '%s\n' "${updated}" > "${tmpfile}" && mv -f "${tmpfile}" "${TOAD_CONFIG}" \
          || rm -f "${tmpfile}"
      fi
    fi
  fi
fi

exec "${TOAD_REAL}" "$@"
