<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Artisan;

class BotStatus extends Command
{
    protected $signature = 'bot:status {--detailed : Show detailed status information}';
    protected $description = 'Check the current status of the Telegram bot';

    public function handle()
    {
        $this->info('🤖 Telegram Bot Status Check');
        $this->info('============================');
        
        $this->checkBotConfiguration();
        $this->checkDatabaseConnection();
        $this->checkTelegramConnection();
        $this->checkWebhookStatus();
        
        if ($this->option('detailed')) {
            $this->showDetailedStatus();
        }
        
        $this->showQuickStats();
        
        return 0;
    }
    
    private function checkBotConfiguration()
    {
        $this->newLine();
        $this->info('📋 Configuration Check');
        $this->line('=====================');
        
        $checks = [
            'Bot Token' => !empty(config('telegram.bot_token') ?? env('TELEGRAM_BOT_TOKEN')),
            'App URL' => !empty(config('app.url')),
            'Database Config' => !empty(config('database.connections.mysql.database')),
            'Cache Config' => !empty(config('cache.default')),
            'Queue Config' => !empty(config('queue.default')),
        ];
        
        foreach ($checks as $check => $status) {
            $this->line(sprintf(
                '%s %s',
                $status ? '✅' : '❌',
                $check
            ));
        }
    }
    
    private function checkDatabaseConnection()
    {
        $this->newLine();
        $this->info('🗄️  Database Connection');
        $this->line('=====================');
        
        try {
            DB::connection()->getPdo();
            $this->line('✅ Database connection successful');
            
            // Check if migrations are up to date
            try {
                $pending = DB::table('migrations')->count();
                $this->line("✅ Migrations status: {$pending} migrations applied");
            } catch (\Exception $e) {
                $this->line('⚠️  Migrations table not found - run php artisan migrate');
            }
            
        } catch (\Exception $e) {
            $this->line('❌ Database connection failed: ' . $e->getMessage());
        }
    }
    
    private function checkTelegramConnection()
    {
        $this->newLine();
        $this->info('🤖 Telegram API Connection');
        $this->line('==========================');
        
        $botToken = config('telegram.bot_token') ?? env('TELEGRAM_BOT_TOKEN');
        
        if (empty($botToken)) {
            $this->line('❌ Bot token not configured');
            return;
        }
        
        try {
            $response = Http::timeout(10)->get("https://api.telegram.org/bot{$botToken}/getMe");
            
            if ($response->successful()) {
                $botInfo = $response->json()['result'];
                $this->line('✅ Telegram API connection successful');
                $this->line("   Bot Name: {$botInfo['first_name']}");
                $this->line("   Username: @{$botInfo['username']}");
                $this->line("   Bot ID: {$botInfo['id']}");
            } else {
                $this->line('❌ Telegram API error: ' . $response->body());
            }
        } catch (\Exception $e) {
            $this->line('❌ Telegram API connection failed: ' . $e->getMessage());
        }
    }
    
    private function checkWebhookStatus()
    {
        $this->newLine();
        $this->info('🌐 Webhook Status');
        $this->line('================');
        
        $botToken = config('telegram.bot_token') ?? env('TELEGRAM_BOT_TOKEN');
        
        if (empty($botToken)) {
            $this->line('❌ Cannot check webhook - bot token not configured');
            return;
        }
        
        try {
            $response = Http::get("https://api.telegram.org/bot{$botToken}/getWebhookInfo");
            
            if ($response->successful()) {
                $webhookInfo = $response->json()['result'];
                
                if (empty($webhookInfo['url'])) {
                    $this->line('❌ Webhook not set');
                    $this->line('   Run: php artisan telegram:set-webhook');
                } else {
                    $this->line('✅ Webhook is configured');
                    $this->line("   URL: {$webhookInfo['url']}");
                    $this->line("   Pending Updates: {$webhookInfo['pending_update_count']}");
                    
                    if (!empty($webhookInfo['last_error_message'])) {
                        $this->line("   ⚠️  Last Error: {$webhookInfo['last_error_message']}");
                        $this->line("   Error Date: {$webhookInfo['last_error_date']}");
                    }
                    
                    if (!empty($webhookInfo['max_connections'])) {
                        $this->line("   Max Connections: {$webhookInfo['max_connections']}");
                    }
                }
            }
        } catch (\Exception $e) {
            $this->line('❌ Failed to check webhook status: ' . $e->getMessage());
        }
    }
    
