/*
 * 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;

import org.apache.paimon.options.MemorySize;
import org.apache.paimon.options.Options;

import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

/** Tests for {@link org.apache.paimon.CoreOptions}. */
public class CoreOptionsTest {

    @Test
    public void testDefaultStartupMode() {
        Options conf = new Options();
        assertThat(conf.get(CoreOptions.SCAN_MODE)).isEqualTo(CoreOptions.StartupMode.DEFAULT);
        assertThat(new CoreOptions(conf).startupMode())
                .isEqualTo(CoreOptions.StartupMode.LATEST_FULL);

        conf = new Options();
        conf.set(CoreOptions.SCAN_TIMESTAMP_MILLIS, System.currentTimeMillis());
        assertThat(new CoreOptions(conf).startupMode())
                .isEqualTo(CoreOptions.StartupMode.FROM_TIMESTAMP);

        conf = new Options();
        conf.set(CoreOptions.SCAN_TIMESTAMP, "2023-12-06 12:12:12");
        assertThat(new CoreOptions(conf).startupMode())
                .isEqualTo(CoreOptions.StartupMode.FROM_TIMESTAMP);
    }

    @Test
    public void testStartupModeCompatibility() {
        Options conf = new Options();
        conf.setString("log.scan", "latest");
        assertThat(new CoreOptions(conf).startupMode()).isEqualTo(CoreOptions.StartupMode.LATEST);

        conf = new Options();
        conf.setString("log.scan.timestamp-millis", String.valueOf(System.currentTimeMillis()));
        assertThat(new CoreOptions(conf).startupMode())
                .isEqualTo(CoreOptions.StartupMode.FROM_TIMESTAMP);
    }

    @Test
    public void testDeprecatedStartupMode() {
        Options conf = new Options();
        conf.set(CoreOptions.SCAN_MODE, CoreOptions.StartupMode.FULL);
        assertThat(new CoreOptions(conf).startupMode())
                .isEqualTo(CoreOptions.StartupMode.LATEST_FULL);
    }

    @Test
    public void testPrepareCommitWaitCompaction() {
        Options conf = new Options();
        CoreOptions options = new CoreOptions(conf);

        assertThat(options.prepareCommitWaitCompaction()).isFalse();

        conf.set(CoreOptions.DELETION_VECTORS_ENABLED, true);
        assertThat(options.prepareCommitWaitCompaction()).isTrue();
        conf.remove(CoreOptions.DELETION_VECTORS_ENABLED.key());

        conf.set(CoreOptions.MERGE_ENGINE, CoreOptions.MergeEngine.FIRST_ROW);
        assertThat(options.prepareCommitWaitCompaction()).isTrue();
        conf.remove(CoreOptions.MERGE_ENGINE.key());

        conf.set(CoreOptions.CHANGELOG_PRODUCER, CoreOptions.ChangelogProducer.LOOKUP);
        assertThat(options.prepareCommitWaitCompaction()).isTrue();

        conf.set(CoreOptions.LOOKUP_WAIT, false);
        assertThat(options.prepareCommitWaitCompaction()).isFalse();
    }

    @Test
    public void testDeletionVectorsMergeOnRead() {
        Options conf = new Options();
        conf.set(CoreOptions.DELETION_VECTORS_MERGE_ON_READ, true);
        CoreOptions options = new CoreOptions(conf);

        assertThat(options.deletionVectorsMergeOnRead()).isTrue();
        assertThat(options.batchScanSkipLevel0()).isFalse();

        conf.set(CoreOptions.DELETION_VECTORS_ENABLED, true);
        assertThat(options.deletionVectorsMergeOnRead()).isTrue();
        assertThat(options.batchScanSkipLevel0()).isFalse();

        conf.set(CoreOptions.DELETION_VECTORS_MERGE_ON_READ, false);
        assertThat(options.deletionVectorsMergeOnRead()).isFalse();
        assertThat(options.batchScanSkipLevel0()).isTrue();
    }

    @Test
    public void testSequenceFieldTrim() {
        Options conf = new Options();
        conf.set(CoreOptions.SEQUENCE_FIELD, " f1 ,f2 ,  f3  ");

        CoreOptions options = new CoreOptions(conf);
        assertThat(options.sequenceField()).containsExactly("f1", "f2", "f3");
    }

    @Test
    public void testIgnoreGlobalIndexColumnUpdateAction() {
        Options conf = new Options();
        conf.setString(CoreOptions.GLOBAL_INDEX_COLUMN_UPDATE_ACTION.key(), "IGNORE");

        assertThat(new CoreOptions(conf).globalIndexColumnUpdateAction())
                .isEqualTo(CoreOptions.GlobalIndexColumnUpdateAction.IGNORE);
    }

