<?php

namespace App\Services\Files;

use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Gd\Driver as GdDriver;
use Intervention\Image\Drivers\Imagick\Driver as ImagickDriver;
use RuntimeException;

class ThumbnailService
{
    protected ImageManager $manager;

    public function __construct(
        protected FileStorageService $storageService
    ) {
        // Use Imagick if available, otherwise GD
        if (extension_loaded('imagick')) {
            $this->manager = new ImageManager(new ImagickDriver());
        } else {
            $this->manager = new ImageManager(new GdDriver());
        }
    }

    /**
     * Generate a thumbnail for an image file.
     */
    public function generate(
        string $sourcePath,
        string $fileUuid,
        string $sizeName = 'medium',
        int $width = 300,
        int $height = 300
    ): ?string {
        // Check if source file exists
        if (! file_exists($sourcePath)) {
            throw new RuntimeException("Source file not found: {$sourcePath}");
        }

        try {
            // Read the image
            $image = $this->manager->read($sourcePath);

            // Resize maintaining aspect ratio
            $image->cover($width, $height);

            // Encode as JPEG
            $quality = config('file_upload.thumbnails.quality', 85);
            $encoded = $image->toJpeg($quality);

            // Generate thumbnail path
            $thumbnailPath = $this->generatePath($fileUuid, $sizeName);

            // Store in S3
            $this->storageService->storeContent(
                $encoded->toString(),
                $thumbnailPath,
                'public'
            );

            return $thumbnailPath;
        } catch (\Exception $e) {
            throw new RuntimeException("Failed to generate thumbnail: {$e->getMessage()}");
        }
    }

    /**
     * Generate thumbnail path for a file.
     */
    public function generatePath(string $fileUuid, string $sizeName = 'medium'): string
    {
        $basePath = config('file_upload.paths.thumbnails', 'thumbnails/{size}');

        $path = str_replace('{size}', $sizeName, $basePath);

        return "{$path}/{$fileUuid}.jpg";
    }

    /**
     * Check if a MIME type supports thumbnail generation.
     */
    public function supportsThumbnail(string $mimeType): bool
    {
        return in_array($mimeType, config('file_upload.thumbnails.supported_mime_types', []));
    }

    /**
     * Generate all configured thumbnail sizes for a file.
     */
    public function generateAllSizes(string $sourcePath, string $fileUuid): array
    {
        $sizes = config('file_upload.thumbnails.sizes', []);
        $paths = [];

        foreach ($sizes as $sizeName => $dimensions) {
            $paths[$sizeName] = $this->generate(
                $sourcePath,
                $fileUuid,
                $sizeName,
                $dimensions['width'],
                $dimensions['height']
            );
        }

        return $paths;
    }
}
