<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Services\Core\ModuleManager;
use App\Services\Core\HealthCheckService;
use Illuminate\Support\Facades\DB;

class SystemInfo extends Command
{
    /**
     * The name and signature of the console command.
     */
    protected $signature = 'system:info 
                           {--modules : Show module information}
                           {--health : Run health checks}
                           {--config : Show configuration status}
                           {--database : Show database information}';

    /**
     * The console command description.
     */
    protected $description = 'Display comprehensive system information and status';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('🤖 LarBot Template System Information');
        $this->line('=====================================');

        // Basic system info
        $this->showBasicInfo();

        if ($this->option('modules')) {
            $this->showModuleInfo();
        }

        if ($this->option('health')) {
            $this->showHealthStatus();
        }

        if ($this->option('config')) {
            $this->showConfigStatus();
        }

        if ($this->option('database')) {
            $this->showDatabaseInfo();
        }

        // If no specific options, show everything
        if (!$this->hasAnyOption()) {
            $this->showModuleInfo();
            $this->showHealthStatus();
            $this->showConfigStatus();
            $this->showDatabaseInfo();
        }
    }

    /**
     * Show basic system information
     */
    private function showBasicInfo(): void
    {
        $this->newLine();
        $this->info('📊 Basic Information');
        $this->line('-------------------');

        $this->table(['Property', 'Value'], [
            ['Framework', 'Laravel ' . app()->version()],
            ['PHP Version', PHP_VERSION],
            ['Environment', app()->environment()],
            ['Debug Mode', config('app.debug') ? '✅ Enabled' : '❌ Disabled'],
            ['Timezone', config('app.timezone')],
            ['URL', config('app.url')],
            ['Memory Limit', ini_get('memory_limit')],
            ['Max Execution Time', ini_get('max_execution_time') . 's'],
        ]);
    }

    /**
     * Show module information
     */
    private function showModuleInfo(): void
    {
        $this->newLine();
        $this->info('📦 Module Information');
        $this->line('--------------------');

        try {
            $moduleManager = app(ModuleManager::class);
            $modules = $moduleManager->getAllModules();

            if (empty($modules)) {
                $this->warn('No modules registered');
                return;
            }

            $moduleData = [];
            foreach ($modules as $module) {
                $moduleData[] = [
                    $module->getModuleName(),
                    $module->getModuleVersion(),
                    $module->isEnabled() ? '✅ Enabled' : '❌ Disabled',
                    implode(', ', $module->getDependencies()) ?: 'None',
                    $module->getPriority()
                ];
            }

            $this->table(
                ['Name', 'Version', 'Status', 'Dependencies', 'Priority'],
                $moduleData
            );

        } catch (\Exception $e) {
            $this->error("Error getting module info: " . $e->getMessage());
        }
    }

    /**
     * Show health status
     */
    private function showHealthStatus(): void
    {
        $this->newLine();
        $this->info('🏥 Health Status');
        $this->line('---------------');

        try {
            $healthService = app(HealthCheckService::class);
            $results = $healthService->runAllChecks();

            $overallStatus = $results['overall_status'] ?? 'unknown';
            $statusColor = match($overallStatus) {
                'healthy' => 'info',
                'warning' => 'comment',
                'critical' => 'error',
                default => 'line'
            };

            $this->$statusColor("Overall Status: " . strtoupper($overallStatus));
            $this->newLine();

            $healthData = [];
            foreach ($results['checks'] ?? [] as $check => $result) {
                $status = $result['status'] ?? 'unknown';
                $statusIcon = match($status) {
                    'ok' => '✅',
                    'warning' => '⚠️',
                    'critical' => '❌',
                    default => '❓'
                };

                $responseTime = isset($result['response_time']) 
                    ? number_format($result['response_time'], 2) . 'ms'
                    : 'N/A';

                $healthData[] = [
                    ucfirst(str_replace('_', ' ', $check)),
                    $statusIcon . ' ' . ucfirst($status),
                    $responseTime,
                    $result['message'] ?? ''
                ];
            }

            $this->table(
                ['Check', 'Status', 'Response Time', 'Message'],
                $healthData
            );

        } catch (\Exception $e) {
            $this->error("Error running health checks: " . $e->getMessage());
        }
    }

    /**
     * Show configuration status
     */
    private function showConfigStatus(): void
    {
        $this->newLine();
        $this->info('⚙️ Configuration Status');
        $this->line('----------------------');

        $configs = [
            ['Telegram Bot Token', config('telegram.bot_token') ? '✅ Set' : '❌ Missing'],
            ['Telegram Bot Username', config('telegram.bot_username') ? '✅ Set' : '❌ Missing'],
            ['Database Connection', $this->checkDatabaseConnection()],
            ['Cache Driver', config('cache.default')],
            ['Queue Driver', config('queue.default')],
            ['Mail Driver', config('mail.default')],
            ['Zarinpal Merchant ID', config('payment.zarinpal.merchant_id') ? '✅ Set' : '❌ Missing'],
            ['App Key', config('app.key') ? '✅ Set' : '❌ Missing'],
        ];

        $this->table(['Configuration', 'Status'], $configs);

        // Check for common configuration issues
        $this->checkConfigurationIssues();
    }

    /**
     * Show database information
     */
    private function showDatabaseInfo(): void
    {
        $this->newLine();
        $this->info('🗄️ Database Information');
        $this->line('----------------------');

        try {
            $connection = DB::connection();
            $pdo = $connection->getPdo();
            
            $dbInfo = [
                ['Connection', config('database.default')],
                ['Host', config('database.connections.' . config('database.default') . '.host')],
                ['Database', config('database.connections.' . config('database.default') . '.database')],
                ['Driver', $pdo->getAttribute(\PDO::ATTR_DRIVER_NAME)],
                ['Version', $pdo->getAttribute(\PDO::ATTR_SERVER_VERSION)],
                ['Status', '✅ Connected'],
            ];

            $this->table(['Property', 'Value'], $dbInfo);

            // Show table counts
            $this->showTableCounts();

        } catch (\Exception $e) {
            $this->error("Database connection failed: " . $e->getMessage());
        }
    }

    /**
     * Show table record counts
     */
    private function showTableCounts(): void
    {
        $this->newLine();
        $this->line('📊 Table Statistics:');

        $tables = [
            'users' => 'Users',
            'broadcast_campaigns' => 'Broadcast Campaigns',
            'broadcast_recipients' => 'Broadcast Recipients',
            'notification_templates' => 'Notification Templates',
            'analytics_events' => 'Analytics Events',
            'content_pages' => 'Content Pages',
            'payments' => 'Payments',
        ];

        $tableCounts = [];
        foreach ($tables as $table => $label) {
            try {
                $count = DB::table($table)->count();
                $tableCounts[] = [$label, number_format($count)];
            } catch (\Exception $e) {
                $tableCounts[] = [$label, 'Table not found'];
            }
        }

        $this->table(['Table', 'Records'], $tableCounts);
    }

    /**
     * Check database connection
     */
    private function checkDatabaseConnection(): string
    {
        try {
            DB::connection()->getPdo();
            return '✅ Connected';
        } catch (\Exception $e) {
            return '❌ Failed';
        }
    }

    /**
     * Check for common configuration issues
     */
    private function checkConfigurationIssues(): void
    {
        $issues = [];

        // Check for missing required configs
        if (!config('app.key')) {
            $issues[] = 'APP_KEY is missing. Run: php artisan key:generate';
        }

        if (!config('telegram.bot_token')) {
            $issues[] = 'TELEGRAM_BOT_TOKEN is missing. Get one from @BotFather';
        }

        if (config('app.debug') && app()->environment('production')) {
            $issues[] = 'APP_DEBUG should be false in production';
        }

        if (!config('payment.zarinpal.merchant_id') && config('modules.payment.enabled')) {
            $issues[] = 'ZARINPAL_MERCHANT_ID is missing but payment module is enabled';
        }

        if (!empty($issues)) {
            $this->newLine();
            $this->warn('⚠️ Configuration Issues Found:');
            foreach ($issues as $issue) {
                $this->line("  • {$issue}");
            }
        }
    }

    /**
     * Check if any option is provided
     */
    private function hasAnyOption(): bool
    {
        return $this->option('modules') || 
               $this->option('health') || 
               $this->option('config') || 
               $this->option('database');
    }
}