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

import (
	
	

	
	
	
	
	
	
	
	
	
)

// VariantGetOptions controls VariantGet.
type VariantGetOptions struct {
	// Path is the path to extract from every variant value.
	Path variant.VariantPath
	// AsType, when nil, makes VariantGet return a VariantArray pointing at the path;
	// when set, the extracted values are cast to it via the cast kernels.
	AsType arrow.DataType
	// Strict makes a lossy cast fail; otherwise a value that cannot convert to AsType
	// nulls only that row, not the rest of its natural-type group.
	Strict bool
}

// VariantGet extracts opts.Path from every value of input. It follows the shredded
// typed_value columns as far as the path allows - stepping into struct fields
// directly and gathering list elements with the take kernel - then reassembles only
// the residual for any remaining path. With AsType nil it returns a VariantArray of
// the extracted values; otherwise it casts them to AsType with the cast kernels.
func ( context.Context,  *extensions.VariantArray,  VariantGetOptions) (arrow.Array, error) {
	if  == nil {
		return nil, fmt.Errorf("%w: VariantGet requires a non-nil VariantArray", arrow.ErrInvalid)
	}

	// Reject nested target storage. Unwrap extension types first: they embed
	// ExtensionBase and so satisfy arrow.NestedType even when backed by e.g. UUID.
	 := .AsType
	if ,  := .(arrow.ExtensionType);  {
		 = .StorageType()
	}
	if ,  := .(arrow.NestedType);  {
		return nil, fmt.Errorf("%w: VariantGet cast to nested type %s", arrow.ErrNotImplemented, .AsType)
	}

	// Empty path, no cast: the values are returned unchanged.
	if .Path.Len() == 0 && .AsType == nil {
		.Retain()

		return , nil
	}

	return shreddedGetPath(, , )
}

// shreddingState is a (value?, typed_value?) column pair at one level of a shredded
// variant, mirroring arrow-rs ShreddingState.
type shreddingState struct {
	value      arrow.TypedArray[[]byte]
	typedValue arrow.Array
	length     int
}

func stateFromInput( *extensions.VariantArray) shreddingState {
	return shreddingState{
		value:      .UntypedValues(),
		typedValue: .Shredded(),
		length:     .Len(),
	}
}

func stateFromFieldStruct( *array.Struct) shreddingState {
	 := .DataType().(*arrow.StructType)

	var  arrow.TypedArray[[]byte]
	if ,  := .FieldIdx("value");  {
		 = .Field().(arrow.TypedArray[[]byte])
	}

	var  arrow.Array
	if ,  := .FieldIdx("typed_value");  {
		 = .Field()
	}

	return shreddingState{value: , typedValue: , length: .Len()}
}

type pathStepKind int

const (
	stepSuccess pathStepKind = iota
	stepMissing
)

type pathStep struct {
	kind  pathStepKind
	state shreddingState
	owned []arrow.Array // intermediate take results the caller must release
}

// missingStep marks a path step whose typed field is absent. The descent loop breaks
// on any residual before stepping, so a step that reaches here is provably missing.
func ( shreddingState) () pathStep {
	return pathStep{kind: stepMissing}
}

// hasResidual reports whether any row carries a value in this level's value column.
func ( shreddingState) () bool {
	return .value != nil && .value.NullN() != .value.Len()
}

func fieldStep( shreddingState,  string) (pathStep, error) {
	if .typedValue == nil {
		return .missingStep(), nil
	}
	,  := .typedValue.(*array.Struct)
	if ! {
		// A field step into a non-object shredded value is a type error, matching the
		// per-row GetByPath path. Any residual was already diverted before this runs.
		return pathStep{}, fmt.Errorf("%w: variant path field %q applied to non-object %s",
			arrow.ErrInvalid, , .typedValue.DataType())
	}
	,  := .DataType().(*arrow.StructType).FieldIdx()
	if ! {
		return .missingStep(), nil
	}
	,  := .Field().(*array.Struct)
	if ! {
		return pathStep{}, fmt.Errorf("%w: expected struct field %q while following path, got %s",
			arrow.ErrInvalid, , .Field().DataType())
	}

	return pathStep{kind: stepSuccess, state: stateFromFieldStruct()}, nil
}

