<?php

namespace App\Services;

use Illuminate\Support\Facades\Log;

class ImageConfigService
{
	/**
	 * Calculate optimal number of images for article content
	 */
	public function calculateImageCount(string $title, string $description): int
	{
		$maxImages = config('google.cost_settings.max_images_per_article', 5);
		$minImages = config('google.cost_settings.min_images_per_article', 2);
		$scalingEnabled = config('google.content_scaling.enabled', true);
		
		if (!$scalingEnabled) {
			Log::info("Content scaling disabled, using max images", ['count' => $maxImages]);
			return $maxImages;
		}
		
		// Estimate content length from title and description
		$estimatedWordCount = $this->estimateContentWordCount($title, $description);
		
		// Calculate images based on content scaling
		$wordsPerImage = config('google.content_scaling.words_per_image', 500);
		$calculatedImages = max(1, round($estimatedWordCount / $wordsPerImage));
		
		// Apply min/max constraints
		$optimalCount = max($minImages, min($maxImages, $calculatedImages));
		
		Log::info("Dynamic image count calculated", [
			'title_length'       => strlen($title),
			'description_length' => strlen($description),
			'estimated_words'    => $estimatedWordCount,
			'words_per_image'    => $wordsPerImage,
			'calculated_images'  => $calculatedImages,
			'optimal_count'      => $optimalCount,
			'min_images'         => $minImages,
			'max_images'         => $maxImages
		]);
		
		return $optimalCount;
	}
	
	/**
	 * Estimate final content word count based on title and description
	 */
	private function estimateContentWordCount(string $title, string $description): int
	{
		// Base word count from title and description
		$titleWords = str_word_count($title);
		$descriptionWords = str_word_count($description);
		
		// Estimation multipliers based on typical article expansion
		$titleMultiplier = 50;  // Title usually expands to ~50x words in full article
		$descriptionMultiplier = 8; // Description usually expands to ~8x words
		
		$estimatedWords = ($titleWords * $titleMultiplier) + ($descriptionWords * $descriptionMultiplier);
		
		// Apply reasonable bounds
		$maxContentLength = config('google.content_scaling.max_content_length_for_scaling', 5000);
		$estimatedWords = min($estimatedWords, $maxContentLength);
		
		// Ensure minimum realistic content length
		$estimatedWords = max($estimatedWords, 800); // Minimum 800 words for any article
		
		return $estimatedWords;
	}
	
	/**
	 * Get image configuration summary for prompts
	 */
	public function getImageConfigForPrompt(string $title, string $description): array
	{
		$imageCount = $this->calculateImageCount($title, $description);
		$maxImages = config('google.cost_settings.max_images_per_article', 5);
		$minImages = config('google.cost_settings.min_images_per_article', 2);
		
		return [
			'optimal_image_count' => $imageCount,
			'min_images'          => $minImages,
			'max_images'          => $maxImages,
			'scaling_enabled'     => config('google.content_scaling.enabled', true),
			'prompt_guidance'     => $this->generatePromptGuidance($imageCount)
		];
	}
	
	/**
	 * Generate guidance text for Claude AI prompts
	 */
	private function generatePromptGuidance(int $imageCount): string
	{
		if ($imageCount <= 2) {
			return "Focus on 1-2 key conceptual images that best represent the main topics.";
		} elseif ($imageCount <= 3) {
			return "Include 2-3 strategic images: one main concept image and 1-2 supporting detail images.";
		} elseif ($imageCount <= 5) {
			return "Create {$imageCount} well-distributed images: introduction image, section concept images, and summary/conclusion image.";
		} else {
			return "Create {$imageCount} comprehensive images covering introduction, main concepts, detailed examples, processes, and conclusion.";
		}
	}
	
	/**
	 * Get cost estimation for calculated image count
	 */
	public function getCostEstimation(string $title, string $description): array
	{
		$imageCount = $this->calculateImageCount($title, $description);
		$aspectRatio = config('google.image_settings.image_config.aspectRatio');
		
		// Cost per image based on aspect ratio
		$costMapping = [
			'ASPECT_RATIO_1_1'  => 0.040,
			'ASPECT_RATIO_16_9' => 0.065,
			'ASPECT_RATIO_9_16' => 0.065,
			'ASPECT_RATIO_4_3'  => 0.055,
			'ASPECT_RATIO_3_4'  => 0.055,
		];
		
		$costPerImage = $costMapping[$aspectRatio] ?? 0.040;
		$totalCost = $imageCount * $costPerImage;
		
		return [
			'image_count'    => $imageCount,
			'cost_per_image' => $costPerImage,
			'total_cost'     => round($totalCost, 3),
			'aspect_ratio'   => $aspectRatio,
			'currency'       => 'USD'
		];
	}
}