<?php

namespace App\Console\Commands;

use App\Services\GoogleAiService;
use Illuminate\Console\Command;

class TestImageGeneration extends Command
{
	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'ai:test-images {--cost-only : Only show cost estimation}';
	
	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Test Google AI image generation and show cost estimation';
	
	/**
	 * Execute the console command.
	 */
	public function handle(): int
	{
		$this->info('🖼️  Google AI Image Generation Test');
		$this->newLine();
		
		// Try to create GoogleAiService - handle missing API key gracefully
		try {
			$googleAi = app(GoogleAiService::class);
			
			// Show current configuration
			$config = $googleAi->getCurrentImageConfig();
			$this->info("📐 Current Configuration:");
			$this->line("   Aspect Ratio: {$config['aspect_ratio']}");
			$this->line("   Dimensions: {$config['dimensions']}");
			$this->line("   Description: {$config['description']}");
			$this->line("   Max Images/Article: {$config['max_images_per_article']}");
			$this->newLine();
			
			// Cost estimation for different scenarios
			$this->info("💰 Cost Estimation:");
			
			$scenarios = [
				['images' => 1, 'description' => '1 image'],
				['images' => 5, 'description' => '1 article (5 images)'],
				['images' => 50, 'description' => '10 articles (50 images)'],
				['images' => 500, 'description' => '100 articles (500 images)'],
				['images' => 5000, 'description' => '1000 articles (5000 images)'],
			];
			
			foreach ($scenarios as $scenario) {
				$cost = $googleAi->estimateCost($scenario['images']);
				$this->line("   {$scenario['description']}: ${$cost['total_estimated_cost']} USD");
			}
			
		} catch (\Exception $e) {
			if (strpos($e->getMessage(), 'API key is not configured') !== false) {
				$this->warn("⚠️  Google AI API key not configured");
				$this->newLine();
				
				// Show cost estimation with default settings
				$this->info("💰 Cost Estimation (based on default ASPECT_RATIO_1_1):");
				$scenarios = [
					['images' => 1, 'cost' => 0.040, 'description' => '1 image'],
					['images' => 5, 'cost' => 0.200, 'description' => '1 article (5 images)'],
					['images' => 50, 'cost' => 2.000, 'description' => '10 articles (50 images)'],
					['images' => 500, 'cost' => 20.000, 'description' => '100 articles (500 images)'],
					['images' => 5000, 'cost' => 200.000, 'description' => '1000 articles (5000 images)'],
				];
				
				foreach ($scenarios as $scenario) {
					$this->line("   {$scenario['description']}: \${$scenario['cost']} USD");
				}
				
				$this->newLine();
				$this->comment("💡 To configure API key:");
				$this->line("1. Get API key from: https://aistudio.google.com/app/apikey");
				$this->line("2. Add to .env: GOOGLE_AI_API_KEY=your_key_here");
				
			} else {
				throw $e;
			}
		}
		
		$this->newLine();
		
		// If cost-only flag is set, skip connection test
		if ($this->option('cost-only')) {
			$this->info("✅ Cost estimation complete. Use --cost-only=false to test API connection.");
			return 0;
		}
		
		// Test API connection (only if API key is configured)
		if (config('google.api_key')) {
			try {
				$googleAi = app(GoogleAiService::class);
				$this->info("🔌 Testing API Connection...");
				
				if ($googleAi->testConnection()) {
					$this->info("✅ API connection successful!");
				} else {
					$this->error("❌ API connection failed. Check your API key and network connection.");
					return 1;
				}
			} catch (\Exception $e) {
				$this->error("❌ API connection error: " . $e->getMessage());
				return 1;
			}
		} else {
			$this->warn("⚠️  Skipping API connection test (no API key configured)");
		}
		
		$this->newLine();
		$this->info("🚀 Ready to generate images! Try creating an article with AI assistant.");
		
		// Show quick start reminder
		$this->newLine();
		$this->comment("Quick Start:");
		$this->line("1. Make sure Redis is running: redis-server");
		$this->line("2. Start queue worker: php artisan queue:work");
		$this->line("3. Go to /admin/mattock/articles/create");
		$this->line("4. Click AI button and create an article");
		
		return 0;
	}
}

