package goabnf

import (
	
	
	
	
	
)

// Generate is an experimental feature that consumes a seed for
// a pseudo-random number generator, used to randomly travel through
// the grammar given a rulename to work on.
// With this, it provides reproducibility, usefull for fuzz crashers.
//
// You can leverage its capacities (maximum repetitions, length
// threshold, etc.) with the functional options.
//
// It is a good capability for testing and fuzzing parsers during
// testing, compliance, fuzzing or optimization.
func ( *Grammar) ( int64,  string,  ...GenerateOption) ([]byte, error) {
	if  := checkCanGenerateSafely(, );  != nil {
		return nil, 
	}

	// Use a pseudo-random number generator
	 := rand.NewSource()

	// Define conditions from options
	 := &genOpts{
		repMax:    16,
		threshold: 256,
	}
	for ,  := range  {
		.apply()
	}

	// Generate actual content (rule exists, checked first)
	 := GetRule(, .Rulemap)
	 := []byte{}
	generateAlt(, , &, .Alternation, )
	return , nil
}

func generateAlt( rand.Source,  *Grammar,  *[]byte,  Alternation,  *genOpts) {
	// Select any possible path in the alternation
	 := .Concatenations[int(.Int63())%len(.Concatenations)]

	// Travel through all the repetitions
	for ,  := range .Repetitions {
		 := .Max
		if  == inf {
			 = .repMax
		}
		 := .Min + int(.Int63())%(-.Min+1)
		for  := 0; generateKeepGoing(, , .Min, len(*), .threshold); ++ {
			switch elem := .Element.(type) {
			case ElemRulename:
				 := GetRule(.Name, .Rulemap)
				(, , , .Alternation, )

			case ElemOption:
				if (.Int63() % 2) == 0 {
					(, , , .Alternation, )
				}

			case ElemGroup:
				(, , , .Alternation, )

			case ElemNumVal:
				switch .Status {
				case StatRange:
					,  := numvalToRune(.Elems[0], .Base), numvalToRune(.Elems[1], .Base)
					// Generation emits UTF-8 text, so clamp to the representable
					// (Unicode) subset; a range wholly above U+10FFFF (or with
					// max < min) yields no character.
					if  > utf8.MaxRune {
						 = utf8.MaxRune
					}
					if  <= utf8.MaxRune &&  <=  {
						 :=  + (rune(.Int63()&0x0F) % ( -  + 1)) // mask 0x0F to keep the 32-bit part (rune size)
						appendPtr(, )
					}

				case StatSeries:
					for ,  := range .Elems {
						 := numvalToRune(, .Base)
						// Skip values that are not real characters; they cannot be
						// emitted as UTF-8 text.
						if utf8.ValidRune() {
							appendPtr(, )
						}
					}
				}

			case ElemCharVal:
				for ,  := range .Values {
					if !.Sensitive && (int(.Int63())%2) == 0 {
						 = runeMax()
					}
					appendPtr(, )
				}
			}

			// Prose-val is not covered, checked before to avoid generation
		}
	}
}

func appendPtr( *[]byte,  ...rune) {
	 := *
	 = append(, []byte(string())...)
	* = 
}

func generateKeepGoing(, , , ,  int) bool {
	// If can do no run and reached threshold, skip
	if  == 0 &&  == 0 &&  >=  {
		return false
	}
	return  < 
}

// GenerateOption is an option for the *Grammar.Generate method.
type GenerateOption interface {
	apply(*genOpts)
}

type genOpts struct {
	repMax    int
	threshold int
}

type repMaxOption int

// WithRepMax defines the maximum repetition to stop generating at.
func ( int) repMaxOption {
	return repMaxOption()
}

func ( repMaxOption) ( *genOpts) {
	.repMax = int()
}

type thresholdOption int

// WithThreshold defines the length threshold to stop generating at.
func ( int) thresholdOption {
	return thresholdOption()
}

func ( thresholdOption) ( *genOpts) {
	.threshold = int()
}

// checkCanGenerateSafely returns no error if the rule can be generated
// safely i.e. if the rule can exist without infinite recursion, AND if it
// does not contain a prose-val as it could not generate from it.
// Factually, it checks if all involved rules have no path v such that it
// produces a cycle (v:rule-*->rule) AND that this path is mandatory
// (no option, no repetition with a minimum of zero).
func checkCanGenerateSafely( *Grammar,  string) error {
	 := GetRule(, .Rulemap)
	if  == nil {
		return &ErrRuleNotFound{
			Rulename: ,
		}
	}
	 := map[string]struct{}{
		: {},
	}
	if  := checkCanGenerateSafelyAlt(, , .Alternation);  != nil {
		if ,  := .(*ErrCyclicRule);  {
			return 
		}
		return &ErrCyclicRule{
			Rulename: ,
		}
	}
	return nil
}

func checkCanGenerateSafelyAlt( *Grammar,  map[string]struct{},  Alternation) error {
	 := make([]error, len(.Concatenations))
	for ,  := range .Concatenations {
		[] = checkCanGenerateSafelyConcat(, , )
	}
	 := true
	for  := 0;  < len() && ; ++ {
		if [] == nil {
			 = false
		}
	}
	if  {
		return errors.Join(...)
	}
	return nil
}

func checkCanGenerateSafelyConcat( *Grammar,  map[string]struct{},  Concatenation) error {
	for ,  := range .Repetitions {
		// If the repetition is not mandatory, we can escape so can
		// generate safely.
		if .Min == 0 {
			continue
		}

		// Deal with the repetition itself then.
		switch elem := .Element.(type) {
		case ElemRulename:
			// Copy rules to only focus on rules that made use come here.
			// If shared with others, the dependency graph can lead to the same rule
			// from another path without it being a cycle, thus must be handled.
			 := duplicateMap()
			for  := range  {
				if strings.EqualFold(.Name, ) {
					return &ErrCyclicRule{
						Rulename: .Name,
					}
				}
			}
			 := GetRule(.Name, .Rulemap)
			[.Name] = struct{}{}
			if  := checkCanGenerateSafelyAlt(, , .Alternation);  != nil {
				if ,  := .(*ErrCyclicRule);  {
					return 
				}
				return &ErrCyclicRule{
					Rulename: .Name,
				}
			}

		case ElemGroup:
			if  := checkCanGenerateSafelyAlt(, , .Alternation);  != nil {
				return 
			}

		case ElemProseVal:
			return ErrHandlingProseVal

			// Other types are not considered for the following reasons:
			// - option: equivalent to rep.min==0, escapable path even if could be cyclic
			// - num-val, char-val: termination paths, can't be cyclic
		}
	}
	return nil
}

func duplicateMap[ comparable,  any]( map[]) map[] {
	 := make(map[], len())
	maps.Copy(, )
	return 
}