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

package kernels

import (
	
	

	
	
	
	
	
	
)

func listElementOutputType( *exec.KernelCtx,  []arrow.DataType) (arrow.DataType, error) {
	,  := [0].(arrow.ListLikeType)
	if ! {
		return nil, fmt.Errorf("%w: list_element requires a list-like input", arrow.ErrType)
	}
	return .Elem(), nil
}

func getListElementIndex( *exec.ExecValue) (uint64, error) {
	if .IsScalar() {
		return listElementScalarIndex(.Scalar)
	}

	if .Array.Len == 0 {
		return 0, fmt.Errorf("%w: list_element index array is empty", arrow.ErrInvalid)
	}
	if .Array.Len > 1 {
		return 0, fmt.Errorf("%w: list_element does not support arrays of list indices", arrow.ErrNotImplemented)
	}
	if .Array.UpdateNullCount() != 0 {
		return 0, fmt.Errorf("%w: list_element index must not contain nulls", arrow.ErrInvalid)
	}

	switch .Array.Type.ID() {
	case arrow.INT8:
		return unsignedIndex(exec.GetSpanValues[int8](&.Array, 1)[0])
	case arrow.INT16:
		return unsignedIndex(exec.GetSpanValues[int16](&.Array, 1)[0])
	case arrow.INT32:
		return unsignedIndex(exec.GetSpanValues[int32](&.Array, 1)[0])
	case arrow.INT64:
		return unsignedIndex(exec.GetSpanValues[int64](&.Array, 1)[0])
	case arrow.UINT8:
		return uint64(exec.GetSpanValues[uint8](&.Array, 1)[0]), nil
	case arrow.UINT16:
		return uint64(exec.GetSpanValues[uint16](&.Array, 1)[0]), nil
	case arrow.UINT32:
		return uint64(exec.GetSpanValues[uint32](&.Array, 1)[0]), nil
	case arrow.UINT64:
		return exec.GetSpanValues[uint64](&.Array, 1)[0], nil
	default:
		return 0, fmt.Errorf("%w: invalid list_element index type %s", arrow.ErrType, .Array.Type)
	}
}

func ( scalar.Scalar) error {
	,  := listElementScalarIndex()
	return 
}

func ( scalar.Scalar) (uint64, error) {
	return listElementScalarIndex()
}

func listElementScalarIndex( scalar.Scalar) (uint64, error) {
	if !.IsValid() {
		return 0, fmt.Errorf("%w: list_element index must not be null", arrow.ErrInvalid)
	}
	return scalarIndex()
}

func scalarIndex( scalar.Scalar) (uint64, error) {
	switch value := .(type) {
	case *scalar.Int8:
		return unsignedIndex(.Value)
	case *scalar.Int16:
		return unsignedIndex(.Value)
	case *scalar.Int32:
		return unsignedIndex(.Value)
	case *scalar.Int64:
		return unsignedIndex(.Value)
	case *scalar.Uint8:
		return uint64(.Value), nil
	case *scalar.Uint16:
		return uint64(.Value), nil
	case *scalar.Uint32:
		return uint64(.Value), nil
	case *scalar.Uint64:
		return .Value, nil
	default:
		return 0, fmt.Errorf("%w: invalid list_element index type %s", arrow.ErrType, .DataType())
	}
}

func unsignedIndex[ arrow.IntType]( ) (uint64, error) {
	if  < 0 {
		return 0, fmt.Errorf("%w: list_element index %d is out of bounds: should be greater than or equal to 0", arrow.ErrInvalid, )
	}
	return uint64(), nil
}

func listElementValueOffsets( *exec.ArraySpan,  int64) (int64, int64, error) {
	 := func(,  int64) (int64, int64, error) {
		if  < 0 ||  <  ||  > .Children[0].Len {
			return 0, 0, fmt.Errorf("%w: list_element input has invalid value offsets", arrow.ErrInvalid)
		}
		return , , nil
	}

	switch .Type.ID() {
	case arrow.LIST:
		 := exec.GetSpanOffsets[int32](, 1)
		return (int64([]), int64([+1]))
	case arrow.LARGE_LIST:
		 := exec.GetSpanOffsets[int64](, 1)
		return ([], [+1])
	case arrow.LIST_VIEW:
		 := exec.GetSpanValues[int32](, 1)
		 := exec.GetSpanValues[int32](, 2)
		 := int64([])
		 := int64([])
		if  < 0 {
			return 0, 0, fmt.Errorf("%w: list_element input has invalid value offsets", arrow.ErrInvalid)
		}
		return (, +)
	case arrow.LARGE_LIST_VIEW:
		 := exec.GetSpanValues[int64](, 1)
		 := exec.GetSpanValues[int64](, 2)
		 := []
		 := []
		if  < 0 ||  < 0 ||  > math.MaxInt64- {
			return 0, 0, fmt.Errorf("%w: list_element input has invalid value offsets", arrow.ErrInvalid)
		}
		return (, +)
	case arrow.FIXED_SIZE_LIST:
		 := int64(.Type.(*arrow.FixedSizeListType).Len())
		if .Offset < 0 ||  < 0 ||  > math.MaxInt64-.Offset {
			return 0, 0, fmt.Errorf("%w: list_element input has invalid value offsets", arrow.ErrInvalid)
		}
		 := .Offset + 
		if  < 0 || ( > 0 &&  > math.MaxInt64/) {
			return 0, 0, fmt.Errorf("%w: list_element input has invalid value offsets", arrow.ErrInvalid)
		}
		 :=  * 
		if  > math.MaxInt64- {
			return 0, 0, fmt.Errorf("%w: list_element input has invalid value offsets", arrow.ErrInvalid)
		}
		return (, +)
	default:
		return 0, 0, fmt.Errorf("%w: unsupported list_element input type %s", arrow.ErrType, .Type)
	}
}