    private function showDetailedStatus()
    {
        $this->newLine();
        $this->info('🔍 Detailed System Status');
        $this->line('=========================');
        
        // PHP Information
        $this->line("PHP Version: " . PHP_VERSION);
        $this->line("Laravel Version: " . app()->version());
        $this->line("Memory Limit: " . ini_get('memory_limit'));
        $this->line("Max Execution Time: " . ini_get('max_execution_time') . 's');
        
        // Storage Information
        $storagePath = storage_path();
        $freeBytes = disk_free_space($storagePath);
        $totalBytes = disk_total_space($storagePath);
        $usedBytes = $totalBytes - $freeBytes;
        
        $this->line("Storage Used: " . $this->formatBytes($usedBytes) . " / " . $this->formatBytes($totalBytes));
        
        // Cache Status
        try {
            cache()->put('status_test', 'working', 60);
            $cacheTest = cache()->get('status_test');
            $this->line('Cache: ' . ($cacheTest === 'working' ? '✅ Working' : '❌ Not working'));
        } catch (\Exception $e) {
            $this->line('Cache: ❌ Error - ' . $e->getMessage());
        }
        
        // Queue Status
        try {
            $queueSize = DB::table('jobs')->count();
            $failedJobs = DB::table('failed_jobs')->count();
            $this->line("Queue: {$queueSize} pending, {$failedJobs} failed");
        } catch (\Exception $e) {
            $this->line('Queue: ❌ Cannot check queue status');
        }
        
        // Module Status
        $this->showModuleStatus();
    }
    
    private function showModuleStatus()
    {
        $this->newLine();
        $this->info('🧩 Module Status');
        $this->line('===============');
        
        $modules = [
            'PersianModule' => 'App\\Modules\\PersianModule',
            'PaymentModule' => 'App\\Modules\\PaymentModule',
            'ContentModule' => 'App\\Modules\\ContentModule',
            'AnalyticsModule' => 'App\\Modules\\AnalyticsModule',
            'NotificationModule' => 'App\\Modules\\NotificationModule',
        ];
        
        foreach ($modules as $name => $class) {
            if (class_exists($class)) {
                $this->line("✅ {$name}");
            } else {
                $this->line("❌ {$name} - Class not found");
            }
        }
    }
    
    private function showQuickStats()
    {
        $this->newLine();
        $this->info('📊 Quick Statistics');
        $this->line('==================');
        
        try {
            // User statistics
            $totalUsers = DB::table('users')->count();
            $activeUsers = DB::table('users')->where('last_activity', '>=', now()->subDays(7))->count();
            $adminUsers = DB::table('users')->where('is_admin', true)->count();
            
            $this->line("Total Users: {$totalUsers}");
            $this->line("Active Users (7 days): {$activeUsers}");
            $this->line("Admin Users: {$adminUsers}");
            
            // Analytics data
            if (DB::getSchemaBuilder()->hasTable('analytics_events')) {
                $todayEvents = DB::table('analytics_events')
                    ->whereDate('created_at', today())
                    ->count();
                $this->line("Events Today: {$todayEvents}");
            }
            
            // Payment statistics
            if (DB::getSchemaBuilder()->hasTable('payments')) {
                $totalPayments = DB::table('payments')->where('status', 'completed')->count();
                $this->line("Completed Payments: {$totalPayments}");
            }
            
        } catch (\Exception $e) {
            $this->line('❌ Cannot retrieve statistics: ' . $e->getMessage());
        }
    }
    
    private function formatBytes($bytes, $precision = 2)
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB');
        
        for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
            $bytes /= 1024;
        }
        
        return round($bytes, $precision) . ' ' . $units[$i];
    }
}