<?php

namespace App\Console\Commands;

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

class TestImageGenerationEnhanced extends Command
{
    protected $signature = 'test:image-generation-enhanced 
                          {--prompt= : Custom prompt to test}
                          {--batch=3 : Number of images to generate in batch}
                          {--model= : Override image model}';
    
    protected $description = 'Test enhanced image generation with improved error handling and English prompts';

    public function handle()
    {
        $this->info('🎨 Testing Enhanced Image Generation with Imagen');
        $this->newLine();

        $googleAi = app(GoogleAiService::class);
        $imageIdGenerator = app(ImageIdGeneratorService::class);
        
        // Override model if specified
        if ($this->option('model')) {
            config(['google.image_model' => $this->option('model')]);
            $this->info("Using model: " . $this->option('model'));
        } else {
            $this->info("Using model: " . config('google.image_model'));
        }
        
        $this->newLine();
        
        // Test prompts - all in English now
        $testPrompts = [
            $this->option('prompt') ?: 'Modern database architecture diagram showing relational tables and connections',
            'API endpoint structure visualization with REST methods and data flow',
            'Security workflow diagram illustrating authentication and authorization process',
            'Cloud infrastructure architecture with servers, databases, and load balancers',
            'Machine learning pipeline diagram showing data processing stages'
        ];

        $batchSize = (int) $this->option('batch');
        $testPrompts = array_slice($testPrompts, 0, $batchSize);
        
        $this->info("Testing {$batchSize} English prompts:");
        foreach ($testPrompts as $index => $prompt) {
            $this->line(sprintf("  %d. %s", $index + 1, $prompt));
        }
        $this->newLine();

        $results = [];
        $successCount = 0;
        $failureCount = 0;

        foreach ($testPrompts as $index => $prompt) {
            $imageId = $imageIdGenerator->generateUniqueImageId($prompt, 'test');
            
            $this->info("🖼️  Generating image " . ($index + 1) . "/{$batchSize}");
            $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']}");
                    $this->line("   🌐 URL: {$result['image_url']}");
                    
                    // Verify file exists and has reasonable size
                    $fullPath = storage_path('app/public/' . $result['image_path']);
                    if (file_exists($fullPath)) {
                        $fileSize = filesize($fullPath);
                        $this->line("   📊 Size: " . $this->formatBytes($fileSize));
                        
                        if ($fileSize < 1024) {
                            $this->warn("   ⚠️  Warning: File size is very small!");
                        }
                    } else {
                        $this->error("   ❌ Warning: File not found at {$fullPath}");
                    }
                    
                } else {
                    $failureCount++;
                    $this->error("   ❌ Failed in {$duration}s");
                    $this->error("   💬 Error: {$result['error']}");
                    
                    // Check if retryable
                    if (isset($result['retryable']) && $result['retryable']) {
                        $this->warn("   🔄 This error is retryable");
                    }
                }
                
                $results[] = array_merge($result, [
                    'duration' => $duration,
                    'prompt' => $prompt
                ]);
                
            } 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
                ];
            }
            
            $this->newLine();
            
            // Add delay between requests to avoid rate limiting
            if ($index < count($testPrompts) - 1) {
                $this->line("   ⏳ Waiting 3 seconds before next request...");
                sleep(3);
            }
        }

        // Summary
        $this->info('📈 Test Results Summary');
        $this->line("   Total images tested: {$batchSize}");
        $this->line("   ✅ Successful: {$successCount}");
        $this->line("   ❌ Failed: {$failureCount}");
        $this->line("   📊 Success rate: " . round(($successCount / $batchSize) * 100, 1) . "%");
        
        if ($failureCount > 0) {
            $this->newLine();
            $this->warn('❌ Failed requests:');
            foreach ($results as $index => $result) {
                if (!$result['success']) {
                    $this->line("   " . ($index + 1) . ". {$result['error']}");
                }
            }
        }
        
        $this->newLine();
        
        // 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->info('⏱️  Performance Analysis');
        $this->line("   Average duration: {$avgDuration}s");
        $this->line("   Fastest: {$minDuration}s");
        $this->line("   Slowest: {$maxDuration}s");
        
        // Cost estimation
        $costInfo = $googleAi->estimateCost($batchSize);
        $this->newLine();
        $this->info('💰 Cost Estimation');
        $this->line("   Cost per image: \${$costInfo['cost_per_image']}");
        $this->line("   Total estimated cost: \${$costInfo['total_estimated_cost']}");
        $this->line("   Aspect ratio: {$costInfo['aspect_ratio']}");
        
        return $successCount === $batchSize ? 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];
    }
}