#!/bin/bash

# =============================================================================
# GESTIONCOB — SCRIPT DE DIAGNÓSTICO COMPLETO
# Versión: 1.0 | Fecha: marzo 2026
# Ejecutar desde la raíz del proyecto: bash diagnostico.sh
# =============================================================================

OUTPUT_FILE="/tmp/diagnostico_gestioncob_$(date +%Y%m%d_%H%M%S).txt"
LARAVEL_ROOT=$(pwd)
DB_CONFIG="$LARAVEL_ROOT/.env"

# Colores para terminal
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
WHITE='\033[1;37m'
NC='\033[0m'

log() { echo -e "$1" | tee -a "$OUTPUT_FILE"; }
section() { log "\n${BLUE}=================================================================${NC}"; log "${WHITE}  $1${NC}"; log "${BLUE}=================================================================${NC}"; }
ok() { log "  ${GREEN}[OK]${NC} $1"; }
fail() { log "  ${RED}[ERROR]${NC} $1"; }
warn() { log "  ${YELLOW}[WARN]${NC} $1"; }
info() { log "  ${CYAN}[INFO]${NC} $1"; }
found() { log "  ${GREEN}[ENCONTRADO]${NC} $1"; }
missing() { log "  ${RED}[FALTANTE]${NC} $1"; }

# Extraer credenciales de .env
get_env() { grep "^$1=" "$DB_CONFIG" 2>/dev/null | cut -d'=' -f2- | tr -d '"' | tr -d "'"; }

log "=============================================================="
log "  GESTIONCOB — DIAGNÓSTICO COMPLETO"
log "  Ejecutado: $(date '+%d/%m/%Y %H:%M:%S')"
log "  Servidor: $(hostname)"
log "  Usuario: $(whoami)"
log "  Directorio: $LARAVEL_ROOT"
log "=============================================================="

# =============================================================================
section "1. ENTORNO Y VERSIONES"
# =============================================================================

info "PHP: $(php -v 2>/dev/null | head -1)"
info "Laravel: $(php artisan --version 2>/dev/null)"
info "Composer: $(composer --version 2>/dev/null | head -1)"
info "MySQL/MariaDB: $(mysql --version 2>/dev/null)"
info "Node: $(node --version 2>/dev/null)"

if [ -f "$LARAVEL_ROOT/artisan" ]; then
    ok "artisan encontrado en: $LARAVEL_ROOT"
else
    fail "artisan NO encontrado — verificar que estás en la raíz de Laravel"
fi

if [ -f "$DB_CONFIG" ]; then
    ok ".env encontrado"
    DB_HOST=$(get_env DB_HOST)
    DB_PORT=$(get_env DB_PORT)
    DB_DATABASE=$(get_env DB_DATABASE)
    DB_USERNAME=$(get_env DB_USERNAME)
    DB_PASSWORD=$(get_env DB_PASSWORD)
    APP_ENV=$(get_env APP_ENV)
    APP_URL=$(get_env APP_URL)
    info "APP_ENV: $APP_ENV"
    info "APP_URL: $APP_URL"
    info "DB: $DB_DATABASE @ $DB_HOST:$DB_PORT"
else
    fail ".env NO encontrado"
fi

# =============================================================================
section "2. CONEXIÓN A BASE DE DATOS"
# =============================================================================

MYSQL_CMD="mysql -h$DB_HOST -P${DB_PORT:-3306} -u$DB_USERNAME -p$DB_PASSWORD $DB_DATABASE -sN"

if $MYSQL_CMD -e "SELECT 1;" > /dev/null 2>&1; then
    ok "Conexión a BD exitosa: $DB_DATABASE"
else
    fail "No se pudo conectar a la BD — verificar credenciales en .env"
    exit 1
fi

# Total de tablas
TOTAL_TABLES=$($MYSQL_CMD -e "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='$DB_DATABASE';")
info "Total de tablas en BD: $TOTAL_TABLES"

# Batch de migraciones
LAST_BATCH=$($MYSQL_CMD -e "SELECT MAX(batch) FROM migrations;" 2>/dev/null)
info "Último batch de migraciones: $LAST_BATCH"

# =============================================================================
section "3. TABLAS — EXISTENCIA Y ESTRUCTURA"
# =============================================================================

