package decoder

import (
	
	
	

	
	
)

type PathString string

func ( PathString) () (*Path, error) {
	 := new(PathBuilder)
	return .Build([]rune())
}

type PathBuilder struct {
	root                    PathNode
	node                    PathNode
	singleQuotePathSelector bool
	doubleQuotePathSelector bool
}

func ( *PathBuilder) ( []rune) (*Path, error) {
	,  := .build()
	if  != nil {
		return nil, 
	}
	return &Path{
		node:                    ,
		RootSelectorOnly:         == nil,
		SingleQuotePathSelector: .singleQuotePathSelector,
		DoubleQuotePathSelector: .doubleQuotePathSelector,
	}, nil
}

func ( *PathBuilder) ( []rune) (PathNode, error) {
	if len() == 0 {
		return nil, errors.ErrEmptyPath()
	}
	if [0] != '$' {
		return nil, errors.ErrInvalidPath("JSON Path must start with a $ character")
	}
	if len() == 1 {
		return nil, nil
	}
	 = [1:]
	,  := .buildNext()
	if  != nil {
		return nil, 
	}
	if len() >  {
		return nil, errors.ErrInvalidPath("remain invalid path %q", [:])
	}
	return .root, nil
}

func ( *PathBuilder) ( []rune,  int) (int, error) {
	if len() >  {
		,  := .buildNext([:])
		if  != nil {
			return 0, 
		}
		return  + 1 + , nil
	}
	return , nil
}

func ( *PathBuilder) ( []rune) (int, error) {
	switch [0] {
	case '.':
		if len() == 1 {
			return 0, errors.ErrInvalidPath("JSON Path ends with dot character")
		}
		,  := .buildSelector([1:])
		if  != nil {
			return 0, 
		}
		return  + 1, nil
	case '[':
		if len() == 1 {
			return 0, errors.ErrInvalidPath("JSON Path ends with left bracket character")
		}
		,  := .buildIndex([1:])
		if  != nil {
			return 0, 
		}
		return  + 1, nil
	default:
		return 0, errors.ErrInvalidPath("expect dot or left bracket character. but found %c character", [0])
	}
}

func ( *PathBuilder) ( []rune) (int, error) {
	switch [0] {
	case '.':
		if len() == 1 {
			return 0, errors.ErrInvalidPath("JSON Path ends with double dot character")
		}
		,  := .buildPathRecursive([1:])
		if  != nil {
			return 0, 
		}
		return 1 + , nil
	case '[', ']', '$', '*':
		return 0, errors.ErrInvalidPath("found invalid path character %c after dot", [0])
	}
	for  := 0;  < len(); ++ {
		switch [] {
		case '$', '*', ']':
			return 0, errors.ErrInvalidPath("found %c character in field selector context", [])
		case '.':
			if +1 >= len() {
				return 0, errors.ErrInvalidPath("JSON Path ends with dot character")
			}
			 := [:]
			.addSelectorNode(string())
			,  := .([+1:])
			if  != nil {
				return 0, 
			}
			return  + 1 + , nil
		case '[':
			if +1 >= len() {
				return 0, errors.ErrInvalidPath("JSON Path ends with left bracket character")
			}
			 := [:]
			.addSelectorNode(string())
			,  := .buildIndex([+1:])
			if  != nil {
				return 0, 
			}
			return  + 1 + , nil
		case '"':
			if +1 >= len() {
				return 0, errors.ErrInvalidPath("JSON Path ends with double quote character")
			}
			,  := .buildQuoteSelector([+1:], DoubleQuotePathSelector)
			if  != nil {
				return 0, 
			}
			return  + 1 + , nil
		}
	}
	.addSelectorNode(string())
	return len(), nil
}

func ( *PathBuilder) ( []rune,  QuotePathSelector) (int, error) {
	switch [0] {
	case '[', ']', '$', '.', '*', '\'', '"':
		return 0, errors.ErrInvalidPath("found invalid path character %c after quote", [0])
	}
	for  := 0;  < len(); ++ {
		switch [] {
		case '\'':
			if  != SingleQuotePathSelector {
				return 0, errors.ErrInvalidPath("found double quote character in field selector with single quote context")
			}
			if len() <= +1 {
				return 0, errors.ErrInvalidPath("JSON Path ends with single quote character in field selector context")
			}
			if [+1] != ']' {
				return 0, errors.ErrInvalidPath("expect right bracket for field selector with single quote but found %c", [+1])
			}
			 := [:]
			.addSelectorNode(string())
			.singleQuotePathSelector = true
			return .buildNextCharIfExists(, +2)
		case '"':
			if  != DoubleQuotePathSelector {
				return 0, errors.ErrInvalidPath("found single quote character in field selector with double quote context")
			}
			 := [:]
			.addSelectorNode(string())
			.doubleQuotePathSelector = true
			return .buildNextCharIfExists(, +1)
		}
	}
	return 0, errors.ErrInvalidPath("couldn't find quote character in selector quote path context")
}