func listElementExec( *exec.KernelCtx,  *exec.ExecSpan,  *exec.ExecResult) error {
	var  exec.ArraySpan
	if .Values[0].IsScalar() {
		.FillFromScalar(.Values[0].Scalar)
	} else {
		 = .Values[0].Array
	}
	 := &
	if len(.Children) == 0 {
		return fmt.Errorf("%w: list_element input has no values child", arrow.ErrInvalid)
	}

	,  := getListElementIndex(&.Values[1])
	if  != nil {
		return 
	}

	 := .Type.(arrow.ListLikeType).Elem()
	if !ListElementOutputTypeSupported() {
		return fmt.Errorf("%w: list_element output type %s is not supported", arrow.ErrNotImplemented, )
	}
	if .Len == 0 {
		 := .Children[0].MakeArray()
		defer .Release()
		 := array.NewSlice(, 0, 0)
		defer .Release()
		.TakeOwnership(.Data())
		return nil
	}
	if !listElementTakeSupported() {
		return listElementConcat(, , , , )
	}

	 := array.NewInt64Builder(exec.GetAllocator(.Ctx))
	defer .Release()
	.Reserve(int(.Len))
	for  := int64(0);  < .Len; ++ {
		if len(.Buffers[0].Buf) != 0 && bitutil.BitIsNotSet(.Buffers[0].Buf, int(.Offset+)) {
			.AppendNull()
			continue
		}

		, ,  := listElementValueOffsets(, )
		if  != nil {
			return 
		}
		if  <  {
			return fmt.Errorf("%w: list_element input has invalid value offsets", arrow.ErrInvalid)
		}
		 := uint64( - )
		if  >=  {
			return fmt.Errorf("%w: list_element index %d is out of bounds: should be in [0, %d)", arrow.ErrInvalid, , )
		}
		.Append( + int64())
	}

	 := .NewArray()
	defer .Release()
	return listElementTakeOrFallback(, &.Children[0], , )
}

func ( arrow.DataType) bool {
	switch .ID() {
	case arrow.BINARY_VIEW, arrow.STRING_VIEW:
		return false
	case arrow.SPARSE_UNION, arrow.DENSE_UNION:
		if .(arrow.UnionType).NumFields() == 0 {
			return false
		}
	case arrow.EXTENSION:
		 := .(arrow.ExtensionType).StorageType()
		// ArraySpan does not preserve a dictionary stored under an extension.
		return .ID() != arrow.DICTIONARY && ()
	case arrow.DICTIONARY:
		return (.(*arrow.DictionaryType).ValueType)
	}

	,  := .(arrow.NestedType)
	if ! {
		return true
	}
	for ,  := range .Fields() {
		if !(.Type) {
			return false
		}
	}
	return true
}

func listElementTakeSupported( arrow.DataType) bool {
	 := .ID()
	if  == arrow.NULL || arrow.IsBinaryLike() || arrow.IsLargeBinaryLike() ||
		arrow.IsFixedSizeBinary() ||  == arrow.SPARSE_UNION ||  == arrow.DENSE_UNION ||
		 == arrow.EXTENSION {
		return true
	}
	if !arrow.IsPrimitive() {
		return false
	}

	// PrimitiveTake has specialized implementations for these widths only.
	// In particular, INTERVAL_MONTH_DAY_NANO is a primitive 128-bit type and
	// must use the generic concatenation fallback below.
	,  := .(arrow.FixedWidthDataType)
	if ! {
		return false
	}
	switch .BitWidth() {
	case 1, 8, 16, 32, 64:
		return true
	default:
		return false
	}
}

