# coding=utf-8
# Copyright 2026 The Perch Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Tests for brute search functionality."""

import shutil
import tempfile

import numpy as np
from perch_hoplite.db import brutalism
from perch_hoplite.db import score_functions
from perch_hoplite.db.tests import test_utils

from absl.testing import absltest
from absl.testing import parameterized

EMBEDDING_SIZE = 8


class BrutalismTest(parameterized.TestCase):

  def setUp(self):
    super().setUp()
    self.tempdir = tempfile.mkdtemp()

  def tearDown(self):
    super().tearDown()
    shutil.rmtree(self.tempdir)

  @parameterized.product(
      db_type=(
          'in_mem',
          'sqlite_usearch',
      ),
      sample_size=(
          None,
          0.5,
          128,
      ),
  )
  def test_threaded_brute_search(self, db_type, sample_size):
    rng = np.random.default_rng(42)
    db = test_utils.make_db(self.tempdir, db_type, 1000, rng, EMBEDDING_SIZE)
    query_idx = db.match_window_ids(limit=1)[0]
    query_embedding = db.get_embedding(query_idx)
    results = brutalism.brute_search(
        db,
        query_embedding,
        search_list_size=10,
        score_fn=score_functions.get_score_fn('cos'),
        sample_size=sample_size,
        rng_seed=42,
    )
    got_ids = [r.window_id for r in results]
    if sample_size is None:
      self.assertIn(query_idx, got_ids)
    self.assertLen(results.search_results, 10)

    # Check agreement of threaded brute search with the non-threaded version.
    t_results = brutalism.threaded_brute_search(
        db,
        query_embedding,
        search_list_size=10,
        batch_size=128,
        score_fn=score_functions.get_score_fn('cos'),
        sample_size=sample_size,
        rng_seed=42,
    )
    t_got_scores = [r.sort_score for r in t_results]
    got_scores = [r.sort_score for r in results]
    np.testing.assert_almost_equal(t_got_scores, got_scores)
    t_got_ids = [r.window_id for r in t_results]
    t_got_scores = [r.sort_score for r in t_results]
    num_equal_to_last = np.sum(np.isclose(t_got_scores, t_got_scores[-1]))
    self.assertSetEqual(
        # Embedding IDs need to be checked as a set due to score ties. Also, the
        # last score (and its corresponding embedding IDs) must be ignored due
        # to potential ties with results beyond top-k.
        set(got_ids[:-num_equal_to_last]),
        set(t_got_ids[:-num_equal_to_last]),
    )

  @parameterized.parameters(*test_utils.DB_TYPES)
  def test_get_random_embedding_scores(self, db_type):
    rng = np.random.default_rng(42)
    db = test_utils.make_db(self.tempdir, db_type, 1000, rng, EMBEDDING_SIZE)
    query_idx = db.match_window_ids(limit=1)[0]
    query_embedding = db.get_embedding(query_idx)
    scores = brutalism.get_random_embedding_scores(
        db,
        query_embedding,
        score_fn=score_functions.get_score_fn('cos'),
        sample_size=64,
        rng_seed=42,
    )
    self.assertEqual(scores.shape, (64,))


if __name__ == '__main__':
  absltest.main()
