// 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.

//go:build go1.22

package compute

import (
	
	

	
	
	
)

var (
	sortIndicesDoc = FunctionDoc{
		Summary: "Return the indices that would sort the input",
		Description: `This function computes an array of indices that define a stable sort.
Supports arrays, chunked arrays, record batches, and tables.
For arrays and chunked arrays, use a single SortKey (ColumnIndex is ignored).
For record batches and tables, use []SortKey to specify columns and sort
order; at least one key is required. Each key must reference a valid column.`,
		ArgNames:    []string{"input"},
		OptionsType: "SortKeys",
	}

	sortIndicesMetaFunc = NewMetaFunction("sort_indices", Unary(), sortIndicesDoc,
		func( context.Context,  FunctionOptions,  ...Datum) (Datum, error) {
			 := [0]
			switch .Kind() {
			case KindArray, KindChunked, KindRecord, KindTable:
				return sortIndicesImpl(, , )
			}

			return nil, fmt.Errorf("%w: unsupported type for sort_indices operation: %s",
				arrow.ErrNotImplemented, )
		})

	sortDoc = FunctionDoc{
		Summary: "Return a sorted copy of the input",
		Description: `This function sorts the input using the same ordering as sort_indices
and returns the reordered values. It is equivalent to take(input,
sort_indices(input, options)).
Supports arrays, chunked arrays, record batches, and tables with the same
SortKeys options as sort_indices.`,
		ArgNames:    []string{"input"},
		OptionsType: "SortKeys",
	}

	sortMetaFunc = NewMetaFunction("sort", Unary(), sortDoc,
		func( context.Context,  FunctionOptions,  ...Datum) (Datum, error) {
			 := [0]
			switch .Kind() {
			case KindArray, KindChunked, KindRecord, KindTable:
			default:
				return nil, fmt.Errorf("%w: unsupported type for sort: %s", arrow.ErrNotImplemented, )
			}

			,  := CallFunction(, "sort_indices", , )
			if  != nil {
				return nil, 
			}
			defer .Release()

			return Take(, *DefaultTakeOptions(), , )
		})
)

const (
	SortOrderAscending  = kernels.Ascending
	SortOrderDescending = kernels.Descending
	SortNullsAtEnd      = kernels.NullsAtEnd
	SortNullsAtStart    = kernels.NullsAtStart
)

// SortKey defines a column to sort by with its ordering, null placement and float ordering options.
// See kernels.SortKey.FloatTotalOrder for IEEE 754 totalOrder sorting of float columns.
type SortKey = kernels.SortKey

// SortOptions defines the desired sort order for the input.
type SortOptions []SortKey

// TypeName implements FunctionOptions.
func (SortOptions) () string { return "SortKeys" }

// DefaultSortKey returns the default sort key: ascending order with nulls last.
func () SortKey {
	return SortKey{
		ColumnIndex:   0,
		Order:         kernels.Ascending,
		NullPlacement: kernels.NullsAtEnd,
	}
}

