<?php

namespace App\Console\Commands;

use App\Jobs\GenerateImagenBatch;
use Illuminate\Bus\Batch;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Log;

class TestImagenBatch extends Command
{
	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'test:imagen-batch {--samples=1 : Number of images per prompt}';
	
	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Test Google Imagen API with batch processing using 5 predefined prompts';
	
	/**
	 * Test prompts for image generation
	 *
	 * @var array
	 */
	private array $testPrompts = [
		[
			'id'  => 'img001',
			'alt' => 'Modern business management transformation dashboard showing real-time analytics, predictive modeling, and AI-driven decision support systems interface',
			'src' => '/storage/uploads/placeholder.png'
		],
		[
			'id'  => 'img002',
			'alt' => 'Futuristic smart city skyline with renewable energy infrastructure, autonomous vehicles, and green architecture integrated with advanced technology',
			'src' => '/storage/uploads/placeholder.png'
		],
		[
			'id'  => 'img003',
			'alt' => 'Digital workspace collaboration platform featuring virtual reality meetings, holographic displays, and seamless remote team interaction tools',
			'src' => '/storage/uploads/placeholder.png'
		],
		[
			'id'  => 'img004',
			'alt' => 'Sustainable agriculture ecosystem with drone monitoring, precision farming technology, IoT sensors, and automated crop management systems',
			'src' => '/storage/uploads/placeholder.png'
		],
		[
			'id'  => 'img005',
			'alt' => 'Advanced medical research laboratory with AI-powered diagnostic equipment, robotic surgery systems, and personalized treatment visualization',
			'src' => '/storage/uploads/placeholder.png'
		],
	];
	
	/**
	 * Execute the console command.
	 */
	public function handle(): int
	{
		$batchCustomId = 'test_' . uniqid() . '_' . now()->format('YmdHis');
		
		$this->info("🚀 Starting Imagen batch test with 1 samples per prompt");
		$this->info("📋 Batch ID: $batchCustomId");
		$this->info("📊 Total prompts: " . count($this->testPrompts));
		$this->info("🖼️  Total images to generate: " . (count($this->testPrompts)));
		
		$this->newLine();
		
		Log::info("Starting Imagen batch test", [
			'batch_id'              => $batchCustomId,
			'prompts_count'         => count($this->testPrompts),
			'total_expected_images' => count($this->testPrompts)
		]);
		
		$startTime = microtime(true);
		$this->info("⏰ Start time: " . now()->format('Y-m-d H:i:s'));
		
		// Create jobs array for batch processing
		$jobs = [];
		foreach ($this->testPrompts as $index => $image) {
			$jobs[] = new GenerateImagenBatch($image['id'], $this->getValidLengthPrompts($image['alt']));
			$this->line("✅ Job $index prepared: " . substr($image['alt'], 0, 60) . "...");
		}
		
		// Dispatch all jobs as a batch
		$batch = Bus::batch($jobs)
			->name("Imagen Generation Test - $batchCustomId")
			->then(function (Batch $batch) {
				Log::info("All Imagen generation jobs completed successfully", [
					'batch_id'       => $batch->id,
					'total_jobs'     => $batch->totalJobs,
					'processed_jobs' => $batch->processedJobs(),
					'failed_jobs'    => $batch->failedJobs
				]);
			})
			->catch(function (Batch $batch, \Throwable $e) {
				Log::error("Imagen generation batch failed", [
					'batch_id'    => $batch->id,
					'error'       => $e->getMessage(),
					'failed_jobs' => $batch->failedJobs
				]);
			})
			->finally(function (Batch $batch) {
				Log::info("Imagen generation batch finished", [
					'batch_id'       => $batch->id,
					'total_jobs'     => $batch->totalJobs,
					'processed_jobs' => $batch->processedJobs(),
					'failed_jobs'    => $batch->failedJobs,
					'finished_at'    => now()->toISOString()
				]);
			})
			->dispatch();
		
		$dispatchTime = microtime(true);
		$dispatchDuration = round($dispatchTime - $startTime, 2);
		
		$this->newLine();
		$this->info("🎯 Batch with " . count($this->testPrompts) . " jobs dispatched successfully in $dispatchDuration seconds");
		$this->info("🆔 Laravel Batch ID: " . $batch->id);
		$this->info("🔄 Jobs are now running in parallel via queue workers");
		$this->info("📝 Monitor progress with: tail -f storage/logs/laravel.log | grep '$batchCustomId'");
		$this->info("🔍 Or check batch status with: php artisan queue:batches");
		
		$this->newLine();
		$this->comment("💡 Performance Test Instructions:");
		$this->comment("1. Monitor the logs to see job completion times");
		$this->comment("2. Check storage/app/public/images/generated/ for saved images");
		$this->comment("3. Use 'php artisan queue:batches' to monitor batch progress");
		$this->comment("4. Watch for any API rate limiting or errors");
		
		Log::info("Imagen batch test dispatched", [
			'batch_id'          => $batchCustomId,
			'laravel_batch_id'  => $batch->id,
			'jobs_count'        => count($this->testPrompts),
			'dispatch_duration' => $dispatchDuration
		]);
		
		return Command::SUCCESS;
	}
	
	private function getValidLengthPrompts($prompts, $length = 350): string
	{
		return implode(' ', array_slice(explode(' ', $prompts), 0, $length));
	}
}
