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

	
	
	
	
	
	
)

// ScalarAggregateOptions controls the general behaviour of the scalar
// aggregate kernels. The field names and tags are the ones the C++
// implementation uses so that serialized expressions round-trip.
//
// The zero value is not the default: use DefaultScalarAggregateOptions for
// the behaviour the functions have when they are called without options.
type ScalarAggregateOptions struct {
	// SkipNulls, if true, ignores null values. Otherwise, if any value is
	// null, the aggregation emits null.
	SkipNulls bool `compute:"skip_nulls"`
	// MinCount is the number of non-null values which have to be observed
	// for the aggregation to emit a value rather than null.
	MinCount uint32 `compute:"min_count"`
}

func (ScalarAggregateOptions) () string { return "ScalarAggregateOptions" }

// DefaultScalarAggregateOptions returns the options the scalar aggregate
// functions use when they are called with nil options: null values are
// skipped and a single non-null value is enough to produce a result.
func () *ScalarAggregateOptions {
	return &ScalarAggregateOptions{SkipNulls: true, MinCount: 1}
}

// CountMode is the enum for the values which CountOptions.Mode can take.
type CountMode int8

const (
	// CountOnlyValid counts only non-null values.
	CountOnlyValid CountMode = iota
	// CountOnlyNull counts only null values.
	CountOnlyNull
	// CountAllRows counts both non-null and null values.
	CountAllRows
)

// CountOptions controls the behaviour of the count aggregate kernel.
type CountOptions struct {
	Mode CountMode `compute:"mode"`
}

func (CountOptions) () string { return "CountOptions" }

// DefaultCountOptions returns the options the count function uses when it is
// called with nil options, which is to count only the non-null values. This
// is also the zero value of CountOptions.
func () *CountOptions { return &CountOptions{Mode: CountOnlyValid} }

// aggState is implemented by every aggregate state in this package, so that
// one set of consume/merge/finalize functions can serve all of the kernels,
// as the C++ ScalarAggregator does.
type aggState interface {
	consume(span *exec.ExecSpan) error
	mergeFrom(src aggState) error
	finalize() (*exec.AggregateResult, error)
}

// AggregateConsume is the exec.ScalarAggConsume shared by the aggregate
// kernels in this package.
func ( *exec.KernelCtx,  *exec.ExecSpan) error {
	,  := .State.(aggState)
	if ! {
		return fmt.Errorf("%w: aggregate kernel state of unexpected type %T", arrow.ErrInvalid, .State)
	}
	return .consume()
}

// AggregateMerge is the exec.ScalarAggMerge shared by the aggregate kernels
// in this package. It folds src into dst, leaving src untouched.
func ( *exec.KernelCtx, ,  exec.KernelState) error {
	,  := .(aggState)
	if ! {
		return fmt.Errorf("%w: aggregate kernel state of unexpected type %T", arrow.ErrInvalid, )
	}
	,  := .(aggState)
	if ! {
		return fmt.Errorf("%w: aggregate kernel state of unexpected type %T", arrow.ErrInvalid, )
	}
	return .mergeFrom()
}

// AggregateFinalize is the exec.ScalarAggFinalize shared by the aggregate
// kernels in this package.
func ( *exec.KernelCtx) (*exec.AggregateResult, error) {
	,  := .State.(aggState)
	if ! {
		return nil, fmt.Errorf("%w: aggregate kernel state of unexpected type %T", arrow.ErrInvalid, .State)
	}
	return .finalize()
}

// spanNullCount returns the number of nulls in the span without writing to
// it. ArraySpan.UpdateNullCount caches its answer in the span, and the
// executor re-slices one span for every chunk of the input, so a kernel which
// updated the count of the span it was handed would leave a stale count
// behind for the following chunk.
func spanNullCount( *exec.ArraySpan) int64 {
	if .Type.ID() == arrow.NULL {
		return .Len
	}
	if  := .Nulls;  != array.UnknownNullCount {
		return 
	}
	if len(.Buffers[0].Buf) == 0 {
		return 0
	}
	return .Len - int64(bitutil.CountSetBits(.Buffers[0].Buf, int(.Offset), int(.Len)))
}

