<?php
namespace Mamba\Modules\Media\Services;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

final class MediaInvalidation {
    
    public function register(): void {
        // Hook into attachment uploads and updates
        add_action('wp_generate_attachment_metadata', [$this, 'handleAttachmentUpdate'], 20, 2);
        add_action('edit_attachment', [$this, 'handleAttachmentEdit']);
        add_action('delete_attachment', [$this, 'handleAttachmentDelete']);
        add_action('wp_update_attachment_metadata', [$this, 'handleMetadataUpdate'], 10, 2);
        
        // Hook into WebP and compression updates
        add_action('updated_post_meta', [$this, 'handleOptimizationUpdate'], 10, 4);
    }
    
    /**
     * Handle new attachment upload or regeneration
     */
    public function handleAttachmentUpdate(array $metadata, int $attachmentId): array {
        if (!$this->isValidImage($attachmentId)) {
            return $metadata;
        }
        
        // Auto-process WebP and compression if enabled
        $this->triggerAutoOptimization($attachmentId, $metadata);
        
        return $metadata;
    }
    
    /**
     * Handle attachment edit (file replacement)
     */
    public function handleAttachmentEdit(int $attachmentId): void {
        if (!$this->isValidImage($attachmentId)) {
            return;
        }
        
        // Auto-process WebP and compression if enabled
        $metadata = wp_get_attachment_metadata($attachmentId);
        if ($metadata) {
            $this->triggerAutoOptimization($attachmentId, $metadata);
        }
    }
    
    /**
     * Handle attachment deletion
     */
    public function handleAttachmentDelete(int $attachmentId): void {
        if (!$this->isValidImage($attachmentId)) {
            return;
        }
        
        // Cleanup is handled by WordPress automatically
    }
    
    /**
     * Handle metadata updates (sizes regenerated, etc.)
     * Note: wp_update_attachment_metadata filter passes ($metadata, $attachmentId)
     */
    public function handleMetadataUpdate(array $metadata, int $attachmentId): array {
        if (!$this->isValidImage($attachmentId)) {
            return $metadata;
        }
        
        // Auto-process WebP and compression if enabled
        $this->triggerAutoOptimization($attachmentId, $metadata);
        
        return $metadata;
    }
    
    /**
     * Handle optimization metadata updates (WebP/AVIF/compression completed)
     */
    public function handleOptimizationUpdate(int $metaId, int $postId, string $metaKey, $metaValue): void {
        // Only handle our optimization metadata
        if (!in_array($metaKey, ['_mamba_webp_conversion', '_mamba_avif_conversion', '_mamba_compression_quality'])) {
            return;
        }
        
        if (!$this->isValidImage($postId)) {
            return;
        }
        
        // Log successful optimization
        if (defined('WP_DEBUG') && WP_DEBUG) {
            $type = 'compression';
            if ($metaKey === '_mamba_webp_conversion') $type = 'webp';
            if ($metaKey === '_mamba_avif_conversion') $type = 'avif';

            $logData = [
                'attachment_id' => $postId,
                'optimization_type' => $type,
                'action' => 'optimization_completed'
            ];
            error_log('Mamba Media Optimization: ' . wp_json_encode($logData));
        }
    }
    
    /**
     * Check if attachment is a valid image
     */
    private function isValidImage(int $attachmentId): bool {
        $mimeType = get_post_mime_type($attachmentId);
        return in_array($mimeType, ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/avif'], true);
    }
    
    /**
     * Trigger automatic optimization for new uploads
     */
    private function triggerAutoOptimization(int $attachmentId, array $metadata): void {
        // Only optimize JPEG/PNG images
        $mimeType = get_post_mime_type($attachmentId);
        if (!in_array($mimeType, ['image/jpeg', 'image/png'], true)) {
            return;
        }
        
        // Trigger compression if enabled
        if (get_option('mamba_enable_image_compression', 0)) {
            $compressor = new ImageCompressor();
            $quality = (int) get_option('mamba_compression_quality', 85);
            
            foreach ($metadata['sizes'] ?? [] as $sizeName => $sizeData) {
                $compressor->processImageSize($attachmentId, $sizeName, $sizeData, $quality);
            }
            
            if (get_option('mamba_compress_full_size', 0)) {
                $compressor->processImageSize($attachmentId, 'full', $metadata, $quality);
            }
        }

        $enableWebP = get_option('mamba_enable_webp_conversion', 0);
        $enableAvif = get_option('mamba_enable_avif_conversion', 0);

        if ($enableWebP || $enableAvif) {
            // Ensure .htaccess rules are in place for Next-Gen support
            $htaccessManager = new HtaccessManager();
            $serverInfo = $htaccessManager->getServerInfo();
            if ($htaccessManager->isSupported() && $serverInfo['is_apache_compatible'] && !$htaccessManager->hasNextGenRules()) {
                $htaccessManager->addNextGenRules();
            }
        }
        
        // Trigger WebP conversion if enabled and supported
        if ($enableWebP && 
            function_exists('wp_image_editor_supports') &&
            wp_image_editor_supports(['mime_type' => 'image/webp'])) {
            
            $webpConverter = new WebPConverter();
            $quality = (int) get_option('mamba_webp_quality', 85);
            
            foreach ($metadata['sizes'] ?? [] as $sizeName => $sizeData) {
                $webpConverter->processImageSize($attachmentId, $sizeName, $sizeData, $quality);
            }
            
            if (get_option('mamba_convert_full_size', 0)) {
                $webpConverter->processImageSize($attachmentId, 'full', $metadata, $quality);
            }
        }

        // Trigger AVIF conversion if enabled and supported
        if ($enableAvif && 
            function_exists('wp_image_editor_supports') &&
            wp_image_editor_supports(['mime_type' => 'image/avif'])) {
            
            $avifConverter = new AvifConverter();
            $quality = (int) get_option('mamba_avif_quality', 65);
            
            foreach ($metadata['sizes'] ?? [] as $sizeName => $sizeData) {
                $avifConverter->processImageSize($attachmentId, $sizeName, $sizeData, $quality);
            }
            
            if (get_option('mamba_convert_full_size_avif', 0)) {
                $avifConverter->processImageSize($attachmentId, 'full', $metadata, $quality);
            }
        }
    }
}