<?php

namespace App\Console\Commands;

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

class SetupBot extends Command
{
    protected $signature = 'bot:setup {--interactive : Run in interactive mode}';
    protected $description = 'Complete bot setup wizard for production deployment';

    public function handle()
    {
        $this->info('🤖 Laravel Telegram Bot Setup Wizard');
        $this->info('====================================');
        
        if ($this->option('interactive')) {
            return $this->runInteractiveSetup();
        }
        
        return $this->runQuickSetup();
    }

    private function runInteractiveSetup()
    {
        $this->info('Starting interactive setup...');
        
        // Step 1: Environment Check
        $this->newLine();
        $this->info('📋 Step 1: Environment Check');
        $this->checkEnvironment();
        
        // Step 2: Database Configuration
        $this->newLine();
        $this->info('🗄️  Step 2: Database Configuration');
        $this->setupDatabase();
        
        // Step 3: Telegram Bot Configuration
        $this->newLine();
        $this->info('🤖 Step 3: Telegram Bot Configuration');
        $this->setupTelegramBot();
        
        // Step 4: Application Configuration
        $this->newLine();
        $this->info('⚙️  Step 4: Application Configuration');
        $this->setupApplication();
        
        // Step 5: Install Dependencies & Run Migrations
        $this->newLine();
        $this->info('📦 Step 5: Installation & Migration');
        $this->runInstallation();
        
        // Step 6: Test Configuration
        $this->newLine();
        $this->info('🧪 Step 6: Testing Configuration');
        $this->testConfiguration();
        
        $this->newLine();
        $this->info('✅ Setup completed successfully!');
        $this->displayFinalInstructions();
        
        return 0;
    }
    
    private function checkEnvironment()
    {
        $checks = [
            'PHP Version (>= 8.1)' => version_compare(PHP_VERSION, '8.1.0', '>='),
            'Composer Available' => $this->commandExists('composer'),
            'Database Extension' => extension_loaded('pdo_mysql'),
            'cURL Extension' => extension_loaded('curl'),
            'JSON Extension' => extension_loaded('json'),
            'Storage Writable' => is_writable(storage_path()),
        ];
        
        foreach ($checks as $check => $status) {
            $this->line(sprintf(
                '%s %s',
                $status ? '✅' : '❌',
                $check
            ));
        }
        
        if (in_array(false, $checks)) {
            $this->error('Some environment requirements are not met. Please fix them before continuing.');
            return false;
        }
        
        $this->info('All environment checks passed!');
        return true;
    }
    
    private function setupDatabase()
    {
        $dbHost = $this->ask('Database Host', 'localhost');
        $dbPort = $this->ask('Database Port', '3306');
        $dbName = $this->ask('Database Name');
        $dbUser = $this->ask('Database Username');
        $dbPassword = $this->secret('Database Password');
        
        // Test database connection
        $this->info('Testing database connection...');
        
        try {
            $pdo = new \PDO(
                "mysql:host={$dbHost};port={$dbPort};dbname={$dbName}",
                $dbUser,
                $dbPassword
            );
            $this->info('✅ Database connection successful!');
        } catch (\Exception $e) {
            $this->error('❌ Database connection failed: ' . $e->getMessage());
            return false;
        }
        
        // Update .env file
        $this->updateEnvFile([
            'DB_HOST' => $dbHost,
            'DB_PORT' => $dbPort,
            'DB_DATABASE' => $dbName,
            'DB_USERNAME' => $dbUser,
            'DB_PASSWORD' => $dbPassword,
        ]);
        
        return true;
    }
    
    private function setupTelegramBot()
    {
        $botToken = $this->secret('Telegram Bot Token (get from @BotFather)');
        
        if (empty($botToken)) {
            $this->error('Bot token is required!');
            return false;
        }
        
        // Validate bot token
        $this->info('Validating bot token...');
        $response = Http::get("https://api.telegram.org/bot{$botToken}/getMe");
        
        if (!$response->successful()) {
            $this->error('❌ Invalid bot token!');
            return false;
        }
        
        $botInfo = $response->json();
        $this->info("✅ Bot validated: @{$botInfo['result']['username']}");
        
        // Get webhook URL
        $appUrl = $this->ask('Application URL (e.g., https://yourdomain.com)', config('app.url'));
        $webhookUrl = rtrim($appUrl, '/') . '/api/telegram/webhook';
        
        $this->updateEnvFile([
            'TELEGRAM_BOT_TOKEN' => $botToken,
            'APP_URL' => $appUrl,
            'TELEGRAM_WEBHOOK_URL' => $webhookUrl,
        ]);
        
        return true;
    }
    