func resolveAggOptions( any) (ScalarAggregateOptions, error) {
	switch o := .(type) {
	case nil:
		return *DefaultScalarAggregateOptions(), nil
	case *ScalarAggregateOptions:
		if  == nil {
			return *DefaultScalarAggregateOptions(), nil
		}
		return *, nil
	case ScalarAggregateOptions:
		return , nil
	}
	return ScalarAggregateOptions{}, fmt.Errorf("%w: attempted to initialize a scalar aggregate kernel with options of type %T",
		arrow.ErrInvalid, )
}

func resolveCountOptions( any) (CountOptions, error) {
	var  CountOptions
	switch o := .(type) {
	case nil:
		 = *DefaultCountOptions()
	case *CountOptions:
		if  == nil {
			 = *DefaultCountOptions()
		} else {
			 = *
		}
	case CountOptions:
		 = 
	default:
		return , fmt.Errorf("%w: attempted to initialize the count kernel with options of type %T",
			arrow.ErrInvalid, )
	}

	switch .Mode {
	case CountOnlyValid, CountOnlyNull, CountAllRows:
	default:
		return , fmt.Errorf("%w: invalid count mode %d", arrow.ErrInvalid, .Mode)
	}
	return , nil
}

// ----------------------------------------------------------------------
// count

type countImpl struct {
	opts     CountOptions
	nulls    int64
	nonNulls int64
}

func ( *countImpl) ( *exec.ExecSpan) error {
	 := &.Values[0]
	switch {
	case .opts.Mode == CountAllRows:
		// ALL never has to look at the validity bitmap.
		.nonNulls += .Len
	case .IsArray():
		 := spanNullCount(&.Array)
		.nulls += 
		.nonNulls += .Array.Len - 
	case .Scalar.IsValid():
		.nonNulls += .Len
	default:
		.nulls += .Len
	}
	return nil
}

func ( *countImpl) ( aggState) error {
	,  := .(*countImpl)
	if ! {
		return fmt.Errorf("%w: cannot merge %T into a count state", arrow.ErrInvalid, )
	}
	.nulls += .nulls
	.nonNulls += .nonNulls
	return nil
}

func ( *countImpl) () (*exec.AggregateResult, error) {
	// ALL is equivalent to ONLY_VALID here because consume counted every
	// row as non-null rather than computing a null count it would not use.
	if .opts.Mode == CountOnlyNull {
		return exec.NewScalarResult(scalar.NewInt64Scalar(.nulls)), nil
	}
	return exec.NewScalarResult(scalar.NewInt64Scalar(.nonNulls)), nil
}

// CountInit is the exec.KernelInitFn for the count kernel.
func ( *exec.KernelCtx,  exec.KernelInitArgs) (exec.KernelState, error) {
	,  := resolveCountOptions(.Options)
	if  != nil {
		return nil, 
	}

	// The logical null count of these types is not the number of unset bits
	// in the validity bitmap of the top-level array, so counting them needs
	// machinery this kernel does not have yet.
	switch .Inputs[0].ID() {
	case arrow.RUN_END_ENCODED, arrow.DICTIONARY, arrow.SPARSE_UNION, arrow.DENSE_UNION:
		if .Mode != CountAllRows {
			return nil, fmt.Errorf("%w: count of %s requires a logical null count",
				arrow.ErrNotImplemented, .Inputs[0])
		}
	}

	return &countImpl{opts: }, nil
}

// ----------------------------------------------------------------------
// sum

// sumBase holds the parts of a sum state which do not depend on the type
// being summed: how many values were seen, whether any null was seen, and the
// options which turn the two into a null or a value at finalize time.
type sumBase struct {
	opts          ScalarAggregateOptions
	count         uint64
	nullsObserved bool
}

