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

import (
	
	
	
	
	
	
	

	
	
	
	
)

// TimestampWithOffsetType represents a timestamp column that stores a timezone offset per row instead of
// applying the same timezone offset to the entire column.
type TimestampWithOffsetType struct {
	arrow.ExtensionBase
}

func isOffsetTypeOk( arrow.DataType) bool {
	switch offsetType := .(type) {
	case *arrow.Int16Type:
		return true
	case *arrow.DictionaryType:
		return arrow.TypeEqual(.ValueType, arrow.PrimitiveTypes.Int16)
	case *arrow.RunEndEncodedType:
		return !.ValueNullable &&
			.ValidRunEndsType(.RunEnds()) &&
			arrow.TypeEqual(.Encoded(), arrow.PrimitiveTypes.Int16)
	default:
		return false
	}
}

// Whether the storageType is compatible with TimestampWithOffset.
//
// Returns (time_unit, offset_type, ok). If ok is false, time_unit and offset_type are garbage.
func isDataTypeCompatible( arrow.DataType) ( arrow.TimeUnit,  arrow.DataType,  bool) {
	 = arrow.Second
	 = arrow.PrimitiveTypes.Int16
	 = false

	,  := .(*arrow.StructType)
	if ! || .NumFields() != 2 {
		return
	}

	if ,  := .Field(0).Type.(*arrow.TimestampType);  && .TimeZone == "UTC" {
		 = .TimeUnit()
	} else {
		return
	}

	 := .Field(1)
	 = .Type

	 = .Field(0).Name == "timestamp" &&
		!.Field(0).Nullable &&
		.Name == "offset_minutes" &&
		isOffsetTypeOk() &&
		!.Nullable
	return
}

// NewTimestampWithOffsetType creates a new TimestampWithOffsetType with the underlying storage type set correctly to
// Struct(timestamp=Timestamp(T, "UTC"), offset_minutes=Int16), where T is any TimeUnit.
func ( arrow.TimeUnit) *TimestampWithOffsetType {
	,  := NewTimestampWithOffsetTypeCustomOffset(, arrow.PrimitiveTypes.Int16)
	// SAFETY: This should never error as Int16 is always a valid offset type

	return 
}

// NewTimestampWithOffsetTypeCustomOffset creates a new TimestampWithOffsetType with the underlying storage type set correctly to
// Struct(timestamp=Timestamp(T, "UTC"), offset_minutes=O), where T is any TimeUnit and O is a valid offset type.
//
// The error will be populated if the data type is not a valid encoding of the offsets field.
func ( arrow.TimeUnit,  arrow.DataType) (*TimestampWithOffsetType, error) {
	if !isOffsetTypeOk() {
		return nil, fmt.Errorf("invalid offset type %s", )
	}

	return &TimestampWithOffsetType{
		ExtensionBase: arrow.ExtensionBase{
			Storage: arrow.StructOf(
				arrow.Field{
					Name: "timestamp",
					Type: &arrow.TimestampType{
						Unit:     ,
						TimeZone: "UTC",
					},
					Nullable: false,
				},
				arrow.Field{
					Name:     "offset_minutes",
					Type:     ,
					Nullable: false,
				},
			),
		},
	}, nil
}

type DictIndexType interface {
	*arrow.Int8Type | *arrow.Int16Type | *arrow.Int32Type | *arrow.Int64Type |
		*arrow.Uint8Type | *arrow.Uint16Type | *arrow.Uint32Type | *arrow.Uint64Type
}

type RunEndsType interface {
	*arrow.Int16Type | *arrow.Int32Type | *arrow.Int64Type
}