func listElementConcat( *exec.KernelCtx,  *exec.ArraySpan,  uint64,  arrow.DataType,  *exec.ExecResult) error {
	 := .Children[0].MakeArray()
	defer .Release()
	 := make([]arrow.Array, 0, int(.Len))
	defer func() {
		for ,  := range  {
			.Release()
		}
	}()

	for  := int64(0);  < .Len; ++ {
		if len(.Buffers[0].Buf) != 0 && bitutil.BitIsNotSet(.Buffers[0].Buf, int(.Offset+)) {
			 = append(, listElementMakeNullLike(, , ))
			continue
		}

		, ,  := listElementValueOffsets(, )
		if  != nil {
			return 
		}
		if  <  {
			return fmt.Errorf("%w: list_element input has invalid value offsets", arrow.ErrInvalid)
		}
		 := uint64( - )
		if  >=  {
			return fmt.Errorf("%w: list_element index %d is out of bounds: should be in [0, %d)", arrow.ErrInvalid, , )
		}
		 :=  + int64()
		 = append(, array.NewSlice(, , +1))
	}

	,  := array.Concatenate(, exec.GetAllocator(.Ctx))
	if  != nil {
		return 
	}
	defer .Release()
	.TakeOwnership(.Data())
	return nil
}

func listElementMakeNullLike( *exec.KernelCtx,  arrow.Array,  arrow.DataType) arrow.Array {
	 := exec.GetAllocator(.Ctx)
	if ,  := .(arrow.ExtensionType);  {
		 := 
		if ,  := .(array.ExtensionArray);  {
			 = .Storage()
		}
		 := (, , .StorageType())
		 := array.NewExtensionArrayWithStorage(, )
		.Release()
		return 
	}
	if .ID() == arrow.RUN_END_ENCODED {
		 := .(*arrow.RunEndEncodedType)
		// Build only the run ends; nested encoded values may not have a builder.
		 := array.NewRunEndEncodedBuilder(, .RunEnds(), arrow.Null)
		defer .Release()
		.AppendNull()
		 := .NewRunEndEncodedArray()
		defer .Release()
		 := (, .(*array.RunEndEncoded).Values(), .Encoded())
		defer .Release()
		return array.NewRunEndEncodedArrayWithType(, .RunEndsArr(), , 1, 0)
	}
	if .Len() == 0 || len(.Data().Buffers()) == 0 ||
		.ID() == arrow.NULL || arrow.IsUnion(.ID()) {
		return array.MakeArrayOfNull(, , 1)
	}

	 := array.NewSlice(, 0, 1)
	defer .Release()

	 := .Data()
	 := memory.NewResizableBuffer()
	.Resize(int(bitutil.BytesForBits(int64(.Offset() + 1))))
	memory.Set(.Bytes(), 0)
	defer .Release()

	 := append([]*memory.Buffer(nil), .Buffers()...)
	[0] = 
	 := array.NewData(.DataType(), 1, , .Children(), 1, .Offset())
	if  := .Dictionary();  != nil {
		.SetDictionary()
	}
	defer .Release()
	return array.MakeFromData()
}

func listElementTakeFallback( *exec.KernelCtx,  *exec.ArraySpan,  arrow.Array,  *exec.ExecResult) error {
	 := .Type
	 := .MakeArray()
	defer .Release()
	if .Len() == 0 {
		 := array.NewSlice(, 0, 0)
		defer .Release()
		.TakeOwnership(.Data())
		return nil
	}

	 := make([]arrow.Array, 0, .Len())
	defer func() {
		for ,  := range  {
			.Release()
		}
	}()

	for  := 0;  < .Len(); ++ {
		if .IsNull() {
			 = append(, listElementMakeNullLike(, , ))
			continue
		}
		,  := listElementTakeIndex(, )
		if  != nil {
			return 
		}
		 = append(, array.NewSlice(, , +1))
	}

	,  := array.Concatenate(, exec.GetAllocator(.Ctx))
	if  != nil {
		return 
	}
	defer .Release()
	.TakeOwnership(.Data())
	return nil
}

func listElementTakeIndex( arrow.Array,  int) (int64, error) {
	switch indexArray := .(type) {
	case *array.Int32:
		return int64(.Value()), nil
	case *array.Int64:
		return .Value(), nil
	default:
		return 0, fmt.Errorf("%w: list_element fallback received unsupported index type %s", arrow.ErrType, .DataType())
	}
}

func listElementTakeOrFallback( *exec.KernelCtx,  *exec.ArraySpan,  arrow.Array,  *exec.ExecResult) error {
	if .Len() == 0 {
		return listElementTakeFallback(, , , )
	}
	if ,  := listElementTake(, , , );  {
		return 
	}
	return listElementTakeFallback(, , , )
}

