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

class AIIO_Scanner {

    public static function scan($args = []) {
        @set_time_limit(120); // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged -- Extends time limit for long-running bulk/scan jobs.

        $settings = aiio_get_settings();
        $threshold = max(1, intval($args['threshold_kb'] ?? ($settings['size_threshold_kb'] ?? 200))) * 1024;

        $ids = array_merge(self::get_image_ids(), self::get_video_ids());
        $ids = array_values(array_unique(array_filter(array_map('intval', $ids))));
        $items = [];
        $stats = [
            'total_images' => count(self::get_image_ids()),
            'total_videos' => count(self::get_video_ids()),
            'over_threshold' => 0,
            'optimizable' => 0,
            'skipped' => 0,
            'total_bytes' => 0,
            'threshold_kb' => intval($threshold / 1024),
        ];

        foreach ($ids as $id) {
            $file = get_attached_file($id);
            if (!$file || !is_file($file)) {
                $stats['skipped']++;
                continue;
            }

            $patterns = AIIO_Usage::parse_exclude_patterns($settings['exclude_filename_patterns'] ?? '');
            if (AIIO_Usage::matches_exclude_pattern(basename($file), $patterns)) {
                $stats['skipped']++;
                continue;
            }

            $size = filesize($file);
            $stats['total_bytes'] += $size;
            $mime = get_post_mime_type($id);
            $reason = '';
            $optimizable = AIIO_Media_Apply::is_optimizable($id, $reason);

            if ($optimizable) {
                $stats['optimizable']++;
            } else {
                $stats['skipped']++;
            }

            if ($size < $threshold) {
                continue;
            }

            $stats['over_threshold']++;
            $items[] = [
                'id' => $id,
                'filename' => basename($file),
                'mime' => $mime,
                'media_type' => strpos((string) $mime, 'video/') === 0 ? 'video' : 'image',
                'bytes' => $size,
                'size_label' => AIIO_Optimizer::format_bytes($size),
                'url' => wp_get_attachment_url($id),
                'thumb' => wp_get_attachment_image_url($id, 'thumbnail'),
                'optimizable' => $optimizable,
                'skip_reason' => $reason,
                'has_backup' => class_exists('AIIO_Backup') ? AIIO_Backup::has_backup($id) : false,
                'last_optimized' => get_post_meta($id, '_aiio_last_optimized', true),
            ];
        }

        usort($items, function ($a, $b) {
            return intval($b['bytes']) <=> intval($a['bytes']);
        });

        $payload = [
            'stats' => $stats,
            'items' => $items,
            'time' => time(),
        ];

        set_transient('aiio_last_scan', $payload, HOUR_IN_SECONDS);
        return $payload;
    }

    public static function get_last_scan() {
        $scan = get_transient('aiio_last_scan');
        return is_array($scan) ? $scan : ['stats' => [], 'items' => [], 'time' => 0];
    }

    public static function get_image_ids() {
        $settings = aiio_get_settings();
        if (!empty($settings['only_etch_images']) && AIIO_Etch::is_active()) {
            return AIIO_Etch::get_used_attachment_ids();
        }
        if (!empty($settings['only_used_images'])) {
            return AIIO_Usage::get_used_attachment_ids();
        }
        $q = new WP_Query([
            'post_type' => 'attachment',
            'post_status' => 'inherit',
            'post_mime_type' => ['image/jpeg', 'image/png'],
            'posts_per_page' => -1,
            'fields' => 'ids',
            'no_found_rows' => true,
            'orderby' => 'ID',
            'order' => 'DESC',
        ]);
        return array_map('intval', $q->posts);
    }

    public static function get_video_ids() {
        if (empty(aiio_get_settings()['video_av1_enabled']) || !AIIO_Video_Optimizer::find_ffmpeg()) {
            return [];
        }
        $q = new WP_Query([
            'post_type'      => 'attachment',
            'post_status'    => 'inherit',
            'post_mime_type' => AIIO_Video_Optimizer::VIDEO_MIMES,
            'posts_per_page' => -1,
            'fields'         => 'ids',
            'no_found_rows'  => true,
            'orderby'        => 'ID',
            'order'          => 'DESC',
        ]);
        return array_map('intval', $q->posts);
    }
}