func ( *PathBuilder) ( []rune) (int, error) {
	switch [0] {
	case '.', '[', ']', '$', '*':
		return 0, errors.ErrInvalidPath("found invalid path character %c after double dot", [0])
	}
	for  := 0;  < len(); ++ {
		switch [] {
		case '$', '*', ']':
			return 0, errors.ErrInvalidPath("found %c character in field selector context", [])
		case '.':
			if +1 >= len() {
				return 0, errors.ErrInvalidPath("JSON Path ends with dot character")
			}
			 := [:]
			.addRecursiveNode(string())
			,  := .buildSelector([+1:])
			if  != nil {
				return 0, 
			}
			return  + 1 + , nil
		case '[':
			if +1 >= len() {
				return 0, errors.ErrInvalidPath("JSON Path ends with left bracket character")
			}
			 := [:]
			.addRecursiveNode(string())
			,  := .buildIndex([+1:])
			if  != nil {
				return 0, 
			}
			return  + 1 + , nil
		}
	}
	.addRecursiveNode(string())
	return len(), nil
}

func ( *PathBuilder) ( []rune) (int, error) {
	switch [0] {
	case '.', '[', ']', '$':
		return 0, errors.ErrInvalidPath("found invalid path character %c after left bracket", [0])
	case '\'':
		if len() == 1 {
			return 0, errors.ErrInvalidPath("JSON Path ends with single quote character")
		}
		,  := .buildQuoteSelector([1:], SingleQuotePathSelector)
		if  != nil {
			return 0, 
		}
		return 1 + , nil
	case '*':
		if len() == 1 {
			return 0, errors.ErrInvalidPath("JSON Path ends with star character")
		}
		if [1] != ']' {
			return 0, errors.ErrInvalidPath("expect right bracket character for index all path but found %c character", [1])
		}
		.addIndexAllNode()
		 := len("*]")
		if len() > 2 {
			,  := .buildNext([2:])
			if  != nil {
				return 0, 
			}
			return  + , nil
		}
		return , nil
	}

	for  := 0;  < len(); ++ {
		switch [] {
		case ']':
			,  := strconv.ParseInt(string([:]), 10, 64)
			if  != nil {
				return 0, errors.ErrInvalidPath("%q is unexpected index path", [:])
			}
			.addIndexNode(int())
			return .buildNextCharIfExists(, +1)
		}
	}
	return 0, errors.ErrInvalidPath("couldn't find right bracket character in index path context")
}

func ( *PathBuilder) () {
	 := newPathIndexAllNode()
	if .root == nil {
		.root = 
		.node = 
	} else {
		.node = .node.chain()
	}
}

func ( *PathBuilder) ( string) {
	 := newPathRecursiveNode()
	if .root == nil {
		.root = 
		.node = 
	} else {
		.node = .node.chain()
	}
}

func ( *PathBuilder) ( string) {
	 := newPathSelectorNode()
	if .root == nil {
		.root = 
		.node = 
	} else {
		.node = .node.chain()
	}
}

func ( *PathBuilder) ( int) {
	 := newPathIndexNode()
	if .root == nil {
		.root = 
		.node = 
	} else {
		.node = .node.chain()
	}
}

type QuotePathSelector int

const (
	SingleQuotePathSelector QuotePathSelector = 1
	DoubleQuotePathSelector QuotePathSelector = 2
)

type Path struct {
	node                    PathNode
	RootSelectorOnly        bool
	SingleQuotePathSelector bool
	DoubleQuotePathSelector bool
}

func ( *Path) ( string) (PathNode, bool, error) {
	if .node == nil {
		return nil, false, nil
	}
	return .node.Field()
}

func ( *Path) (,  reflect.Value) error {
	if .node == nil {
		return nil
	}
	return .node.Get(, )
}

func ( *Path) () string {
	if .node == nil {
		return "$"
	}
	return .node.String()
}

type PathNode interface {
	fmt.Stringer
	Index(idx int) (PathNode, bool, error)
	Field(fieldName string) (PathNode, bool, error)
	Get(src, dst reflect.Value) error
	chain(PathNode) PathNode
	// single reports whether Get of the path from the node on gives one value: no node of it is [*] or .., whose Get
	// gives a slice of all the values they select.
	single() bool
}

type BasePathNode struct {
	child PathNode
}

func ( *BasePathNode) ( PathNode) PathNode {
	.child = 
	return 
}

func ( *BasePathNode) () bool {
	return .child == nil || .child.single()
}