// NewTimestampWithOffsetTypeDictionaryEncoded creates a new TimestampWithOffsetType with the underlying storage type set correctly to
// Struct(timestamp=Timestamp(T, "UTC"), offset_minutes=Dictionary(I, Int16)), where T is any TimeUnit and I is a
// valid Dictionary index type.
func [ DictIndexType]( arrow.TimeUnit,  ) *TimestampWithOffsetType {
	 := arrow.DictionaryType{
		IndexType: arrow.DataType(),
		ValueType: arrow.PrimitiveTypes.Int16,
		Ordered:   false,
	}
	,  := NewTimestampWithOffsetTypeCustomOffset(, &)
	// SAFETY: This should never error as DictIndexType is always a valid index type

	return 
}

// NewTimestampWithOffsetTypeRunEndEncoded creates a new TimestampWithOffsetType with the underlying storage type set correctly to
// Struct(timestamp=Timestamp(T, "UTC"), offset_minutes=RunEndEncoded(E, Int16)), where T is any TimeUnit and E is a
// valid run-ends type.
func [ RunEndsType]( arrow.TimeUnit,  ) *TimestampWithOffsetType {
	 := arrow.RunEndEncodedOf(arrow.DataType(), arrow.PrimitiveTypes.Int16)
	.ValueNullable = false

	,  := NewTimestampWithOffsetTypeCustomOffset(, )
	// SAFETY: This should never error as RunEndsType always a valid run ends type

	return 

}

func ( *TimestampWithOffsetType) () reflect.Type {
	return reflect.TypeOf(TimestampWithOffsetArray{})
}

func ( *TimestampWithOffsetType) () string { return "arrow.timestamp_with_offset" }

func ( *TimestampWithOffsetType) () string {
	return fmt.Sprintf("extension<%s>", .ExtensionName())
}

func ( *TimestampWithOffsetType) () ([]byte, error) {
	return []byte(fmt.Sprintf(`{"name":"%s","metadata":%s}`, .ExtensionName(), .Serialize())), nil
}

func ( *TimestampWithOffsetType) () string { return "" }

func ( *TimestampWithOffsetType) ( arrow.DataType,  string) (arrow.ExtensionType, error) {
	if  != "" &&  != "{}" {
		return nil, fmt.Errorf("serialized metadata for TimestampWithOffset extension type must be '' or '{}', found: %s", )
	}

	, ,  := isDataTypeCompatible()
	if ! {
		return nil, fmt.Errorf("invalid storage type for TimestampWithOffsetType: %s", .Name())
	}

	return NewTimestampWithOffsetTypeCustomOffset(, )
}

func ( *TimestampWithOffsetType) ( arrow.ExtensionType) bool {
	return .ExtensionName() == .ExtensionName() &&
		arrow.TypeEqual(.StorageType(), .StorageType())
}

func ( *TimestampWithOffsetType) () arrow.DataType {
	return .ExtensionBase.Storage.(*arrow.StructType).Field(1).Type
}

func ( *TimestampWithOffsetType) () arrow.TimeUnit {
	return .ExtensionBase.Storage.(*arrow.StructType).Field(0).Type.(*arrow.TimestampType).TimeUnit()
}

func ( *TimestampWithOffsetType) ( memory.Allocator) array.Builder {
	,  := NewTimestampWithOffsetBuilder(, .TimeUnit(), .OffsetType())
	return 
}

// TimestampWithOffsetArray is a simple array of struct
type TimestampWithOffsetArray struct {
	array.ExtensionArrayBase
}

func ( *TimestampWithOffsetArray) () string {
	var  strings.Builder
	.WriteString("[")
	for  := 0;  < .Len(); ++ {
		if  > 0 {
			.WriteString(" ")
		}
		switch {
		case .IsNull():
			.WriteString(array.NullValueStr)
		default:
			fmt.Fprintf(&, "\"%s\"", .Value())
		}
	}
	.WriteString("]")
	return .String()
}

func timeFromFieldValues( arrow.Timestamp,  int16,  arrow.TimeUnit) time.Time {
	// Derive the sign from the whole offset: integer hours is 0 for any offset
	// with magnitude below one hour and so cannot carry a negative sign (e.g.
	// -30 minutes must format as "UTC-00:30", not "UTC+00:30").
	 := "+"
	 := int()
	if  < 0 {
		 = "-"
		 = -
	}

	 := fmt.Sprintf("UTC%s%02d:%02d", , /60, %60)
	 := time.FixedZone(, int()*60)
	return .ToTime().In()
}