// observe folds the value and null counts of one span into the state. It
// returns the number of non-null values in the span and whether their values
// still have to be accumulated: once a null has been seen with SkipNulls
// false, the result is null whatever the values are.
func ( *sumBase) ( *exec.ExecSpan) ( int64,  bool) {
	 := &.Values[0]
	if .IsArray() {
		 := spanNullCount(&.Array)
		 = .Array.Len - 
		.nullsObserved = .nullsObserved ||  > 0
	} else if .Scalar.IsValid() {
		 = .Len
	} else {
		.nullsObserved = true
	}
	.count += uint64()
	return ,  > 0 && (.opts.SkipNulls || !.nullsObserved)
}

func ( *sumBase) ( *sumBase) {
	.count += .count
	.nullsObserved = .nullsObserved || .nullsObserved
}

// emitNull reports whether finalize has to produce a null rather than the
// accumulated value.
func ( *sumBase) () bool {
	return (!.opts.SkipNulls && .nullsObserved) || .count < uint64(.opts.MinCount)
}

// intSumImpl sums the signed integer types into an int64. Go defines the
// wrap-around, so an overflowing sum wraps rather than being undefined as it
// is in C++, but the value produced is the same one C++ produces in practice.
type intSumImpl[ int8 | int16 | int32 | int64] struct {
	sumBase
	sum int64
}

func ( *intSumImpl[]) ( *exec.ExecSpan) error {
	if ,  := .observe(); ! {
		return nil
	}
	 := &.Values[0]
	if .IsArray() {
		visitValues(&.Array, func( [], ,  int64) {
			for  := int64(0);  < ; ++ {
				.sum += int64([+])
			}
		})
	} else {
		.sum += int64(UnboxScalar[](.Scalar.(scalar.PrimitiveScalar))) * .Len
	}
	return nil
}

func ( *intSumImpl[]) ( aggState) error {
	,  := .(*intSumImpl[])
	if ! {
		return fmt.Errorf("%w: cannot merge %T into a sum state", arrow.ErrInvalid, )
	}
	.mergeBase(&.sumBase)
	.sum += .sum
	return nil
}

func ( *intSumImpl[]) () (*exec.AggregateResult, error) {
	if .emitNull() {
		return exec.NewScalarResult(scalar.MakeNullScalar(arrow.PrimitiveTypes.Int64)), nil
	}
	return exec.NewScalarResult(scalar.NewInt64Scalar(.sum)), nil
}

// uintSumImpl sums the unsigned integer types into a uint64.
type uintSumImpl[ uint8 | uint16 | uint32 | uint64] struct {
	sumBase
	sum uint64
}

func ( *uintSumImpl[]) ( *exec.ExecSpan) error {
	if ,  := .observe(); ! {
		return nil
	}
	 := &.Values[0]
	if .IsArray() {
		visitValues(&.Array, func( [], ,  int64) {
			for  := int64(0);  < ; ++ {
				.sum += uint64([+])
			}
		})
	} else {
		.sum += uint64(UnboxScalar[](.Scalar.(scalar.PrimitiveScalar))) * uint64(.Len)
	}
	return nil
}

func ( *uintSumImpl[]) ( aggState) error {
	,  := .(*uintSumImpl[])
	if ! {
		return fmt.Errorf("%w: cannot merge %T into a sum state", arrow.ErrInvalid, )
	}
	.mergeBase(&.sumBase)
	.sum += .sum
	return nil
}

func ( *uintSumImpl[]) () (*exec.AggregateResult, error) {
	if .emitNull() {
		return exec.NewScalarResult(scalar.MakeNullScalar(arrow.PrimitiveTypes.Uint64)), nil
	}
	return exec.NewScalarResult(scalar.NewUint64Scalar(.sum)), nil
}

// floatSumImpl sums the floating point types into a float64 using the same
// pairwise summation the C++ implementation uses, so that the result is the
// same one down to the last bit.
type floatSumImpl[ float32 | float64] struct {
	sumBase
	sum float64
}

