package goabnf

import (
	
	
	
)

type node struct {
	Rulename       string
	index, lowlink int
	onStack        bool
	Dependencies   []string
}

// Depgraph contains for each rule the rules it depends on.
// Notice it does not differentiate between a mandatory dependency
// or an avoidable one.
type Depgraph map[string]*node

// DependencyGraph creates a dependency graph for a whole grammar.
// It includes core rules only if necessary.
func ( *Grammar) () Depgraph {
	 := Depgraph{}
	for ,  := range coreRules {
		[strings.ToLower(.Name)] = &node{
			Rulename:     .Name,
			Dependencies: getDependencies(.Alternation),
		}
	}
	for ,  := range .Rulemap {
		[strings.ToLower(.Name)] = &node{
			Rulename:     .Name,
			Dependencies: getDependencies(.Alternation),
		}
	}
	return 
}

func getDependencies( Alternation) []string {
	 := []string{}
	for ,  := range .Concatenations {
		for ,  := range .Repetitions {
			switch v := .Element.(type) {
			case ElemGroup:
				 = appendDeps(, (.Alternation)...)
			case ElemOption:
				 = appendDeps(, (.Alternation)...)
			case ElemRulename:
				 = appendDeps(, strings.ToLower(.Name))
			}
		}
	}
	return 
}

func appendDeps( []string,  ...string) []string {
	for ,  := range  {
		if !slices.Contains(, ) {
			 = append(, )
		}
	}
	return 
}

// Mermaid returns a flowchart of the dependency graph.
func ( Depgraph) () string {
	var  strings.Builder
	.WriteString("flowchart TD\n")
	for ,  := range  {
		for ,  := range .Dependencies {
			fmt.Fprintf(&, "\t%s --> %s\n", .Rulename, )
		}
		.WriteString("\n")
	}
	return .String()
}

// IsDag find Strongly Connected Components using Tarjan's algorithm
// and returns whether it contains cycle or not.
// Could be improved by Nuutila's or Pearce's algorithms, or replaced
// by Kosaraju's algorithm.
func ( *Grammar) () bool {
	 := &cycle{
		index: 0,
		stack: []*node{},
		dg:    .DependencyGraph(),
	}
	.find()

	for ,  := range .sccs {
		if len() > 1 {
			return false
		}
	}
	return true
}

// RuleContainsCycle returns whether the rule contains a cycle or not.
// It travels through the whole rule dependency graph, such that
// it checks if the rule is cyclic AND if one of its dependency is too.
func ( *Grammar) ( string) (bool, error) {
	// Check the rule exists
	 := GetRule(, .Rulemap)
	if  == nil {
		return false, &ErrRuleNotFound{
			Rulename: ,
		}
	}

	// Get all SCCs
	 := &cycle{
		index: 0,
		stack: []*node{},
		dg:    .DependencyGraph(),
	}
	.find()

	return ruleContainsCycle(.sccs, ), nil
}

func ruleContainsCycle( [][]*node,  string) bool {
	// Index nodes by lowercase name and flag those sitting in a non-trivial SCC
	// (size > 1 == a cycle). Precomputing this removes the O(V) SCC scan that
	// the previous implementation did on every recursive step.
	 := make(map[string]*node, len())
	 := make(map[string]bool, len())

	for ,  := range  {
		 := len() > 1
		for ,  := range  {
			 := strings.ToLower(.Rulename)
			[] = 
			[] = 
		}
	}
	return ruleCycleVisit(strings.ToLower(), , , map[string]bool{})
}

// ruleCycleVisit reports whether the rule (or any transitive dependency) is
// cyclic. The visited set keeps each rule explored at most once: without it a
// diamond-shaped dependency DAG is walked along every root-to-leaf path, which
// is exponential. Marking on entry is safe because a cyclic rule returns true
// here before it can ever be marked-and-skipped, so a memoized rule is always
// genuinely acyclic.
func ruleCycleVisit( string,  map[string]*node, ,  map[string]bool) bool {
	if [] {
		return false
	}
	[] = true
	 := []
	if  == nil {
		// Unknown rule: treat as acyclic (matches the previous behaviour).
		return false
	}

	// Self-loop (a size-1 SCC with a self-edge is not flagged by inCycle).
	for ,  := range .Dependencies {
		if strings.ToLower() ==  {
			return true
		}
	}
	if [] {
		// If it depends on itself or is part of an SCC, then is cylic
		return true
	}

	for ,  := range .Dependencies {
		 := strings.ToLower()
		if  ==  {
			continue
		}
		if (, , , ) {
			return true
		}
	}
	return false
}

type cycle struct {
	index int
	stack []*node
	sccs  [][]*node

	dg Depgraph
}

func ( *cycle) () {
	for ,  := range .dg {
		if .index == 0 {
			.strongconnect()
		}
	}
}

func ( *cycle) ( *node) {
	// Set the depth index for v to the smallest unused index
	.index = .index
	.lowlink = .index
	.index++
	.stack = append(.stack, )
	.onStack = true

	// Consider successors of v
	for ,  := range .Dependencies {
		,  := .dg[]
		if ! {
			// core rules, as we know they won't have a cycle thus
			// no SCC, we don't need to recurse.
			continue
		}
		if .index == 0 {
			// Successor w has not yet been visited; recurse on it
			.()
			.lowlink = min(.lowlink, .lowlink)
		} else {
			if .onStack {
				// Successor w is in stack S and hence in the current SCC
				// If w is not on stack, then (v, w) is an edge pointing
				// to an SCC already found and must be ignored.
				.lowlink = min(.lowlink, .index)
			}
		}
	}
	// If v is a root node, pop the stack and generate an SCC
	if .lowlink == .index {
		 := []*node{}
		 := (*node)(nil)
		for  == nil || !strings.EqualFold(.Rulename, .Rulename) {
			 = .stack[len(.stack)-1]
			.stack = .stack[:len(.stack)-1]
			.onStack = false
			 = append(, )
		}
		.sccs = append(.sccs, )
	}
}