package jsonschema

import (
	
	gourl 
	
	
	
)

// Format defined specific format.
type Format struct {
	// Name of format.
	Name string

	// Validate checks if given value is of this format.
	Validate func(v any) error
}

var formats = map[string]*Format{
	"json-pointer":          {"json-pointer", validateJSONPointer},
	"relative-json-pointer": {"relative-json-pointer", validateRelativeJSONPointer},
	"uuid":                  {"uuid", validateUUID},
	"duration":              {"duration", validateDuration},
	"period":                {"period", validatePeriod},
	"ipv4":                  {"ipv4", validateIPV4},
	"ipv6":                  {"ipv6", validateIPV6},
	"hostname":              {"hostname", validateHostname},
	"email":                 {"email", validateEmail},
	"date":                  {"date", validateDate},
	"time":                  {"time", validateTime},
	"date-time":             {"date-time", validateDateTime},
	"uri":                   {"uri", validateURI},
	"iri":                   {"iri", validateURI},
	"uri-reference":         {"uri-reference", validateURIReference},
	"iri-reference":         {"iri-reference", validateURIReference},
	"uri-template":          {"uri-template", validateURITemplate},
	"semver":                {"semver", validateSemver},
}

// see https://www.rfc-editor.org/rfc/rfc6901#section-3
func validateJSONPointer( any) error {
	,  := .(string)
	if ! {
		return nil
	}
	if  == "" {
		return nil
	}
	if !strings.HasPrefix(, "/") {
		return LocalizableError("not starting with /")
	}
	for ,  := range strings.Split(, "/")[1:] {
		 := false
		for ,  := range  {
			if  {
				 = false
				if  != '0' &&  != '1' {
					return LocalizableError("~ must be followed by 0 or 1")
				}
				continue
			}
			if  == '~' {
				 = true
				continue
			}
			switch {
			case  >= '\x00' &&  <= '\x2E':
			case  >= '\x30' &&  <= '\x7D':
			case  >= '\x7F' &&  <= '\U0010FFFF':
			default:
				return LocalizableError("invalid character %q", )
			}
		}
		if  {
			return LocalizableError("~ must be followed by 0 or 1")
		}
	}
	return nil
}

// see https://tools.ietf.org/html/draft-handrews-relative-json-pointer-01#section-3
func validateRelativeJSONPointer( any) error {
	,  := .(string)
	if ! {
		return nil
	}

	// start with non-negative-integer
	 := 0
	for ,  := range  {
		if  >= '0' &&  <= '9' {
			++
		} else {
			break
		}
	}
	if  == 0 {
		return LocalizableError("must start with non-negative integer")
	}
	if  > 1 && strings.HasPrefix(, "0") {
		return LocalizableError("starts with zero")
	}
	 = [:]

	// followed by either json-pointer or '#'
	if  == "#" {
		return nil
	}
	return validateJSONPointer()
}

// see https://datatracker.ietf.org/doc/html/rfc4122#page-4
func validateUUID( any) error {
	,  := .(string)
	if ! {
		return nil
	}

	 := []int{8, 4, 4, 4, 12}
	 := strings.Split(, "-")
	if len() != len() {
		return LocalizableError("must have %d elements", len())
	}
	for ,  := range  {
		if len() != [] {
			return LocalizableError("element %d must be %d characters long", +1, [])
		}
		for ,  := range  {
			switch {
			case  >= '0' &&  <= '9':
			case  >= 'a' &&  <= 'f':
			case  >= 'A' &&  <= 'F':
			default:
				return LocalizableError("non-hex character %q", )
			}
		}
	}
	return nil
}

// see https://datatracker.ietf.org/doc/html/rfc3339#appendix-A
func validateDuration( any) error {
	,  := .(string)
	if ! {
		return nil
	}

	// must start with 'P'
	,  = strings.CutPrefix(, "P")
	if ! {
		return LocalizableError("must start with P")
	}
	if  == "" {
		return LocalizableError("nothing after P")
	}

	// dur-week
	if ,  := strings.CutSuffix(, "W");  {
		if  == "" {
			return LocalizableError("no number in week")
		}
		for ,  := range  {
			if  < '0' ||  > '9' {
				return LocalizableError("invalid week")
			}
		}
		return nil
	}

	 := []string{"YMD", "HMS"}
	for ,  := range strings.Split(, "T") {
		if  != 0 &&  == "" {
			return LocalizableError("no time elements")
		}
		if  >= len() {
			return LocalizableError("more than one T")
		}
		 := []
		for  != "" {
			 := 0
			for ,  := range  {
				if  >= '0' &&  <= '9' {
					++
				} else {
					break
				}
			}
			if  == 0 {
				return LocalizableError("missing number")
			}
			 = [:]
			if  == "" {
				return LocalizableError("missing unit")
			}
			 := [0]
			 := strings.IndexByte(, )
			if  == -1 {
				if strings.IndexByte([], ) != -1 {
					return LocalizableError("unit %q out of order", )
				}
				return LocalizableError("invalid unit %q", )
			}
			 = [+1:]
			 = [1:]
		}
	}

	return nil
}

