package apidiff

import (
	
	
	
	
	
	
	
	
	

	
	
	

	
)

const loadMode = packages.NeedName |
	packages.NeedFiles |
	packages.NeedImports |
	packages.NeedDeps |
	packages.NeedTypes |
	packages.NeedModule

// ModuleRequest specifies a module to compare between OldRev and a batch’s
// target revision.
type ModuleRequest struct {
	Path   string
	Dir    string
	OldRev string
}

// Compare loads exported packages for modDir at oldRev and newRev via v and
// returns their API diff. workspaceDirs lists all repo-relative module dirs so
// intra-workspace dependencies resolve locally without hitting a remote proxy.
func (
	 context.Context,
	 vcs.VCS,
	, ,  string,
	 []string,
) (ModuleDiff, error) {
	,  := CompareBatch(, , , []ModuleRequest{{
		Path:   ,
		Dir:    ,
		OldRev: ,
	}}, )
	if  != nil {
		return ModuleDiff{}, 
	}
	return [], nil
}

// CompareBatch compares multiple modules against their respective OldRevs in a
// single batched pass. Each unique commit revision is exported and loaded at
// most once, and distinct commits are loaded concurrently.
func (
	 context.Context,
	 vcs.VCS,
	 string,
	 []ModuleRequest,
	 []string,
) (map[string]ModuleDiff, error) {
	if len() == 0 {
		return nil, nil
	}

	,  := .ResolveRev(, )
	if  != nil {
		return nil, fmt.Errorf("resolve %s: %w", , )
	}
	 := .ID

	// Resolve each unique OldRev to its canonical commit ID so tags pointing to
	// the same commit share a single export and packages.Load pass.
	 := make(map[string]string)
	 := make(map[string]map[string]bool)
	 := func(,  string) {
		 := vcs.CleanRelPath()
		if [] == nil {
			[] = make(map[string]bool)
		}
		[][] = true
	}

	for ,  := range  {
		,  := [.OldRev]
		if ! {
			,  := .ResolveRev(, .OldRev)
			if  != nil {
				return nil, fmt.Errorf("resolve %s: %w", .OldRev, )
			}
			 = .ID
			[.OldRev] = 
		}
		if  ==  {
			continue
		}
		(, .Dir)
		(, .Dir)
	}

	// Load packages for each unique commit concurrently with bounded parallelism.
	type  struct {
		 map[string][]*packages.Package
		       error
	}
	 := make(map[string], len())
	var  sync.Mutex
	var  sync.WaitGroup
	 := make(chan struct{}, min(max(runtime.GOMAXPROCS(0), 1), 4))

	,  := context.WithCancel()
	defer ()

	for ,  := range  {
		 := slices.Sorted(maps.Keys())
		.Go(func() {
			select {
			case  <- struct{}{}:
				defer func() { <- }()
			case <-.Done():
				return
			}
			,  := loadCommitModules(, , , , )
			.Lock()
			[] = {: , : }
			.Unlock()
			if  != nil {
				()
			}
		})
	}
	.Wait()

	for ,  := range  {
		if . != nil {
			return nil, fmt.Errorf("load packages at %s: %w", , .)
		}
	}

	 := make(map[string]ModuleDiff, len())
	for ,  := range  {
		 := vcs.CleanRelPath(.Dir)
		 := [.OldRev]
		if  ==  {
			[.Path] = ModuleDiff{}
			continue
		}
		 := [].[]
		 := [].[]
		[.Path] = DiffPackages(, )
	}
	return , nil
}

func (
	 context.Context,
	 vcs.VCS,
	 string,
	 []string,
	 []string,
) (map[string][]*packages.Package, error) {
	,  := os.MkdirTemp("", "goship-apidiff-*")
	if  != nil {
		return nil, fmt.Errorf("create temp dir: %w", )
	}
	defer func() { _ = os.RemoveAll() }()

	if ,  := filepath.EvalSymlinks();  == nil {
		 = 
	}

	if  := materializeCommit(, , , , , );  != nil {
		return nil, 
	}

	// Collect all workspace modules that exist at rev for go.work.
	 := make(map[string]bool)
	var  []string
	for ,  := range append(slices.Clone(), ...) {
		 := vcs.CleanRelPath()
		if [] {
			continue
		}
		[] = true
		 := filepath.Join(, filepath.FromSlash(), "go.mod")
		if  == "." {
			 = filepath.Join(, "go.mod")
		}
		if ,  := os.Stat();  == nil {
			 = append(, )
		}
	}
	slices.Sort()

	 := append(os.Environ(), "GOWORK=off")
	 := 
	if len() > 0 {
		 := filepath.Join(, "go.work")
		var  bytes.Buffer
		if  := maxWorkspaceGoVersion(, );  != "" {
			fmt.Fprintf(&, "go %s\n\n", )
		}
		.WriteString("use (\n")
		for ,  := range  {
			if  == "." {
				.WriteString("\t.\n")
			} else {
				fmt.Fprintf(&, "\t./%s\n", )
			}
		}
		.WriteString(")\n")
		if  := os.WriteFile(, .Bytes(), 0o644);  == nil {
			 = append(os.Environ(), "GOWORK="+)
		}
	}

	 := make([]string, 0, len())
	 := make(map[string]string, len())
	for ,  := range  {
		if  == "." {
			 = append(, "./...")
			[filepath.Clean()] = "."
		} else {
			 = append(, "./"++"/...")
			[filepath.Clean(filepath.Join(, filepath.FromSlash()))] = 
		}
	}

	 := &packages.Config{
		Context: ,
		Mode:    loadMode,
		Dir:     ,
		Env:     ,
	}
	,  := packages.Load(, ...)
	if  != nil {
		return nil, 
	}

	 := make(map[string][]*packages.Package, len())
	for ,  := range  {
		if .Module == nil || .Module.Dir == "" {
			continue
		}
		 := filepath.Clean(.Module.Dir)
		if ,  := [];  {
			[] = append([], )
		}
	}
	return , nil
}

func (
	 context.Context,
	 vcs.VCS,
	,  string,
	,  []string,
) error {
	if ,  := .(vcs.Exporter);  {
		return .Export(, , )
	}

	 := make(map[string]bool)
	for ,  := range append(slices.Clone(), ...) {
		 := vcs.CleanRelPath()
		if [] {
			continue
		}
		[] = true
		,  := .ListFiles(, , )
		if  != nil || len() == 0 {
			continue
		}
		for ,  := range  {
			,  := .ReadFile(, , .Path)
			if  != nil {
				return fmt.Errorf("read %s@%s: %w", .Path, , )
			}
			if  := vcs.WriteDirFile(, .Path, );  != nil {
				return fmt.Errorf("materialize %s: %w", .Path, )
			}
		}
	}
	return nil
}

func ( string,  []string) string {
	var  string
	for ,  := range  {
		 := filepath.Join(, filepath.FromSlash(), "go.mod")
		if  == "." {
			 = filepath.Join(, "go.mod")
		}
		,  := os.ReadFile()
		if  != nil {
			continue
		}
		,  := modfile.ParseLax(, , nil)
		if  != nil || .Go == nil || .Go.Version == "" {
			continue
		}
		if  == "" || semver.Compare("v"+.Go.Version, "v"+) > 0 {
			 = .Go.Version
		}
	}
	return 
}