// indexStep gathers element index from every row of a shredded list with the take
// kernel, producing the shredding state one level deeper.
func indexStep( context.Context,  memory.Allocator,  shreddingState,  int) (pathStep, error) {
	if .typedValue == nil {
		return .missingStep(), nil
	}
	,  := .typedValue.(array.ListLike)
	if ! {
		return .missingStep(), nil
	}
	,  := .ListValues().(*array.Struct)
	if ! {
		return .missingStep(), nil
	}

	 := array.NewUint64Builder()
	defer .Release()
	.Reserve(.length)
	for  := 0;  < .length; ++ {
		,  := .ValueOffsets()
		if .IsValid() &&  >= 0 && int64() < - {
			.Append(uint64( + int64()))
		} else {
			.AppendNull()
		}
	}
	 := .NewArray()
	defer .Release()

	 := .DataType().(*arrow.StructType)
	var  []arrow.Array
	var  shreddingState
	.length = .length

	if ,  := .FieldIdx("value");  {
		,  := TakeArray(, .Field(), )
		if  != nil {
			return pathStep{}, 
		}
		 = append(, )
		.value = .(arrow.TypedArray[[]byte])
	}
	if ,  := .FieldIdx("typed_value");  {
		,  := TakeArray(, .Field(), )
		if  != nil {
			releaseAll()

			return pathStep{}, 
		}
		 = append(, )
		.typedValue = 
	}

	return pathStep{kind: stepSuccess, state: , owned: }, nil
}

func releaseAll( []arrow.Array) {
	for ,  := range  {
		.Release()
	}
}

func shreddedGetPath( context.Context,  *extensions.VariantArray,  VariantGetOptions) (arrow.Array, error) {
	 := GetAllocator()
	 := stateFromInput()
	 := newNullTracker(.Len(), )
	defer .release()
	.merge(.Storage())

	var  []arrow.Array
	defer func() { releaseAll() }()

	 := 0
	for  < .Path.Len() {
		// residual-backed rows live in the value column, unreachable by the typed_value descent; reassemble per-row.
		if .hasResidual() {
			break
		}

		, ,  := .Path.StepAt()
		var (
			 pathStep
			  error
		)
		if  {
			,  = fieldStep(, )
		} else {
			,  = indexStep(, , , )
		}
		if  != nil {
			return nil, 
		}

		if .kind == stepSuccess {
			.merge(.typedValue)
			 = .state
			 = append(, .owned...)
			++

			continue
		}

		// stepMissing: the typed field is provably absent (no residual, checked above).
		return allNullResult(, .Len(), .AsType), nil
	}

	 := subPath(.Path, )

	// Try to return the typed column directly before building the target array,
	// so a perfect shredding does not allocate a struct and bitmap it discards.
	if .Len() == 0 && .AsType != nil {
		if  := perfectShredded(, , .AsType);  != nil {
			defer .Release()

			return CastArray(, , NewCastOptions(.AsType, .Strict))
		}
	}

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

	if .Len() == 0 && .AsType == nil {
		.Retain()

		return , nil
	}

	,  := extractLeaves(, )
	if  != nil {
		return nil, 
	}
	if .AsType == nil {
		return buildLeafVariantArray(, ), nil
	}

	return castLeaves(, , , .AsType, .Strict)
}

// perfectShredded returns the typed_value column when the path landed on a fully
// shredded value of exactly AsType and no ancestor nulls need merging; otherwise
// the caller's reassembly path produces the same values.
func perfectShredded( shreddingState,  *nullTracker,  arrow.DataType) arrow.Array {
	if .typedValue == nil || !.allValid() {
		return nil
	}
	if !arrow.TypeEqual(.typedValue.DataType(), ) {
		return nil
	}
	if .value != nil && .value.NullN() != .value.Len() {
		return nil
	}

	.typedValue.Retain()

	return .typedValue
}

