#!/usr/bin/env bash
# scripts/audit-skills.sh — Auditoría opt-in de skills usando snyk-agent-scan.
#
# Analiza el directorio habilidades/ buscando: prompt injection, secretos
# hardcodeados, URLs sospechosas y estructura inválida de SKILL.md.
#
# Opt-in: solo ejecuta si SWL_AUDIT_SKILLS=1.
# Sin la variable, imprime instrucciones y sale con código 0 (no rompe /swl:salud).
#
# Uso:
#   SWL_AUDIT_SKILLS=1 bash scripts/audit-skills.sh
#
# Requisito: pip install uv  (o pipx install uv)

set -euo pipefail

PREFIX="[audit-skills]"

# ---------------------------------------------------------------------------
# Guard de opt-in
# ---------------------------------------------------------------------------

if [ -z "${SWL_AUDIT_SKILLS:-}" ]; then
  echo "$PREFIX Auditoría de skills deshabilitada (opt-in)."
  echo "$PREFIX Para activar: SWL_AUDIT_SKILLS=1 bash scripts/audit-skills.sh"
  echo "$PREFIX Requiere: pip install uv"
  exit 0
fi

# ---------------------------------------------------------------------------
# Verificar disponibilidad de uvx / uv
# ---------------------------------------------------------------------------

if command -v uvx >/dev/null 2>&1; then
  RUNNER="uvx"
elif command -v uv >/dev/null 2>&1; then
  RUNNER="uv run"
else
  echo "$PREFIX uvx/uv no disponible."
  echo "$PREFIX Instalar con: pip install uv  (o: pipx install uv)"
  echo "$PREFIX La auditoría de skills no se ejecutó — continúa sin error."
  exit 0
fi

# ---------------------------------------------------------------------------
# Detectar directorio de habilidades
# ---------------------------------------------------------------------------

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
SKILLS_DIR="$REPO_ROOT/habilidades"

if [ ! -d "$SKILLS_DIR" ]; then
  echo "$PREFIX Directorio habilidades/ no encontrado en $REPO_ROOT"
  echo "$PREFIX La auditoría de skills no se ejecutó — continúa sin error."
  exit 0
fi

echo "$PREFIX Iniciando auditoría de skills en $SKILLS_DIR ..."
echo "$PREFIX Runner: $RUNNER"

# ---------------------------------------------------------------------------
# Ejecutar snyk-agent-scan inspect
# ---------------------------------------------------------------------------

if ! $RUNNER snyk-agent-scan@latest inspect --skills "$SKILLS_DIR" 2>&1; then
  echo ""
  echo "$PREFIX El comando snyk-agent-scan terminó con error o no está publicado."
  echo "$PREFIX Posibles causas:"
  echo "$PREFIX   - El paquete 'snyk-agent-scan' no está disponible en PyPI."
  echo "$PREFIX   - Fallo de red durante la descarga."
  echo "$PREFIX   - La versión @latest no es compatible con el runtime actual."
  echo "$PREFIX La auditoría de skills no se completó — continúa sin error."
  exit 0
fi

echo ""
echo "$PREFIX Auditoría completada."