func validateIPV4( any) error {
	,  := .(string)
	if ! {
		return nil
	}
	 := strings.Split(, ".")
	if len() != 4 {
		return LocalizableError("expected four decimals")
	}
	for ,  := range  {
		if len() > 1 && [0] == '0' {
			return LocalizableError("leading zeros")
		}
		,  := strconv.Atoi()
		if  != nil {
			return 
		}
		if  < 0 ||  > 255 {
			return LocalizableError("decimal must be between 0 and 255")
		}
	}
	return nil
}

func validateIPV6( any) error {
	,  := .(string)
	if ! {
		return nil
	}
	if !strings.Contains(, ":") {
		return LocalizableError("missing colon")
	}
	,  := netip.ParseAddr()
	if  != nil {
		return 
	}
	if .Zone() != "" {
		return LocalizableError("zone id is not a part of ipv6 address")
	}
	return nil
}

// see https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names
func validateHostname( any) error {
	,  := .(string)
	if ! {
		return nil
	}

	// entire hostname (including the delimiting dots but not a trailing dot) has a maximum of 253 ASCII characters
	 = strings.TrimSuffix(, ".")
	if len() > 253 {
		return LocalizableError("more than 253 characters long")
	}

	// Hostnames are composed of series of labels concatenated with dots, as are all domain names
	for ,  := range strings.Split(, ".") {
		// Each label must be from 1 to 63 characters long
		if len() < 1 || len() > 63 {
			return LocalizableError("label must be 1 to 63 characters long")
		}

		// labels must not start or end with a hyphen
		if strings.HasPrefix(, "-") {
			return LocalizableError("label starts with hyphen")
		}
		if strings.HasSuffix(, "-") {
			return LocalizableError("label ends with hyphen")
		}

		// labels may contain only the ASCII letters 'a' through 'z' (in a case-insensitive manner),
		// the digits '0' through '9', and the hyphen ('-')
		for ,  := range  {
			switch {
			case  >= 'a' &&  <= 'z':
			case  >= 'A' &&  <= 'Z':
			case  >= '0' &&  <= '9':
			case  == '-':
			default:
				return LocalizableError("invalid character %q", )
			}
		}
	}
	return nil
}

// see https://en.wikipedia.org/wiki/Email_address
func validateEmail( any) error {
	,  := .(string)
	if ! {
		return nil
	}
	// entire email address to be no more than 254 characters long
	if len() > 254 {
		return LocalizableError("more than 255 characters long")
	}

	// email address is generally recognized as having two parts joined with an at-sign
	 := strings.LastIndexByte(, '@')
	if  == -1 {
		return LocalizableError("missing @")
	}
	,  := [:], [+1:]

	// local part may be up to 64 characters long
	if len() > 64 {
		return LocalizableError("local part more than 64 characters long")
	}

	if len() > 1 && strings.HasPrefix(, `"`) && strings.HasSuffix(, `"`) {
		// quoted
		 := [1 : len()-1]
		if strings.IndexByte(, '\\') != -1 || strings.IndexByte(, '"') != -1 {
			return LocalizableError("backslash and quote are not allowed within quoted local part")
		}
	} else {
		// unquoted
		if strings.HasPrefix(, ".") {
			return LocalizableError("starts with dot")
		}
		if strings.HasSuffix(, ".") {
			return LocalizableError("ends with dot")
		}

		// consecutive dots not allowed
		if strings.Contains(, "..") {
			return LocalizableError("consecutive dots")
		}

		// check allowed chars
		for ,  := range  {
			switch {
			case  >= 'a' &&  <= 'z':
			case  >= 'A' &&  <= 'Z':
			case  >= '0' &&  <= '9':
			case strings.ContainsRune(".!#$%&'*+-/=?^_`{|}~", ):
			default:
				return LocalizableError("invalid character %q", )
			}
		}
	}

	// domain if enclosed in brackets, must match an IP address
	if strings.HasPrefix(, "[") && strings.HasSuffix(, "]") {
		 = [1 : len()-1]
		if ,  := strings.CutPrefix(, "IPv6:");  {
			if  := validateIPV6();  != nil {
				return LocalizableError("invalid ipv6 address: %v", )
			}
			return nil
		}
		if  := validateIPV4();  != nil {
			return LocalizableError("invalid ipv4 address: %v", )
		}
		return nil
	}

	// domain must match the requirements for a hostname
	if  := validateHostname();  != nil {
		return LocalizableError("invalid domain: %v", )
	}

	return nil
}

