package release

import (
	
	
	
	

	
	
	
	
	
)

// ModuleChange summarizes VCS change state for a module since its latest tag.
type ModuleChange struct {
	LatestTag    string
	LatestVer    string
	Changed      bool
	ChangedFiles int
	APIDiff      *apidiff.ModuleDiff
}

// Snapshot is an immutable, I/O-free capture of repository state at a revision.
type Snapshot struct {
	VCS       string
	Discovery string
	Revision  vcs.Revision
	Modules   []*modgraph.Module
	Tags      []string
	Changes   map[string]ModuleChange // keyed by module path
}

// SnapshotOptions configures VCS and workspace I/O for CollectSnapshot.
type SnapshotOptions struct {
	VCS       vcs.VCS
	Workspace workspace.Loader
	Rev       string
	Filter    modgraph.FilterOptions
	APIDiff   bool
}

// CollectSnapshot performs all read-only VCS and workspace I/O required to
// construct an immutable Snapshot.
func ( context.Context,  SnapshotOptions) (*Snapshot, error) {
	,  := .VCS.ResolveRev(, .Rev)
	if  != nil {
		return nil, 
	}
	,  := .Workspace.Load(, .VCS, .ID)
	if  != nil {
		return nil, 
	}
	,  := .VCS.Tags()
	if  != nil {
		return nil, 
	}

	// Filter early so excluded modules do not incur VCS diff or apidiff work.
	, ,  := modgraph.Filter(, .Filter)
	if  != nil {
		return nil, 
	}

	 := make([]ModuleChange, len())
	 := make([]error, len())

	,  := context.WithCancel()
	defer ()

	 := make(chan struct{}, min(max(runtime.GOMAXPROCS(0), 1), 8))
	var  sync.WaitGroup
	for ,  := range  {
		,  := version.LatestTag(, .Dir)
		 := ModuleChange{
			LatestTag: ,
			LatestVer: ,
			Changed:   true,
		}
		if  == "" {
			[] = 
			continue
		}
		.Go(func() {
			select {
			case  <- struct{}{}:
				defer func() { <- }()
			case <-.Done():
				return
			}
			,  := .VCS.ChangedFiles(, .LatestTag, .ID, .Dir)
			if  != nil {
				[] = 
				()
				return
			}
			.ChangedFiles = len()
			.Changed = .ChangedFiles > 0
			[] = 
		})
	}
	.Wait()

	for ,  := range  {
		if  != nil {
			return nil, 
		}
	}

	 := make(map[string]ModuleChange, len())
	var  []apidiff.ModuleRequest
	for ,  := range  {
		 := []
		[.Path] = 
		if .APIDiff && .LatestTag != "" && .Changed {
			 = append(, apidiff.ModuleRequest{
				Path:   .Path,
				Dir:    .Dir,
				OldRev: .LatestTag,
			})
		}
	}

	if len() > 0 {
		 := transitiveWorkspaceDirs(, )
		,  := apidiff.CompareBatch(, .VCS, .ID, , )
		if  != nil {
			return nil, 
		}
		for ,  := range  {
			 := []
			.APIDiff = &
			[] = 
		}
	}

	return &Snapshot{
		VCS:       .VCS.Name(),
		Discovery: .Workspace.Name(),
		Revision:  ,
		Modules:   ,
		Tags:      ,
		Changes:   ,
	}, nil
}

// InspectOptions configures repository module inspection (for list, graph, and diff).
type InspectOptions struct {
	VCS       vcs.VCS
	Workspace workspace.Loader
	Rev       string
	Filter    modgraph.FilterOptions
	APIDiff   bool
}

// ModuleStatus describes the current VCS and dependency state of a module.
type ModuleStatus struct {
	Path          string              `json:"path"`
	Dir           string              `json:"dir"`
	Layer         int                 `json:"layer"`
	LatestTag     string              `json:"latestTag,omitzero"`
	LatestVer     string              `json:"latestVersion,omitzero"`
	Changed       bool                `json:"changed"`
	ChangedFiles  int                 `json:"changedFiles,omitzero"`
	Deps          []string            `json:"deps,omitzero"`
	APIDiff       *apidiff.ModuleDiff `json:"apiDiff,omitzero"`
	SuggestedBump version.BumpKind    `json:"suggestedBump,omitzero"`
}

