package jsonschema

import (
	
	
	
)

// A Draft represents json-schema specification.
type Draft struct {
	version       int
	url           string
	sch           *Schema
	id            string             // property name used to represent id
	subschemas    []SchemaPath       // locations of subschemas
	vocabPrefix   string             // prefix used for vocabulary
	allVocabs     map[string]*Schema // names of supported vocabs with its schemas
	defaultVocabs []string           // names of default vocabs
}

// String returns the specification url.
func ( *Draft) () string {
	return .url
}

var (
	Draft4 = &Draft{
		version: 4,
		url:     "http://json-schema.org/draft-04/schema",
		id:      "id",
		subschemas: []SchemaPath{
			// type agonistic
			schemaPath("definitions/*"),
			schemaPath("not"),
			schemaPath("allOf/[]"),
			schemaPath("anyOf/[]"),
			schemaPath("oneOf/[]"),
			// object
			schemaPath("properties/*"),
			schemaPath("additionalProperties"),
			schemaPath("patternProperties/*"),
			// array
			schemaPath("items"),
			schemaPath("items/[]"),
			schemaPath("additionalItems"),
			schemaPath("dependencies/*"),
		},
		vocabPrefix:   "",
		allVocabs:     map[string]*Schema{},
		defaultVocabs: []string{},
	}

	Draft6 = &Draft{
		version: 6,
		url:     "http://json-schema.org/draft-06/schema",
		id:      "$id",
		subschemas: joinSubschemas(Draft4.subschemas,
			schemaPath("propertyNames"),
			schemaPath("contains"),
		),
		vocabPrefix:   "",
		allVocabs:     map[string]*Schema{},
		defaultVocabs: []string{},
	}

	Draft7 = &Draft{
		version: 7,
		url:     "http://json-schema.org/draft-07/schema",
		id:      "$id",
		subschemas: joinSubschemas(Draft6.subschemas,
			schemaPath("if"),
			schemaPath("then"),
			schemaPath("else"),
		),
		vocabPrefix:   "",
		allVocabs:     map[string]*Schema{},
		defaultVocabs: []string{},
	}

	Draft2019 = &Draft{
		version: 2019,
		url:     "https://json-schema.org/draft/2019-09/schema",
		id:      "$id",
		subschemas: joinSubschemas(Draft7.subschemas,
			schemaPath("$defs/*"),
			schemaPath("dependentSchemas/*"),
			schemaPath("unevaluatedProperties"),
			schemaPath("unevaluatedItems"),
			schemaPath("contentSchema"),
		),
		vocabPrefix: "https://json-schema.org/draft/2019-09/vocab/",
		allVocabs: map[string]*Schema{
			"core":       nil,
			"applicator": nil,
			"validation": nil,
			"meta-data":  nil,
			"format":     nil,
			"content":    nil,
		},
		defaultVocabs: []string{"core", "applicator", "validation"},
	}

	Draft2020 = &Draft{
		version: 2020,
		url:     "https://json-schema.org/draft/2020-12/schema",
		id:      "$id",
		subschemas: joinSubschemas(Draft2019.subschemas,
			schemaPath("prefixItems/[]"),
		),
		vocabPrefix: "https://json-schema.org/draft/2020-12/vocab/",
		allVocabs: map[string]*Schema{
			"core":              nil,
			"applicator":        nil,
			"unevaluated":       nil,
			"validation":        nil,
			"meta-data":         nil,
			"format-annotation": nil,
			"format-assertion":  nil,
			"content":           nil,
		},
		defaultVocabs: []string{"core", "applicator", "unevaluated", "validation"},
	}

	draftLatest = Draft2020
)

func init() {
	 := NewCompiler()
	.AssertFormat()
	for ,  := range []*Draft{Draft4, Draft6, Draft7, Draft2019, Draft2020} {
		.sch = .MustCompile(.url)
		for  := range .allVocabs {
			.allVocabs[] = .MustCompile(strings.TrimSuffix(.url, "schema") + "meta/" + )
		}
	}
}

func draftFromURL( string) *Draft {
	,  := split()
	if  != "" {
		return nil
	}
	,  := strings.CutPrefix(, "http://")
	if ! {
		, _ = strings.CutPrefix(, "https://")
	}
	switch  {
	case "json-schema.org/schema":
		return draftLatest
	case "json-schema.org/draft/2020-12/schema":
		return Draft2020
	case "json-schema.org/draft/2019-09/schema":
		return Draft2019
	case "json-schema.org/draft-07/schema":
		return Draft7
	case "json-schema.org/draft-06/schema":
		return Draft6
	case "json-schema.org/draft-04/schema":
		return Draft4
	default:
		return nil
	}
}

