package jsonschema

import (
	
	
	
	
	
	

	
	
)

func ( *Schema) ( any) error {
	return .validate(, nil, nil, nil, false, nil)
}

func ( *Schema) ( any,  RegexpEngine,  *Schema,  map[jsonPointer]*resource,  bool,  map[string]*Vocabulary) error {
	 := validator{
		v:            ,
		vloc:         make([]string, 0, 8),
		sch:          ,
		scp:          &scope{, "", 0, nil},
		uneval:       unevalFrom(, , false),
		errors:       nil,
		boolResult:   false,
		regexpEngine: ,
		meta:         ,
		resources:    ,
		assertVocabs: ,
		vocabularies: ,
	}
	if ,  := .validate();  != nil {
		 := .(*ValidationError)
		var  []*ValidationError
		if ,  := .ErrorKind.(*kind.Group);  {
			 = .Causes
		} else {
			 = []*ValidationError{}
		}
		return &ValidationError{
			SchemaURL:        .Location,
			InstanceLocation: nil,
			ErrorKind:        &kind.Schema{Location: .Location},
			Causes:           ,
		}
	}

	return nil
}

type validator struct {
	v            any
	vloc         []string
	sch          *Schema
	scp          *scope
	uneval       *uneval
	errors       []*ValidationError
	boolResult   bool // is interested to know valid or not (but not actuall error)
	regexpEngine RegexpEngine

	// meta validation
	meta         *Schema                   // set only when validating with metaschema
	resources    map[jsonPointer]*resource // resources which should be validated with their dialect
	assertVocabs bool
	vocabularies map[string]*Vocabulary
}

func ( *validator) () (*uneval, error) {
	 := .sch
	 := .v

	// boolean --
	if .Bool != nil {
		if *.Bool {
			return .uneval, nil
		} else {
			return nil, .error(&kind.FalseSchema{})
		}
	}

	// check cycle --
	if  := .scp.checkCycle();  != nil {
		return nil, .error(&kind.RefCycle{
			URL:              .Location,
			KeywordLocation1: .scp.kwLoc(),
			KeywordLocation2: .kwLoc(),
		})
	}

	 := typeOf()
	if  == invalidType {
		return nil, .error(&kind.InvalidJsonValue{Value: })
	}

	// type --
	if .Types != nil && !.Types.IsEmpty() {
		 := .Types.contains() || (.Types.contains(integerType) &&  == numberType && isInteger())
		if ! {
			return nil, .error(&kind.Type{Got: .String(), Want: .Types.ToStrings()})
		}
	}

	// const --
	if .Const != nil {
		,  := equals(, *.Const)
		if  != nil {
			return nil, .error()
		} else if ! {
			return nil, .error(&kind.Const{Got: , Want: *.Const})
		}
	}

	// enum --
	if .Enum != nil {
		 := .Enum.types.contains(typeOf())
		if  {
			 = false
			for ,  := range .Enum.Values {
				,  := equals(, )
				if  != nil {
					return nil, .error()
				} else if  {
					 = true
					break
				}
			}
		}
		if ! {
			return nil, .error(&kind.Enum{Got: , Want: .Enum.Values})
		}
	}

	// format --
	if .Format != nil {
		var  error
		if .Format.Name == "regex" && .regexpEngine != nil {
			 = .regexpEngine.validate()
		} else {
			 = .Format.Validate()
		}
		if  != nil {
			return nil, .error(&kind.Format{Got: , Want: .Format.Name, Err: })
		}
	}

	// $ref --
	if .Ref != nil {
		 := .validateRef(.Ref, "$ref")
		if .DraftVersion < 2019 {
			return .uneval, 
		}
		if  != nil {
			.addErr()
		}
	}

	// type specific validations --
	switch v := .(type) {
	case map[string]any:
		.objValidate()
	case []any:
		.arrValidate()
	case string:
		.strValidate()
	case json.Number, float32, float64, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
		.numValidate()
	}

	if len(.errors) == 0 || !.boolResult {
		if .DraftVersion >= 2019 {
			.validateRefs()
		}
		.condValidate()

		for ,  := range .Extensions {
			.Validate(&ValidatorContext{}, )
		}

		if .DraftVersion >= 2019 {
			.unevalValidate()
		}
	}

	switch len(.errors) {
	case 0:
		return .uneval, nil
	case 1:
		return nil, .errors[0]
	default:
		 := .error(&kind.Group{})
		.Causes = .errors
		return nil, 
	}
}

