/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */
package org.apache.lucene.search;

import java.io.IOException;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.KnnByteVectorField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.QueryTimeout;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.VectorSimilarityFunction;
import org.apache.lucene.search.knn.KnnCollectorManager;
import org.apache.lucene.search.knn.KnnSearchStrategy;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.TestVectorUtil;

public class TestKnnByteVectorQuery extends BaseKnnVectorQueryTestCase {
  @Override
  AbstractKnnVectorQuery getKnnVectorQuery(String field, float[] query, int k, Query queryFilter) {
    return new KnnByteVectorQuery(field, floatToBytes(query), k, queryFilter);
  }

  @Override
  AbstractKnnVectorQuery getThrowingKnnVectorQuery(String field, float[] vec, int k, Query query) {
    return new ThrowingKnnVectorQuery(field, floatToBytes(vec), k, query);
  }

  @Override
  AbstractKnnVectorQuery getCappedResultsThrowingKnnVectorQuery(
      String field, float[] vec, int k, Query query, int maxResults) {
    return new CappedResultsThrowingKnnVectorQuery(field, floatToBytes(vec), k, query, maxResults);
  }

  @Override
  float[] randomVector(int dim) {
    byte[] b = TestVectorUtil.randomVectorBytes(dim);
    float[] v = new float[b.length];
    int vi = 0;
    for (int i = 0; i < v.length; i++) {
      v[vi++] = b[i];
    }
    return v;
  }

  @Override
  Field getKnnVectorField(
      String name, float[] vector, VectorSimilarityFunction similarityFunction) {
    return new KnnByteVectorField(name, floatToBytes(vector), similarityFunction);
  }

  @Override
  Field getKnnVectorField(String name, float[] vector) {
    return new KnnByteVectorField(name, floatToBytes(vector), VectorSimilarityFunction.EUCLIDEAN);
  }

  static byte[] floatToBytes(float[] query) {
    byte[] bytes = new byte[query.length];
    for (int i = 0; i < query.length; i++) {
      assert query[i] <= Byte.MAX_VALUE && query[i] >= Byte.MIN_VALUE && (query[i] % 1) == 0
          : "float value cannot be converted to byte; provided: " + query[i];
      bytes[i] = (byte) query[i];
    }
    return bytes;
  }

  public void testToString() throws IOException {
    try (Directory indexStore =
            getIndexStore("field", new float[] {0, 1}, new float[] {1, 2}, new float[] {0, 0});
        IndexReader reader = DirectoryReader.open(indexStore)) {
      AbstractKnnVectorQuery query = getKnnVectorQuery("field", new float[] {0, 1}, 10);
      assertEquals("KnnByteVectorQuery:field[0,...][10]", query.toString("ignored"));

      assertDocScoreQueryToString(query.rewrite(newSearcher(reader)));

      // test with filter
      Query filter = new TermQuery(new Term("id", "text"));
      query = getKnnVectorQuery("field", new float[] {0, 1}, 10, filter);
      assertEquals("KnnByteVectorQuery:field[0,...][10][id:text]", query.toString("ignored"));
    }
  }

  public void testGetTarget() {
    byte[] queryVectorBytes = floatToBytes(new float[] {0, 1});
    KnnByteVectorQuery q1 = new KnnByteVectorQuery("f1", queryVectorBytes, 10);
    assertArrayEquals(queryVectorBytes, q1.getTargetCopy());
    assertNotSame(queryVectorBytes, q1.getTargetCopy());
  }

  public void testVectorEncodingMismatch() throws IOException {
    try (Directory indexStore =
            getIndexStore("field", new float[] {0, 1}, new float[] {1, 2}, new float[] {0, 0});
        IndexReader reader = DirectoryReader.open(indexStore)) {
      Query filter = null;
      if (random().nextBoolean()) {
        filter = MatchAllDocsQuery.INSTANCE;
      }
      AbstractKnnVectorQuery query =
          new KnnFloatVectorQuery("field", new float[] {0, 1}, 10, filter);
      IndexSearcher searcher = newSearcher(reader);
      expectThrows(IllegalStateException.class, () -> searcher.search(query, 10));
    }
  }

  static class ThrowingKnnVectorQuery extends KnnByteVectorQuery {

    public ThrowingKnnVectorQuery(String field, byte[] target, int k, Query filter) {
      super(field, target, k, filter, new KnnSearchStrategy.Hnsw(0));
    }

    @Override
    protected TopDocs exactSearch(
        LeafReaderContext context, DocIdSetIterator acceptIterator, QueryTimeout queryTimeout) {
      throw new UnsupportedOperationException("exact search is not supported");
    }

    @Override
    public String toString(String field) {
      return null;
    }
  }

  static class CappedResultsThrowingKnnVectorQuery extends ThrowingKnnVectorQuery {

    private final int maxResults;

    public CappedResultsThrowingKnnVectorQuery(
        String field, byte[] target, int k, Query filter, int maxResults) {
      super(field, target, k, filter);
      this.maxResults = maxResults;
    }

    @Override
    protected TopDocs approximateSearch(
        LeafReaderContext context,
        AcceptDocs acceptDocs,
        int visitedLimit,
        KnnCollectorManager knnCollectorManager)
        throws IOException {
      TopDocs topDocs =
          super.approximateSearch(context, acceptDocs, Integer.MAX_VALUE, knnCollectorManager);
      long results = Math.min(topDocs.totalHits.value(), maxResults);
      ScoreDoc[] scoreDocs = new ScoreDoc[(int) results];
      System.arraycopy(topDocs.scoreDocs, 0, scoreDocs, 0, scoreDocs.length);

      return new TopDocs(new TotalHits(results, TotalHits.Relation.EQUAL_TO), scoreDocs);
    }
  }
}
