<?php
if (!defined('ABSPATH')) exit;

/**
 * Routes optimize apply/preview to image or video handlers.
 */
class AIIO_Media_Apply {

    public static function preview($attachment_id) {
        if (AIIO_Video_Optimizer::is_video_attachment($attachment_id)) {
            return self::preview_video($attachment_id);
        }
        return AIIO_Optimizer::preview($attachment_id);
    }

    public static function apply($attachment_id, $args = []) {
        if (AIIO_Video_Optimizer::is_video_attachment($attachment_id)) {
            return AIIO_Video_Optimizer::apply($attachment_id, $args);
        }
        return AIIO_Optimizer::apply($attachment_id, $args);
    }

    public static function is_optimizable($attachment_id, &$reason = '') {
        if (AIIO_Video_Optimizer::is_video_attachment($attachment_id)) {
            return AIIO_Video_Optimizer::is_optimizable($attachment_id, $reason);
        }
        return AIIO_Optimizer::is_optimizable($attachment_id, $reason);
    }

    private static function preview_video($attachment_id) {
        if (!AIIO_Video_Optimizer::is_optimizable($attachment_id, $reason)) {
            return new WP_Error('aiio_video_not_optimizable', $reason);
        }
        $file = get_attached_file($attachment_id);
        $before = filesize($file);
        $sidecar = AIIO_Video_Optimizer::sidecar_path($file);
        $existing = is_file($sidecar) ? filesize($sidecar) : 0;

        return [
            'attachment_id' => (int) $attachment_id,
            'type'          => 'video',
            'before_bytes'  => $before,
            'after_bytes'   => $existing ?: $before,
            'saved_bytes'   => $existing ? max(0, $before - $existing) : 0,
            'saved_percent' => ($existing && $before > 0) ? round((max(0, $before - $existing) / $before) * 100, 1) : 0,
            'mime'          => get_post_mime_type($attachment_id),
            'filename'      => basename($file),
            'can_av1'       => true,
            'av1_webm'      => $existing ? ['path' => $sidecar, 'bytes' => $existing] : null,
            'note'          => __('Creates an AV1 WebM sidecar via ffmpeg. Original video is kept.', 'pewit-ai-image-optimizer'),
        ];
    }
}
