#!/usr/bin/env bash
# create-full.sh — pipeline completo para crear un agente o robot funcional
#
# Ejecuta en orden: scaffold → build → register → verify E2EE → [convert robot] → [notify dev]
# NO arranca el agente — primero personalizar agent.go, config.yaml y prompts/system.md
#
# Uso:
#   ./dev-scripts/agent/create-full.sh <agent-id> "Display Name"              # agente (default)
#   ./dev-scripts/agent/create-full.sh <agent-id> "Display Name" --type robot # robot
#
# Requisitos en .env:
#   MATRIX_ADMIN_TOKEN, MATRIX_HOMESERVER, MATRIX_SERVER_NAME
#   DEVELOPER_MATRIX_USERS (opcional, para notificación al developer)

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

need_arg "${1:-}"

ID="$1"
DISPLAYNAME="${2:-$ID}"
TYPE="agent"
NORM="$(normalize_id "$ID")"
SCRIPT_DIR="$(dirname "$0")"

# Parse --type flag
shift 2 2>/dev/null || shift 1 2>/dev/null || true
while [[ $# -gt 0 ]]; do
  case "$1" in
    --type)
      TYPE="${2:-agent}"
      shift 2
      ;;
    --type=*)
      TYPE="${1#--type=}"
      shift
      ;;
    *)
      shift
      ;;
  esac
done

if [[ "$TYPE" == "robot" ]]; then
  TYPE_LABEL="robot"
  TYPE_EMOJI="🤖"
else
  TYPE_LABEL="agente"
  TYPE_EMOJI="🧠"
fi

echo ""
echo -e "${BLU}═══════════════════════════════════════════════════════${RST}"
echo -e "${BLU}  Creando ${TYPE_LABEL}: ${GRN}$ID${BLU} ($DISPLAYNAME) ${TYPE_EMOJI}${RST}"
echo -e "${BLU}═══════════════════════════════════════════════════════${RST}"
echo ""

# ── Paso 1: Scaffold ─────────────────────────────────────────────────────
TOTAL_STEPS=6
[[ "$TYPE" == "robot" ]] && TOTAL_STEPS=7

info "Paso 1/${TOTAL_STEPS} — Scaffold (agent.go, config.yaml, prompts, launcher)"
echo ""

"$SCRIPT_DIR/new-agent.sh" "$ID" "$DISPLAYNAME"

echo ""

# ── Paso 2: Verificar compilación ─────────────────────────────────────────
info "Paso 2/${TOTAL_STEPS} — Verificando compilación..."

if "$GO" build -tags goolm ./... 2>&1; then
  ok "Compilación exitosa"
else
  fail "Error de compilación — revisa agents/$ID/agent.go y cmd/launcher/main.go"
fi

echo ""

# ── Paso 3: Registrar en Matrix ──────────────────────────────────────────
info "Paso 3/${TOTAL_STEPS} — Registrando en Matrix..."
echo ""

# Reload .env in case new-agent.sh or previous steps changed it
load_env

"$SCRIPT_DIR/register.sh" "$ID" "$DISPLAYNAME"

echo ""

# ── Paso 4: Verificar E2EE ───────────────────────────────────────────────
info "Paso 4/${TOTAL_STEPS} — Verificación E2EE (cross-signing + recovery key)..."
echo ""

# Reload .env to pick up token, password, pickle key from register.sh
load_env

"$SCRIPT_DIR/verify.sh" "$ID"

echo ""

# ── Paso 5 (robots): Convertir a robot ───────────────────────────────────
if [[ "$TYPE" == "robot" ]]; then
  info "Paso 5/${TOTAL_STEPS} — Convirtiendo a robot..."
  echo ""

  "$SCRIPT_DIR/convert-to-robot.sh" "$ID" "$DISPLAYNAME"

  # Rebuild after conversion
  info "Recompilando tras conversión..."
  "$GO" build -tags goolm ./... 2>&1 || fail "Error de compilación tras conversión a robot"
  ok "Recompilación exitosa"

  echo ""
fi

# ── Paso auto-avatar: Generar avatar automatico ─────────────────────────
AVATAR_STEP=$((TOTAL_STEPS - 1))
info "Paso ${AVATAR_STEP}/${TOTAL_STEPS} — Generando avatar automatico..."
echo ""

# Resuelve el binario de agentctl
if [[ -f "$REPO_ROOT/bin/agentctl" ]]; then
  CTL="$REPO_ROOT/bin/agentctl"
else
  CTL="$GO run -tags goolm ./cmd/agentctl"
fi

if $CTL auto-avatar "$ID" 2>&1; then
  ok "Avatar generado y aplicado"
else
  warn "No se pudo generar avatar automatico (se puede hacer despues con: agentctl auto-avatar $ID)"
fi

echo ""

# ── Paso final: Notificar al developer ───────────────────────────────────
NOTIFY_STEP=$TOTAL_STEPS
info "Paso ${NOTIFY_STEP}/${TOTAL_STEPS} — Notificando a desarrolladores..."
echo ""

# Reload .env (verify.sh may have added recovery key)
load_env

"$SCRIPT_DIR/notify-developer.sh" "$ID" "$TYPE" "$DISPLAYNAME" || true

echo ""

# ── Resumen ──────────────────────────────────────────────────────────────
echo -e "${GRN}═══════════════════════════════════════════════════════${RST}"
echo -e "${GRN}  ✓ ${TYPE_LABEL^} $ID creado exitosamente ${TYPE_EMOJI}${RST}"
echo -e "${GRN}═══════════════════════════════════════════════════════${RST}"
echo ""
echo -e "  ${BLU}Archivos creados:${RST}"
echo -e "    agents/$ID/agent.go"
echo -e "    agents/$ID/config.yaml"
if [[ "$TYPE" != "robot" ]]; then
  echo -e "    agents/$ID/prompts/system.md"
fi
echo ""
echo -e "  ${BLU}Variables en .env:${RST}"
echo -e "    MATRIX_TOKEN_${NORM}"
echo -e "    MATRIX_PASSWORD_${NORM}"
echo -e "    PICKLE_KEY_${NORM}"
echo -e "    SSSS_RECOVERY_KEY_${NORM}"
echo ""
echo -e "  ${BLU}Launcher actualizado:${RST}"
echo -e "    cmd/launcher/main.go (import)"
echo ""
echo -e "${YLW}Siguiente paso:${RST}"
echo ""
if [[ "$TYPE" == "robot" ]]; then
  echo -e "  1. Añadir comandos custom:"
  echo -e "     ${DIM}agents/$ID/commands.go${RST}"
  echo ""
  echo -e "  2. Registrar comandos en el launcher:"
  echo -e "     ${DIM}cmd/launcher/main.go${RST}"
else
  echo -e "  1. Personalizar los archivos del agente:"
  echo -e "     ${DIM}agents/$ID/agent.go${RST}            — reglas de decisión"
  echo -e "     ${DIM}agents/$ID/config.yaml${RST}         — LLM, tools, personalidad"
  echo -e "     ${DIM}agents/$ID/prompts/system.md${RST}   — system prompt"
fi
echo ""
echo -e "  Arrancar:"
echo -e "     ${DIM}./dev-scripts/server/start.sh${RST}"
echo ""