// pathValue returns the value which v holds through pointers and interfaces, followed in a loop, or the zero Value if
// one of them is nil: null, which has no member or element. It returns an error if a pointer leads back to itself
// ( see pointerVisits ).
func pathValue( reflect.Value) (reflect.Value, error) {
	var  pointerVisits
	for .Kind() == reflect.Ptr || .Kind() == reflect.Interface {
		if .IsNil() {
			return reflect.Value{}, nil
		}
		if .Kind() == reflect.Ptr {
			if  := .follow();  != nil {
				return reflect.Value{}, 
			}
		}
		 = .Elem()
	}
	return , nil
}

// pathTypeName names the type of v, a value from pathValue, in an error.
func pathTypeName( reflect.Value) string {
	if !.IsValid() {
		return "null"
	}
	return .Type().String()
}

// isPathField reports whether a path selects field, of a struct, by its name: whether the JSON object of the struct
// has the field and its value can be read. An unexported field has not, nor a field tagged "-".
func isPathField( reflect.StructField) bool {
	return .IsExported() && !runtime.IsIgnoredStructField()
}

// isUnsupportedValue reports whether err, of Get, is that the value cannot be gone through, as it holds itself or is
// nested too deep ( see visits ): [*] and .. report it, where they leave out a value in which the rest of the path
// selects nothing.
func isUnsupportedValue( error) bool {
	,  := .(*errors.UnsupportedValueError)
	return 
}

// mapKeyName returns the name which key, of a map, is in its JSON object, if it is of a string kind, or an interface
// which holds one. A path selects no other key by a name.
func mapKeyName( reflect.Value) (string, bool) {
	if .Kind() == reflect.Interface {
		 = .Elem()
	}
	if .Kind() != reflect.String {
		return "", false
	}
	return .String(), true
}

// appendPathValue appends v, which Get of the path from child on gave, to values: the values in v one by one if that
// path gives a slice of them ( see PathNode.single ).
func appendPathValue( []any,  any,  PathNode) []any {
	if  == nil || .single() {
		return append(, )
	}
	,  := .([]any)
	return append(, ...)
}

type PathSelectorNode struct {
	*BasePathNode
	selector string
}

func newPathSelectorNode( string) *PathSelectorNode {
	return &PathSelectorNode{
		BasePathNode: &BasePathNode{},
		selector:     ,
	}
}

func ( *PathSelectorNode) ( int) (PathNode, bool, error) {
	return nil, false, &errors.PathError{}
}

func ( *PathSelectorNode) ( string) (PathNode, bool, error) {
	if .selector ==  {
		return .child, true, nil
	}
	return nil, false, nil
}

func ( *PathSelectorNode) (,  reflect.Value) error {
	,  := pathValue()
	if  != nil {
		return 
	}
	switch .Kind() {
	case reflect.Map:
		 := .MapRange()
		for .Next() {
			,  := mapKeyName(.Key())
			if ! {
				continue
			}
			, ,  := .Field()
			if  != nil {
				return 
			}
			if  {
				if  != nil {
					return .Get(.Value(), )
				}
				return AssignValue(.Value(), )
			}
		}
	case reflect.Struct:
		 := .Type()
		for  := 0;  < .NumField(); ++ {
			if !isPathField(.Field()) {
				continue
			}
			 := runtime.StructTagFromField(.Field())
			, ,  := .Field(.Key)
			if  != nil {
				return 
			}
			if  {
				if  != nil {
					return .Get(.Field(), )
				}
				return AssignValue(.Field(), )
			}
		}
	}
	return fmt.Errorf("failed to get %s value from %s", .selector, pathTypeName())
}

func ( *PathSelectorNode) () string {
	 := fmt.Sprintf(".%s", .selector)
	if .child != nil {
		 += .child.String()
	}
	return 
}

type PathIndexNode struct {
	*BasePathNode
	selector int
}

func newPathIndexNode( int) *PathIndexNode {
	return &PathIndexNode{
		BasePathNode: &BasePathNode{},
		selector:     ,
	}
}

func ( *PathIndexNode) ( int) (PathNode, bool, error) {
	if .selector ==  {
		return .child, true, nil
	}
	return nil, false, nil
}

func ( *PathIndexNode) ( string) (PathNode, bool, error) {
	return nil, false, &errors.PathError{}
}

func ( *PathIndexNode) (,  reflect.Value) error {
	,  := pathValue()
	if  != nil {
		return 
	}
	switch .Kind() {
	case reflect.Array, reflect.Slice:
		if .selector >= 0 && .selector < .Len() {
			if .child != nil {
				return .child.Get(.Index(.selector), )
			}
			return AssignValue(.Index(.selector), )
		}
	}
	return fmt.Errorf("failed to get [%d] value from %s", .selector, pathTypeName())
}

func ( *PathIndexNode) () string {
	 := fmt.Sprintf("[%d]", .selector)
	if .child != nil {
		 += .child.String()
	}
	return 
}

type PathIndexAllNode struct {
	*BasePathNode
}

