#!/bin/bash
# =============================================================================
# IDS - Debug Sistema Completo
# =============================================================================
# Verifica stato completo del sistema: database, servizi, log
# =============================================================================

# Colori
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

echo -e "${BLUE}"
echo "╔═══════════════════════════════════════════════╗"
echo "║   🔍 DEBUG SISTEMA IDS                        ║"
echo "╚═══════════════════════════════════════════════╝"
echo -e "${NC}"

# Carica variabili da .env
IDS_DIR="/opt/ids"
if [ -f "$IDS_DIR/.env" ]; then
    set -a
    source "$IDS_DIR/.env"
    set +a
fi

# Verifica DATABASE_URL
if [ -z "$DATABASE_URL" ]; then
    echo -e "${RED}❌ DATABASE_URL non impostato${NC}"
    echo -e "${YELLOW}   File .env non trovato o DATABASE_URL mancante${NC}"
    exit 1
fi

# 1. VERIFICA DATABASE
echo -e "\n${BLUE}═══ 1. VERIFICA DATABASE ═══${NC}"
echo -e "${BLUE}📊 Conta record per tabella:${NC}"
psql "$DATABASE_URL" << 'EOF'
SELECT 'network_logs' as tabella, COUNT(*) as record FROM network_logs
UNION ALL
SELECT 'detections', COUNT(*) FROM detections
UNION ALL
SELECT 'training_history', COUNT(*) FROM training_history
UNION ALL
SELECT 'routers', COUNT(*) FROM routers
UNION ALL
SELECT 'whitelist', COUNT(*) FROM whitelist
ORDER BY tabella;
EOF

echo -e "\n${BLUE}📋 Schema tabella routers:${NC}"
psql "$DATABASE_URL" -c "\d routers"

echo -e "\n${BLUE}📝 Ultimi 5 network_logs:${NC}"
psql "$DATABASE_URL" << 'EOF'
SELECT 
  timestamp, 
  router_name, 
  source_ip, 
  destination_ip, 
  protocol,
  packet_length
FROM network_logs 
ORDER BY timestamp DESC 
LIMIT 5;
EOF

echo -e "\n${BLUE}📜 Training history:${NC}"
psql "$DATABASE_URL" << 'EOF'
SELECT 
  trained_at,
  model_version,
  records_processed,
  features_count,
  status,
  notes
FROM training_history 
ORDER BY trained_at DESC 
LIMIT 5;
EOF

echo -e "\n${BLUE}🚨 Detections:${NC}"
psql "$DATABASE_URL" << 'EOF'
SELECT 
  detected_at,
  source_ip,
  risk_score,
  anomaly_type,
  blocked,
  log_count
FROM detections 
ORDER BY detected_at DESC 
LIMIT 5;
EOF

# 2. VERIFICA SERVIZI
echo -e "\n${BLUE}═══ 2. STATO SERVIZI ═══${NC}"
echo -e "${BLUE}🔍 Processi attivi:${NC}"
ps aux | grep -E 'python.*main|npm.*dev|syslog_parser' | grep -v grep || echo -e "${YELLOW}   Nessun servizio IDS attivo${NC}"

# 3. BACKEND PYTHON ML
echo -e "\n${BLUE}═══ 3. BACKEND PYTHON ML ═══${NC}"
if curl -s http://localhost:8000/health > /dev/null 2>&1; then
    echo -e "${GREEN}✅ Backend Python attivo${NC}"
    echo -e "${BLUE}📊 Statistiche ML:${NC}"
    curl -s http://localhost:8000/stats | jq '.' || curl -s http://localhost:8000/stats
else
    echo -e "${RED}❌ Backend Python NON risponde su porta 8000${NC}"
    echo -e "${YELLOW}   Verifica log: tail -50 /var/log/ids/backend.log${NC}"
fi

# 4. FRONTEND NODE.JS
echo -e "\n${BLUE}═══ 4. FRONTEND NODE.JS ═══${NC}"
if curl -s http://localhost:5000 > /dev/null 2>&1; then
    echo -e "${GREEN}✅ Frontend Node attivo${NC}"
    echo -e "${BLUE}📊 Test API:${NC}"
    curl -s http://localhost:5000/api/stats | jq '.' || curl -s http://localhost:5000/api/stats
else
    echo -e "${RED}❌ Frontend Node NON risponde su porta 5000${NC}"
    echo -e "${YELLOW}   Verifica log: tail -50 /var/log/ids/frontend.log${NC}"
fi

# 5. SYSLOG PARSER
echo -e "\n${BLUE}═══ 5. SYSLOG PARSER ═══${NC}"
if ps aux | grep -E 'syslog_parser\.py' | grep -v grep > /dev/null; then
    echo -e "${GREEN}✅ Syslog Parser attivo${NC}"
    echo -e "${BLUE}📝 Ultimi log (parser):${NC}"
    tail -20 /var/log/ids/syslog_parser.log
else
    echo -e "${RED}❌ Syslog Parser NON attivo${NC}"
    echo -e "${YELLOW}   Avvia: cd /opt/ids/python_ml && nohup python syslog_parser.py > /var/log/ids/syslog_parser.log 2>&1 &${NC}"
fi

# 6. LOG ERRORI
echo -e "\n${BLUE}═══ 6. ERRORI RECENTI ═══${NC}"
echo -e "${BLUE}🔴 Errori backend Python:${NC}"
tail -50 /var/log/ids/backend.log | grep -i error | tail -10 || echo -e "${GREEN}   Nessun errore${NC}"

echo -e "\n${BLUE}🔴 Errori frontend Node:${NC}"
tail -50 /var/log/ids/frontend.log | grep -i "\[DB ERROR\]" | tail -10 || echo -e "${GREEN}   Nessun errore${NC}"

# 7. RIEPILOGO
echo -e "\n${BLUE}╔═══════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║   📋 RIEPILOGO                                ║${NC}"
echo -e "${BLUE}╚═══════════════════════════════════════════════╝${NC}"

LOGS_COUNT=$(psql "$DATABASE_URL" -t -c "SELECT COUNT(*) FROM network_logs" 2>/dev/null | xargs)
DETECTIONS_COUNT=$(psql "$DATABASE_URL" -t -c "SELECT COUNT(*) FROM detections" 2>/dev/null | xargs)
TRAINING_COUNT=$(psql "$DATABASE_URL" -t -c "SELECT COUNT(*) FROM training_history" 2>/dev/null | xargs)

echo -e "${BLUE}Database:${NC}"
echo -e "  • Network logs: ${YELLOW}$LOGS_COUNT${NC}"
echo -e "  • Detections: ${YELLOW}$DETECTIONS_COUNT${NC}"
echo -e "  • Training history: ${YELLOW}$TRAINING_COUNT${NC}"

echo ""
echo -e "${BLUE}🔧 COMANDI UTILI:${NC}"
echo -e "  • Riavvia tutto: ${YELLOW}sudo -u ids /opt/ids/deployment/restart_all.sh${NC}"
echo -e "  • Test training: ${YELLOW}curl -X POST http://localhost:8000/train -H 'Content-Type: application/json' -d '{\"max_records\": 1000}'${NC}"
echo -e "  • Log frontend: ${YELLOW}tail -f /var/log/ids/frontend.log${NC}"
echo -e "  • Log backend: ${YELLOW}tail -f /var/log/ids/backend.log${NC}"
echo ""