func ( *floatSumImpl[]) ( *exec.ExecSpan) error {
	,  := .observe()
	if ! {
		return nil
	}
	 := &.Values[0]
	if .IsArray() {
		.sum += pairwiseSum[](&.Array, )
	} else {
		// C++ multiplies the unboxed value by the span length in the value's
		// own type before widening it to the accumulator.
		 := UnboxScalar[](.Scalar.(scalar.PrimitiveScalar))
		.sum += float64( * (.Len))
	}
	return nil
}

func ( *floatSumImpl[]) ( aggState) error {
	,  := .(*floatSumImpl[])
	if ! {
		return fmt.Errorf("%w: cannot merge %T into a sum state", arrow.ErrInvalid, )
	}
	.mergeBase(&.sumBase)
	.sum += .sum
	return nil
}

func ( *floatSumImpl[]) () (*exec.AggregateResult, error) {
	if .emitNull() {
		return exec.NewScalarResult(scalar.MakeNullScalar(arrow.PrimitiveTypes.Float64)), nil
	}
	return exec.NewScalarResult(scalar.NewFloat64Scalar(.sum)), nil
}

// boolSumImpl sums boolean input as the number of true values, into a uint64.
type boolSumImpl struct {
	sumBase
	sum uint64
}

func ( *boolSumImpl) ( *exec.ExecSpan) error {
	if ,  := .observe(); ! {
		return nil
	}
	 := &.Values[0]
	if .IsArray() {
		.sum += uint64(trueCount(&.Array))
	} else if .Scalar.(*scalar.Boolean).Value {
		.sum += uint64(.Len)
	}
	return nil
}

func ( *boolSumImpl) ( aggState) error {
	,  := .(*boolSumImpl)
	if ! {
		return fmt.Errorf("%w: cannot merge %T into a sum state", arrow.ErrInvalid, )
	}
	.mergeBase(&.sumBase)
	.sum += .sum
	return nil
}

func ( *boolSumImpl) () (*exec.AggregateResult, error) {
	if .emitNull() {
		return exec.NewScalarResult(scalar.MakeNullScalar(arrow.PrimitiveTypes.Uint64)), nil
	}
	return exec.NewScalarResult(scalar.NewUint64Scalar(.sum)), nil
}

// nullSumImpl sums null-typed input, whose every value is null, into an
// int64. It reproduces the C++ NullSumImpl: the only thing it has to track is
// whether anything at all was consumed.
type nullSumImpl struct {
	opts    ScalarAggregateOptions
	isEmpty bool
}

func ( *nullSumImpl) ( *exec.ExecSpan) error {
	 := &.Values[0]
	if .IsScalar() || spanNullCount(&.Array) > 0 {
		.isEmpty = false
	}
	return nil
}

func ( *nullSumImpl) ( aggState) error {
	,  := .(*nullSumImpl)
	if ! {
		return fmt.Errorf("%w: cannot merge %T into a sum state", arrow.ErrInvalid, )
	}
	.isEmpty = .isEmpty && .isEmpty
	return nil
}

func ( *nullSumImpl) () (*exec.AggregateResult, error) {
	if (.opts.SkipNulls || .isEmpty) && .opts.MinCount == 0 {
		return exec.NewScalarResult(scalar.NewInt64Scalar(0)), nil
	}
	return exec.NewScalarResult(scalar.MakeNullScalar(arrow.PrimitiveTypes.Int64)), nil
}