check_table() {
    local table=$1
    local exists=$($MYSQL_CMD -e "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='$DB_DATABASE' AND table_name='$table';" 2>/dev/null)
    if [ "$exists" = "1" ]; then
        local count=$($MYSQL_CMD -e "SELECT COUNT(*) FROM $table;" 2>/dev/null)
        ok "Tabla '$table' existe — $count registros"
        return 0
    else
        fail "Tabla '$table' NO EXISTE"
        return 1
    fi
}

log "\n  --- Tablas Core ---"
check_table "users"
check_table "clientes_corporativos"
check_table "deudores"
check_table "procesos"
check_table "actuaciones"
check_table "documentos_caso"

log "\n  --- Tablas V2 (nuevas) ---"
check_table "obligaciones"
check_table "tiempos_subprocesos"
check_table "validaciones_flujo"
check_table "reportes_gestion"

log "\n  --- Tablas de Workflow ---"
check_table "estados_proceso"
check_table "transiciones_proceso"

log "\n  --- Tablas FO-SG-025 / Seg. Jurídico ---"
# Verificar si existe como ordenes_gestion o seguimientos_juridicos
OG_EXISTS=$($MYSQL_CMD -e "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='$DB_DATABASE' AND table_name='ordenes_gestion';" 2>/dev/null)
SJ_EXISTS=$($MYSQL_CMD -e "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='$DB_DATABASE' AND table_name='seguimientos_juridicos';" 2>/dev/null)
if [ "$OG_EXISTS" = "1" ]; then
    warn "Tabla 'ordenes_gestion' AÚN EXISTE (no fue renombrada a seguimientos_juridicos)"
    COUNT=$($MYSQL_CMD -e "SELECT COUNT(*) FROM ordenes_gestion;" 2>/dev/null)
    info "  registros en ordenes_gestion: $COUNT"
fi
if [ "$SJ_EXISTS" = "1" ]; then
    ok "Tabla 'seguimientos_juridicos' existe"
    COUNT=$($MYSQL_CMD -e "SELECT COUNT(*) FROM seguimientos_juridicos;" 2>/dev/null)
    info "  registros en seguimientos_juridicos: $COUNT"
fi
if [ "$OG_EXISTS" = "0" ] && [ "$SJ_EXISTS" = "0" ]; then
    fail "Ninguna tabla FO-SG-025 encontrada (ni ordenes_gestion ni seguimientos_juridicos)"
fi

log "\n  --- Otras tablas relevantes ---"
check_table "seguimientos_judiciales"
check_table "oficios_medidas"
check_table "medidas_cautelares"
check_table "acuerdos_pago"
check_table "gestiones_negociacion"
check_table "roles"
check_table "permissions"
check_table "model_has_roles"

# =============================================================================
section "4. COLUMNAS CRÍTICAS EN TABLAS"
# =============================================================================

check_column() {
    local table=$1
    local column=$2
    local exists=$($MYSQL_CMD -e "SELECT COUNT(*) FROM information_schema.columns WHERE table_schema='$DB_DATABASE' AND table_name='$table' AND column_name='$column';" 2>/dev/null)
    if [ "$exists" = "1" ]; then
        local type=$($MYSQL_CMD -e "SELECT COLUMN_TYPE FROM information_schema.columns WHERE table_schema='$DB_DATABASE' AND table_name='$table' AND column_name='$column';" 2>/dev/null)
        ok "$table.$column ($type)"
        return 0
    else
        fail "$table.$column — NO EXISTE"
        return 1
    fi
}

log "\n  --- procesos: campos financieros V2 ---"
check_column "procesos" "saldo_capital"
check_column "procesos" "saldo_intereses"
check_column "procesos" "saldo_total"
check_column "procesos" "cuantia_total"

log "\n  --- procesos: campos de bloqueo y fechas V2 ---"
check_column "procesos" "fecha_completitud_docs"
check_column "procesos" "flujo_bloqueado"
check_column "procesos" "razon_bloqueo"
check_column "procesos" "bloqueado_por"
check_column "procesos" "bloqueado_at"
check_column "procesos" "codigo_carpeta_virtual"
check_column "procesos" "consecutivo_yber"

log "\n  --- deudores: campos V2 ---"
check_column "deudores" "numero_juicio"
check_column "deudores" "consecutivo_yber"
check_column "deudores" "ciudad_residencia"
check_column "deudores" "departamento"

log "\n  --- Unicidad de deudores (BUG reportado) ---"
UNIQUE_DOC=$($MYSQL_CMD -e "SELECT COUNT(*) FROM information_schema.statistics WHERE table_schema='$DB_DATABASE' AND table_name='deudores' AND column_name='numero_documento' AND non_unique=0;" 2>/dev/null)
if [ "$UNIQUE_DOC" = "1" ] || [ "$UNIQUE_DOC" -gt "0" ] 2>/dev/null; then
    fail "ÍNDICE UNIQUE en deudores.numero_documento — esto impide crear el mismo deudor con múltiples obligaciones (BUG REPORTADO)"