func buildTargetVariant( *extensions.VariantArray,  shreddingState,  *nullTracker,  memory.Allocator) (*extensions.VariantArray, error) {
	// Read the raw metadata column rather than input.Metadata(), which asserts plain
	// binary and panics on dictionary-encoded metadata; the raw column preserves
	// dictionary/large-binary encoding and is decoded by the target's own reader.
	 := .Storage().(*array.Struct)
	,  := .DataType().(*arrow.StructType).FieldIdx("metadata")
	if ! {
		return nil, fmt.Errorf("%w: variant storage is missing its metadata field", arrow.ErrInvalid)
	}
	 := .Field()

	 := []arrow.Field{{Name: "metadata", Type: .DataType(), Nullable: false}}
	 := []arrow.Array{}
	if .value != nil {
		 = append(, arrow.Field{Name: "value", Type: .value.DataType(), Nullable: true})
		 = append(, .value)
	}
	if .typedValue != nil {
		 = append(, arrow.Field{Name: "typed_value", Type: .typedValue.DataType(), Nullable: true})
		 = append(, .typedValue)
	}

	,  := .validityBitmap()
	,  := array.NewStructArrayWithFieldsAndNulls(, , , , 0)
	if  != nil {
		return nil, 
	}
	defer .Release()

	,  := extensions.NewVariantType(.DataType())
	if  != nil {
		return nil, 
	}

	return array.NewExtensionArrayWithStorage(, ).(*extensions.VariantArray), nil
}

// subPath returns the suffix of p starting at from, rebuilt through the opaque API.
func subPath( variant.VariantPath,  int) variant.VariantPath {
	var  variant.VariantPath
	for  := ;  < .Len(); ++ {
		if , ,  := .StepAt();  {
			 = .Field()
		} else {
			 = .Index()
		}
	}

	return 
}

// variantLeaf is one row's extracted value; present is false when the path is
// absent for that row (or the row is null).
type variantLeaf struct {
	value   variant.Value
	present bool
}

func extractLeaves( *extensions.VariantArray,  variant.VariantPath) ([]variantLeaf, error) {
	 := make([]variantLeaf, .Len())
	for  := range  {
		if .IsNull() {
			continue
		}
		,  := .Value()
		if  != nil {
			return nil, fmt.Errorf("variant: reassembling row %d: %w", , )
		}
		, ,  := .GetByPath()
		if  != nil {
			return nil, 
		}
		[] = variantLeaf{value: , present: }
	}

	return , nil
}

func buildLeafVariantArray( memory.Allocator,  []variantLeaf) arrow.Array {
	 := extensions.NewVariantBuilder(, extensions.NewDefaultVariantType())
	defer .Release()
	.Reserve(len())
	for ,  := range  {
		if !.present {
			.AppendNull()

			continue
		}
		.Append(.value)
	}

	return .NewArray()
}

// castLeaves converts each leaf to asType (arrow-rs variant_get parity): leaves are
// grouped by natural type, each group cast with the cast kernels, then scattered back
// so the result is order-independent. Strict errors on a lossy cast, else null.
func castLeaves( context.Context,  memory.Allocator,  []variantLeaf,  arrow.DataType,  bool) (arrow.Array, error) {
	type  struct {
		   arrow.DataType
		 []int
	}
	 := make(map[string]*)
	var  []string
	for ,  := range  {
		if !.present || .value.Type() == variant.Null {
			continue
		}
		 := naturalArrowType(.value)
		if  == nil {
			// Object/array leaves have no primitive natural type. Under Strict this is an
			// impossible cast (errors like any other); otherwise the row stays null.
			if  {
				return nil, fmt.Errorf("%w: cannot cast non-primitive variant leaf to %s", arrow.ErrInvalid, )
			}

			continue
		}
		 := .String()
		 := []
		if  == nil {
			 = &{: }
			[] = 
			 = append(, )
		}
		. = append(., )
	}

	 := make([]uint64, len())
	 := make([]bool, len())
	var  []arrow.Array
	defer func() { releaseAll() }()

	var  uint64
	for ,  := range  {
		 := []
		 := buildTypedColumn(, ., , .)
		,  := CastArray(, , NewCastOptions(, ))
		.Release()
		if  == nil {
			 = append(, )
			for ,  := range . {
				[] = 
				[] = true
				++
			}

			continue
		}
		if  {
			return nil, 
		}
		// Non-strict: retry each row alone so only the inconvertible rows null, not the whole group.
		for ,  := range . {
			 := buildTypedColumn(, ., , []int{})
			,  := CastArray(, , NewCastOptions(, ))
			.Release()
			if  != nil {
				continue // this row alone is inconvertible; it stays null
			}
			 = append(, )
			[] = 
			[] = true
			++
		}
	}

	if len() == 0 {
		return allNullResult(, len(), ), nil
	}

	// One natural type covering every row already sits in original order.
	if len() == 1 &&  == uint64(len()) {
		[0].Retain()

		return [0], nil
	}

	,  := array.Concatenate(, )
	if  != nil {
		return nil, 
	}
	defer .Release()

	 := array.NewUint64Builder()
	defer .Release()
	.AppendValues(, )
	 := .NewArray()
	defer .Release()

	return TakeArray(, , )
}