func ( *validator) ( map[string]any) {
	 := .sch

	// minProperties --
	if .MinProperties != nil {
		if len() < *.MinProperties {
			.addError(&kind.MinProperties{Got: len(), Want: *.MinProperties})
		}
	}

	// maxProperties --
	if .MaxProperties != nil {
		if len() > *.MaxProperties {
			.addError(&kind.MaxProperties{Got: len(), Want: *.MaxProperties})
		}
	}

	// required --
	if len(.Required) > 0 {
		if  := .findMissing(, .Required);  != nil {
			.addError(&kind.Required{Missing: })
		}
	}

	if .boolResult && len(.errors) > 0 {
		return
	}

	// dependencies --
	for ,  := range .Dependencies {
		if ,  := [];  {
			switch dep := .(type) {
			case []string:
				if  := .findMissing(, );  != nil {
					.addError(&kind.Dependency{Prop: , Missing: })
				}
			case *Schema:
				.addErr(.validateSelf(, "", false))
			}
		}
	}

	var  []string
	for ,  := range  {
		if .boolResult && len(.errors) > 0 {
			return
		}
		 := false

		// properties --
		if ,  := .Properties[];  {
			 = true
			.addErr(.validateVal(, , ))
		}

		// patternProperties --
		for ,  := range .PatternProperties {
			if .MatchString() {
				 = true
				.addErr(.validateVal(, , ))
			}
		}

		if ! && .AdditionalProperties != nil {
			 = true
			switch additional := .AdditionalProperties.(type) {
			case bool:
				if ! {
					 = append(, )
				}
			case *Schema:
				.addErr(.validateVal(, , ))
			}
		}

		if  {
			delete(.uneval.props, )
		}
	}
	if len() > 0 {
		.addError(&kind.AdditionalProperties{Properties: })
	}

	if .DraftVersion == 4 {
		return
	}

	// propertyNames --
	if .PropertyNames != nil {
		for  := range  {
			, ,  := .PropertyNames, .meta, .resources
			 := .metaResource()
			if  != nil {
				 = .dialect.getSchema(.assertVocabs, .vocabularies)
				 = 
			}
			if  := .validate(, .regexpEngine, , , .assertVocabs, .vocabularies);  != nil {
				 := .(*ValidationError)
				.InstanceLocation = .vloc
				.SchemaURL = .PropertyNames.Location
				.ErrorKind = &kind.PropertyNames{Property: }
				.addErr()
			}
		}
	}

	if .DraftVersion == 6 {
		return
	}

	// dependentSchemas --
	for ,  := range .DependentSchemas {
		if ,  := [];  {
			.addErr(.validateSelf(, "", false))
		}
	}

	// dependentRequired --
	for ,  := range .DependentRequired {
		if ,  := [];  {
			if  := .findMissing(, );  != nil {
				.addError(&kind.DependentRequired{Prop: , Missing: })
			}
		}
	}
}

func ( *validator) ( []any) {
	 := .sch

	// minItems --
	if .MinItems != nil {
		if len() < *.MinItems {
			.addError(&kind.MinItems{Got: len(), Want: *.MinItems})
		}
	}

	// maxItems --
	if .MaxItems != nil {
		if len() > *.MaxItems {
			.addError(&kind.MaxItems{Got: len(), Want: *.MaxItems})
		}
	}

	// uniqueItems --
	if .UniqueItems && len() > 1 {
		, ,  := duplicates()
		if  != nil {
			.addError()
		} else if  != -1 {
			.addError(&kind.UniqueItems{Duplicates: [2]int{, }})
		}
	}

	if .DraftVersion < 2020 {
		 := 0

		// items --
		switch items := .Items.(type) {
		case *Schema:
			for ,  := range  {
				.addErr(.validateVal(, , strconv.Itoa()))
			}
			 = len()
		case []*Schema:
			 := minInt(len(), len())
			for ,  := range [:] {
				.addErr(.validateVal([], , strconv.Itoa()))
			}
			 = 
		}

		// additionalItems --
		if .AdditionalItems != nil {
			switch additional := .AdditionalItems.(type) {
			case bool:
				if ! &&  != len() {
					.addError(&kind.AdditionalItems{Count: len() - })
				}
			case *Schema:
				for ,  := range [:] {
					.addErr(.validateVal(, , strconv.Itoa(+)))
				}
			}
		}
	} else {
		 := minInt(len(.PrefixItems), len())

		// prefixItems --
		for ,  := range [:] {
			.addErr(.validateVal(.PrefixItems[], , strconv.Itoa()))
		}

		// items2020 --
		if .Items2020 != nil {
			for ,  := range [:] {
				.addErr(.validateVal(.Items2020, , strconv.Itoa(+)))
			}
		}
	}

	// contains --
	if .Contains != nil {
		var  []*ValidationError
		var  []int

		for ,  := range  {
			if  := .validateVal(.Contains, , strconv.Itoa());  != nil {
				 = append(, .(*ValidationError))
			} else {
				 = append(, )
				if .DraftVersion >= 2020 {
					delete(.uneval.items, )
				}
			}
		}

		// minContains --
		if .MinContains != nil {
			if len() < *.MinContains {
				.addErrors(, &kind.MinContains{Got: , Want: *.MinContains})
			}
		} else if len() == 0 {
			.addErrors(, &kind.Contains{})
		}

		// maxContains --
		if .MaxContains != nil {
			if len() > *.MaxContains {
				.addError(&kind.MaxContains{Got: , Want: *.MaxContains})
			}
		}
	}
}