else
    ok "No hay índice UNIQUE absoluto en deudores.numero_documento"
fi

log "\n  --- clientes_corporativos: campos V2 ---"
check_column "clientes_corporativos" "codigo_carpeta"
check_column "clientes_corporativos" "consecutivo_actual"
check_column "clientes_corporativos" "sla_dias_radicacion"
check_column "clientes_corporativos" "plataforma_externa"

log "\n  --- actuaciones: campos de email V2 ---"
check_column "actuaciones" "destinatario_nombre"
check_column "actuaciones" "destinatario_email"
check_column "actuaciones" "asunto"
check_column "actuaciones" "adjunto_path"

log "\n  --- seguimientos_judiciales: columnas (BUG B1) ---"
check_column "seguimientos_judiciales" "estado_rama"
check_column "seguimientos_judiciales" "ultima_actuacion"
check_column "seguimientos_judiciales" "fuente"
# Verificar columna con typo 'estado_arma' (el bug original)
ARMA=$($MYSQL_CMD -e "SELECT COUNT(*) FROM information_schema.columns WHERE table_schema='$DB_DATABASE' AND table_name='seguimientos_judiciales' AND column_name='estado_arma';" 2>/dev/null)
if [ "$ARMA" = "1" ]; then
    fail "Columna 'estado_arma' (TYPO) AÚN EXISTE en seguimientos_judiciales"
fi

log "\n  --- oficios_medidas: columnas (BUG B2) ---"
check_column "oficios_medidas" "tipo_oficio"
TIPO_MEDIDA=$($MYSQL_CMD -e "SELECT COUNT(*) FROM information_schema.columns WHERE table_schema='$DB_DATABASE' AND table_name='oficios_medidas' AND column_name='tipo_medida';" 2>/dev/null)
if [ "$TIPO_MEDIDA" = "1" ]; then
    fail "Columna 'tipo_medida' (VIEJA) aún existe en oficios_medidas — puede causar conflicto"
fi

log "\n  --- reportes_gestion: columnas ---"
check_column "reportes_gestion" "tipo_reporte"
check_column "reportes_gestion" "juzgado"
check_column "reportes_gestion" "radicado_juzgado"
check_column "reportes_gestion" "etapa_procesal"

log "\n  --- obligaciones: estructura ---"
check_column "obligaciones" "proceso_id"
check_column "obligaciones" "numero_obligacion"
check_column "obligaciones" "saldo_capital"
check_column "obligaciones" "saldo_intereses"
check_column "obligaciones" "saldo_total"

# Todos los campos de ordenes_gestion o seguimientos_juridicos
FO_TABLE="ordenes_gestion"
if [ "$SJ_EXISTS" = "1" ]; then FO_TABLE="seguimientos_juridicos"; fi
log "\n  --- $FO_TABLE: checkboxes V2 ---"
check_column "$FO_TABLE" "check_liquidacion_credito"
check_column "$FO_TABLE" "check_plan_pago"
check_column "$FO_TABLE" "check_investigacion_bienes"
check_column "$FO_TABLE" "check_fosyga"
check_column "$FO_TABLE" "check_poder"
check_column "$FO_TABLE" "check_formato"

# =============================================================================
section "5. ENUMS CRÍTICOS"
# =============================================================================

log "\n  --- actuaciones.tipo (enum completo) ---"
ENUM_TIPO=$($MYSQL_CMD -e "SELECT COLUMN_TYPE FROM information_schema.columns WHERE table_schema='$DB_DATABASE' AND table_name='actuaciones' AND column_name='tipo';" 2>/dev/null)
info "ENUM tipo en actuaciones: $ENUM_TIPO"

# Verificar valores críticos
for val in "seguimiento_judicial" "envio_juzgado" "envio_cliente" "envio_deudor" "medidas_cautelares" "nueva_actuacion"; do
    if echo "$ENUM_TIPO" | grep -q "'$val'"; then
        ok "  '$val' presente en enum"
    else
        fail "  '$val' FALTANTE en enum actuaciones.tipo"
    fi
done