    private function setupApplication()
    {
        $appName = $this->ask('Application Name', 'Laravel Telegram Bot');
        $appEnv = $this->choice('Environment', ['production', 'local', 'staging'], 'production');
        $appDebug = $this->confirm('Enable Debug Mode?', false);
        
        // Generate app key if not exists
        if (empty(config('app.key'))) {
            $this->info('Generating application key...');
            Artisan::call('key:generate', ['--force' => true]);
        }
        
        $this->updateEnvFile([
            'APP_NAME' => '"' . $appName . '"',
            'APP_ENV' => $appEnv,
            'APP_DEBUG' => $appDebug ? 'true' : 'false',
        ]);
        
        return true;
    }
    
    private function runInstallation()
    {
        $this->info('Installing composer dependencies...');
        $this->line('Running: composer install --optimize-autoloader --no-dev');
        exec('composer install --optimize-autoloader --no-dev 2>&1', $output, $returnCode);
        
        if ($returnCode !== 0) {
            $this->error('Composer install failed!');
            $this->line(implode("\n", $output));
            return false;
        }
        
        $this->info('✅ Dependencies installed successfully!');
        
        // Run migrations
        $this->info('Running database migrations...');
        
        try {
            Artisan::call('migrate', ['--force' => true]);
            $this->info('✅ Database migrations completed!');
        } catch (\Exception $e) {
            $this->error('❌ Migration failed: ' . $e->getMessage());
            return false;
        }
        
        // Optimize application
        $this->info('Optimizing application...');
        Artisan::call('optimize');
        $this->info('✅ Application optimized!');
        
        return true;
    }
    
    private function testConfiguration()
    {
        $this->info('Testing bot configuration...');
        
        // Test webhook setting
        if ($this->confirm('Set Telegram webhook now?', true)) {
            try {
                Artisan::call('telegram:set-webhook');
                $this->info('✅ Webhook set successfully!');
            } catch (\Exception $e) {
                $this->error('❌ Webhook setup failed: ' . $e->getMessage());
            }
        }
        
        // Test database connection
        try {
            DB::connection()->getPdo();
            $this->info('✅ Database connection working!');
        } catch (\Exception $e) {
            $this->error('❌ Database connection failed: ' . $e->getMessage());
        }
        
        // Create admin user
        if ($this->confirm('Create admin user?', true)) {
            $this->createAdminUser();
        }
    }
    
    private function createAdminUser()
    {
        $telegramId = $this->ask('Your Telegram User ID (send /start to @userinfobot to get it)');
        $firstName = $this->ask('First Name');
        $username = $this->ask('Telegram Username (optional)', null);
        
        try {
            $user = \App\Models\User::updateOrCreate(
                ['telegram_id' => $telegramId],
                [
                    'first_name' => $firstName,
                    'username' => $username,
                    'is_admin' => true,
                    'is_active' => true,
                ]
            );
            
            $this->info("✅ Admin user created: {$user->first_name} (ID: {$user->telegram_id})");
        } catch (\Exception $e) {
            $this->error('❌ Failed to create admin user: ' . $e->getMessage());
        }
    }
    
    private function displayFinalInstructions()
    {
        $this->newLine();
        $this->info('🎉 Your Telegram Bot is now ready!');
        $this->newLine();
        
        $this->line('Next steps:');
        $this->line('1. Send /start to your bot on Telegram');
        $this->line('2. Access admin panel at: ' . config('app.url') . '/admin');
        $this->line('3. Configure modules in the admin panel');
        $this->line('4. Test bot functionality');
        $this->newLine();
        
        $this->line('Useful commands:');
        $this->line('• php artisan bot:status     - Check bot status');
        $this->line('• php artisan bot:test       - Test bot functionality');
        $this->line('• php artisan telegram:info  - Get bot information');
        $this->line('• php artisan queue:work     - Start background job processing');
    }
    
    private function updateEnvFile(array $values)
    {
        $envPath = base_path('.env');
        
        if (!File::exists($envPath)) {
            File::copy(base_path('.env.example'), $envPath);
        }
        
        $envContent = File::get($envPath);
        
        foreach ($values as $key => $value) {
            $pattern = "/^{$key}=.*/m";
            $replacement = "{$key}={$value}";
            
            if (preg_match($pattern, $envContent)) {
                $envContent = preg_replace($pattern, $replacement, $envContent);
            } else {
                $envContent .= "\n{$replacement}";
            }
        }
        
        File::put($envPath, $envContent);
    }
    
    private function commandExists($command)
    {
        $return = shell_exec(sprintf("which %s", escapeshellarg($command)));
        return !empty($return);
    }
    
    private function runQuickSetup()
    {
        $this->info('Running quick setup with existing configuration...');
        
        // Quick installation for CI/CD or scripted deployment
        if (File::exists(base_path('.env'))) {
            Artisan::call('migrate', ['--force' => true]);
            Artisan::call('optimize');
            $this->info('✅ Quick setup completed!');
        } else {
            $this->error('No .env file found. Please run with --interactive flag.');
            return 1;
        }
        
        return 0;
    }
}