func ( *validator) ( string) {
	 := .sch

	 := -1
	if .MinLength != nil || .MaxLength != nil {
		 = utf8.RuneCount([]byte())
	}

	// minLength --
	if .MinLength != nil {
		if  < *.MinLength {
			.addError(&kind.MinLength{Got: , Want: *.MinLength})
		}
	}

	// maxLength --
	if .MaxLength != nil {
		if  > *.MaxLength {
			.addError(&kind.MaxLength{Got: , Want: *.MaxLength})
		}
	}

	// pattern --
	if .Pattern != nil {
		if !.Pattern.MatchString() {
			.addError(&kind.Pattern{Got: , Want: .Pattern.String()})
		}
	}

	if .DraftVersion == 6 {
		return
	}

	var  error

	// contentEncoding --
	 := []byte()
	if .ContentEncoding != nil {
		,  = .ContentEncoding.Decode()
		if  != nil {
			 = nil
			.addError(&kind.ContentEncoding{Want: .ContentEncoding.Name, Err: })
		}
	}

	var  *any
	if  != nil && .ContentMediaType != nil {
		if .ContentSchema == nil {
			 = .ContentMediaType.Validate()
		} else {
			var  any
			,  = .ContentMediaType.UnmarshalJSON()
			if  == nil {
				 = &
			}
		}
		if  != nil {
			.addError(&kind.ContentMediaType{
				Got:  ,
				Want: .ContentMediaType.Name,
				Err:  ,
			})
		}
	}

	if  != nil && .ContentSchema != nil {
		, ,  := .ContentSchema, .meta, .resources
		 := .metaResource()
		if  != nil {
			 = .dialect.getSchema(.assertVocabs, .vocabularies)
			 = 
		}
		if  = .validate(*, .regexpEngine, , , .assertVocabs, .vocabularies);  != nil {
			 := .(*ValidationError)
			.InstanceLocation = .vloc
			.SchemaURL = .Location
			.ErrorKind = &kind.ContentSchema{}
			.addErr()
		}
	}
}

func ( *validator) ( any) {
	 := .sch

	var  *big.Rat
	 := func() *big.Rat {
		if  == nil {
			, _ = new(big.Rat).SetString(fmt.Sprintf("%v", ))
		}
		return 
	}

	// minimum --
	if .Minimum != nil && ().Cmp(.Minimum) < 0 {
		.addError(&kind.Minimum{Got: (), Want: .Minimum})
	}

	// maximum --
	if .Maximum != nil && ().Cmp(.Maximum) > 0 {
		.addError(&kind.Maximum{Got: (), Want: .Maximum})
	}

	// exclusiveMinimum
	if .ExclusiveMinimum != nil && ().Cmp(.ExclusiveMinimum) <= 0 {
		.addError(&kind.ExclusiveMinimum{Got: (), Want: .ExclusiveMinimum})
	}

	// exclusiveMaximum
	if .ExclusiveMaximum != nil && ().Cmp(.ExclusiveMaximum) >= 0 {
		.addError(&kind.ExclusiveMaximum{Got: (), Want: .ExclusiveMaximum})
	}

	// multipleOf
	if .MultipleOf != nil {
		if  := new(big.Rat).Quo((), .MultipleOf); !.IsInt() {
			.addError(&kind.MultipleOf{Got: (), Want: .MultipleOf})
		}
	}
}