func fieldValuesFromTime( time.Time,  arrow.TimeUnit) (arrow.Timestamp, int16) {
	,  := .Zone()
	 := int16( / 60)
	,  := arrow.TimestampFromTime(.UTC(), )
	return , 
}

// Get the raw arrow values at the given index
//
// SAFETY: the value at i must not be nil
func ( *TimestampWithOffsetArray) ( int) (arrow.Timestamp, int16, arrow.TimeUnit) {
	 := .Storage().(*array.Struct)

	 := .Field(0)
	 := .(*array.Timestamp)

	 := .DataType().(*arrow.TimestampType).Unit
	 := .Value()

	var  int16

	switch offsets := .Field(1).(type) {
	case *array.Int16:
		 = .Value()
	case *array.Dictionary:
		 = .Dictionary().(*array.Int16).Value(.GetValueIndex())
	case *array.RunEndEncoded:
		 = .Values().(*array.Int16).Value(.GetPhysicalIndex())
	}

	return , , 
}

func ( *TimestampWithOffsetArray) ( int) time.Time {
	if .IsNull() {
		return time.Time{}
	}
	, ,  := .rawValueUnsafe()
	return timeFromFieldValues(, , )
}

// Iterates over the array returning the timestamp at each position.
//
// The second parameter indicates whether the timestamp is valid or not.
//
// This will iterate using the fastest method given the underlying storage array
func ( *TimestampWithOffsetArray) () iter.Seq2[time.Time, bool] {
	return func( func(time.Time, bool) bool) {
		 := .Storage().(*array.Struct)
		 := .Field(1)
		if ,  := .(*array.RunEndEncoded);  {
			 := .Field(0)
			 := .DataType().(*arrow.TimestampType).Unit
			 := .(*array.Timestamp)

			 := .Values().(*array.Int16)
			// Run-ends are absolute over the unsliced offsets child, so a sliced
			// array must begin at the physical run covering its logical offset and
			// advance using absolute positions (logicalOffset + i).
			 := .Offset()
			 := .GetPhysicalOffset()

			var  (func(int) int)
			switch arr := .RunEndsArr().(type) {
			case *array.Int16:
				 = func( int) int { return int(.Value()) }
			case *array.Int32:
				 = func( int) int { return int(.Value()) }
			case *array.Int64:
				 = func( int) int { return int(.Value()) }
			}

			for  := 0;  < .Len(); ++ {
				if + >= () {
					 += 1
				}

				var  time.Time
				 := .IsValid()
				if  {
					 := .Value()
					 := .Value()
					 := timeFromFieldValues(, , )
					 = 
				}

				if !(, ) {
					return
				}
			}
		} else {
			for  := 0;  < .Len(); ++ {
				var  time.Time
				 := .IsValid()
				if  {
					, ,  := .rawValueUnsafe()
					 := timeFromFieldValues(, , )
					 = 
				}

				if !(, ) {
					return
				}
			}
		}
	}
}

func ( *TimestampWithOffsetArray) () []time.Time {
	return slices.Collect(func( func(time.Time) bool) {
		for  := range .iterValues() {
			if !() {
				return
			}
		}
	})
}

func ( *TimestampWithOffsetArray) ( int) string {
	switch {
	case .IsNull():
		return array.NullValueStr
	default:
		return .Value().String()
	}
}

func ( *TimestampWithOffsetArray) () ([]byte, error) {
	 := make([]interface{}, .Len())
	 := 0
	for ,  := range .iterValues() {
		if ! {
			[] = nil
		} else {
			[] = 
		}
		 += 1
	}
	return json.Marshal()
}

func ( *TimestampWithOffsetArray) ( int) interface{} {
	if .IsNull() {
		return nil
	}
	return .Value()
}