// see see https://datatracker.ietf.org/doc/html/rfc3339#section-5.6
func validateDate( any) error {
	,  := .(string)
	if ! {
		return nil
	}
	,  := time.Parse("2006-01-02", )
	return 
}

// see https://datatracker.ietf.org/doc/html/rfc3339#section-5.6
// NOTE: golang time package does not support leap seconds.
func validateTime( any) error {
	,  := .(string)
	if ! {
		return nil
	}

	// min: hh:mm:ssZ
	if len() < 9 {
		return LocalizableError("less than 9 characters long")
	}
	if [2] != ':' || [5] != ':' {
		return LocalizableError("missing colon in correct place")
	}

	// parse hh:mm:ss
	var  []int
	for ,  := range strings.SplitN([:8], ":", 3) {
		,  := strconv.Atoi()
		if  != nil {
			return LocalizableError("invalid hour/min/sec")
		}
		if  < 0 {
			return LocalizableError("non-positive hour/min/sec")
		}
		 = append(, )
	}
	if len() != 3 {
		return LocalizableError("missing hour/min/sec")
	}
	, ,  := [0], [1], [2]
	if  > 23 ||  > 59 ||  > 60 {
		return LocalizableError("hour/min/sec out of range")
	}
	 = [8:]

	// parse sec-frac if present
	if ,  := strings.CutPrefix(, ".");  {
		 := 0
		for ,  := range  {
			if  >= '0' &&  <= '9' {
				++
			} else {
				break
			}
		}
		if  == 0 {
			return LocalizableError("no digits in second fraction")
		}
		 = [:]
	}

	if  != "z" &&  != "Z" {
		// parse time-numoffset
		if len() != 6 {
			return LocalizableError("offset must be 6 characters long")
		}
		var  int
		switch [0] {
		case '+':
			 = -1
		case '-':
			 = +1
		default:
			return LocalizableError("offset must begin with plus/minus")
		}
		 = [1:]
		if [2] != ':' {
			return LocalizableError("missing colon in offset in correct place")
		}

		var  []int
		for ,  := range strings.SplitN(, ":", 2) {
			,  := strconv.Atoi()
			if  != nil {
				return LocalizableError("invalid hour/min in offset")
			}
			if  < 0 {
				return LocalizableError("non-positive hour/min in offset")
			}
			 = append(, )
		}
		,  := [0], [1]
		if  > 23 ||  > 59 {
			return LocalizableError("hour/min in offset out of range")
		}

		// apply timezone
		 := (*60 + ) + *(*60+)
		if  < 0 {
			 += 24 * 60
		}
		,  = /60, %60
	}

	// check leap second
	if  >= 60 && ( != 23 ||  != 59) {
		return LocalizableError("invalid leap second")
	}

	return nil
}

// see https://datatracker.ietf.org/doc/html/rfc3339#section-5.6
func validateDateTime( any) error {
	,  := .(string)
	if ! {
		return nil
	}

	// min: yyyy-mm-ddThh:mm:ssZ
	if len() < 20 {
		return LocalizableError("less than 20 characters long")
	}

	if [10] != 't' && [10] != 'T' {
		return LocalizableError("11th character must be t or T")
	}
	if  := validateDate([:10]);  != nil {
		return LocalizableError("invalid date element: %v", )
	}
	if  := validateTime([11:]);  != nil {
		return LocalizableError("invalid time element: %v", )
	}
	return nil
}

