<?php

namespace App\Services;

class ImageIdGeneratorService
{
    /**
     * Generate unique image ID using MD5 hash based on content and timestamp
     */
    public function generateUniqueImageId(string $prompt, string $prefix = 'img'): string
    {
        // Create unique string from prompt + timestamp + random
        $uniqueString = $prompt . microtime() . mt_rand(1000, 9999);
        
        // Generate MD5 hash and take first 8 characters
        $hash = substr(md5($uniqueString), 0, 8);
        
        return $prefix . '-' . $hash;
    }
    
    /**
     * Generate featured image ID - always unique per article
     */
    public function generateFeaturedImageId(string $title, int $conversationId): string
    {
        $uniqueString = 'featured-' . $title . '-' . $conversationId . '-' . microtime();
        $hash = substr(md5($uniqueString), 0, 8);
        
        return 'img-featured-' . $hash;
    }
    
    /**
     * Extract image ID from img tag (for frontend processing)
     */
    public function extractImageIdFromTag(string $imgTag): ?string
    {
        // Extract id attribute from img tag
        if (preg_match('/id=["\']([^"\']+)["\']/', $imgTag, $matches)) {
            return $matches[1];
        }
        
        return null;
    }
    
    /**
     * Generate batch of unique IDs for multiple images
     */
    public function generateBatchIds(array $prompts, string $prefix = 'img'): array
    {
        $ids = [];
        
        foreach ($prompts as $index => $prompt) {
            $ids[] = [
                'prompt' => $prompt,
                'id' => $this->generateUniqueImageId($prompt, $prefix),
                'index' => $index
            ];
        }
        
        return $ids;
    }
}