// sortIndicesImpl adapts any supported Datum to kernels.SortIndices (internal/kernels), which
// implements a stable lexicographic sort over []*arrow.Chunked (one logical column per sort key,
// same row count).
//
// Only the columns referenced by sort keys are passed to the kernel; the rest of the batch/table
// is irrelevant to index computation. Chunked wrappers we allocate with arrow.NewChunked must be
// released in the defer below (needsRelease); table column *arrow.Chunked values are borrowed from
// the table and must not be released here.
func sortIndicesImpl( context.Context,  FunctionOptions,  Datum) (Datum, error) {
	 := .(SortOptions)
	if len() == 0 {
		return nil, fmt.Errorf("%w: must provide at least one sort key", arrow.ErrInvalid)
	}

	var  []*arrow.Chunked
	// For KindRecord/KindTable, sortKeys stays aligned with inputSortKeys (multi-column sort).
	// For KindArray/KindChunked, sortKeys is replaced with a single key (see those cases).
	 := []kernels.SortKey()
	var  []bool

	switch .Kind() {
	case KindArray:
		// Single column: one Array wrapped as a one-chunk Chunked (kernel API).
		 := .(*ArrayDatum).MakeArray()
		defer .Release()
		 := arrow.NewChunked(.DataType(), []arrow.Array{})
		 = []*arrow.Chunked{}
		 = []bool{true}

		// Only the first key is used; ColumnIndex is meaningless for a bare array—copy the key and
		// set index 0 so the kernel sees a consistent (column, key) pair (order/null placement preserved).
		 := [0]
		.ColumnIndex = 0
		 = []kernels.SortKey{}

	case KindChunked:
		// Single column: use the Chunked as-is (caller-owned; do not Release).
		 := .(*ChunkedDatum).Value
		 = []*arrow.Chunked{}
		 = []bool{false}

		 := [0]
		.ColumnIndex = 0
		 = []kernels.SortKey{}

	case KindRecord:
		 := .(*RecordDatum).Value

		 = make([]*arrow.Chunked, len())
		 = make([]bool, len())
		for ,  := range  {
			if .ColumnIndex < 0 || int64(.ColumnIndex) >= .NumCols() {
				return nil, fmt.Errorf("%w: sort key %d has invalid column index %d", arrow.ErrInvalid, , .ColumnIndex)
			}
			 := .Column(.ColumnIndex)
			// One batch column as a single-chunk Chunked per key; we own these Chunked values.
			[] = arrow.NewChunked(.DataType(), []arrow.Array{})
			[] = true
		}

	case KindTable:
		 := .(*TableDatum).Value

		 = make([]*arrow.Chunked, len())
		 = make([]bool, len())
		for ,  := range  {
			if .ColumnIndex < 0 || int64(.ColumnIndex) >= .NumCols() {
				return nil, fmt.Errorf("%w: sort key %d has invalid column index %d", arrow.ErrInvalid, , .ColumnIndex)
			}
			// Table columns are already Chunked; borrow from the table (do not Release).
			[] = .Column(.ColumnIndex).Data()
			[] = false
		}

	default:
		return nil, fmt.Errorf("%w: unsupported type for sort_indices operation: %s", arrow.ErrNotImplemented, )
	}

	defer func() {
		for ,  := range  {
			if  {
				[].Release()
			}
		}
	}()

	 := exec.GetAllocator()
	 := &exec.KernelCtx{Ctx: exec.WithAllocator(, )}

	,  := kernels.SortIndices(, , )
	if  != nil {
		return nil, 
	}

	return &ArrayDatum{Value: .MakeData()}, nil
}

// SortIndices computes the indices that would sort the input.
// For arrays and chunked arrays, pass a single SortKey (ColumnIndex is ignored).
// For record batches and tables, pass []SortKey to specify multi-column sort order.
// Temporary sorting buffers use the context's allocator and are released before returning.
// The caller must release the returned datum.
func ( context.Context,  Datum,  SortOptions) (Datum, error) {
	return CallFunction(, "sort_indices", , )
}

// SortIndicesArray computes the indices that would sort the input array.
// As with [SortIndices], temporary sorting buffers use the context's allocator
// and are released before returning. The caller must release the returned array.
func ( context.Context,  arrow.Array,  SortKey) (arrow.Array, error) {
	 := NewDatumWithoutOwning()

	,  := SortIndices(, , SortOptions{})
	if  != nil {
		return nil, 
	}
	defer .Release()

	return .(*ArrayDatum).MakeArray(), nil
}

// SortIndicesChunked computes the indices that would sort the input chunked array.
// As with [SortIndices], temporary sorting buffers use the context's allocator
// and are released before returning. The caller must release the returned array.
func ( context.Context,  *arrow.Chunked,  SortKey) (arrow.Array, error) {
	 := NewDatumWithoutOwning()

	,  := SortIndices(, , SortOptions{})
	if  != nil {
		return nil, 
	}
	defer .Release()

	return .(*ArrayDatum).MakeArray(), nil
}

// SortIndicesRecordBatch computes the indices that would sort the record batch (stable, lexicographic by keys).
// As with [SortIndices], temporary sorting buffers use the context's allocator
// and are released before returning. The caller must release the returned array.
func ( context.Context,  arrow.RecordBatch,  []SortKey) (arrow.Array, error) {
	if len() == 0 {
		return nil, fmt.Errorf("%w: at least one sort key is required", arrow.ErrInvalid)
	}

	 := NewDatumWithoutOwning()

	,  := SortIndices(, , SortOptions())
	if  != nil {
		return nil, 
	}
	defer .Release()

	return .(*ArrayDatum).MakeArray(), nil
}

// SortIndicesTable computes the indices that would sort the table (stable, lexicographic by keys).
// As with [SortIndices], temporary sorting buffers use the context's allocator
// and are released before returning. The caller must release the returned array.
func ( context.Context,  arrow.Table,  []SortKey) (arrow.Array, error) {
	if len() == 0 {
		return nil, fmt.Errorf("%w: at least one sort key is required", arrow.ErrInvalid)
	}

	 := NewDatumWithoutOwning()

	,  := SortIndices(, , SortOptions())
	if  != nil {
		return nil, 
	}
	defer .Release()

	return .(*ArrayDatum).MakeArray(), nil
}