    @Test
    public void testIndexSearchModes() {
        Options conf = new Options();
        CoreOptions options = new CoreOptions(conf);
        assertThat(options.globalIndexSearchMode()).isNull();
        assertThat(options.scalarIndexSearchMode())
                .isEqualTo(CoreOptions.GlobalIndexSearchMode.FAST);
        assertThat(options.vectorIndexSearchMode())
                .isEqualTo(CoreOptions.GlobalIndexSearchMode.FAST);
        assertThat(options.fullTextIndexSearchMode())
                .isEqualTo(CoreOptions.GlobalIndexSearchMode.FAST);

        conf.set(CoreOptions.GLOBAL_INDEX_SEARCH_MODE, CoreOptions.GlobalIndexSearchMode.DETAIL);
        options = new CoreOptions(conf);
        assertThat(options.scalarIndexSearchMode())
                .isEqualTo(CoreOptions.GlobalIndexSearchMode.DETAIL);
        assertThat(options.vectorIndexSearchMode())
                .isEqualTo(CoreOptions.GlobalIndexSearchMode.DETAIL);
        assertThat(options.fullTextIndexSearchMode())
                .isEqualTo(CoreOptions.GlobalIndexSearchMode.DETAIL);

        conf.set(CoreOptions.SCALAR_INDEX_SEARCH_MODE, CoreOptions.GlobalIndexSearchMode.FAST);
        conf.set(CoreOptions.VECTOR_INDEX_SEARCH_MODE, CoreOptions.GlobalIndexSearchMode.FULL);
        conf.set(CoreOptions.FULL_TEXT_INDEX_SEARCH_MODE, CoreOptions.GlobalIndexSearchMode.FULL);
        options = new CoreOptions(conf);
        assertThat(options.scalarIndexSearchMode())
                .isEqualTo(CoreOptions.GlobalIndexSearchMode.FAST);
        assertThat(options.vectorIndexSearchMode())
                .isEqualTo(CoreOptions.GlobalIndexSearchMode.FULL);
        assertThat(options.fullTextIndexSearchMode())
                .isEqualTo(CoreOptions.GlobalIndexSearchMode.FULL);
    }

    @Test
    public void testBlobSplitByFileSizeDefault() {
        Options conf = new Options();
        conf.set(CoreOptions.BLOB_SPLIT_BY_FILE_SIZE, false);
        CoreOptions options = new CoreOptions(conf);
        assertThat(options.blobSplitByFileSize()).isFalse();

        conf.set(CoreOptions.BLOB_SPLIT_BY_FILE_SIZE, true);
        options = new CoreOptions(conf);
        assertThat(options.blobSplitByFileSize()).isTrue();

        conf = new Options();
        conf.set(CoreOptions.BLOB_AS_DESCRIPTOR, true);
        options = new CoreOptions(conf);
        assertThat(options.blobSplitByFileSize()).isFalse();

        conf = new Options();
        conf.set(CoreOptions.BLOB_AS_DESCRIPTOR, false);
        options = new CoreOptions(conf);
        assertThat(options.blobSplitByFileSize()).isTrue();
    }

