#!/usr/bin/env bash
# convert-to-robot.sh — convierte un scaffold de agente a robot
#
# Uso:
#   ./dev-scripts/agent/convert-to-robot.sh <agent-id>
#
# Cambios:
#   1. Reescribe config.yaml desde _template_robot (manteniendo Matrix/E2EE)
#   2. Simplifica agent.go (Rules() retorna nil)
#   3. Elimina prompts/ (robots no necesitan system prompt)
#   4. Pone command_prefix: "" por defecto (sin prefijo)

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

need_arg "${1:-}"

ID="$1"
NORM="$(normalize_id "$ID")"
PACKAGE="$(echo "$ID" | tr '-' '_' | sed 's/_bot//')"
DIR="agents/$ID"
DEVICE_ID=""

[[ -d "$DIR" ]] || fail "No existe agents/$ID — ejecuta create-full.sh primero"

info "Convirtiendo $ID a robot..."

# ── Extraer device_id del config actual ──────────────────────────────────
if [[ -f "$DIR/config.yaml" ]]; then
  DEVICE_ID="$(grep -m1 'device_id:' "$DIR/config.yaml" | awk '{print $2}' | tr -d '"')"
fi

# ── Reescribir config.yaml ───────────────────────────────────────────────
cat > "$DIR/config.yaml" << YAML
# ============================================
# ${ID} — Robot (command-only, sin LLM)
# ============================================
agent:
  id: ${ID}
  name: "${2:-$ID}"
  version: "0.1.0"
  type: robot
  enabled: true
  template: false
  description: ""
  tags: [robot]

personality:
  prefix: ""
  language: es

matrix:
  homeserver: "\${MATRIX_HOMESERVER}"
  user_id: "@${ID}:\${MATRIX_SERVER_NAME}"
  access_token_env: MATRIX_TOKEN_${NORM}
  device_id: "${DEVICE_ID}"

  encryption:
    enabled: true
    store_path: "./agents/${ID}/data/crypto/"
    pickle_key_env: PICKLE_KEY_${NORM}
    trust_mode: tofu
    recovery_key_env: SSSS_RECOVERY_KEY_${NORM}

  rooms:
    listen: []
    respond: []
    admin: []

  filters:
    command_prefix: ""
    mention_respond: false
    dm_respond: false
    ignore_bots: true
    ignore_users: []
    unauthorized_response: silent
    min_power_level: 0

  threads:
    enabled: true
    auto_thread: false

security:
  audit:
    enabled: false
    log_file: ""
    log_to_room: ""
    include: []
  secrets:
    provider: env
  sanitize:
    enabled: false
    mode: warn
    min_severity: medium
    disabled_patterns: []
  tool_rate_limit:
    enabled: false
    max_calls_per_min: 10
    cleanup_interval_s: 60
YAML

ok "config.yaml reescrito como robot (command_prefix: \"\", sin LLM)"

# ── Simplificar agent.go ─────────────────────────────────────────────────
cat > "$DIR/agent.go" << GO
package ${PACKAGE}

import (
	"github.com/enmanuel/agents/devagents"
	"github.com/enmanuel/agents/pkg/decision"
)

func init() {
	devagents.Register("${ID}", Rules)
}

// Rules returns nil — robots only respond to commands.
func Rules() []decision.Rule {
	return nil
}
GO

ok "agent.go simplificado (Rules() retorna nil)"

# ── Eliminar prompts/ ────────────────────────────────────────────────────
if [[ -d "$DIR/prompts" ]]; then
  rm -rf "$DIR/prompts"
  ok "prompts/ eliminado (robots no necesitan system prompt)"
fi

echo ""
ok "$ID convertido a robot"
