/*
 * 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.paimon.codegen;

import org.apache.paimon.data.BinaryRow;
import org.apache.paimon.data.BinaryRowWriter;
import org.apache.paimon.data.GenericRow;
import org.apache.paimon.data.Timestamp;
import org.apache.paimon.data.serializer.AbstractRowDataSerializer;
import org.apache.paimon.data.serializer.BinaryRowSerializer;
import org.apache.paimon.memory.HeapMemorySegmentPool;
import org.apache.paimon.memory.MemorySegment;
import org.apache.paimon.memory.MemorySegmentPool;
import org.apache.paimon.sort.BinaryInMemorySortBuffer;
import org.apache.paimon.types.DataType;
import org.apache.paimon.types.DataTypes;
import org.apache.paimon.utils.MutableObjectIterator;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.function.IntFunction;

import static org.apache.paimon.codegen.CodeGenUtils.newNormalizedKeyComputer;
import static org.apache.paimon.codegen.CodeGenUtils.newRecordComparator;
import static org.assertj.core.api.Assertions.assertThat;

/**
 * Tests the {@link NormalizedKeyComputer} generated by {@link SortCodeGenerator} for timestamps,
 * covering non-compact precisions (sub-millisecond ordering). Both timestamp roots share the same
 * {@link Timestamp} runtime representation, so every case is run for {@code TIMESTAMP} and {@code
 * TIMESTAMP WITH LOCAL TIME ZONE}.
 */
class NormalizedKeyComputerTest {

    private static final int NON_COMPACT_PRECISION = 9;

    /** The two timestamp roots that share the {@link Timestamp} representation and key layout. */
    private enum TimestampKind {
        WITHOUT_TIME_ZONE(DataTypes::TIMESTAMP),
        WITH_LOCAL_TIME_ZONE(DataTypes::TIMESTAMP_WITH_LOCAL_TIME_ZONE);

        private final IntFunction<DataType> factory;

        TimestampKind(IntFunction<DataType> factory) {
            this.factory = factory;
        }

        DataType of(int precision) {
            return factory.apply(precision);
        }
    }

    @ParameterizedTest
    @EnumSource(TimestampKind.class)
    public void testCompactTimestampKeyMetadata(TimestampKind kind) {
        NormalizedKeyComputer computer = keyComputer(kind.of(3));
        // 1 null-aware byte + 8 bytes millisecond
        assertThat(computer.getNumKeyBytes()).isEqualTo(9);
        assertThat(computer.isKeyFullyDetermines()).isTrue();
    }

    @ParameterizedTest
    @EnumSource(TimestampKind.class)
    public void testNonCompactTimestampKeyMetadata(TimestampKind kind) {
        for (int precision : new int[] {4, 6, 9}) {
            NormalizedKeyComputer computer = keyComputer(kind.of(precision));
            // 1 null-aware byte + 8 bytes millisecond + 4 bytes nanoOfMillisecond
            assertThat(computer.getNumKeyBytes()).as("precision %d", precision).isEqualTo(13);
            assertThat(computer.isKeyFullyDetermines()).as("precision %d", precision).isTrue();
        }
    }

    @ParameterizedTest
    @EnumSource(TimestampKind.class)
    public void testSubMillisecondOrdering(TimestampKind kind) {
        NormalizedKeyComputer computer = keyComputer(kind.of(NON_COMPACT_PRECISION));
        Timestamp lo = Timestamp.fromEpochMillis(1000, 111_111);
        Timestamp hi = Timestamp.fromEpochMillis(1000, 222_222);

        assertThat(normalizedCompare(computer, lo, hi)).isNegative();
        assertThat(normalizedCompare(computer, hi, lo)).isPositive();
        assertThat(normalizedCompare(computer, lo, lo)).isZero();
    }

    @ParameterizedTest
    @EnumSource(TimestampKind.class)
    public void testCompareKeyMatchesCompareToForAllPairs(TimestampKind kind) {
        NormalizedKeyComputer computer = keyComputer(kind.of(NON_COMPACT_PRECISION));
        List<Timestamp> values = timestampSpread();
        for (Timestamp a : values) {
            for (Timestamp b : values) {
                assertThat(sign(normalizedCompare(computer, a, b)))
                        .as("compare(%s, %s)", a, b)
                        .isEqualTo(sign(a.compareTo(b)));
            }
        }
    }

