<?php

namespace App\Console\Commands;

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

class TestGoogleAiCommand extends Command
{
	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'test:google-ai {prompt=Default test prompt}';
	
	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Test Google AI API with a custom prompt';
	
	/**
	 * Execute the console command.
	 */
	public function handle()
	{
		$prompt = $this->argument('prompt');
		
		$this->info("🧪 Testing Google AI API...");
		$this->info("Prompt: {$prompt}");
		$this->line('');
		
		try {
			$this->info("📋 Configuration Check:");
			$this->line("API Key: " . (config('google.api_key') ? '✅ SET (' . substr(config('google.api_key'), 0, 10) . '...)' : '❌ NOT SET'));
			$this->line("Base URL: " . config('google.base_url'));
			$this->line("Model: " . config('google.image_model'));
			$this->line("Timeout: " . config('google.timeout') . 's');
			$this->line('');
			
			$service = app(GoogleAiService::class);
			
			$this->info("🚀 Calling Google AI API...");
			
			// Test the API call
			$result = $service->generateImage($prompt, 'test-' . uniqid());
			
			if ($result['success']) {
				$this->info("✅ SUCCESS!");
				$this->line("Image ID: " . $result['image_id']);
				$this->line("Image Path: " . $result['image_path']);
				$this->line("Cost: $" . $result['cost'] . " USD");
				$this->line("Model: " . $result['model']);
				$this->line("Aspect Ratio: " . $result['aspect_ratio']);
			} else {
				$this->error("❌ FAILED!");
				$this->error("Error: " . $result['error']);
			}
			
		} catch (\Exception $e) {
			$this->error("❌ EXCEPTION: " . $e->getMessage());
			$this->line("File: " . $e->getFile() . ':' . $e->getLine());
			
			// Log chi tiết để debug
			Log::error('Google AI Test Command Failed', [
				'prompt' => $prompt,
				'error'  => $e->getMessage(),
				'trace'  => $e->getTraceAsString()
			]);
		}
		
		$this->line('');
		$this->info("📝 Check the log file for detailed information:");
		$this->line("tail -f storage/logs/laravel.log");
	}
}