func ( *Draft) ( map[string]any) string {
	if .version < 2019 {
		if ,  := ["$ref"];  {
			// All other properties in a "$ref" object MUST be ignored
			return ""
		}
	}

	,  := strVal(, .id)
	if ! {
		return ""
	}
	, _ = split() // ignore fragment
	return 
}

func ( *Draft) ( url,  any,  map[string]*Vocabulary) ([]string, error) {
	if .version < 2019 {
		return nil, nil
	}
	,  := .(map[string]any)
	if ! {
		return nil, nil
	}
	,  := ["$vocabulary"]
	if ! {
		return nil, nil
	}
	,  = .(map[string]any)
	if ! {
		return nil, nil
	}

	var  []string
	for ,  := range  {
		if ,  := .(bool); ! || ! {
			continue
		}
		,  := strings.CutPrefix(, .vocabPrefix)
		if  {
			if ,  := .allVocabs[];  {
				if !slices.Contains(, ) {
					 = append(, )
					continue
				}
			}
		}
		if ,  := []; ! {
			return nil, &UnsupportedVocabularyError{.String(), }
		}
		if !slices.Contains(, ) {
			 = append(, )
		}
	}
	if !slices.Contains(, "core") {
		 = append(, "core")
	}
	return , nil
}

// --

type dialect struct {
	draft  *Draft
	vocabs []string // nil means use draft.defaultVocabs
}

func ( *dialect) ( string) bool {
	if  == "core" || .draft.version < 2019 {
		return true
	}
	if .vocabs != nil {
		return slices.Contains(.vocabs, )
	}
	return slices.Contains(.draft.defaultVocabs, )
}

func ( *dialect) ( bool,  map[string]*Vocabulary) []string {
	if len() == 0 {
		return .vocabs
	}
	if .draft.version < 2019 {
		 = true
	}
	if ! {
		return .vocabs
	}
	var  []string
	if .vocabs == nil {
		 = slices.Clone(.draft.defaultVocabs)
	} else {
		 = slices.Clone(.vocabs)
	}
	for  := range  {
		if !slices.Contains(, ) {
			 = append(, )
		}
	}
	return 
}

func ( *dialect) ( bool,  map[string]*Vocabulary) *Schema {
	 := .activeVocabs(, )
	if  == nil {
		return .draft.sch
	}

	var  []*Schema
	for ,  := range  {
		 := .draft.allVocabs[]
		if  == nil {
			if ,  := [];  {
				 = .Schema
			}
		}
		if  != nil {
			 = append(, )
		}
	}
	if !slices.Contains(, "core") {
		 := .draft.allVocabs["core"]
		if  == nil {
			 = .draft.sch
		}
		 = append(, )
	}
	 := &Schema{
		Location:     "urn:mem:metaschema",
		up:           urlPtr{url("urn:mem:metaschema"), ""},
		DraftVersion: .draft.version,
		AllOf:        ,
	}
	.resource = 
	if .DraftVersion >= 2020 {
		.DynamicAnchor = "meta"
		.dynamicAnchors = map[string]*Schema{
			"meta": ,
		}
	}
	return 
}

// --

type ParseIDError struct {
	URL string
}

func ( *ParseIDError) () string {
	return fmt.Sprintf("error in parsing id at %q", .URL)
}

// --

type ParseAnchorError struct {
	URL string
}

func ( *ParseAnchorError) () string {
	return fmt.Sprintf("error in parsing anchor at %q", .URL)
}

// --

type DuplicateIDError struct {
	ID   string
	URL  string
	Ptr1 string
	Ptr2 string
}

func ( *DuplicateIDError) () string {
	return fmt.Sprintf("duplicate id %q in %q at %q and %q", .ID, .URL, .Ptr1, .Ptr2)
}

// --

type DuplicateAnchorError struct {
	Anchor string
	URL    string
	Ptr1   string
	Ptr2   string
}

func ( *DuplicateAnchorError) () string {
	return fmt.Sprintf("duplicate anchor %q in %q at %q and %q", .Anchor, .URL, .Ptr1, .Ptr2)
}

// --

func joinSubschemas( []SchemaPath,  ...SchemaPath) []SchemaPath {
	var  []SchemaPath
	 = append(, ...)
	 = append(, ...)
	return 
}