    @ParameterizedTest
    @EnumSource(TimestampKind.class)
    public void testEndToEndSortByNonCompactTimestamp(TimestampKind kind) throws Exception {
        List<Timestamp> values = new ArrayList<>();
        for (Timestamp value : timestampSpread()) {
            // duplicate each value so equal normalized keys are exercised
            values.add(value);
            values.add(value);
        }
        Collections.shuffle(values, new Random(42));

        List<Timestamp> expected = new ArrayList<>(values);
        expected.sort(Timestamp::compareTo);

        assertThat(sortThroughBuffer(values, kind.of(NON_COMPACT_PRECISION), NON_COMPACT_PRECISION))
                .containsExactlyElementsOf(expected);
    }

    @Test
    public void testLocalZonedKeyMatchesTimestampKey() {
        // both roots must emit byte-for-byte identical normalized keys for the same value
        NormalizedKeyComputer tsComputer =
                keyComputer(TimestampKind.WITHOUT_TIME_ZONE.of(NON_COMPACT_PRECISION));
        NormalizedKeyComputer ltzComputer =
                keyComputer(TimestampKind.WITH_LOCAL_TIME_ZONE.of(NON_COMPACT_PRECISION));
        for (Timestamp value : timestampSpread()) {
            assertThat(keyBytes(ltzComputer, value))
                    .as("key bytes for %s", value)
                    .isEqualTo(keyBytes(tsComputer, value));
        }
    }

    private static NormalizedKeyComputer keyComputer(DataType type) {
        return newNormalizedKeyComputer(Collections.singletonList(type), new int[] {0});
    }

    private static byte[] keyBytes(NormalizedKeyComputer computer, Timestamp value) {
        byte[] bytes = new byte[computer.getNumKeyBytes()];
        computer.putKey(GenericRow.of(value), MemorySegment.wrap(bytes), 0);
        return bytes;
    }

    private static int normalizedCompare(NormalizedKeyComputer computer, Timestamp a, Timestamp b) {
        int numKeyBytes = computer.getNumKeyBytes();
        MemorySegment segA = MemorySegment.wrap(new byte[numKeyBytes]);
        MemorySegment segB = MemorySegment.wrap(new byte[numKeyBytes]);
        computer.putKey(GenericRow.of(a), segA, 0);
        computer.putKey(GenericRow.of(b), segB, 0);
        return computer.compareKey(segA, 0, segB, 0);
    }

    private static List<Timestamp> timestampSpread() {
        List<Timestamp> values = new ArrayList<>();
        long[] milliseconds = {-86_400_000L, -1000L, -1L, 0L, 1L, 1000L, 1_600_000_000_000L};
        int[] nanos = {0, 1, 500_000, 999_999};
        for (long millisecond : milliseconds) {
            for (int nano : nanos) {
                values.add(Timestamp.fromEpochMillis(millisecond, nano));
            }
        }
        return values;
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    private static List<Timestamp> sortThroughBuffer(
            List<Timestamp> values, DataType type, int precision) throws Exception {
        List<DataType> fieldTypes = Collections.singletonList(type);
        BinaryRowSerializer serializer = new BinaryRowSerializer(1);
        MemorySegmentPool pool =
                new HeapMemorySegmentPool(1024 * 1024, MemorySegmentPool.DEFAULT_PAGE_SIZE);
        BinaryInMemorySortBuffer buffer =
                BinaryInMemorySortBuffer.createBuffer(
                        newNormalizedKeyComputer(fieldTypes, new int[] {0}),
                        (AbstractRowDataSerializer) serializer,
                        newRecordComparator(fieldTypes, new int[] {0}),
                        pool);

        BinaryRow row = new BinaryRow(1);
        BinaryRowWriter writer = new BinaryRowWriter(row);
        for (Timestamp value : values) {
            writer.reset();
            writer.writeTimestamp(0, value, precision);
            writer.complete();
            assertThat(buffer.write(row)).isTrue();
        }

        List<Timestamp> sorted = new ArrayList<>();
        MutableObjectIterator<BinaryRow> iterator = buffer.sortedIterator();
        BinaryRow reuse = serializer.createInstance();
        BinaryRow next;
        while ((next = iterator.next(reuse)) != null) {
            sorted.add(next.getTimestamp(0, precision));
        }
        buffer.clear();
        return sorted;
    }

    private static int sign(int value) {
        return Integer.compare(value, 0);
    }
}