    @Test
    public void testMapStorageLayout() {
        Options conf = new Options();
        CoreOptions options = new CoreOptions(conf);
        assertThat(options.mapStorageLayout("metrics"))
                .isEqualTo(CoreOptions.MapStorageLayout.DEFAULT);
        assertThat(options.mapSharedShreddingMaxColumns("metrics")).isEqualTo(256);
        assertThat(options.mapSharedShreddingColumnPlacementPolicy("metrics"))
                .isEqualTo(CoreOptions.MapSharedShreddingColumnPlacementPolicy.LRU);

        conf.setString("fields.metrics.map.storage-layout", "shared-shredding");
        conf.setString("fields.metrics.map.shared-shredding.max-columns", "32");
        conf.setString("fields.metrics.map.shared-shredding.column-placement-policy", "sequential");
        options = new CoreOptions(conf);
        assertThat(options.mapStorageLayout("metrics"))
                .isEqualTo(CoreOptions.MapStorageLayout.SHARED_SHREDDING);
        assertThat(options.mapSharedShreddingMaxColumns("metrics")).isEqualTo(32);
        assertThat(options.mapSharedShreddingColumnPlacementPolicy("metrics"))
                .isEqualTo(CoreOptions.MapSharedShreddingColumnPlacementPolicy.SEQUENTIAL);

        conf.setString("fields.metrics.map.shared-shredding.column-placement-policy", "lru");
        options = new CoreOptions(conf);
        assertThat(options.mapSharedShreddingColumnPlacementPolicy("metrics"))
                .isEqualTo(CoreOptions.MapSharedShreddingColumnPlacementPolicy.LRU);

        conf = new Options();
        conf.setString("fields.metrics.map.storage-layout", "Shared-Shredding");
        conf.setString("fields.metrics.map.shared-shredding.column-placement-policy", "PLAIN");
        options = new CoreOptions(conf);
        assertThat(options.mapStorageLayout("metrics"))
                .isEqualTo(CoreOptions.MapStorageLayout.SHARED_SHREDDING);
        assertThat(options.mapSharedShreddingColumnPlacementPolicy("metrics"))
                .isEqualTo(CoreOptions.MapSharedShreddingColumnPlacementPolicy.PLAIN);

        conf = new Options();
        conf.setString("fields.metrics.map.storage-layout", "invalid");
        final CoreOptions invalidLayoutOptions = new CoreOptions(conf);
        assertThatThrownBy(() -> invalidLayoutOptions.mapStorageLayout("metrics"))
                .hasMessageContaining("invalid");

        conf = new Options();
        conf.setString("fields.metrics.map.shared-shredding.column-placement-policy", "invalid");
        final CoreOptions invalidPlacementPolicyOptions = new CoreOptions(conf);
        assertThatThrownBy(
                        () ->
                                invalidPlacementPolicyOptions
                                        .mapSharedShreddingColumnPlacementPolicy("metrics"))
                .hasMessageContaining("invalid");

        conf = new Options();
        conf.setString("fields.metrics.map.shared-shredding.max-columns", "0");
        final CoreOptions zeroMaxColumnsOptions = new CoreOptions(conf);
        assertThatThrownBy(() -> zeroMaxColumnsOptions.mapSharedShreddingMaxColumns("metrics"))
                .hasMessageContaining("options map.shared-shredding.max-columns must > 0");

        conf.setString("fields.metrics.map.shared-shredding.max-columns", "-1");
        final CoreOptions negativeMaxColumnsOptions = new CoreOptions(conf);
        assertThatThrownBy(() -> negativeMaxColumnsOptions.mapSharedShreddingMaxColumns("metrics"))
                .hasMessageContaining("options map.shared-shredding.max-columns must > 0");
    }

    @Test
    public void testBlobCopyBufferSize() {
        Options conf = new Options();
        // default preserves the historical 4 KiB buffer.
        assertThat(new CoreOptions(conf).blobCopyBufferSize()).isEqualTo(4 * 1024);

        conf.set(CoreOptions.BLOB_COPY_BUFFER_SIZE, MemorySize.parse("64 kb"));
        assertThat(new CoreOptions(conf).blobCopyBufferSize()).isEqualTo(64 * 1024);

        // zero is rejected early with an option-named message.
        conf.set(CoreOptions.BLOB_COPY_BUFFER_SIZE, MemorySize.parse("0 bytes"));
        assertThatThrownBy(() -> new CoreOptions(conf).blobCopyBufferSize())
                .isInstanceOf(IllegalArgumentException.class)
                .hasMessageContaining("blob.copy-buffer-size");

        // There is no arbitrary memory ceiling; only the Java int-sized array limit applies.
        conf.set(CoreOptions.BLOB_COPY_BUFFER_SIZE, MemorySize.parse("512 mb"));
        assertThat(new CoreOptions(conf).blobCopyBufferSize()).isEqualTo(512 * 1024 * 1024);
        conf.set(CoreOptions.BLOB_COPY_BUFFER_SIZE, MemorySize.parse(Integer.MAX_VALUE + " bytes"));
        assertThat(new CoreOptions(conf).blobCopyBufferSize()).isEqualTo(Integer.MAX_VALUE);
        conf.set(CoreOptions.BLOB_COPY_BUFFER_SIZE, MemorySize.parse("2 gb"));
        assertThatThrownBy(() -> new CoreOptions(conf).blobCopyBufferSize())
                .isInstanceOf(IllegalArgumentException.class)
                .hasMessageContaining("blob.copy-buffer-size");
    }

    @Test
    public void testLocalKvDbBlockSize() {
        Options conf = new Options();
        assertThat(new CoreOptions(conf).localKvDbBlockSize()).isEqualTo(4 * 1024);

        conf.set(CoreOptions.LOCAL_KV_DB_BLOCK_SIZE, MemorySize.parse("8 kb"));
        assertThat(new CoreOptions(conf).localKvDbBlockSize()).isEqualTo(8 * 1024);

        conf.set(CoreOptions.LOCAL_KV_DB_BLOCK_SIZE, MemorySize.parse("0 bytes"));
        assertThatThrownBy(() -> new CoreOptions(conf).localKvDbBlockSize())
                .isInstanceOf(IllegalArgumentException.class)
                .hasMessageContaining("local-kv-db.block-size");

        conf.set(CoreOptions.LOCAL_KV_DB_BLOCK_SIZE, MemorySize.parse("2 gb"));
        assertThatThrownBy(() -> new CoreOptions(conf).localKvDbBlockSize())
                .isInstanceOf(IllegalArgumentException.class)
                .hasMessageContaining("local-kv-db.block-size");
    }
}