func ( *validator) () {
	 := .sch

	// not --
	if .Not != nil {
		if .validateSelf(.Not, "", true) == nil {
			.addError(&kind.Not{})
		}
	}

	// allOf --
	if len(.AllOf) > 0 {
		var  []*ValidationError
		for ,  := range .AllOf {
			if  := .validateSelf(, "", false);  != nil {
				 = append(, .(*ValidationError))
				if .boolResult {
					break
				}
			}
		}
		if len() != 0 {
			.addErrors(, &kind.AllOf{})
		}
	}

	// anyOf
	if len(.AnyOf) > 0 {
		var  bool
		var  []*ValidationError
		for ,  := range .AnyOf {
			if  := .validateSelf(, "", false);  != nil {
				 = append(, .(*ValidationError))
			} else {
				 = true
				// for uneval, all schemas must be evaluated
				if .uneval.isEmpty() {
					break
				}
			}
		}
		if ! {
			.addErrors(, &kind.AnyOf{})
		}
	}

	// oneOf
	if len(.OneOf) > 0 {
		var  = -1
		var  []*ValidationError
		for ,  := range .OneOf {
			if  := .validateSelf(, "",  != -1);  != nil {
				if  == -1 {
					 = append(, .(*ValidationError))
				}
			} else {
				if  == -1 {
					 = 
				} else {
					.addError(&kind.OneOf{Subschemas: []int{, }})
					break
				}
			}
		}
		if  == -1 {
			.addErrors(, &kind.OneOf{Subschemas: nil})
		}
	}

	// if, then, else --
	if .If != nil {
		if .validateSelf(.If, "", true) == nil {
			if .Then != nil {
				.addErr(.validateSelf(.Then, "", false))
			}
		} else if .Else != nil {
			.addErr(.validateSelf(.Else, "", false))
		}
	}
}

func ( *validator) () {
	 := .sch

	// unevaluatedProperties
	if ,  := .v.(map[string]any);  && .UnevaluatedProperties != nil {
		for  := range .uneval.props {
			if ,  := [];  {
				.addErr(.validateVal(.UnevaluatedProperties, , ))
			}
		}
		.uneval.props = nil
	}

	// unevaluatedItems
	if ,  := .v.([]any);  && .UnevaluatedItems != nil {
		for  := range .uneval.items {
			.addErr(.validateVal(.UnevaluatedItems, [], strconv.Itoa()))
		}
		.uneval.items = nil
	}
}

// validation helpers --

func ( *validator) ( *Schema,  string,  bool) error {
	 := .scp.child(, , .scp.vid)
	 := unevalFrom(.v, , !.uneval.isEmpty())
	 := validator{
		v:            .v,
		vloc:         .vloc,
		sch:          ,
		scp:          ,
		uneval:       ,
		errors:       nil,
		boolResult:   .boolResult || ,
		regexpEngine: .regexpEngine,
		meta:         .meta,
		resources:    .resources,
		assertVocabs: .assertVocabs,
		vocabularies: .vocabularies,
	}
	.handleMeta()
	,  := .validate()
	if  == nil {
		.uneval.merge()
	}
	return 
}

func ( *validator) ( *Schema,  any,  string) error {
	 := append(.vloc, )
	 := .scp.child(, "", .scp.vid+1)
	 := unevalFrom(, , false)
	 := validator{
		v:            ,
		vloc:         ,
		sch:          ,
		scp:          ,
		uneval:       ,
		errors:       nil,
		boolResult:   .boolResult,
		regexpEngine: .regexpEngine,
		meta:         .meta,
		resources:    .resources,
		assertVocabs: .assertVocabs,
		vocabularies: .vocabularies,
	}
	.handleMeta()
	,  := .validate()
	return 
}

func ( *validator) ( *Schema,  any,  []string) error {
	 := append(.vloc, ...)
	 := .scp.child(, "", .scp.vid+1)
	 := unevalFrom(, , false)
	 := validator{
		v:            ,
		vloc:         ,
		sch:          ,
		scp:          ,
		uneval:       ,
		errors:       nil,
		boolResult:   .boolResult,
		regexpEngine: .regexpEngine,
		meta:         .meta,
		resources:    .resources,
		assertVocabs: .assertVocabs,
		vocabularies: .vocabularies,
	}
	.handleMeta()
	,  := .validate()
	return 
}

func ( *validator) ( *Schema) *resource {
	if  != .meta {
		return nil
	}
	 := ""
	for ,  := range .instanceLocation() {
		 += "/"
		 += escape()
	}
	return .resources[jsonPointer()]
}

func ( *validator) () {
	 := .metaResource(.sch)
	if  == nil {
		return
	}
	 := .dialect.getSchema(.assertVocabs, .vocabularies)
	.meta = 
	.sch = 
}

// reference validation --

func ( *validator) ( *Schema,  string) error {
	 := .validateSelf(, , false)
	if  != nil {
		 := .error(&kind.Reference{Keyword: , URL: .Location})
		 := .(*ValidationError)
		if ,  := .ErrorKind.(*kind.Group);  {
			.Causes = .Causes
		} else {
			.Causes = append(.Causes, )
		}
		return 
	}
	return nil
}

