<?php

namespace App\Console\Commands;

use App\Services\GoogleAiService;
use App\Services\ImageIdGeneratorService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class TestSequentialImageGeneration extends Command
{
    protected $signature = 'test:sequential-images 
                          {--count=5 : Number of images to generate}
                          {--delay=3 : Delay between requests in seconds}';
    
    protected $description = 'Test sequential image generation to avoid rate limiting';

    public function handle()
    {
        $count = (int) $this->option('count');
        $delay = (int) $this->option('delay');
        
        $this->info("🔄 Testing Sequential Image Generation");
        $this->line("   Images: {$count}");
        $this->line("   Delay: {$delay} seconds between requests");
        $this->newLine();

        $googleAi = app(GoogleAiService::class);
        $imageIdGenerator = app(ImageIdGeneratorService::class);
        
        // Test prompts in English
        $testPrompts = [
            'Modern database architecture diagram with tables and relationships',
            'API gateway structure showing microservices communication',
            'Cloud infrastructure diagram with load balancers and servers',
            'Machine learning pipeline visualization with data flow',
            'Security architecture diagram with authentication layers',
            'DevOps workflow showing CI/CD pipeline stages',
            'Blockchain network topology with consensus mechanism',
            'IoT system architecture with edge computing nodes',
            'Data analytics dashboard with charts and metrics',
            'Microservices architecture with service mesh'
        ];

        $selectedPrompts = array_slice($testPrompts, 0, $count);
        
        $results = [];
        $successCount = 0;
        $failureCount = 0;

        foreach ($selectedPrompts as $index => $prompt) {
            $imageId = $imageIdGenerator->generateUniqueImageId($prompt, 'seq-test');
            
            $this->info("🖼️  Generating image " . ($index + 1) . "/{$count}");
            $this->line("   ID: {$imageId}");
            $this->line("   Prompt: {$prompt}");
            
            $startTime = microtime(true);
            
            try {
                $result = $googleAi->generateImage($prompt, $imageId);
                $duration = round(microtime(true) - $startTime, 2);
                
                if ($result['success']) {
                    $successCount++;
                    $this->info("   ✅ Success in {$duration}s");
                    $this->line("   📁 Path: {$result['image_path']}");
                    
                    // Verify file
                    $fullPath = storage_path('app/public/' . $result['image_path']);
                    if (file_exists($fullPath)) {
                        $fileSize = filesize($fullPath);
                        $this->line("   📊 Size: " . $this->formatBytes($fileSize));
                    }
                    
                } else {
                    $failureCount++;
                    $this->error("   ❌ Failed in {$duration}s");
                    $this->error("   💬 Error: {$result['error']}");
                }
                
                $results[] = array_merge($result, [
                    'duration' => $duration,
                    'prompt' => $prompt,
                    'index' => $index
                ]);
                
            } catch (\Exception $e) {
                $failureCount++;
                $duration = round(microtime(true) - $startTime, 2);
                $this->error("   ❌ Exception in {$duration}s: " . $e->getMessage());
                
                $results[] = [
                    'success' => false,
                    'error' => $e->getMessage(),
                    'duration' => $duration,
                    'prompt' => $prompt,
                    'index' => $index
                ];
            }
            
            // Add delay between requests (except for the last one)
            if ($index < count($selectedPrompts) - 1) {
                $this->line("   ⏳ Waiting {$delay} seconds before next request...");
                sleep($delay);
            }
            
            $this->newLine();
        }

        // Summary
        $this->info('📈 Sequential Test Results');
        $this->line("   Total images: {$count}");
        $this->line("   ✅ Successful: {$successCount}");
        $this->line("   ❌ Failed: {$failureCount}");
        $this->line("   📊 Success rate: " . round(($successCount / $count) * 100, 1) . "%");
        
        if ($failureCount > 0) {
            $this->newLine();
            $this->warn('❌ Failed requests:');
            foreach ($results as $result) {
                if (!$result['success']) {
                    $this->line("   " . ($result['index'] + 1) . ". {$result['error']}");
                }
            }
        }
        
        // Performance analysis
        $durations = array_column($results, 'duration');
        $avgDuration = round(array_sum($durations) / count($durations), 2);
        $maxDuration = round(max($durations), 2);
        $minDuration = round(min($durations), 2);
        
        $this->newLine();
        $this->info('⏱️  Performance Analysis');
        $this->line("   Average duration: {$avgDuration}s");
        $this->line("   Fastest: {$minDuration}s");
        $this->line("   Slowest: {$maxDuration}s");
        $this->line("   Total time: " . round(array_sum($durations), 1) . "s");
        
        // Rate limiting insights
        $this->newLine();
        $this->info('📊 Rate Limiting Analysis');
        $this->line("   Requests per minute: " . round(60 / $delay, 1));
        $this->line("   Delay between requests: {$delay}s");
        
        if ($successCount / $count >= 0.9) {
            $this->info("   ✅ Rate limiting: GOOD (90%+ success rate)");
        } elseif ($successCount / $count >= 0.7) {
            $this->warn("   ⚠️  Rate limiting: MODERATE (70-90% success rate)");
            $this->line("   💡 Consider increasing delay to " . ($delay + 2) . "s");
        } else {
            $this->error("   ❌ Rate limiting: POOR (<70% success rate)");
            $this->line("   💡 Consider increasing delay to " . ($delay + 5) . "s");
        }

        return $successCount === $count ? self::SUCCESS : self::FAILURE;
    }
    
    private function formatBytes($size, $precision = 2)
    {
        $units = ['B', 'KB', 'MB', 'GB'];
        
        for ($i = 0; $size > 1024 && $i < count($units) - 1; $i++) {
            $size /= 1024;
        }
        
        return round($size, $precision) . ' ' . $units[$i];
    }
}