log "\n  --- procesos.estado (enum o workflow dinámico) ---"
ESTADO_COL=$($MYSQL_CMD -e "SELECT COLUMN_TYPE FROM information_schema.columns WHERE table_schema='$DB_DATABASE' AND table_name='procesos' AND column_name='estado';" 2>/dev/null)
info "Tipo columna estado en procesos: $ESTADO_COL"

# =============================================================================
section "6. WORKFLOW DINÁMICO — ESTADOS Y TRANSICIONES"
# =============================================================================

log "\n  --- Estados configurados ---"
ESTADOS=$($MYSQL_CMD -e "SELECT id, nombre, slug, orden FROM estados_proceso ORDER BY orden;" 2>/dev/null)
if [ -n "$ESTADOS" ]; then
    info "Estados encontrados:"
    echo "$ESTADOS" | while read line; do info "  $line"; done
else
    fail "No se encontraron estados en estados_proceso"
fi

log "\n  --- Transiciones configuradas ---"
TRANSICIONES=$($MYSQL_CMD -e "SELECT ep_origen.nombre AS desde, ep_destino.nombre AS hasta, t.requiere_permiso FROM transiciones_proceso t JOIN estados_proceso ep_origen ON t.estado_origen_id = ep_origen.id JOIN estados_proceso ep_destino ON t.estado_destino_id = ep_destino.id ORDER BY ep_origen.orden;" 2>/dev/null)
if [ -n "$TRANSICIONES" ]; then
    info "Transiciones encontradas:"
    echo "$TRANSICIONES" | while read line; do info "  $line"; done
else
    fail "No se encontraron transiciones en transiciones_proceso"
    warn "ESTE ES PROBABLEMENTE EL MOTIVO POR EL QUE NO AVANZA DE ESTADO (BUG BF2)"
fi

# Verificar si hay procesos reales en estados específicos
log "\n  --- Distribución de procesos por estado ---"
DIST=$($MYSQL_CMD -e "SELECT estado, COUNT(*) as total FROM procesos GROUP BY estado ORDER BY total DESC;" 2>/dev/null)
echo "$DIST" | while read line; do info "  $line"; done

# =============================================================================
section "7. ARCHIVOS PHP — COMPONENTES LIVEWIRE CLAVE"
# =============================================================================

check_file() {
    local path=$1
    local label=$2
    if [ -f "$LARAVEL_ROOT/$path" ]; then
        local lines=$(wc -l < "$LARAVEL_ROOT/$path")
        local modified=$(stat -c '%y' "$LARAVEL_ROOT/$path" 2>/dev/null | cut -d'.' -f1)
        ok "$label ($lines líneas) — modificado: $modified"
        return 0
    else
        fail "$label — NO EXISTE en $path"
        return 1
    fi
}

log "\n  --- DashboardMain.php (DUPLICADO REPORTADO) ---"
DASH1="$LARAVEL_ROOT/app/Livewire/DashboardMain.php"
DASH2="$LARAVEL_ROOT/app/Livewire/Dashboard/DashboardMain.php"
if [ -f "$DASH1" ] && [ -f "$DASH2" ]; then
    fail "DashboardMain.php DUPLICADO:"
    info "  1. $DASH1 ($(wc -l < $DASH1) líneas)"
    info "  2. $DASH2 ($(wc -l < $DASH2) líneas)"
    # Ver cuál está registrado en rutas
    ROUTE_DASH=$(grep -r "DashboardMain" "$LARAVEL_ROOT/routes/" 2>/dev/null)
    if [ -n "$ROUTE_DASH" ]; then
        info "  Ruta apunta a: $ROUTE_DASH"
    fi
    ROUTE_DASH2=$(grep -r "DashboardMain" "$LARAVEL_ROOT/resources/views/livewire/" 2>/dev/null | head -3)
    if [ -n "$ROUTE_DASH2" ]; then
        info "  Usado en vistas: $ROUTE_DASH2"
    fi
elif [ -f "$DASH1" ]; then
    ok "Solo existe: app/Livewire/DashboardMain.php (sin duplicado)"
elif [ -f "$DASH2" ]; then
    ok "Solo existe: app/Livewire/Dashboard/DashboardMain.php (sin duplicado)"
else
    fail "DashboardMain.php NO encontrado en ninguna ruta"
fi