func ( *validator) ( *Schema) *Schema {
	 := 
	 := .scp
	for  != nil {
		if .sch.resource.RecursiveAnchor {
			 = .sch
		}
		 = .parent
	}
	return 
}

func ( *validator) ( string,  *Schema) *Schema {
	 := 
	 := .scp
	for  != nil {
		if ,  := .sch.resource.dynamicAnchors[];  {
			 = 
		}
		 = .parent
	}
	return 
}

func ( *validator) () {
	// $recursiveRef --
	if  := .sch.RecursiveRef;  != nil {
		if .RecursiveAnchor {
			 = .resolveRecursiveAnchor()
		}
		.addErr(.validateRef(, "$recursiveRef"))
	}

	// $dynamicRef --
	if  := .sch.DynamicRef;  != nil {
		 := .Ref // initial target
		if .Anchor != "" {
			// $dynamicRef includes anchor
			if .DynamicAnchor == .Anchor {
				// initial target has matching $dynamicAnchor
				 = .resolveDynamicAnchor(.Anchor, )
			}
		}
		.addErr(.validateRef(, "$dynamicRef"))
	}
}

// error helpers --

func ( *validator) () []string {
	return slices.Clone(.vloc)
}

func ( *validator) ( ErrorKind) *ValidationError {
	if .boolResult {
		return &ValidationError{}
	}
	return &ValidationError{
		SchemaURL:        .sch.Location,
		InstanceLocation: .instanceLocation(),
		ErrorKind:        ,
		Causes:           nil,
	}
}

func ( *validator) ( error) {
	if  != nil {
		.errors = append(.errors, .(*ValidationError))
	}
}

func ( *validator) ( ErrorKind) {
	.errors = append(.errors, .error())
}

func ( *validator) ( []*ValidationError,  ErrorKind) {
	 := .error()
	.Causes = 
	.errors = append(.errors, )
}

func ( *validator) ( map[string]any,  []string) []string {
	var  []string
	for ,  := range  {
		if ,  := []; ! {
			if .boolResult {
				return []string{} // non-nil
			}
			 = append(, )
		}
	}
	return 
}

// --

type scope struct {
	sch *Schema

	// if empty, compute from self.sch and self.parent.sch.
	// not empty, only when there is a jump i.e, $ref, $XXXRef
	refKeyword string

	// unique id of value being validated
	// if two scopes validate same value, they will have
	// same vid
	vid int

	parent *scope
}

func ( *scope) ( *Schema,  string,  int) *scope {
	return &scope{, , , }
}

func ( *scope) () *scope {
	 := .parent
	for  != nil {
		if .vid != .vid {
			break
		}
		if .sch == .sch {
			return 
		}
		 = .parent
	}
	return nil
}

func ( *scope) () string {
	var  string
	for .parent != nil {
		if .refKeyword != "" {
			 = fmt.Sprintf("/%s%s", escape(.refKeyword), )
		} else {
			 := .sch.Location
			 := .parent.sch.Location
			 = fmt.Sprintf("%s%s", [len():], )
		}
		 = .parent
	}
	return 
}

// --

type uneval struct {
	props map[string]struct{}
	items map[int]struct{}
}

func unevalFrom( any,  *Schema,  bool) *uneval {
	 := &uneval{}
	switch v := .(type) {
	case map[string]any:
		if !.allPropsEvaluated && ( || .UnevaluatedProperties != nil) {
			.props = map[string]struct{}{}
			for  := range  {
				.props[] = struct{}{}
			}
		}
	case []any:
		if !.allItemsEvaluated && ( || .UnevaluatedItems != nil) && .numItemsEvaluated < len() {
			.items = map[int]struct{}{}
			for  := .numItemsEvaluated;  < len(); ++ {
				.items[] = struct{}{}
			}
		}
	}
	return 
}

func ( *uneval) ( *uneval) {
	for  := range .props {
		if ,  := .props[]; ! {
			delete(.props, )
		}
	}
	for  := range .items {
		if ,  := .items[]; ! {
			delete(.items, )
		}
	}
}

func ( *uneval) () bool {
	return len(.props) == 0 && len(.items) == 0
}

// --

type ValidationError struct {
	// absolute, dereferenced schema location.
	SchemaURL string

	// location of the JSON value within the instance being validated.
	InstanceLocation []string

	// kind of error
	ErrorKind ErrorKind

	// holds nested errors
	Causes []*ValidationError
}

type ErrorKind interface {
	KeywordPath() []string
	LocalizedString(*message.Printer) string
}