<?php

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

class AIEO_DMM_Reco_Penalty {

    public static function bootstrap() {
        static $done = false;
        if ($done) { return; }
        $done = true;
        add_filter('aieo_reco_filter_candidates', array(__CLASS__, 'filter_candidates'), 10, 2);
    }

    
    public static function filter_candidates($instock_ids, $original_ids = array()) {
        if (empty($instock_ids) || !is_array($instock_ids)) { return $instock_ids; }
        if (!class_exists('AIEO_DMM_Product_Behavior_Metrics')) { return $instock_ids; }

        
        
        if (!apply_filters('aieo_dmm_reco_penalty_enabled', true)) {
            return $instock_ids;
        }

        $drop_threshold = (float) apply_filters('aieo_dmm_reco_drop_threshold', 0.0);

        $scored = array();
        foreach ($instock_ids as $pid) {
            $pid = (int) $pid;
            if ($pid <= 0) { continue; }
            $penalty = AIEO_DMM_Product_Behavior_Metrics::reco_penalty($pid);
            if ($penalty <= $drop_threshold) {
                
                continue;
            }
            $scored[] = array('id' => $pid, 'penalty' => $penalty);
        }

        
        
        
        
        $i = 0;
        foreach ($scored as &$row) { $row['__idx'] = $i++; }
        unset($row);
        usort($scored, static function ($a, $b) {
            if ($a['penalty'] !== $b['penalty']) {
                return $b['penalty'] <=> $a['penalty'];
            }
            return $a['__idx'] <=> $b['__idx'];
        });

        $out = array();
        foreach ($scored as $row) { $out[] = (int) $row['id']; }
        return $out;
    }
}