// Sort returns a sorted copy of the input datum by calling the registered "sort" function
// ([SortIndices] then [Take]). Supported kinds are [KindArray], [KindChunked], [KindRecord], and [KindTable].
// As with [SortIndices], temporary sorting buffers use the context's allocator
// and are released before returning. The caller must release the returned datum.
func ( context.Context,  Datum,  SortOptions) (Datum, error) {
	return CallFunction(, "sort", , )
}

// SortArray returns a sorted copy of the input array.
// As with [SortIndices], temporary sorting buffers use the context's allocator
// and are released before returning. The caller must release the returned array.
func ( context.Context,  arrow.Array,  SortKey) (arrow.Array, error) {
	,  := SortIndicesArray(, , )
	if  != nil {
		return nil, 
	}
	defer .Release()

	return TakeArray(, , )
}

// SortChunked returns a sorted copy of the input chunked array.
// As with [SortIndices], temporary sorting buffers use the context's allocator
// and are released before returning. The caller must release the returned chunked array.
func ( context.Context,  *arrow.Chunked,  SortKey) (*arrow.Chunked, error) {
	 := NewDatumWithoutOwning()

	,  := SortIndices(, , SortOptions{})
	if  != nil {
		return nil, 
	}
	defer .Release()

	,  := Take(, *DefaultTakeOptions(), , )
	if  != nil {
		return nil, 
	}
	defer .Release()

	 := .(*ChunkedDatum).Value
	.Retain()
	return , nil
}

// SortRecordBatch returns a sorted copy of the record batch using lexicographic ordering across the specified columns.
// Each SortKey specifies a column index and its sort order and null placement.
// When multiple keys are provided, ties in earlier columns are broken by later columns.
// As with [SortIndices], temporary sorting buffers use the context's allocator
// and are released before returning. The caller must release the returned record batch.
//
// Example:
//
//	keys := []kernels.SortKey{
//	    {ColumnIndex: 0, Order: kernels.Ascending, NullPlacement: kernels.NullsLast},
//	    {ColumnIndex: 1, Order: kernels.Descending, NullPlacement: kernels.NullsFirst},
//	}
//	sorted, err := compute.SortRecordBatch(ctx, batch, keys)
func ( context.Context,  arrow.RecordBatch,  []kernels.SortKey) (arrow.RecordBatch, error) {
	if len() == 0 {
		return nil, fmt.Errorf("%w: at least one sort key is required", arrow.ErrInvalid)
	}

	 := NewDatumWithoutOwning()

	,  := SortIndices(, , SortOptions())
	if  != nil {
		return nil, 
	}
	defer .Release()

	,  := Take(, *DefaultTakeOptions(), , )
	if  != nil {
		return nil, 
	}

	 := .(*RecordDatum).Value
	.Retain()
	.Release()

	return , nil
}

// SortTable returns a sorted copy of the table using lexicographic ordering across the specified columns.
// Each SortKey specifies a column index and its sort order and null placement.
// When multiple keys are provided, ties in earlier columns are broken by later columns.
// As with [SortIndices], temporary sorting buffers use the context's allocator
// and are released before returning. The caller must release the returned table.
//
// Example:
//
//	keys := []kernels.SortKey{
//	    {ColumnIndex: 0, Order: kernels.Ascending, NullPlacement: kernels.NullsLast},
//	    {ColumnIndex: 1, Order: kernels.Descending, NullPlacement: kernels.NullsFirst},
//	}
//	sorted, err := compute.SortTable(ctx, table, keys)
func ( context.Context,  arrow.Table,  []kernels.SortKey) (arrow.Table, error) {
	if len() == 0 {
		return nil, fmt.Errorf("%w: at least one sort key is required", arrow.ErrInvalid)
	}

	 := NewDatumWithoutOwning()

	,  := SortIndices(, , SortOptions())
	if  != nil {
		return nil, 
	}
	defer .Release()

	,  := Take(, *DefaultTakeOptions(), , )
	if  != nil {
		return nil, 
	}

	 := .(*TableDatum).Value
	.Retain()
	.Release()

	return , nil
}

// RegisterVectorSort registers the sort_indices and sort functions.
func ( FunctionRegistry) {
	 := SortOptions{DefaultSortKey()}
	sortIndicesMetaFunc.defaultOpts = 
	sortMetaFunc.defaultOpts = 
	.AddFunction(sortIndicesMetaFunc, false)
	.AddFunction(sortMetaFunc, false)
}