log "\n  --- Componentes Livewire principales ---"
check_file "app/Livewire/ProcesoManager.php" "ProcesoManager"
check_file "app/Livewire/ProcesoDetail.php" "ProcesoDetail"
check_file "app/Livewire/DeudorManager.php" "DeudorManager"
check_file "app/Livewire/ClienteManager.php" "ClienteManager"
check_file "app/Livewire/ChecklistMedidas.php" "ChecklistMedidas"
check_file "app/Livewire/EnvioCorreo.php" "EnvioCorreo"
check_file "app/Livewire/OrdenGestionManager.php" "OrdenGestionManager (FO-SG-025)"
check_file "app/Livewire/SeguimientoJuridicoManager.php" "SeguimientoJuridicoManager (renombrado)"

log "\n  --- Modelos V2 ---"
check_file "app/Models/Obligacion.php" "Modelo Obligacion"
check_file "app/Models/TiempoSubproceso.php" "Modelo TiempoSubproceso"
check_file "app/Models/ValidacionFlujo.php" "Modelo ValidacionFlujo"
check_file "app/Models/ReporteGestion.php" "Modelo ReporteGestion"
check_file "app/Models/Proceso.php" "Modelo Proceso"
check_file "app/Models/Deudor.php" "Modelo Deudor"
check_file "app/Models/ClienteCorporativo.php" "Modelo ClienteCorporativo"

log "\n  --- Servicios ---"
check_file "app/Services/ValidacionFlujoService.php" "ValidacionFlujoService"
check_file "app/Services/PDFMergeService.php" "PDFMergeService"

# =============================================================================
section "8. ANÁLISIS BUG BF1 — NO PERMITE CREAR PROCESO"
# =============================================================================

log "\n  --- ProcesoManager: método store/crear ---"
if [ -f "$LARAVEL_ROOT/app/Livewire/ProcesoManager.php" ]; then
    # Buscar el método de creación
    STORE_METHOD=$(grep -n "function crearProceso\|function store\|function crear\|function save\|function guardar" "$LARAVEL_ROOT/app/Livewire/ProcesoManager.php" 2>/dev/null)
    if [ -n "$STORE_METHOD" ]; then
        info "Métodos de creación encontrados:"
        echo "$STORE_METHOD" | while read line; do info "  $line"; done
    else
        warn "No se encontró método claro de creación en ProcesoManager"
    fi

    # Buscar referencias a los campos V2
    grep -n "saldo_capital\|saldo_intereses\|saldo_total\|cuantia" "$LARAVEL_ROOT/app/Livewire/ProcesoManager.php" 2>/dev/null | head -10 | while read line; do info "  $line"; done

    # Buscar validaciones
    VALIDATIONS=$(grep -n "rules\|validate\|required" "$LARAVEL_ROOT/app/Livewire/ProcesoManager.php" 2>/dev/null | head -20)
    if [ -n "$VALIDATIONS" ]; then
        info "Reglas de validación en ProcesoManager:"
        echo "$VALIDATIONS" | while read line; do info "  $line"; done
    fi

    # Buscar try/catch o errores
    grep -n "try\|catch\|Exception\|error\|Error" "$LARAVEL_ROOT/app/Livewire/ProcesoManager.php" 2>/dev/null | head -10 | while read line; do info "  $line"; done
fi

# Ver últimos errores de Laravel
log "\n  --- Últimos errores en laravel.log ---"
if [ -f "$LARAVEL_ROOT/storage/logs/laravel.log" ]; then
    LOG_SIZE=$(wc -l < "$LARAVEL_ROOT/storage/logs/laravel.log")
    info "Tamaño del log: $LOG_SIZE líneas"
    log "\n  Últimas 60 líneas del log de errores:"
    tail -60 "$LARAVEL_ROOT/storage/logs/laravel.log" | tee -a "$OUTPUT_FILE"
else
    warn "No se encontró storage/logs/laravel.log"
fi

# =============================================================================
section "9. ANÁLISIS BUG BF2 — NO AVANZA DE ESTADO"
# =============================================================================