// SumInit is the exec.KernelInitFn for every kernel of the sum function; it
// picks the accumulator from the input type the way the C++ SumLikeInit
// visitor does.
func ( *exec.KernelCtx,  exec.KernelInitArgs) (exec.KernelState, error) {
	,  := resolveAggOptions(.Options)
	if  != nil {
		return nil, 
	}

	 := sumBase{opts: }
	switch .Inputs[0].ID() {
	case arrow.INT8:
		return &intSumImpl[int8]{sumBase: }, nil
	case arrow.INT16:
		return &intSumImpl[int16]{sumBase: }, nil
	case arrow.INT32:
		return &intSumImpl[int32]{sumBase: }, nil
	case arrow.INT64:
		return &intSumImpl[int64]{sumBase: }, nil
	case arrow.UINT8:
		return &uintSumImpl[uint8]{sumBase: }, nil
	case arrow.UINT16:
		return &uintSumImpl[uint16]{sumBase: }, nil
	case arrow.UINT32:
		return &uintSumImpl[uint32]{sumBase: }, nil
	case arrow.UINT64:
		return &uintSumImpl[uint64]{sumBase: }, nil
	case arrow.FLOAT32:
		return &floatSumImpl[float32]{sumBase: }, nil
	case arrow.FLOAT64:
		return &floatSumImpl[float64]{sumBase: }, nil
	case arrow.BOOL:
		return &boolSumImpl{sumBase: }, nil
	case arrow.NULL:
		return &nullSumImpl{opts: , isEmpty: true}, nil
	}
	return nil, fmt.Errorf("%w: no sum implemented for %s", arrow.ErrNotImplemented, .Inputs[0])
}

// ----------------------------------------------------------------------
// value iteration helpers

// visitValues calls fn once for every run of valid values in the span,
// passing the typed values of the span along with the position and length of
// the run relative to the start of the span.
func visitValues[ arrow.FixedWidthType]( *exec.ArraySpan,  func( [], ,  int64)) {
	 := exec.GetSpanValues[](, 1)
	bitutils.VisitSetBitRunsNoErr(.Buffers[0].Buf, .Offset, .Len, func(,  int64) {
		(, , )
	})
}

// trueCount returns the number of values in the boolean span which are both
// valid and true.
func trueCount( *exec.ArraySpan) int64 {
	 := .Buffers[1].Buf
	if len() == 0 {
		return 0
	}
	if len(.Buffers[0].Buf) == 0 {
		return int64(bitutil.CountSetBits(, int(.Offset), int(.Len)))
	}

	var  int64
	bitutils.VisitSetBitRunsNoErr(.Buffers[0].Buf, .Offset, .Len, func(,  int64) {
		 += int64(bitutil.CountSetBits(, int(.Offset+), int()))
	})
	return 
}

// pairwiseSum is a port of the non-recursive pairwise summation the C++
// implementation uses for floating point input, so that the two produce
// bit-for-bit identical results.
//
// https://en.wikipedia.org/wiki/Pairwise_summation
func pairwiseSum[ float32 | float64]( *exec.ArraySpan,  int64) float64 {
	if  == 0 {
		return 0
	}

	// number of inputs to accumulate before merging with another block
	const  = 16 // same as numpy
	// levels (tree depth) = ceil(log2(len)) + 1, a bit larger than necessary
	 := bits.Len64(uint64(-1)) + 1
	// temporary summation per level
	 := make([]float64, +1)
	// whether two summations are ready and should be reduced to the level
	// above; one bit per level, bit 0 is level 0, and so on
	var  uint64
	// level of the root node holding the final summation
	var  int

	// reduce the summation of one block (which may be smaller than blockSize)
	// from a leaf node, continuing to the level above whenever two summations
	// are ready for a non-leaf node
	 := func( float64) {
		,  := 0, uint64(1)
		[] += 
		 ^= 
		for & == 0 {
			 = []
			[] = 0
			++
			 <<= 1
			[] += 
			 ^= 
		}
		if  >  {
			 = 
		}
	}

	visitValues[](, func( [], ,  int64) {
		 := [:]
		,  := /, %
		for  := int64(0);  < ; ++ {
			var  float64
			for  := 0;  < ; ++ {
				 += float64([])
			}
			()
			 = [:]
		}
		if  > 0 {
			var  float64
			for  := int64(0);  < ; ++ {
				 += float64([])
			}
			()
		}
	})

	// reduce the intermediate summations from all of the non-leaf nodes
	for  := 1;  <= ; ++ {
		[] += [-1]
	}
	return []
}