#!/usr/bin/env bash
# register.sh — registra un nuevo bot en el servidor Matrix via Synapse admin API
#
# Uso:
#   ./dev-scripts/agent/register.sh <username> [displayname]
#
# Ejemplos:
#   ./dev-scripts/agent/register.sh assistant-bot "Assistant"
#   ./dev-scripts/agent/register.sh devops-bot "DevOps Agent"
#
# Genera y guarda en .env:
#   MATRIX_TOKEN_<NORM>=...     (access token)
#   MATRIX_PASSWORD_<NORM>=...  (password para UIA)
#   PICKLE_KEY_<NORM>=...       (E2EE crypto store key)
#
# Requiere en .env:
#   MATRIX_ADMIN_TOKEN=syt_...
#   MATRIX_HOMESERVER=https://...

source "$(dirname "$0")/../_common.sh"
load_env

need_arg "${1:-}"

USERNAME="$1"
DISPLAYNAME="${2:-$USERNAME}"
NORM="$(normalize_id "$USERNAME")"
ENV_VAR="MATRIX_TOKEN_${NORM}"

[[ -n "${MATRIX_ADMIN_TOKEN:-}" ]] || fail "MATRIX_ADMIN_TOKEN no está en .env"
[[ -n "${MATRIX_HOMESERVER:-}" ]]  || fail "MATRIX_HOMESERVER no está en .env"

info "Registrando @${USERNAME}:${MATRIX_SERVER_NAME:-$MATRIX_HOMESERVER}..."
dim "  Env var prefix: ${NORM}"
echo ""

# Ejecutar cmd/register y capturar su output completo
OUTPUT=$("$GO" run ./cmd/register \
  --homeserver "$MATRIX_HOMESERVER" \
  --username   "$USERNAME" \
  --displayname "$DISPLAYNAME" \
  --env-var    "$ENV_VAR" 2>&1) || fail "cmd/register falló:\n$OUTPUT"

echo "$OUTPUT"
echo ""

# ── Parsear y guardar cada variable en .env ──────────────────────────────

save_env_var() {
  local key="$1" value="$2"
  [[ -n "$value" ]] || return

  # Quote values with spaces
  if [[ "$value" == *" "* ]]; then
    value="\"${value}\""
  fi

  if grep -q "^${key}=" .env; then
    awk -v key="$key" -v val="$value" \
      'index($0, key "=") == 1 { print key "=" val; next } { print }' \
      .env > /tmp/_env_tmp && mv /tmp/_env_tmp .env
    ok "$key actualizado en .env"
  else
    printf '%s=%s\n' "$key" "$value" >> .env
    ok "$key añadido a .env"
  fi
}

# Extract parseable lines from output
TOKEN=$(echo "$OUTPUT" | grep "^${ENV_VAR}=" | cut -d= -f2-)
PASSWORD=$(echo "$OUTPUT" | grep "^MATRIX_PASSWORD_${NORM}=" | cut -d= -f2-)
PICKLE_KEY=$(echo "$OUTPUT" | grep "^PICKLE_KEY_${NORM}=" | cut -d= -f2-)

[[ -n "$TOKEN" ]] || fail "No se encontró '${ENV_VAR}=' en el output"

save_env_var "$ENV_VAR" "$TOKEN"
save_env_var "MATRIX_PASSWORD_${NORM}" "$PASSWORD"
save_env_var "PICKLE_KEY_${NORM}" "$PICKLE_KEY"

echo ""
echo -e "${YLW}Siguientes pasos:${RST}"
echo ""
echo -e "  ${DIM}1. ./dev-scripts/agent/verify.sh $USERNAME${RST}   # genera cross-signing keys E2EE"
echo -e "  ${DIM}2. ./dev-scripts/server/start.sh $USERNAME${RST}    # arranca el agente"
echo ""
