package modsum

import (
	
	
	
	
	
	
	
	

	
)

// RewriteResult holds the pure output of RewriteModule.
type RewriteResult struct {
	GoMod      []byte
	GoSum      []byte
	ModChanged bool
	SumChanged bool
}

// RewriteModule updates go.mod and go.sum bytes in memory for all required
// modules present in updates.
func ( string, ,  []byte,  map[string]Checksums) (RewriteResult, error) {
	,  := modfile.Parse(, , nil)
	if  != nil {
		return RewriteResult{}, fmt.Errorf("parse %s: %w", , )
	}

	 := make(map[string]string)
	 := make(map[string]Checksums)
	for ,  := range .Require {
		,  := [.Mod.Path]
		if ! {
			continue
		}
		if .Mod.Version != .Version {
			[.Mod.Path] = .Mod.Version
			if  := .AddRequire(.Mod.Path, .Version);  != nil {
				return RewriteResult{}, fmt.Errorf("update require %s in %s: %w", .Mod.Path, , )
			}
		}
		[.Mod.Path] = 
	}
	if len() == 0 {
		return RewriteResult{GoMod: , GoSum: }, nil
	}

	.Cleanup()
	,  := .Format()
	if  != nil {
		return RewriteResult{}, fmt.Errorf("format %s: %w", , )
	}

	 := mergeGoSum(, , )
	return RewriteResult{
		GoMod:      ,
		GoSum:      ,
		ModChanged: !bytes.Equal(, ),
		SumChanged: !bytes.Equal(, ),
	}, nil
}

// UpdateModule reads go.mod and go.sum from modAbsDir, applies RewriteModule,
// and writes back only the files that changed.
func ( string,  map[string]Checksums) ([]string, error) {
	 := filepath.Join(, "go.mod")
	,  := os.ReadFile()
	if  != nil {
		return nil, fmt.Errorf("read %s: %w", , )
	}

	 := filepath.Join(, "go.sum")
	,  := os.ReadFile()
	if  != nil && !errors.Is(, os.ErrNotExist) {
		return nil, fmt.Errorf("read %s: %w", , )
	}

	,  := RewriteModule(, , , )
	if  != nil {
		return nil, 
	}

	var  []string
	if .ModChanged {
		if  := os.WriteFile(, .GoMod, 0o644);  != nil {
			return nil, fmt.Errorf("write %s: %w", , )
		}
		 = append(, "go.mod")
	}
	if .SumChanged {
		if  := os.WriteFile(, .GoSum, 0o644);  != nil {
			return nil, fmt.Errorf("write %s: %w", , )
		}
		 = append(, "go.sum")
	}
	return , nil
}

type sumEntry struct {
	mod  string
	ver  string // may include "/go.mod" suffix
	hash string
}

func ( []byte,  map[string]string,  map[string]Checksums) []byte {
	var  []sumEntry
	for  := range strings.Lines(string()) {
		 := strings.Fields()
		if len() != 3 {
			continue
		}
		 := sumEntry{mod: [0], ver: [1], hash: [2]}
		if ,  := [.mod];  {
			if .ver ==  || .ver == +"/go.mod" {
				continue
			}
		}
		if ,  := [.mod];  {
			if .ver == .Version || .ver == .Version+"/go.mod" {
				continue
			}
		}
		 = append(, )
	}

	for ,  := range  {
		 = append(,
			sumEntry{mod: .Module, ver: .Version, hash: .ZipHash},
			sumEntry{mod: .Module, ver: .Version + "/go.mod", hash: .ModHash},
		)
	}

	slices.SortFunc(, func(,  sumEntry) int {
		return cmp.Or(
			cmp.Compare(.mod, .mod),
			cmp.Compare(.ver, .ver),
			cmp.Compare(.hash, .hash),
		)
	})
	 = slices.Compact()

	var  bytes.Buffer
	for ,  := range  {
		fmt.Fprintf(&, "%s %s %s\n", .mod, .ver, .hash)
	}
	return .Bytes()
}