func listElementDenseUnionTake( *exec.KernelCtx,  *exec.ArraySpan,  arrow.Array,  *exec.ExecResult) error {
	var  exec.ArraySpan
	.SetMembers(.Data())
	 := &exec.ExecSpan{
		Len: int64(.Len()),
		Values: []exec.ExecValue{
			{Array: *},
			{Array: },
		},
	}
	 := *
	.State = TakeOptions{BoundsCheck: false}
	if  := TakeExec(DenseUnionImpl)(&, , );  != nil {
		return 
	}

	for  := range .Children {
		 := .Children[].MakeArray()
		.Children[] = exec.ArraySpan{}
		 := &exec.ExecResult{Type: .Children[].Type}
		 := listElementTakeOrFallback(, &.Children[], , )
		.Release()
		if  != nil {
			.Release()
			return 
		}

		 := .MakeData()
		.Children[].TakeOwnership()
		.Release()
	}
	return nil
}

func listElementSparseUnionTake( *exec.KernelCtx,  *exec.ArraySpan,  arrow.Array,  *exec.ExecResult) error {
	 := .MakeArray()
	defer .Release()

	 := .(*array.SparseUnion)
	 := .Type.(*arrow.SparseUnionType)
	 := array.NewInt8Builder(exec.GetAllocator(.Ctx))
	defer .Release()
	.Reserve(.Len())

	for  := 0;  < .Len(); ++ {
		if .IsNull() {
			.Append(.TypeCodes()[0])
		} else {
			,  := listElementTakeIndex(, )
			if  != nil {
				return 
			}
			.Append(.TypeCode(int()))
		}
	}

	 := .NewArray()
	defer .Release()

	 := make([]arrow.Array, len(.Children))
	defer func() {
		for ,  := range  {
			if  != nil {
				.Release()
			}
		}
	}()
	for  := range .Children {
		 := .Field()
		var  exec.ArraySpan
		.SetMembers(.Data())
		 := &exec.ExecResult{Type: .Type}
		if  := listElementTakeOrFallback(, &, , );  != nil {
			.Release()
			return 
		}
		[] = .MakeArray()
	}

	 := make([]arrow.ArrayData, len())
	for ,  := range  {
		[] = .Data()
	}
	 := array.NewData(, .Len(),
		[]*memory.Buffer{nil, .Data().Buffers()[1]}, , 0, 0)
	 := array.NewSparseUnionData()
	.Release()
	defer .Release()
	.TakeOwnership(.Data())
	return nil
}

func listElementTake( *exec.KernelCtx,  *exec.ArraySpan,  arrow.Array,  *exec.ExecResult) (bool, error) {
	if !listElementTakeSupported(.Type) {
		return false, nil
	}

	var  exec.ArraySpan
	.SetMembers(.Data())
	 := &exec.ExecSpan{
		Len: int64(.Len()),
		Values: []exec.ExecValue{
			{Array: *},
			{Array: },
		},
	}
	 := *
	.State = TakeOptions{BoundsCheck: false}

	switch  := .Type.ID(); {
	case  == arrow.NULL:
		return true, NullTake(&, , )
	case arrow.IsPrimitive():
		return true, PrimitiveTake(&, , )
	case arrow.IsBinaryLike():
		return true, TakeExec(VarBinaryImpl[int32])(&, , )
	case arrow.IsLargeBinaryLike():
		return true, TakeExec(VarBinaryImpl[int64])(&, , )
	case arrow.IsFixedSizeBinary():
		return true, TakeExec(FSBImpl)(&, , )
	case  == arrow.SPARSE_UNION:
		return true, listElementSparseUnionTake(, , , )
	case  == arrow.DENSE_UNION:
		return true, listElementDenseUnionTake(, , , )
	case  == arrow.EXTENSION:
		 := .Type.(arrow.ExtensionType)
		 := *
		.Type = .StorageType()
		,  := (, &, , )
		if  {
			// The storage take produces the physical buffers and children. Restore
			// the logical extension type so ArraySpan.MakeData reconstructs an
			// ExtensionArray around them.
			.Type = .Type
		}
		return , 
	default:
		return false, nil
	}
}

func () []exec.ScalarKernel {
	 := make([]exec.ScalarKernel, 0, 5)
	for ,  := range []arrow.Type{
		arrow.LIST,
		arrow.LARGE_LIST,
		arrow.LIST_VIEW,
		arrow.LARGE_LIST_VIEW,
		arrow.FIXED_SIZE_LIST,
	} {
		 := exec.NewScalarKernel(
			[]exec.InputType{
				exec.NewIDInput(),
				exec.NewMatchedInput(exec.Integer()),
			},
			exec.NewComputedOutputType(listElementOutputType),
			listElementExec,
			nil)
		.NullHandling = exec.NullComputedNoPrealloc
		.MemAlloc = exec.MemNoPrealloc
		 = append(, )
	}
	return 
}