// SkippedInfo records a module excluded from inspection or release.
type SkippedInfo struct {
	Path   string `json:"path"`
	Dir    string `json:"dir"`
	Reason string `json:"reason"`
}

// Inspection holds the result of inspecting a repository’s Go modules.
type Inspection struct {
	VCS       string           `json:"vcs"`
	Discovery string           `json:"discovery"`
	Revision  vcs.Revision     `json:"revision"`
	Layers    [][]ModuleStatus `json:"layers"`
	Skipped   []SkippedInfo    `json:"skipped,omitzero"`
}

// Inspect collects a Snapshot and delegates to the pure InspectSnapshot.
func ( context.Context,  InspectOptions) (*Inspection, error) {
	,  := CollectSnapshot(, SnapshotOptions())
	if  != nil {
		return nil, 
	}
	return InspectSnapshot(, .Filter)
}

// InspectSnapshot is a pure function that filters snap.Modules, builds the
// layered dependency graph, and produces an Inspection.
func ( *Snapshot,  modgraph.FilterOptions) (*Inspection, error) {
	, ,  := modgraph.Filter(.Modules, )
	if  != nil {
		return nil, 
	}
	if len() == 0 {
		return nil, modgraph.ErrNoModules
	}
	,  := modgraph.Build()
	if  != nil {
		return nil, 
	}

	 := make([][]ModuleStatus, len(.Layers()))
	for ,  := range .Layers() {
		 := make([]ModuleStatus, len())
		for ,  := range  {
			 := changeFor(, )
			var  []string
			for ,  := range .DepsOf(.Path) {
				 = append(, .Path)
			}
			var  version.BumpKind
			if .APIDiff != nil {
				 = .APIDiff.SuggestedBump(.LatestVer)
			}
			[] = ModuleStatus{
				Path:          .Path,
				Dir:           .Dir,
				Layer:         ,
				LatestTag:     .LatestTag,
				LatestVer:     .LatestVer,
				Changed:       .Changed,
				ChangedFiles:  .ChangedFiles,
				Deps:          ,
				APIDiff:       .APIDiff,
				SuggestedBump: ,
			}
		}
		[] = 
	}

	return &Inspection{
		VCS:       .VCS,
		Discovery: .Discovery,
		Revision:  .Revision,
		Layers:    ,
		Skipped:   toSkippedInfo(),
	}, nil
}

func ( *Snapshot,  *modgraph.Module) ModuleChange {
	if .Changes != nil {
		if ,  := .Changes[.Path];  {
			return 
		}
	}
	,  := version.LatestTag(.Tags, .Dir)
	return ModuleChange{
		LatestTag: ,
		LatestVer: ,
		Changed:    == "",
	}
}

func ( []modgraph.SkippedModule) []SkippedInfo {
	 := make([]SkippedInfo, len())
	for ,  := range  {
		[] = SkippedInfo{
			Path:   .Module.Path,
			Dir:    .Module.Dir,
			Reason: .Reason,
		}
	}
	return 
}

// transitiveWorkspaceDirs returns the repo-relative directories of all modules
// in reqs plus their transitive intra-workspace dependencies in kept.
func ( []*modgraph.Module,  []apidiff.ModuleRequest) []string {
	,  := modgraph.Build()
	if  != nil {
		 := make([]string, len())
		for ,  := range  {
			[] = .Dir
		}
		return 
	}

	 := make(map[string]bool)
	var  []string
	var  func( string)
	 = func( string) {
		if [] {
			return
		}
		[] = true
		if ,  := .Module();  {
			 = append(, .Dir)
		}
		for ,  := range .DepsOf() {
			(.Path)
		}
	}
	for ,  := range  {
		(.Path)
	}
	slices.Sort()
	return slices.Compact()
}