#!/bin/bash

# Comprehensive Log and Error Checker for Explorer
# This script checks all components and generates a full error report

set -euo pipefail

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

# Configuration
CHAIN_ID=138
RPC_URL="${RPC_URL:-http://192.168.11.250:8545}"
API_BASE="${API_BASE:-http://localhost:8080/api}"
BLOCKSCOUT_API="${BLOCKSCOUT_API:-https://explorer.d-bis.org/api}"
REPORT_FILE="logs/error-report-$(date +%Y%m%d-%H%M%S).md"

# Create logs directory
mkdir -p logs

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Explorer Log and Error Checker${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# Function to log errors
log_error() {
    echo -e "${RED}❌ ERROR:${NC} $1" | tee -a "$REPORT_FILE"
}

log_warning() {
    echo -e "${YELLOW}⚠️  WARNING:${NC} $1" | tee -a "$REPORT_FILE"
}

log_success() {
    echo -e "${GREEN}✅ SUCCESS:${NC} $1" | tee -a "$REPORT_FILE"
}

log_info() {
    echo -e "${BLUE}ℹ️  INFO:${NC} $1" | tee -a "$REPORT_FILE"
}

# Initialize report
cat > "$REPORT_FILE" <<EOF
# Explorer Error Report

**Generated**: $(date)
**Chain ID**: $CHAIN_ID
**RPC URL**: $RPC_URL
**API Base**: $API_BASE
**Blockscout API**: $BLOCKSCOUT_API

---

## 1. Network Connectivity

EOF

# 1. Check RPC Connectivity
echo -e "${BLUE}1. Checking RPC Connectivity...${NC}"
if command -v cast &> /dev/null; then
    if cast block-number --rpc-url "$RPC_URL" &> /dev/null; then
        BLOCK_NUMBER=$(cast block-number --rpc-url "$RPC_URL")
        log_success "RPC is accessible. Current block: $BLOCK_NUMBER"
        echo "- **RPC Status**: ✅ Accessible" >> "$REPORT_FILE"
        echo "- **Current Block**: $BLOCK_NUMBER" >> "$REPORT_FILE"
    else
        log_error "RPC is not accessible at $RPC_URL"
        echo "- **RPC Status**: ❌ Not accessible" >> "$REPORT_FILE"
    fi
else
    log_warning "cast command not found. Skipping RPC check."
    echo "- **RPC Status**: ⚠️  Cannot check (cast not installed)" >> "$REPORT_FILE"
fi
echo "" >> "$REPORT_FILE"

# 2. Check API Endpoints
echo -e "${BLUE}2. Checking API Endpoints...${NC}"
echo "## 2. API Endpoints" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

# Check /api/v2/stats
echo "### /api/v2/stats" >> "$REPORT_FILE"
if curl -s -f -o /dev/null -w "%{http_code}" "$API_BASE/v2/stats" | grep -q "200"; then
    STATS_RESPONSE=$(curl -s "$API_BASE/v2/stats")
    log_success "Stats endpoint is accessible"
    echo "- **Status**: ✅ Accessible" >> "$REPORT_FILE"
    echo "- **Response**: \`\`\`json" >> "$REPORT_FILE"
    echo "$STATS_RESPONSE" | jq '.' 2>/dev/null || echo "$STATS_RESPONSE" >> "$REPORT_FILE"
    echo "\`\`\`" >> "$REPORT_FILE"
else
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "$API_BASE/v2/stats" || echo "000")
    log_error "Stats endpoint returned HTTP $HTTP_CODE"
    echo "- **Status**: ❌ HTTP $HTTP_CODE" >> "$REPORT_FILE"
fi
echo "" >> "$REPORT_FILE"

# Check /api/v1/blocks
echo "### /api/v1/blocks" >> "$REPORT_FILE"
if curl -s -f -o /dev/null -w "%{http_code}" "$API_BASE/v1/blocks?page=1&page_size=1" | grep -q "200"; then
    log_success "Blocks endpoint is accessible"
    echo "- **Status**: ✅ Accessible" >> "$REPORT_FILE"
else
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "$API_BASE/v1/blocks?page=1&page_size=1" || echo "000")
    log_error "Blocks endpoint returned HTTP $HTTP_CODE"
    echo "- **Status**: ❌ HTTP $HTTP_CODE" >> "$REPORT_FILE"
fi
echo "" >> "$REPORT_FILE"