log "\n  --- ProcesoDetail: métodos de cambio de estado ---"
if [ -f "$LARAVEL_ROOT/app/Livewire/ProcesoDetail.php" ]; then
    ESTADO_METHODS=$(grep -n "function cambiarEstado\|function avanzarEstado\|function moverEstado\|function transicionar\|estado_destino\|estado_origen" "$LARAVEL_ROOT/app/Livewire/ProcesoDetail.php" 2>/dev/null)
    if [ -n "$ESTADO_METHODS" ]; then
        info "Métodos de cambio de estado:"
        echo "$ESTADO_METHODS" | while read line; do info "  $line"; done
    else
        warn "No se encontraron métodos de cambio de estado en ProcesoDetail"
    fi

    # Buscar referencias a transiciones
    grep -n "transicion\|Transicion\|TransicionProceso\|estados_proceso\|workflow" "$LARAVEL_ROOT/app/Livewire/ProcesoDetail.php" 2>/dev/null | head -15 | while read line; do info "  $line"; done

    # Buscar botones de avance en la vista blade correspondiente
    BLADE_DETAIL="$LARAVEL_ROOT/resources/views/livewire/proceso-detail.blade.php"
    if [ -f "$BLADE_DETAIL" ]; then
        ok "Vista proceso-detail.blade.php encontrada"
        BUTTONS=$(grep -n "wire:click.*estado\|wire:click.*avanzar\|wire:click.*cambiar\|→ Redacción\|→ Radicado\|→ Análisis" "$BLADE_DETAIL" 2>/dev/null | head -15)
        if [ -n "$BUTTONS" ]; then
            info "Botones de cambio de estado en blade:"
            echo "$BUTTONS" | while read line; do info "  $line"; done
        fi
    fi
fi

# =============================================================================
section "10. ANÁLISIS BUG BF3 — VALIDACIÓN UNIQUE DEUDOR"
# =============================================================================

log "\n  --- Índices en tabla deudores ---"
INDICES=$($MYSQL_CMD -e "SHOW INDEX FROM deudores;" 2>/dev/null)
info "Todos los índices de deudores:"
echo "$INDICES" | while read line; do info "  $line"; done

log "\n  --- DeudorManager: validación de unicidad ---"
if [ -f "$LARAVEL_ROOT/app/Livewire/DeudorManager.php" ]; then
    UNIQUE_RULES=$(grep -n "unique\|numero_documento\|validation" "$LARAVEL_ROOT/app/Livewire/DeudorManager.php" 2>/dev/null | head -20)
    if [ -n "$UNIQUE_RULES" ]; then
        info "Reglas unique/validación en DeudorManager:"
        echo "$UNIQUE_RULES" | while read line; do info "  $line"; done
    fi
fi

# Modelo Deudor
if [ -f "$LARAVEL_ROOT/app/Models/Deudor.php" ]; then
    UNIQUE_MODEL=$(grep -n "unique\|numero_documento\|rules" "$LARAVEL_ROOT/app/Models/Deudor.php" 2>/dev/null | head -10)
    if [ -n "$UNIQUE_MODEL" ]; then
        info "En Modelo Deudor.php:"
        echo "$UNIQUE_MODEL" | while read line; do info "  $line"; done
    fi
fi

# =============================================================================
section "11. FORMULARIO NUEVO PROCESO — CAMPOS Y VISTA"
# =============================================================================

log "\n  --- Vista del modal Nuevo Proceso ---"
# Buscar el blade del ProcesoManager
PROCESO_BLADE=""
for blade in "$LARAVEL_ROOT/resources/views/livewire/proceso-manager.blade.php" \
             "$LARAVEL_ROOT/resources/views/livewire/procesos/manager.blade.php" \
             "$LARAVEL_ROOT/resources/views/livewire/procesos.blade.php"; do
    if [ -f "$blade" ]; then
        PROCESO_BLADE="$blade"
        ok "Vista ProcesoManager encontrada: $blade"
        break
    fi
done

if [ -n "$PROCESO_BLADE" ]; then
    info "Campos en el formulario Nuevo Proceso:"
    grep -n "wire:model\|name=\|label\|placeholder" "$PROCESO_BLADE" 2>/dev/null | head -40 | while read line; do info "  $line"; done

    # Buscar el campo Total Deuda y su tamaño CSS
    info "\nAncho/tamaño campo Total Deuda:"
    grep -n -i "total.deuda\|saldo_total\|Total Deuda" "$PROCESO_BLADE" 2>/dev/null | head -10 | while read line; do info "  $line"; done

    # Buscar validación de fechas
    info "\nValidación de fechas en blade:"
    grep -n "vencimiento\|fecha_ingreso\|min=\|max=" "$PROCESO_BLADE" 2>/dev/null | head -10 | while read line; do info "  $line"; done
fi

# =============================================================================
section "12. FORMULARIO NUEVO DEUDOR — CAMPOS DUPLICADOS"
# =============================================================================

DEUDOR_BLADE=""
for blade in "$LARAVEL_ROOT/resources/views/livewire/deudor-manager.blade.php" \
             "$LARAVEL_ROOT/resources/views/livewire/deudores/manager.blade.php" \
             "$LARAVEL_ROOT/resources/views/livewire/deudores.blade.php"; do
    if [ -f "$blade" ]; then
        DEUDOR_BLADE="$blade"
        ok "Vista DeudorManager encontrada: $blade"
        break
    fi