func parseURL( string) (*gourl.URL, error) {
	,  := gourl.Parse()
	if  != nil {
		return nil, 
	}

	// gourl does not validate ipv6 host address
	 := .Hostname()
	if strings.Contains(, ":") {
		if !strings.Contains(.Host, "[") || !strings.Contains(.Host, "]") {
			return nil, LocalizableError("ipv6 address not enclosed in brackets")
		}
		if  := validateIPV6();  != nil {
			return nil, LocalizableError("invalid ipv6 address: %v", )
		}
	}

	return , nil
}

func validateURI( any) error {
	,  := .(string)
	if ! {
		return nil
	}
	,  := parseURL()
	if  != nil {
		return 
	}
	if !.IsAbs() {
		return LocalizableError("relative url")
	}
	return nil
}

func validateURIReference( any) error {
	,  := .(string)
	if ! {
		return nil
	}
	if strings.Contains(, `\`) {
		return LocalizableError(`contains \`)
	}
	,  := parseURL()
	return 
}

func validateURITemplate( any) error {
	,  := .(string)
	if ! {
		return nil
	}
	,  := parseURL()
	if  != nil {
		return 
	}
	for ,  := range strings.Split(.RawPath, "/") {
		,  = decode()
		if  != nil {
			return LocalizableError("percent decode failed: %v", )
		}
		 := true
		for ,  := range  {
			var  bool
			switch  {
			case '{':
				 = true
			case '}':
				 = false
			default:
				continue
			}
			if  !=  {
				return LocalizableError("nested curly braces")
			}
			 = !
		}
		if ! {
			return LocalizableError("no matching closing brace")
		}
	}
	return nil
}

func validatePeriod( any) error {
	,  := .(string)
	if ! {
		return nil
	}

	 := strings.IndexByte(, '/')
	if  == -1 {
		return LocalizableError("missing slash")
	}

	,  := [:], [+1:]
	if strings.HasPrefix(, "P") {
		if  := validateDuration();  != nil {
			return LocalizableError("invalid start duration: %v", )
		}
		if  := validateDateTime();  != nil {
			return LocalizableError("invalid end date-time: %v", )
		}
	} else {
		if  := validateDateTime();  != nil {
			return LocalizableError("invalid start date-time: %v", )
		}
		if strings.HasPrefix(, "P") {
			if  := validateDuration();  != nil {
				return LocalizableError("invalid end duration: %v", )
			}
		} else if  := validateDateTime();  != nil {
			return LocalizableError("invalid end date-time: %v", )
		}
	}

	return nil
}

// see https://semver.org/#backusnaur-form-grammar-for-valid-semver-versions
func validateSemver( any) error {
	,  := .(string)
	if ! {
		return nil
	}

	// build --
	if  := strings.IndexByte(, '+');  != -1 {
		 := [+1:]
		if  == "" {
			return LocalizableError("build is empty")
		}
		for ,  := range strings.Split(, ".") {
			if  == "" {
				return LocalizableError("build identifier is empty")
			}
			for ,  := range  {
				switch {
				case  >= '0' &&  <= '9':
				case ( >= 'a' &&  <= 'z') || ( >= 'A' &&  <= 'Z') ||  == '-':
				default:
					return LocalizableError("invalid character %q in build identifier", )
				}
			}
		}
		 = [:]
	}

	// pre-release --
	if  := strings.IndexByte(, '-');  != -1 {
		 := [+1:]
		for ,  := range strings.Split(, ".") {
			if  == "" {
				return LocalizableError("pre-release identifier is empty")
			}
			 := true
			for ,  := range  {
				switch {
				case  >= '0' &&  <= '9':
				case ( >= 'a' &&  <= 'z') || ( >= 'A' &&  <= 'Z') ||  == '-':
					 = false
				default:
					return LocalizableError("invalid character %q in pre-release identifier", )
				}
			}
			if  && len() > 1 && [0] == '0' {
				return LocalizableError("pre-release numeric identifier starts with zero")
			}
		}
		 = [:]
	}

	// versionCore --
	 := strings.Split(, ".")
	if len() != 3 {
		return LocalizableError("versionCore must have 3 numbers separated by dot")
	}
	 := []string{"major", "minor", "patch"}
	for ,  := range  {
		if  == "" {
			return LocalizableError("%s is empty", [])
		}
		if len() > 1 && [0] == '0' {
			return LocalizableError("%s starts with zero", [])
		}
		for ,  := range  {
			if  < '0' ||  > '9' {
				return LocalizableError("%s contains non-digit", [])
			}
		}
	}

	return nil
}