func ( *TimestampWithOffsetArray) ( int) any {
	if .IsNull() {
		return nil
	}
	return .Value()
}

// noLastOffset is the sentinel value for TimestampWithOffsetBuilder.lastOffset
// indicating that no run-end-encoded run has been started yet. It is deliberately
// outside the range of valid timezone offsets in minutes (roughly [-720, 840]) so
// it can never compare equal to a real offset.
const noLastOffset int16 = math.MaxInt16

// TimestampWithOffsetBuilder is a convenience builder for the TimestampWithOffset extension type,
// allowing arrays to be built with boolean values rather than the underlying storage type.
type TimestampWithOffsetBuilder struct {
	*array.ExtensionBuilder

	// The layout used to parse any timestamps from strings. Defaults to time.RFC3339
	Layout     string
	unit       arrow.TimeUnit
	offsetType arrow.DataType
	// lastOffset tracks the offset of the current run when the offsets are run-end
	// encoded, so we know when to start a new run. It is initialized to noLastOffset
	// to signal that no run has been started yet.
	lastOffset int16
}

// NewTimestampWithOffsetBuilder creates a new TimestampWithOffsetBuilder, exposing a convenient and efficient interface
// for writing time.Time values to the underlying storage array.
func ( memory.Allocator,  arrow.TimeUnit,  arrow.DataType) (*TimestampWithOffsetBuilder, error) {
	,  := NewTimestampWithOffsetTypeCustomOffset(, )
	if  != nil {
		return nil, 
	}

	return &TimestampWithOffsetBuilder{
		unit:             ,
		offsetType:       ,
		lastOffset:       noLastOffset,
		Layout:           time.RFC3339,
		ExtensionBuilder: array.NewExtensionBuilder(, ),
	}, nil
}

// NewArray must route through this type's NewExtensionArray (not the embedded
// ExtensionBuilder's) so that the run-end-encoding tracker is reset on reuse.
func ( *TimestampWithOffsetBuilder) () arrow.Array {
	return .NewExtensionArray()
}

type timestampWithOffsetCheckpoint struct {
	builder    *TimestampWithOffsetBuilder
	lastOffset int16
}

func ( *timestampWithOffsetCheckpoint) () {
	.lastOffset = .builder.lastOffset
}

func ( *timestampWithOffsetCheckpoint) () {
	.builder.lastOffset = .lastOffset
}

// NewCheckpoint returns a checkpoint for the builder's run-end offset state.
func ( *TimestampWithOffsetBuilder) () array.CheckpointState {
	return &timestampWithOffsetCheckpoint{builder: }
}

// NewExtensionArray finalizes the current array and resets lastOffset so a
// reused builder starts a fresh run instead of continuing a run that belonged
// to the array just finalized (the underlying REE builder is reset too).
func ( *TimestampWithOffsetBuilder) () array.ExtensionArray {
	 := .ExtensionBuilder.NewExtensionArray()
	.lastOffset = noLastOffset
	return 
}

// AppendNull resets the run-end-encoding tracker: the embedded struct builder
// appends a null offset run, so a following value must start a new run instead
// of continuing the null run.
//
// NOTE(#918): this writes a null into the non-nullable offset_minutes storage
// field rather than a default value. This is intentional; comparison and JSON
// round-trip parity for non-nullable inner struct fields is tracked separately
// in https://github.com/apache/arrow-go/issues/918. Logical values (instant,
// offset, validity) are preserved, but a full array.RecordEqual round-trip is
// not guaranteed here.
func ( *TimestampWithOffsetBuilder) () {
	.ExtensionBuilder.AppendNull()
	.lastOffset = noLastOffset
}

func ( *TimestampWithOffsetBuilder) ( int) {
	.ExtensionBuilder.AppendNulls()
	.lastOffset = noLastOffset
}