done

if [ -n "$DEUDOR_BLADE" ]; then
    info "Campos en el formulario Nuevo Deudor:"
    grep -n "wire:model\|label\|Ciudad\|ciudad\|Banco\|banco\|juicio\|obligacion" "$DEUDOR_BLADE" 2>/dev/null | head -30 | while read line; do info "  $line"; done
fi

# =============================================================================
section "13. DASHBOARD — VARIABLES Y DUPLICADO"
# =============================================================================

DASH_ACTIVE=""
if [ -f "$DASH1" ] && [ -f "$DASH2" ]; then
    warn "Ambos DashboardMain.php existen — analizando cuál usa el router"
    ROUTE_CHECK=$(grep -rn "DashboardMain\|dashboard-main" "$LARAVEL_ROOT/routes/" 2>/dev/null)
    info "Referencias en routes/: $ROUTE_CHECK"
    VIEW_CHECK=$(grep -rn "livewire.*dashboard\|Dashboard.*Main" "$LARAVEL_ROOT/resources/views/layouts/" 2>/dev/null | head -5)
    info "Referencias en layouts: $VIEW_CHECK"
fi

# Analizar el DashboardMain activo (el más reciente)
for DASH_FILE in "$DASH2" "$DASH1"; do
    if [ -f "$DASH_FILE" ]; then
        DASH_ACTIVE="$DASH_FILE"
        break
    fi
done

if [ -n "$DASH_ACTIVE" ]; then
    info "Analizando: $DASH_ACTIVE"
    # Verificar variables que se pasan a la vista
    RETURN_VIEW=$(grep -n "return view\|->with\|compact(" "$DASH_ACTIVE" 2>/dev/null | head -10)
    info "Return view/variables pasadas:"
    echo "$RETURN_VIEW" | while read line; do info "  $line"; done

    # Verificar variables V2
    for var in "totalSaldoTotal" "totalBloqueados" "totalObligaciones" "docsCompletos"; do
        if grep -q "$var" "$DASH_ACTIVE" 2>/dev/null; then
            ok "Variable '$var' definida en Dashboard"
        else
            fail "Variable '$var' NO encontrada en Dashboard"
        fi
    done
fi

# =============================================================================
section "14. EXPORTACIÓN CSV — wire:click"
# =============================================================================

if [ -f "$LARAVEL_ROOT/app/Livewire/ProcesoManager.php" ]; then
    CSV_METHOD=$(grep -n "exportar\|StreamedResponse\|wire:click.*export\|wire:click.prevent" "$LARAVEL_ROOT/app/Livewire/ProcesoManager.php" 2>/dev/null | head -10)
    info "Métodos de exportación en ProcesoManager:"
    echo "$CSV_METHOD" | while read line; do info "  $line"; done
fi

# Buscar en blade
if [ -n "$PROCESO_BLADE" ]; then
    CSV_BLADE=$(grep -n "Exportar\|exportar\|wire:click.*CSV\|wire:click.prevent" "$PROCESO_BLADE" 2>/dev/null | head -10)
    info "Botones de exportación en blade:"
    echo "$CSV_BLADE" | while read line; do info "  $line"; done
fi

# =============================================================================
section "15. LABEL 'FUERA DE SLA' EN DASHBOARD"
# =============================================================================

SLA_REFS=$(grep -rn "Fuera de SLA\|fuera_de_sla\|FueraDeSLA\|out_of_sla" "$LARAVEL_ROOT/resources/views/" 2>/dev/null | head -10)
if [ -n "$SLA_REFS" ]; then
    info "Referencias a 'Fuera de SLA' en vistas:"
    echo "$SLA_REFS" | while read line; do info "  $line"; done
else
    warn "No se encontró 'Fuera de SLA' en vistas — puede estar en el componente PHP"
fi
SLA_PHP=$(grep -rn "Fuera de SLA\|fuera_de_sla" "$LARAVEL_ROOT/app/" 2>/dev/null | head -10)
echo "$SLA_PHP" | while read line; do info "  $line"; done

# =============================================================================
section "16. MIGRACIONES — ESTADO COMPLETO"
# =============================================================================

log "\n  --- Últimas 20 migraciones ejecutadas ---"
$MYSQL_CMD -e "SELECT migration, batch FROM migrations ORDER BY batch DESC, id DESC LIMIT 20;" 2>/dev/null | while read line; do info "  $line"; done

