<?php

declare(strict_types=1);

namespace Numinix\SeekmodoSdk\Search;

/**
 * Applies lightweight CTR boosts from local click telemetry.
 */
final class LocalClickBias
{
    /** @var array<string, array<int, int>> */
    private array $counts = [];

    /**
     * @param iterable<array{keyword: string, object_id: int}> $events
     */
    public function load(iterable $events): void
    {
        $this->counts = [];
        foreach ($events as $event) {
            $kw = mb_strtolower(trim((string) ($event['keyword'] ?? '')));
            $id = (int) ($event['object_id'] ?? 0);
            if ($kw === '' || $id <= 0) {
                continue;
            }
            if (!isset($this->counts[$kw][$id])) {
                $this->counts[$kw][$id] = 0;
            }
            $this->counts[$kw][$id]++;
        }
    }

    /**
     * @param list<int> $ids
     * @return list<int>
     */
    public function rerank(string $q, array $ids): array
    {
        $kw = mb_strtolower(trim($q));
        if ($kw === '' || $ids === []) {
            return $ids;
        }
        $bias = $this->counts[$kw] ?? [];
        if ($bias === []) {
            return $ids;
        }

        $scored = [];
        foreach ($ids as $id) {
            $n = (int) $id;
            $scored[] = ['id' => $n, 'score' => $bias[$n] ?? 0];
        }
        usort($scored, static fn (array $a, array $b): int => $b['score'] <=> $a['score']);

        return array_values(array_map(static fn (array $row): int => (int) $row['id'], $scored));
    }
}