# Check /api/v1/transactions
echo "### /api/v1/transactions" >> "$REPORT_FILE"
if curl -s -f -o /dev/null -w "%{http_code}" "$API_BASE/v1/transactions?page=1&page_size=1" | grep -q "200"; then
    log_success "Transactions endpoint is accessible"
    echo "- **Status**: ✅ Accessible" >> "$REPORT_FILE"
else
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "$API_BASE/v1/transactions?page=1&page_size=1" || echo "000")
    log_error "Transactions endpoint returned HTTP $HTTP_CODE"
    echo "- **Status**: ❌ HTTP $HTTP_CODE" >> "$REPORT_FILE"
fi
echo "" >> "$REPORT_FILE"

# Check Etherscan-compatible API
echo "### /api?module=block&action=eth_block_number" >> "$REPORT_FILE"
if curl -s -f -o /dev/null -w "%{http_code}" "$API_BASE?module=block&action=eth_block_number" | grep -q "200"; then
    ETHERSCAN_RESPONSE=$(curl -s "$API_BASE?module=block&action=eth_block_number")
    log_success "Etherscan-compatible API is accessible"
    echo "- **Status**: ✅ Accessible" >> "$REPORT_FILE"
    echo "- **Response**: \`\`\`json" >> "$REPORT_FILE"
    echo "$ETHERSCAN_RESPONSE" | jq '.' 2>/dev/null || echo "$ETHERSCAN_RESPONSE" >> "$REPORT_FILE"
    echo "\`\`\`" >> "$REPORT_FILE"
else
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "$API_BASE?module=block&action=eth_block_number" || echo "000")
    log_error "Etherscan-compatible API returned HTTP $HTTP_CODE"
    echo "- **Status**: ❌ HTTP $HTTP_CODE" >> "$REPORT_FILE"
fi
echo "" >> "$REPORT_FILE"

# 3. Check Blockscout API
echo -e "${BLUE}3. Checking Blockscout API...${NC}"
echo "## 3. Blockscout API (ChainID 138)" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

# Check Blockscout blocks endpoint
echo "### Blockscout /api/v2/blocks" >> "$REPORT_FILE"
if curl -s -f -o /dev/null -w "%{http_code}" "$BLOCKSCOUT_API/v2/blocks?page=1&page_size=1" | grep -q "200"; then
    BLOCKSCOUT_BLOCKS=$(curl -s "$BLOCKSCOUT_API/v2/blocks?page=1&page_size=1")
    log_success "Blockscout blocks endpoint is accessible"
    echo "- **Status**: ✅ Accessible" >> "$REPORT_FILE"
    echo "- **Response Sample**: \`\`\`json" >> "$REPORT_FILE"
    echo "$BLOCKSCOUT_BLOCKS" | jq '.items[0] // .' 2>/dev/null | head -20 >> "$REPORT_FILE" || echo "$BLOCKSCOUT_BLOCKS" | head -20 >> "$REPORT_FILE"
    echo "\`\`\`" >> "$REPORT_FILE"
else
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "$BLOCKSCOUT_API/v2/blocks?page=1&page_size=1" || echo "000")
    log_error "Blockscout blocks endpoint returned HTTP $HTTP_CODE"
    echo "- **Status**: ❌ HTTP $HTTP_CODE" >> "$REPORT_FILE"
fi
echo "" >> "$REPORT_FILE"

# Check Blockscout transactions endpoint
echo "### Blockscout /api/v2/transactions" >> "$REPORT_FILE"
if curl -s -f -o /dev/null -w "%{http_code}" "$BLOCKSCOUT_API/v2/transactions?page=1&page_size=1" | grep -q "200"; then
    BLOCKSCOUT_TXS=$(curl -s "$BLOCKSCOUT_API/v2/transactions?page=1&page_size=1")
    log_success "Blockscout transactions endpoint is accessible"
    echo "- **Status**: ✅ Accessible" >> "$REPORT_FILE"
    echo "- **Response Sample**: \`\`\`json" >> "$REPORT_FILE"
    echo "$BLOCKSCOUT_TXS" | jq '.items[0] // .' 2>/dev/null | head -20 >> "$REPORT_FILE" || echo "$BLOCKSCOUT_TXS" | head -20 >> "$REPORT_FILE"
    echo "\`\`\`" >> "$REPORT_FILE"
else
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "$BLOCKSCOUT_API/v2/transactions?page=1&page_size=1" || echo "000")
    log_error "Blockscout transactions endpoint returned HTTP $HTTP_CODE"
    echo "- **Status**: ❌ HTTP $HTTP_CODE" >> "$REPORT_FILE"
