<?php

namespace App\Console\Commands;

use App\Services\GoogleAiService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;

class CheckImagenConfig extends Command
{
    protected $signature = 'check:imagen-config 
                          {--fix : Automatically fix configuration issues}
                          {--clear-cache : Clear all caches before checking}';
    
    protected $description = 'Check and fix Imagen configuration issues';

    public function handle()
    {
        $this->info('🔍 Checking Imagen Configuration');
        $this->newLine();

        // Clear caches if requested
        if ($this->option('clear-cache')) {
            $this->info('🧹 Clearing caches...');
            Artisan::call('config:clear');
            Artisan::call('cache:clear');
            $this->info('✅ Caches cleared');
            $this->newLine();
        }

        // Check environment file
        $this->checkEnvironmentFile();
        
        // Check config values
        $this->checkConfigValues();
        
        // Test service initialization
        $this->testServiceInitialization();
        
        // Test API connectivity
        $this->testApiConnectivity();
        
        $this->newLine();
        $this->info('🎯 Configuration check completed');
    }
    
    private function checkEnvironmentFile()
    {
        $this->info('📁 Checking .env file...');
        
        $envPath = base_path('.env');
        if (!file_exists($envPath)) {
            $this->error('❌ .env file not found');
            return;
        }
        
        $envContent = file_get_contents($envPath);
        
        // Check for Google AI settings
        $requiredSettings = [
            'GOOGLE_AI_API_KEY',
            'GOOGLE_AI_IMAGE_MODEL',
        ];
        
        $issues = [];
        foreach ($requiredSettings as $setting) {
            if (strpos($envContent, $setting) === false) {
                $issues[] = "Missing {$setting}";
            } elseif (preg_match("/{$setting}=\s*$/m", $envContent)) {
                $issues[] = "Empty value for {$setting}";
            }
        }
        
        if (empty($issues)) {
            $this->info('✅ .env file contains required settings');
            
            // Show current model setting
            if (preg_match('/GOOGLE_AI_IMAGE_MODEL=(.+)$/m', $envContent, $matches)) {
                $currentModel = trim($matches[1]);
                $this->line("   Current model: {$currentModel}");
                
                if ($currentModel !== 'imagen-4.0-fast-generate-preview-06-06') {
                    $this->warn("   ⚠️  Recommended model: imagen-4.0-fast-generate-preview-06-06");
                    
                    if ($this->option('fix')) {
                        $this->info('🔧 Updating model in .env...');
                        $newContent = preg_replace(
                            '/GOOGLE_AI_IMAGE_MODEL=.+$/m',
                            'GOOGLE_AI_IMAGE_MODEL=imagen-4.0-fast-generate-preview-06-06',
                            $envContent
                        );
                        file_put_contents($envPath, $newContent);
                        $this->info('✅ Model updated in .env');
                    }
                }
            }
        } else {
            $this->error('❌ .env file issues:');
            foreach ($issues as $issue) {
                $this->line("   - {$issue}");
            }
        }
        
        $this->newLine();
    }
    
    private function checkConfigValues()
    {
        $this->info('⚙️  Checking config values...');
        
        $configs = [
            'google.api_key' => env('GOOGLE_AI_API_KEY'),
            'google.image_model' => env('GOOGLE_AI_IMAGE_MODEL'),
            'google.base_url' => env('GOOGLE_AI_BASE_URL'),
            'google.timeout' => env('GOOGLE_AI_TIMEOUT'),
        ];
        
        foreach ($configs as $key => $value) {
            if (empty($value)) {
                $this->error("❌ {$key}: not set");
            } else {
                $this->info("✅ {$key}: " . (strlen($value) > 50 ? substr($value, 0, 47) . '...' : $value));
            }
        }
        
        // Check actual config() values
        $this->line('');
        $this->line('📋 Resolved config values:');
        $resolvedConfigs = [
            'google.api_key' => config('google.api_key'),
            'google.image_model' => config('google.image_model'),
            'google.base_url' => config('google.base_url'),
            'google.timeout' => config('google.timeout'),
        ];
        
        foreach ($resolvedConfigs as $key => $value) {
            if (empty($value)) {
                $this->error("❌ {$key}: null/empty");
            } else {
                $displayValue = $key === 'google.api_key' 
                    ? (strlen($value) > 10 ? substr($value, 0, 10) . '...' : $value)
                    : $value;
                $this->info("✅ {$key}: {$displayValue}");
            }
        }
        
        $this->newLine();
    }
    
    private function testServiceInitialization()
    {
        $this->info('🚀 Testing GoogleAiService initialization...');
        
        try {
            $service = app(GoogleAiService::class);
            $this->info('✅ GoogleAiService initialized successfully');
            
            // Test getCurrentImageConfig method
            $config = $service->getCurrentImageConfig();
            $this->line("   Aspect ratio: {$config['aspect_ratio']}");
            $this->line("   Dimensions: {$config['dimensions']}");
            $this->line("   Max images per article: {$config['max_images_per_article']}");
            
        } catch (\Exception $e) {
            $this->error('❌ GoogleAiService initialization failed: ' . $e->getMessage());
        }
        
        $this->newLine();
    }
    
    private function testApiConnectivity()
    {
        $this->info('🌐 Testing API connectivity...');
        
        try {
            $service = app(GoogleAiService::class);
            $connected = $service->testConnection();
            
            if ($connected) {
                $this->info('✅ API connection successful');
            } else {
                $this->error('❌ API connection failed');
            }
            
        } catch (\Exception $e) {
            $this->error('❌ API connection test failed: ' . $e->getMessage());
        }
        
        $this->newLine();
    }
}