func ( *TimestampWithOffsetBuilder) ( time.Time) {
	,  := fieldValuesFromTime(, .unit)
	 := int16()
	 := .Builder.(*array.StructBuilder)

	.Append(true)
	.FieldBuilder(0).(*array.TimestampBuilder).Append()

	switch offsets := .FieldBuilder(1).(type) {
	case *array.Int16Builder:
		.Append()
	case *array.Int16DictionaryBuilder:
		.Append()
	case *array.RunEndEncodedBuilder:
		if  != .lastOffset {
			.Append(1)
			.ValueBuilder().(*array.Int16Builder).Append()
		} else {
			.ContinueRun(1)
		}

		.lastOffset = 
	}

}

// By default, this will try to parse the string using the RFC3339 layout.
//
// You can change the default layout by using builder.SetLayout()
func ( *TimestampWithOffsetBuilder) ( string) error {
	if  == array.NullValueStr {
		.AppendNull()
		return nil
	}

	,  := time.Parse(.Layout, )
	if  != nil {
		return 
	}

	.Append()
	return nil
}

func ( *TimestampWithOffsetBuilder) ( []time.Time,  []bool) {
	if len() != len() && len() != 0 {
		panic("len(values) != len(valids) && len(valids) != 0")
	}
	if len() == 0 {
		 = make([]bool, len())
		for  := range  {
			[] = true
		}
	}

	 := .Builder.(*array.StructBuilder)
	 := .FieldBuilder(0).(*array.TimestampBuilder)

	.AppendValues()
	// SAFETY: by this point we know all buffers have available space given the earlier
	// call to structBuilder.AppendValues which calls Reserve internally, so it's OK to
	// call UnsafeAppend on inner builders

	switch offsets := .FieldBuilder(1).(type) {
	case *array.Int16Builder:
		for ,  := range  {
			,  := fieldValuesFromTime(, .unit)
			.UnsafeAppend()
			.UnsafeAppend()
		}
	case *array.Int16DictionaryBuilder:
		for ,  := range  {
			,  := fieldValuesFromTime(, .unit)
			.UnsafeAppend()
			.UnsafeAppend()
		}
	case *array.RunEndEncodedBuilder:
		 := .ValueBuilder().(*array.Int16Builder)
		for ,  := range  {
			,  := fieldValuesFromTime(, .unit)
			.UnsafeAppend()

			// A null row's offset is masked by the struct validity bitmap, so we
			// continue the current run to maximize compression. A run must still be
			// started when none exists yet (e.g. leading null rows), otherwise
			// ContinueRun would advance the run-ends without a matching entry in the
			// values child and produce an invalid run-end encoded array. lastOffset
			// is only updated when a new run starts, so a null row never splits a
			// contiguous run into two adjacent runs sharing the same value.
			 := []
			if .lastOffset == noLastOffset || ( &&  != .lastOffset) {
				.Append(1)
				.Append()
				.lastOffset = 
			} else {
				.ContinueRun(1)
			}
		}
	}
}

func ( *TimestampWithOffsetBuilder) ( *json.Decoder) error {
	,  := .Token()
	if  != nil {
		return fmt.Errorf("failed to decode json: %w", )
	}

	switch raw := .(type) {
	case string:
		,  := time.Parse(.Layout, )
		if  != nil {
			return fmt.Errorf("failed to parse string \"%s\" as time.Time using layout \"%s\"", , .Layout)
		}
		.Append()
	case nil:
		.AppendNull()
	default:
		return fmt.Errorf("expected date string")
	}

	return nil
}

func ( *TimestampWithOffsetBuilder) ( *json.Decoder) error {
	for .More() {
		if  := .UnmarshalOne();  != nil {
			return 
		}
	}
	return nil
}

var (
	_ arrow.ExtensionType          = (*TimestampWithOffsetType)(nil)
	_ array.CustomExtensionBuilder = (*TimestampWithOffsetType)(nil)
	_ array.ExtensionArray         = (*TimestampWithOffsetArray)(nil)
	_ array.Builder                = (*TimestampWithOffsetBuilder)(nil)
)