// buildTypedColumn materializes the given leaf rows, all of natural type dt, into a
// homogeneous Arrow array the cast kernels can consume.
func buildTypedColumn( memory.Allocator,  arrow.DataType,  []variantLeaf,  []int) arrow.Array {
	 := array.NewBuilder(, )
	defer .Release()
	.Reserve(len())
	for ,  := range  {
		if !appendNatural(, [].value) {
			.AppendNull()
		}
	}

	return .NewArray()
}

// allNullResult builds the all-null output for a provably missing path.
func allNullResult( memory.Allocator,  int,  arrow.DataType) arrow.Array {
	if  != nil {
		return array.MakeArrayOfNull(, , )
	}

	// MakeArrayOfNull cannot build the variant extension type (its storage struct's
	// metadata/value are non-nullable), so append encoded variant nulls instead.
	 := extensions.NewVariantBuilder(, extensions.NewDefaultVariantType())
	defer .Release()
	for range  {
		.AppendNull()
	}

	return .NewArray()
}

// nullTracker accumulates ancestor validity bitmaps with a bitmap AND.
type nullTracker struct {
	length int
	mem    memory.Allocator
	buf    *memory.Buffer // validity bitmap (1 = valid); nil means all valid
}

func newNullTracker( int,  memory.Allocator) *nullTracker {
	return &nullTracker{length: , mem: }
}

// merge folds arr's validity into the accumulated mask. Arrow validity bits are
// 1=valid, so accumulating ancestor nulls is a bitmap AND (a row is null in the
// result when it is null at any level) - the validity-space equivalent of OR-ing
// null masks.
func ( *nullTracker) ( arrow.Array) {
	if  == nil {
		return
	}
	 := .Data().Buffers()[0]
	if  == nil {
		return // all valid
	}
	 := int64(.Data().Offset())
	if .buf == nil {
		.buf = bitutil.BitmapAndAlloc(.mem, .Bytes(), .Bytes(), , , int64(.length), 0)

		return
	}
	 := bitutil.BitmapAndAlloc(.mem, .buf.Bytes(), .Bytes(), 0, , int64(.length), 0)
	.buf.Release()
	.buf = 
}

func ( *nullTracker) () bool { return .buf == nil }

func ( *nullTracker) () (*memory.Buffer, int) {
	if .buf == nil {
		return nil, 0
	}

	return .buf, .length - bitutil.CountSetBits(.buf.Bytes(), 0, .length)
}

func ( *nullTracker) () {
	if .buf != nil {
		.buf.Release()
		.buf = nil
	}
}

