#!/bin/bash

echo "📊 Telegram Proxy Bot Monitor"
echo "============================="

# Check if bot is running
echo "🔍 Bot Status:"
if docker compose ps | grep -q "Up"; then
    echo "✅ Bot is running"

    # Show container stats
    echo ""
    echo "📈 Resource Usage:"
    docker stats telegram-proxy-bot --no-stream --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.MemPerc}}"

else
    echo "❌ Bot is not running"
    echo "💡 Start with: docker compose up -d"
    exit 1
fi

# Check cache file
echo ""
echo "💾 Cache Status:"
if [ -f "data/proxy_cache.json" ]; then
    if command -v jq &> /dev/null; then
        COLLECTED=$(cat data/proxy_cache.json | jq '.collected_proxies | length' 2>/dev/null || echo "N/A")
        SENT=$(cat data/proxy_cache.json | jq '.sent_proxies | length' 2>/dev/null || echo "N/A")
        LAST_UPDATE=$(cat data/proxy_cache.json | jq -r '.last_update' 2>/dev/null || echo "N/A")

        echo "   📦 Collected Proxies: $COLLECTED"
        echo "   📤 Sent Proxies: $SENT"
        echo "   🕐 Last Update: $LAST_UPDATE"

        # Calculate unsent proxies
        if [ "$COLLECTED" != "N/A" ] && [ "$SENT" != "N/A" ]; then
            UNSENT=$((COLLECTED - SENT))
            echo "   ⏳ Unsent Proxies: $UNSENT"
        fi
    else
        CACHE_SIZE=$(wc -l < data/proxy_cache.json)
        echo "   📁 Cache file size: $CACHE_SIZE lines"
        echo "   💡 Install 'jq' for detailed stats: apt install jq"
    fi
else
    echo "   ❌ Cache file not found"
fi

# Check log file
echo ""
echo "📝 Log Status:"
if [ -f "logs/proxy_bot.log" ]; then
    LOG_SIZE=$(wc -l < logs/proxy_bot.log 2>/dev/null || echo "0")
    echo "   📄 Log entries: $LOG_SIZE lines"

    # Show last few important log entries
    echo "   🔍 Recent activity:"
    tail -n 5 logs/proxy_bot.log | while read line; do
        echo "      $line"
    done
else
    echo "   ⚠️  Log file not found"
fi

# Check disk usage
echo ""
echo "💽 Disk Usage:"
echo "   📊 Data directory: $(du -sh data/ 2>/dev/null | cut -f1 || echo "N/A")"
echo "   📊 Log directory: $(du -sh logs/ 2>/dev/null | cut -f1 || echo "N/A")"

# Show recent docker logs
echo ""
echo "🔍 Recent Docker Logs (last 10 lines):"
echo "----------------------------------------"
docker compose logs --tail=10 proxy-bot 2>/dev/null | sed 's/^/   /'

echo ""
echo "📋 Available Commands:"
echo "   Full logs:        docker compose logs -f"
echo "   Restart bot:      docker compose restart"
echo "   Stop bot:         docker compose down"
echo "   Update cache:     cat data/proxy_cache.json | jq ."
echo "   Live monitoring:  watch -n 5 ./monitor.sh"

# Auto-refresh option
echo ""
read -p "🔄 Auto-refresh every 10 seconds? (y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    while true; do
        clear
        bash $0
        echo ""
        echo "⏰ Refreshing in 10 seconds... (Ctrl+C to stop)"
        sleep 10
    done
fi
