#!/bin/bash
# Script de monitoreo post-ciclo SAT 3:00 AM
set -euo pipefail

LOG_FILE="/root/.pm2/logs/horux-api-out-0.log"
ERROR_LOG="/root/.pm2/logs/horux-api-error-0.log"
REPORT_FILE="/tmp/sat_cron_report_$(date +%Y%m%d).txt"

echo "========================================" > "$REPORT_FILE"
echo "REPORTE DE EXTRACCION SAT 3:00 AM" >> "$REPORT_FILE"
echo "Fecha: $(date)" >> "$REPORT_FILE"
echo "========================================" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

# Buscar el ciclo de hoy (asumiendo que corre entre 07:50 y 08:10 UTC)
echo "--- ULTIMO CICLO SAT CRON ---" >> "$REPORT_FILE"
grep -n "\[SAT Cron\] Iniciando ciclo" "$LOG_FILE" | tail -5 >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

# Errores específicos del ciclo
echo "--- ERRORES EN LOG DE ERRORES ---" >> "$REPORT_FILE"
grep -n "DateTimeParseError\|P2000\|Error.*SAT\|Error.*extraccion\|Error.*CFDI\|Error.*guardar" "$ERROR_LOG" | tail -20 >> "$REPORT_FILE" || echo "Sin errores específicos encontrados" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

# Resumen de tenants procesados
echo "--- RESUMEN DE PROCESAMIENTO ---" >> "$REPORT_FILE"
grep -n "Procesando tenant\|tenant procesado\|CFDIs insertados\|CFDIs omitidos\|Error procesando tenant" "$LOG_FILE" | tail -20 >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

# Errores de parsing de fechas específicamente
echo "--- ERRORES DE FECHA (DateTimeParseError) ---" >> "$REPORT_FILE"
grep -n "DateTimeParseError\|Invalid value for argument\`fecha" "$ERROR_LOG" | tail -10 >> "$REPORT_FILE" || echo "Sin errores de fecha" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

# Verificar contribuyentes y CFDIs de Husberto (TOAH680201RA2)
echo "--- ESTADO HUSBERTO (TOAH680201RA2) ---" >> "$REPORT_FILE"
PGPASSWORD=ZxHMrmnwanvLfLDdNJdRthFjWF2Lj1Rb psql -h localhost -U postgres -d horux360 -t -c "SELECT COUNT(*) FROM cfdis WHERE contribuyente_id = '128c0ab0-b307-492b-bb82-7e55d390f41f';" >> "$REPORT_FILE"
echo "CFDIs asignados al contribuyente Husberto (arriba)" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

cat "$REPORT_FILE"