log "\n  --- Migraciones pendientes (si las hay) ---"
php artisan migrate:status 2>/dev/null | tail -30 | tee -a "$OUTPUT_FILE"

# =============================================================================
section "17. PERMISOS Y ROLES"
# =============================================================================

log "\n  --- Roles definidos ---"
$MYSQL_CMD -e "SELECT id, name, guard_name FROM roles ORDER BY id;" 2>/dev/null | while read line; do info "  $line"; done

log "\n  --- Total permisos ---"
TOTAL_PERMS=$($MYSQL_CMD -e "SELECT COUNT(*) FROM permissions;" 2>/dev/null)
info "Total de permisos: $TOTAL_PERMS"

log "\n  --- Usuarios activos ---"
$MYSQL_CMD -e "SELECT u.id, u.name, u.email, r.name as rol FROM users u LEFT JOIN model_has_roles mhr ON mhr.model_id = u.id AND mhr.model_type = 'App\\\\Models\\\\User' LEFT JOIN roles r ON r.id = mhr.role_id ORDER BY u.id;" 2>/dev/null | while read line; do info "  $line"; done

# =============================================================================
section "18. DATOS DE MUESTRA — PROCESOS RECIENTES"
# =============================================================================

log "\n  --- Últimos 5 procesos creados ---"
$MYSQL_CMD -e "SELECT id, radicado_interno, estado, saldo_capital, saldo_intereses, saldo_total, flujo_bloqueado, fecha_completitud_docs, created_at FROM procesos ORDER BY id DESC LIMIT 5;" 2>/dev/null | while read line; do info "  $line"; done

log "\n  --- Obligaciones por proceso (muestra) ---"
$MYSQL_CMD -e "SELECT proceso_id, COUNT(*) as total_obligaciones, SUM(saldo_total) as total FROM obligaciones GROUP BY proceso_id ORDER BY proceso_id DESC LIMIT 5;" 2>/dev/null | while read line; do info "  $line"; done

log "\n  --- Clientes con código carpeta ---"
$MYSQL_CMD -e "SELECT id, nombre, codigo_carpeta, consecutivo_actual FROM clientes_corporativos ORDER BY id;" 2>/dev/null | while read line; do info "  $line"; done

# =============================================================================
section "19. ARCHIVOS DE CONFIGURACIÓN CLAVE"
# =============================================================================

# Config app
if [ -f "$LARAVEL_ROOT/config/app.php" ]; then
    TIMEZONE=$(grep "timezone" "$LARAVEL_ROOT/config/app.php" | head -1)
    info "Timezone: $TIMEZONE"
fi

# SMTP configurado
MAIL_MAILER=$(get_env MAIL_MAILER)
MAIL_HOST=$(get_env MAIL_HOST)
MAIL_PORT=$(get_env MAIL_PORT)
MAIL_FROM=$(get_env MAIL_FROM_ADDRESS)
info "Mail driver: $MAIL_MAILER"
info "Mail host: $MAIL_HOST:$MAIL_PORT"
info "Mail from: $MAIL_FROM"

if [ "$MAIL_HOST" = "localhost" ] || [ -z "$MAIL_HOST" ] || [ "$MAIL_MAILER" = "log" ]; then
    warn "SMTP NO configurado para envío real — emails van al log"
else
    ok "SMTP configurado: $MAIL_HOST"
fi

# =============================================================================
section "20. RESUMEN EJECUTIVO DEL DIAGNÓSTICO"
# =============================================================================

log "\n"
log "  ╔══════════════════════════════════════════════════════════╗"
log "  ║           RESUMEN — PUNTOS CRÍTICOS DETECTADOS          ║"
log "  ╚══════════════════════════════════════════════════════════╝"
log "\n  Revisa las marcas [ERROR] y [WARN] arriba para el detalle."
log "\n  Archivo de salida guardado en: $OUTPUT_FILE"
log "\n  Compartir con el equipo de desarrollo para el sprint de correcciones."
log "\n  Fecha: $(date '+%d/%m/%Y %H:%M:%S')"
log "=============================================================="

echo ""
echo -e "${GREEN}✅ Diagnóstico completado.${NC}"
echo -e "${CYAN}📄 Archivo guardado en: $OUTPUT_FILE${NC}"
echo ""
echo -e "${YELLOW}Para compartir el resultado completo ejecuta:${NC}"
echo -e "  cat $OUTPUT_FILE"
echo ""

