package modgraph

import (
	
	
	
)

// Require represents a single module requirement from go.mod.
type Require struct {
	Path     string
	Version  string
	Indirect bool
}

// Module represents a Go module participating in the dependency graph.
type Module struct {
	// Path is the Go module path (from go.mod’s module directive).
	Path string
	// Dir is the repo-relative slash path (e.g. "." or "clock").
	Dir string
	// Requires lists all require directives in the module’s go.mod.
	Requires []Require
}

// Graph represents a directed acyclic dependency graph of Go modules.
type Graph struct {
	modules    map[string]*Module
	deps       map[string][]*Module // module -> intra-graph dependencies
	dependents map[string][]*Module // module -> intra-graph reverse dependencies
	layers     [][]*Module
}

// Build constructs a Graph from modules, detects dependency cycles, and
// partitions the modules into topological layers using Kahn’s algorithm.
//
// Layer 0 contains modules with no intra-graph dependencies. Each subsequent
// layer k contains modules whose intra-graph dependencies all appear in layers
// strictly less than k.
func ( []*Module) (*Graph, error) {
	 := make(map[string]*Module, len())
	 := make(map[string]string, len())
	for ,  := range  {
		if ,  := [.Path];  {
			return nil, fmt.Errorf("duplicate module path %q", .Path)
		}
		if ,  := [.Dir];  {
			return nil, fmt.Errorf("duplicate module directory %q (%s and %s)", .Dir, , .Path)
		}
		[.Path] = 
		[.Dir] = .Path
	}

	 := make(map[string][]*Module, len())
	 := make(map[string][]*Module, len())
	 := make(map[string]int, len())

	for ,  := range  {
		 := make(map[string]bool)
		for ,  := range .Requires {
			if .Path == .Path || [.Path] {
				continue
			}
			,  := [.Path]
			if ! {
				continue
			}
			[.Path] = true
			[.Path] = append([.Path], )
			[.Path] = append([.Path], )
			[.Path]++
		}
	}

	for  := range  {
		slices.SortFunc([], compareModules)
	}
	for  := range  {
		slices.SortFunc([], compareModules)
	}

	// Kahn’s algorithm grouped by level so independent modules share a layer.
	var  []*Module
	for ,  := range  {
		if [.Path] == 0 {
			 = append(, )
		}
	}
	slices.SortFunc(, compareModules)

	var  [][]*Module
	 := 0
	for len() > 0 {
		 = append(, )
		 += len()

		var  []*Module
		for ,  := range  {
			for ,  := range [.Path] {
				[.Path]--
				if [.Path] == 0 {
					 = append(, )
				}
			}
		}
		slices.SortFunc(, compareModules)
		 = 
	}

	if  != len() {
		 := findCycle(, , )
		return nil, fmt.Errorf("circular module dependency: %s", strings.Join(, " -> "))
	}

	return &Graph{
		modules:    ,
		deps:       ,
		dependents: ,
		layers:     ,
	}, nil
}

// Layers returns the modules partitioned into topological layers.
func ( *Graph) () [][]*Module {
	return .layers
}

// Modules returns all modules in topological order.
func ( *Graph) () []*Module {
	var  []*Module
	for ,  := range .layers {
		 = append(, ...)
	}
	return 
}

// Module looks up a module by its Go module path.
func ( *Graph) ( string) (*Module, bool) {
	,  := .modules[]
	return , 
}

// DepsOf returns the sorted intra-graph dependencies of modPath.
func ( *Graph) ( string) []*Module {
	return .deps[]
}

// DependentsOf returns the sorted intra-graph modules that depend on modPath.
func ( *Graph) ( string) []*Module {
	return .dependents[]
}

// TransitiveDependents returns the set of all module paths in g that are either
// in seeds or depend (directly or transitively) on a module in seeds.
func ( *Graph) ( []string) map[string]bool {
	 := make(map[string]bool, len())
	 := make([]string, 0, len())
	for ,  := range  {
		if ,  := .modules[];  && ![] {
			[] = true
			 = append(, )
		}
	}
	for len() > 0 {
		 := [0]
		 = [1:]
		for ,  := range .dependents[] {
			if ![.Path] {
				[.Path] = true
				 = append(, .Path)
			}
		}
	}
	return 
}

// Subgraph returns a new layered Graph containing only modules whose Path is
// present in selected.
func ( *Graph) ( map[string]bool) (*Graph, error) {
	var  []*Module
	for ,  := range .Modules() {
		if [.Path] {
			 = append(, )
		}
	}
	return Build()
}

func (,  *Module) int {
	return strings.Compare(.Path, .Path)
}

func ( map[string]*Module,  map[string][]*Module,  map[string]int) []string {
	var  []string
	for ,  := range  {
		if  > 0 {
			 = append(, )
		}
	}
	slices.Sort()

	const (
		 = 0
		  = 1
		   = 2
	)
	 := make(map[string]int, len())
	var  []string
	var  []string

	var  func(string) bool
	 = func( string) bool {
		[] = 
		 = append(, )
		for ,  := range [] {
			 := .Path
			if [] == 0 {
				continue
			}
			if [] ==  {
				 := slices.Index(, )
				 = append([]string(nil), [:]...)
				 = append(, )
				return true
			}
			if [] ==  && () {
				return true
			}
		}
		 = [:len()-1]
		[] = 
		return false
	}

	for ,  := range  {
		if [] ==  && () {
			return 
		}
	}
	return 
}