fi
echo "" >> "$REPORT_FILE"

# 4. Check Database Connectivity
echo -e "${BLUE}4. Checking Database Connectivity...${NC}"
echo "## 4. Database Connectivity" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

# Check if backend is running (indirect database check)
if pgrep -f "backend/api/rest/main" > /dev/null; then
    log_success "Backend API server is running"
    echo "- **Backend Status**: ✅ Running" >> "$REPORT_FILE"
else
    log_warning "Backend API server is not running"
    echo "- **Backend Status**: ⚠️  Not running" >> "$REPORT_FILE"
    echo "- **Note**: Cannot check database directly without backend running" >> "$REPORT_FILE"
fi
echo "" >> "$REPORT_FILE"

# 5. Check Frontend Files
echo -e "${BLUE}5. Checking Frontend Files...${NC}"
echo "## 5. Frontend Files" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

FRONTEND_FILE="frontend/public/index.html"
if [ -f "$FRONTEND_FILE" ]; then
    log_success "Frontend index.html exists"
    echo "- **Status**: ✅ File exists" >> "$REPORT_FILE"
    
    # Check for ethers library
    if grep -q "ethers" "$FRONTEND_FILE"; then
        log_success "Ethers library reference found"
        echo "- **Ethers Library**: ✅ Referenced" >> "$REPORT_FILE"
    else
        log_error "Ethers library reference not found"
        echo "- **Ethers Library**: ❌ Not found" >> "$REPORT_FILE"
    fi
    
    # Check for Blockscout API
    if grep -q "BLOCKSCOUT_API" "$FRONTEND_FILE"; then
        log_success "Blockscout API configuration found"
        echo "- **Blockscout API Config**: ✅ Found" >> "$REPORT_FILE"
    else
        log_warning "Blockscout API configuration not found"
        echo "- **Blockscout API Config**: ⚠️  Not found" >> "$REPORT_FILE"
    fi
    
    # Check for CHAIN_ID
    if grep -q "CHAIN_ID.*138" "$FRONTEND_FILE"; then
        log_success "ChainID 138 configuration found"
        echo "- **ChainID Config**: ✅ Found" >> "$REPORT_FILE"
    else
        log_warning "ChainID 138 configuration not found"
        echo "- **ChainID Config**: ⚠️  Not found" >> "$REPORT_FILE"
    fi
else
    log_error "Frontend index.html not found at $FRONTEND_FILE"
    echo "- **Status**: ❌ File not found" >> "$REPORT_FILE"
fi
echo "" >> "$REPORT_FILE"

# 6. Check Browser Console Errors (simulated)
echo -e "${BLUE}6. Checking for Common Frontend Issues...${NC}"
echo "## 6. Frontend Issues" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

if [ -f "$FRONTEND_FILE" ]; then
    # Check for console.error patterns
    ERROR_COUNT=$(grep -c "console.error" "$FRONTEND_FILE" || echo "0")
    log_info "Found $ERROR_COUNT console.error calls in frontend"
    echo "- **Error Handlers**: $ERROR_COUNT found" >> "$REPORT_FILE"
    
    # Check for try-catch blocks
    TRY_COUNT=$(grep -c "try {" "$FRONTEND_FILE" || echo "0")
    log_info "Found $TRY_COUNT try-catch blocks in frontend"
    echo "- **Error Handling**: $TRY_COUNT try-catch blocks" >> "$REPORT_FILE"
    
    # Check for API_BASE usage
    if grep -q "API_BASE" "$FRONTEND_FILE"; then
        API_BASE_VALUE=$(grep "const API_BASE" "$FRONTEND_FILE" | head -1 | sed 's/.*= *\([^;]*\).*/\1/' | tr -d "'\"")
        log_info "API_BASE configured as: $API_BASE_VALUE"
        echo "- **API_BASE**: $API_BASE_VALUE" >> "$REPORT_FILE"
    fi
fi
echo "" >> "$REPORT_FILE"

# 7. Check Backend Logs (if available)
echo -e "${BLUE}7. Checking Backend Logs...${NC}"
echo "## 7. Backend Logs" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