func naturalArrowType( variant.Value) arrow.DataType {
	switch .Type() {
	case variant.Bool:
		return arrow.FixedWidthTypes.Boolean
	case variant.Int8:
		return arrow.PrimitiveTypes.Int8
	case variant.Int16:
		return arrow.PrimitiveTypes.Int16
	case variant.Int32:
		return arrow.PrimitiveTypes.Int32
	case variant.Int64:
		return arrow.PrimitiveTypes.Int64
	case variant.Float:
		return arrow.PrimitiveTypes.Float32
	case variant.Double:
		return arrow.PrimitiveTypes.Float64
	case variant.String:
		return arrow.BinaryTypes.String
	case variant.Binary:
		return arrow.BinaryTypes.Binary
	case variant.Date:
		return arrow.FixedWidthTypes.Date32
	case variant.Time:
		return arrow.FixedWidthTypes.Time64us
	case variant.TimestampMicros:
		return &arrow.TimestampType{Unit: arrow.Microsecond, TimeZone: "UTC"}
	case variant.TimestampMicrosNTZ:
		return &arrow.TimestampType{Unit: arrow.Microsecond}
	case variant.TimestampNanos:
		return &arrow.TimestampType{Unit: arrow.Nanosecond, TimeZone: "UTC"}
	case variant.TimestampNanosNTZ:
		return &arrow.TimestampType{Unit: arrow.Nanosecond}
	case variant.UUID:
		return extensions.NewUUIDType()
	case variant.Decimal4, variant.Decimal8, variant.Decimal16:
		return &arrow.Decimal128Type{Precision: 38, Scale: int32(decimalScale())}
	}

	return nil
}

// appendNatural appends v to bldr when v's value matches bldr's element type,
// reporting whether it did; callers group leaves by natural type first, so it matches.
func appendNatural( array.Builder,  variant.Value) bool {
	switch b := .(type) {
	case *array.BooleanBuilder:
		if ,  := .Value().(bool);  {
			.Append()

			return true
		}
	case *array.Int8Builder:
		if ,  := .Value().(int8);  {
			.Append()

			return true
		}
	case *array.Int16Builder:
		if ,  := .Value().(int16);  {
			.Append()

			return true
		}
	case *array.Int32Builder:
		if ,  := .Value().(int32);  {
			.Append()

			return true
		}
	case *array.Int64Builder:
		if ,  := .Value().(int64);  {
			.Append()

			return true
		}
	case *array.Float32Builder:
		if ,  := .Value().(float32);  {
			.Append()

			return true
		}
	case *array.Float64Builder:
		if ,  := .Value().(float64);  {
			.Append()

			return true
		}
	case *array.StringBuilder:
		if ,  := .Value().(string);  {
			.Append()

			return true
		}
	case *array.BinaryBuilder:
		if ,  := .Value().([]byte);  {
			.Append()

			return true
		}
	case *array.Date32Builder:
		if ,  := .Value().(arrow.Date32);  {
			.Append()

			return true
		}
	case *array.Time64Builder:
		if ,  := .Value().(arrow.Time64);  {
			.Append()

			return true
		}
	case *array.TimestampBuilder:
		if ,  := .Value().(arrow.Timestamp);  {
			.Append()

			return true
		}
	case *extensions.UUIDBuilder:
		if ,  := .Value().(uuid.UUID);  {
			.Append()

			return true
		}
	case *array.Decimal128Builder:
		if ,  := decimalAsNum128();  && int32(decimalScale()) == .Type().(*arrow.Decimal128Type).Scale {
			.Append()

			return true
		}
	}

	return false
}

func decimalScale( variant.Value) uint8 {
	switch d := .Value().(type) {
	case variant.DecimalValue[decimal.Decimal32]:
		return .Scale
	case variant.DecimalValue[decimal.Decimal64]:
		return .Scale
	case variant.DecimalValue[decimal.Decimal128]:
		return .Scale
	}

	return 0
}

func decimalAsNum128( variant.Value) (decimal128.Num, bool) {
	switch d := .Value().(type) {
	case variant.DecimalValue[decimal.Decimal32]:
		return decimal128.FromI64(int64(.Value.(decimal.Decimal32))), true
	case variant.DecimalValue[decimal.Decimal64]:
		return decimal128.FromI64(int64(.Value.(decimal.Decimal64))), true
	case variant.DecimalValue[decimal.Decimal128]:
		return .Value.(decimal.Decimal128), true
	}

	return decimal128.Num{}, false
}