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

/**
 * Score Booster — bulk regenerate schema for posts below target score or missing schema.
 */
class AISB_Score_Booster {

    public static function posts_needing_boost($max_score = 80, $limit = 300) {
        $post_types = AISB_CPT_Registry::get_enabled_post_types();
        $ids = [];

        $q = new WP_Query([
            'post_type'      => $post_types,
            'post_status'    => 'publish',
            'posts_per_page' => $limit,
            'fields'         => 'ids',
            'no_found_rows'  => true,
            'orderby'        => 'modified',
            'order'          => 'DESC',
        ]);

        foreach ($q->posts as $post_id) {
            $schema = AISB_Schema::get_json($post_id);
            if (!$schema) {
                $ids[] = (int) $post_id;
                continue;
            }
            $result = AISB_Rich_Results_Score::compute($schema);
            if ((int) ($result['score'] ?? 0) < $max_score) {
                $ids[] = (int) $post_id;
            }
        }

        return $ids;
    }

    public static function create_boost_job($max_score = 80) {
        $ids = self::posts_needing_boost($max_score);
        if (empty($ids)) {
            return new WP_Error('aisb_boost_none', __('No posts need a schema boost.', 'pewit-ai-schema-builder'));
        }
        return AISB_Queue::create_job($ids, 'score_boost');
    }
}