# Check systemd logs if backend is a service
if systemctl list-units --type=service | grep -q "explorer\|blockscout\|api"; then
    log_info "Checking systemd service logs..."
    echo "### Systemd Service Logs" >> "$REPORT_FILE"
    systemctl list-units --type=service | grep -E "explorer|blockscout|api" | while read -r service; do
        SERVICE_NAME=$(echo "$service" | awk '{print $1}')
        if systemctl is-active --quiet "$SERVICE_NAME"; then
            log_success "Service $SERVICE_NAME is active"
            echo "- **$SERVICE_NAME**: ✅ Active" >> "$REPORT_FILE"
            
            # Get recent errors
            RECENT_ERRORS=$(journalctl -u "$SERVICE_NAME" --since "10 minutes ago" --no-pager | grep -i "error\|fail\|panic" | tail -5 || echo "No recent errors")
            if [ "$RECENT_ERRORS" != "No recent errors" ]; then
                log_warning "Recent errors found in $SERVICE_NAME"
                echo "  - Recent Errors:" >> "$REPORT_FILE"
                echo "\`\`\`" >> "$REPORT_FILE"
                echo "$RECENT_ERRORS" >> "$REPORT_FILE"
                echo "\`\`\`" >> "$REPORT_FILE"
            fi
        else
            log_warning "Service $SERVICE_NAME is not active"
            echo "- **$SERVICE_NAME**: ⚠️  Not active" >> "$REPORT_FILE"
        fi
    done
else
    log_info "No systemd services found for explorer"
    echo "- **Status**: No systemd services found" >> "$REPORT_FILE"
fi
echo "" >> "$REPORT_FILE"

# 8. Network Connectivity Tests
echo -e "${BLUE}8. Testing Network Connectivity...${NC}"
echo "## 8. Network Connectivity" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

# Test DNS resolution
if host explorer.d-bis.org &> /dev/null; then
    DNS_IP=$(host explorer.d-bis.org | grep "has address" | awk '{print $4}' | head -1)
    log_success "DNS resolution works. explorer.d-bis.org -> $DNS_IP"
    echo "- **DNS**: ✅ Resolves to $DNS_IP" >> "$REPORT_FILE"
else
    log_error "DNS resolution failed for explorer.d-bis.org"
    echo "- **DNS**: ❌ Failed" >> "$REPORT_FILE"
fi

# Test HTTPS connectivity
if curl -s -f -o /dev/null --max-time 5 "https://explorer.d-bis.org" &> /dev/null; then
    log_success "HTTPS connectivity to explorer.d-bis.org works"
    echo "- **HTTPS**: ✅ Accessible" >> "$REPORT_FILE"
else
    log_error "HTTPS connectivity to explorer.d-bis.org failed"
    echo "- **HTTPS**: ❌ Failed" >> "$REPORT_FILE"
fi
echo "" >> "$REPORT_FILE"

# 9. Summary
echo -e "${BLUE}9. Generating Summary...${NC}"
echo "## 9. Summary" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
echo "### Issues Found" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

# Count errors and warnings from the report
ERROR_COUNT=$(grep -c "❌\|❌" "$REPORT_FILE" || echo "0")
WARNING_COUNT=$(grep -c "⚠️\|⚠️" "$REPORT_FILE" || echo "0")

echo "- **Total Errors**: $ERROR_COUNT" >> "$REPORT_FILE"
echo "- **Total Warnings**: $WARNING_COUNT" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

echo "### Recommendations" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

if [ "$ERROR_COUNT" -gt 0 ]; then
    echo "1. Review error sections above" >> "$REPORT_FILE"
    echo "2. Check backend server logs" >> "$REPORT_FILE"
    echo "3. Verify network connectivity" >> "$REPORT_FILE"
    echo "4. Check database connection" >> "$REPORT_FILE"
else
    echo "✅ No critical errors found!" >> "$REPORT_FILE"
fi
echo "" >> "$REPORT_FILE"

echo "---" >> "$REPORT_FILE"
echo "**Report Generated**: $(date)" >> "$REPORT_FILE"

# Display summary
echo ""
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Summary${NC}"
echo -e "${BLUE}========================================${NC}"
echo -e "Errors: ${RED}$ERROR_COUNT${NC}"
echo -e "Warnings: ${YELLOW}$WARNING_COUNT${NC}"
echo -e "Report saved to: ${GREEN}$REPORT_FILE${NC}"
echo ""

# Open report if on a system with a default text editor
if command -v xdg-open &> /dev/null; then
    echo "Opening report..."
    xdg-open "$REPORT_FILE" 2>/dev/null || true
elif command -v open &> /dev/null; then
    echo "Opening report..."
    open "$REPORT_FILE" 2>/dev/null || true
fi

