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

import (
	
	
	
	
	

	
	
	
	
)

// MatchSubstringOptions controls the substring matching functions such as
// starts_with, which match Pattern literally, not as a regular
// expression. With IgnoreCase, string input matches Unicode simple case
// folds and binary input matches ASCII case folds.
type MatchSubstringOptions struct {
	Pattern    string `compute:"pattern"`
	IgnoreCase bool   `compute:"ignore_case"`
}

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

type matchSubstringState struct {
	pattern []byte
}

type foldUTF8State struct {
	pattern []rune
}

// foldASCIIState holds the pattern with each byte lowered by foldASCII.
type foldASCIIState struct {
	pattern []byte
}

func initMatchSubstring( bool) exec.KernelInitFn {
	return func( *exec.KernelCtx,  exec.KernelInitArgs) (exec.KernelState, error) {
		,  := .Options.(MatchSubstringOptions)
		if ,  := .Options.(*MatchSubstringOptions);  &&  != nil {
			,  = *, true
		}
		if ! {
			return nil, fmt.Errorf("%w: attempted to initialize kernel state from invalid function options",
				arrow.ErrInvalid)
		}

		switch {
		case !.IgnoreCase:
			return matchSubstringState{pattern: []byte(.Pattern)}, nil
		case :
			if !utf8.ValidString(.Pattern) {
				return nil, fmt.Errorf("%w: case-insensitive pattern must be valid UTF-8 for string input",
					arrow.ErrInvalid)
			}
			return foldUTF8State{pattern: []rune(.Pattern)}, nil
		default:
			 := []byte(.Pattern)
			for ,  := range  {
				[] = foldASCII()
			}
			return foldASCIIState{pattern: }, nil
		}
	}
}

func startsWith( *exec.KernelCtx,  []byte,  *error) bool {
	return bytes.HasPrefix(, .State.(matchSubstringState).pattern)
}

// viewStartsWith decides from the view header alone when it can, and
// reads the data buffer only for the part of pattern past the prefix.
func viewStartsWith( *arrow.ViewHeader, ,  []byte) bool {
	if .Len() < len() {
		return false
	}
	if .IsInline() {
		return bytes.HasPrefix(.InlineBytes(), )
	}
	 := .Prefix()
	 := min(len(), arrow.ViewPrefixLen)
	if !bytes.Equal([:], [:]) {
		return false
	}
	 := int(.BufferOffset())
	return bytes.Equal([+:+len()], [:])
}

func viewBytes( *arrow.ViewHeader,  []byte) []byte {
	if .IsInline() {
		return .InlineBytes()
	}
	 := int(.BufferOffset())
	return [ : +.Len()]
}

// startsWithView reads out-of-line values from Buffers[2], so inputs with
// more than one data buffer must be coalesced before execution.
func startsWithView( *exec.KernelCtx,  *exec.ExecSpan,  *exec.ExecResult) error {
	var (
		       = &.Values[0].Array
		      = arrow.ViewHeaderTraits.CastFromBytes(.Buffers[1].Buf)[.Offset:]
		       = .Buffers[2].Buf
		    = .Buffers[1].Buf
		     = int(.Offset)
		 func( int64)
	)
	 := func( func(*exec.KernelCtx, []byte, *error) bool) func(int64) {
		return func( int64) {
			bitutil.SetBitTo(, , (, viewBytes(&[], ), nil))
			++
		}
	}
	switch st := .State.(type) {
	case matchSubstringState:
		 := .pattern
		 = func( int64) {
			bitutil.SetBitTo(, , viewStartsWith(&[], , ))
			++
		}
	case foldUTF8State:
		 = (startsWithFoldUTF8)
	case foldASCIIState:
		 = (startsWithFoldASCII)
	}
	bitutils.VisitBitBlocks(.Buffers[0].Buf, .Offset, .Len, ,
		func() {
			bitutil.ClearBit(, )
			++
		})
	return nil
}

func startsWithFoldUTF8( *exec.KernelCtx,  []byte,  *error) bool {
	for ,  := range .State.(foldUTF8State).pattern {
		,  := utf8.DecodeRune()
		if ( == utf8.RuneError &&  <= 1) || !equalSimpleFold(, ) {
			return false
		}
		 = [:]
	}
	return true
}

func equalSimpleFold(,  rune) bool {
	for  := ; ; {
		if  ==  {
			return true
		}
		if  = unicode.SimpleFold();  ==  {
			return false
		}
	}
}

func startsWithFoldASCII( *exec.KernelCtx,  []byte,  *error) bool {
	 := .State.(foldASCIIState).pattern
	if len() < len() {
		return false
	}
	for ,  := range  {
		if foldASCII([]) !=  {
			return false
		}
	}
	return true
}

func foldASCII( byte) byte {
	if 'A' <=  &&  <= 'Z' {
		return  + 0x20
	}
	return 
}

func startsWithExec[ int32 | int64]() exec.ArrayKernelExec {
	 := ScalarUnaryNotNullBinaryArgBoolOut[](false, startsWith)
	 := ScalarUnaryNotNullBinaryArgBoolOut[](false, startsWithFoldUTF8)
	 := ScalarUnaryNotNullBinaryArgBoolOut[](false, startsWithFoldASCII)
	return func( *exec.KernelCtx,  *exec.ExecSpan,  *exec.ExecResult) error {
		switch .State.(type) {
		case foldUTF8State:
			return (, , )
		case foldASCIIState:
			return (, , )
		default:
			return (, , )
		}
	}
}

// GetStartsWithKernels returns the kernels for the starts_with function
// over the binary, string and view types.
func () []exec.ScalarKernel {
	 := exec.NewOutputType(arrow.FixedWidthTypes.Boolean)
	 := append(slices.Clip(baseBinaryTypes), arrow.BinaryTypes.BinaryView, arrow.BinaryTypes.StringView)
	 := make([]exec.ScalarKernel, 0, len())
	for ,  := range  {
		var  exec.ArrayKernelExec
		switch .ID() {
		case arrow.BINARY_VIEW, arrow.STRING_VIEW:
			 = startsWithView
		case arrow.LARGE_BINARY, arrow.LARGE_STRING:
			 = startsWithExec[int64]()
		default:
			 = startsWithExec[int32]()
		}
		 := exec.NewScalarKernel([]exec.InputType{exec.NewExactInput()}, , ,
			initMatchSubstring(.(arrow.BinaryDataType).IsUtf8()))
		.NullHandling = exec.NullIntersection
		.MemAlloc = exec.MemPrealloc
		 = append(, )
	}
	return 
}