func newPathIndexAllNode() *PathIndexAllNode {
	return &PathIndexAllNode{
		BasePathNode: &BasePathNode{},
	}
}

func ( *PathIndexAllNode) ( int) (PathNode, bool, error) {
	return .child, true, nil
}

func ( *PathIndexAllNode) ( string) (PathNode, bool, error) {
	return nil, false, &errors.PathError{}
}

func ( *PathIndexAllNode) () bool {
	return false
}

func ( *PathIndexAllNode) (,  reflect.Value) error {
	,  := pathValue()
	if  != nil {
		return 
	}
	switch .Kind() {
	case reflect.Array, reflect.Slice:
		var  []any
		for  := 0;  < .Len(); ++ {
			var  any
			 := reflect.ValueOf(&)
			if .child != nil {
				if  := .child.Get(.Index(), );  != nil {
					if isUnsupportedValue() {
						return 
					}
					// the rest of the path selects nothing in the element
					continue
				}
			} else {
				if  := AssignValue(.Index(), );  != nil {
					return 
				}
			}
			 = appendPathValue(, , .child)
		}
		return AssignValue(reflect.ValueOf(), )
	}
	return fmt.Errorf("failed to get all value from %s", pathTypeName())
}

func ( *PathIndexAllNode) () string {
	 := "[*]"
	if .child != nil {
		 += .child.String()
	}
	return 
}

type PathRecursiveNode struct {
	*BasePathNode
	selector string
}

func newPathRecursiveNode( string) *PathRecursiveNode {
	return &PathRecursiveNode{
		BasePathNode: &BasePathNode{},
		selector:     ,
	}
}

func ( *PathRecursiveNode) ( string) (PathNode, bool, error) {
	if .selector ==  {
		return .child, true, nil
	}
	return nil, false, nil
}

func ( *PathRecursiveNode) ( int) (PathNode, bool, error) {
	return , true, nil
}

func ( *PathRecursiveNode) () bool {
	return false
}

// Get assigns to dst a slice of the values which the name of n has at any depth of src, in the members of objects
// and the elements of arrays, with the rest of the path applied to each of them: a value in which the rest finds
// nothing adds nothing.
func ( *PathRecursiveNode) (,  reflect.Value) error {
	var  []any
	if  := .collect(, &, &visits{});  != nil {
		return 
	}
	return AssignValue(reflect.ValueOf(), )
}

// collect appends to values what Get selects in v.
func ( *PathRecursiveNode) ( reflect.Value,  *[]any,  *visits) error {
	,  := pathValue()
	if  != nil {
		return 
	}
	switch .Kind() {
	case reflect.Map, reflect.Slice, reflect.Array, reflect.Struct:
	default:
		return nil
	}
	if  := .enter();  != nil {
		return 
	}
	defer .leave()
	return .collectContents(, , )
}

// collectContents is collect of v, an object or an array: a map, a struct, a slice or an array.
func ( *PathRecursiveNode) ( reflect.Value,  *[]any,  *visits) error {
	switch .Kind() {
	case reflect.Map:
		 := .MapRange()
		for .Next() {
			if ,  := mapKeyName(.Key());  &&  == .selector {
				var  error
				if *,  = .appendSelected(*, .Value());  != nil {
					return 
				}
			}
			if  := .collect(.Value(), , );  != nil {
				return 
			}
		}
	case reflect.Struct:
		 := .Type()
		for  := 0;  < .NumField(); ++ {
			 := .Field()
			if !isPathField() {
				continue
			}
			 := runtime.StructTagFromField()
			if .Key == .selector {
				var  error
				if *,  = .appendSelected(*, .Field());  != nil {
					return 
				}
			}
			 := .collect
			if .Anonymous && .Type.Kind() == reflect.Struct && !.IsTaggedKey {
				// a struct embedded by its value, with no name in its tag, is a part of the object of v, as Marshal
				// writes it, not a level
				 = .
			}
			if  := (.Field(), , );  != nil {
				return 
			}
		}
	default:
		for  := 0;  < .Len(); ++ {
			if  := .collect(.Index(), , );  != nil {
				return 
			}
		}
	}
	return nil
}

// appendSelected appends to values v, a value of the name of n, with the rest of the path applied to it: nothing if
// the rest selects nothing in it.
func ( *PathRecursiveNode) ( []any,  reflect.Value) ([]any, error) {
	if .child == nil {
		return append(, .Interface()), nil
	}
	var  any
	if  := .child.Get(, reflect.ValueOf(&));  != nil {
		if isUnsupportedValue() {
			return nil, 
		}
		return , nil
	}
	return appendPathValue(, , .child), nil
}

func ( *PathRecursiveNode) () string {
	 := fmt.Sprintf("..%s", .selector)
	if .child != nil {
		 += .child.String()
	}
	return 
}