package release

import (
	
	
	
	
	
	

	
	
)

// ExecuteOptions configures execution of a validated Plan.
type ExecuteOptions struct {
	VCS    vcs.VCS
	Push   bool
	Remote string
	OnStep func(event StepEvent)
}

// StepKind identifies a lifecycle event emitted during Execute.
type StepKind string

// Supported lifecycle event kinds emitted during Execute.
const (
	StepCommit   StepKind = "commit"
	StepTag      StepKind = "tag"
	StepChecksum StepKind = "checksum"
	StepPublish  StepKind = "publish"
	StepPush     StepKind = "push"
)

// StepEvent reports progress during Execute.
type StepEvent struct {
	Kind    StepKind
	Layer   int
	Module  string
	Tag     string
	Commit  string
	Message string
}

// Result summarizes a completed release execution.
type Result struct {
	Publish vcs.PublishResult `json:"publish"`
	Commits []CommitRecord    `json:"commits,omitzero"`
	Pushed  bool              `json:"pushed"`
	Remote  string            `json:"remote,omitzero"`
}

// CommitRecord records a dependency-update commit created during a release.
type CommitRecord struct {
	Layer   int      `json:"layer"`
	ID      string   `json:"id"`
	Message string   `json:"message"`
	Files   []string `json:"files"`
}

// Execute runs plan inside an isolated VCS session, computing module checksums
// locally through sess.FS() and publishing commits and tags atomically at the
// end. Execute performs no direct os/filepath I/O.
func ( context.Context,  *Plan,  ExecuteOptions) (*Result, error) {
	,  := .VCS.Begin(, .Revision)
	if  != nil {
		return nil, 
	}
	defer func() {
		_ = .Close()
	}()

	 := func( StepEvent) {
		if .OnStep != nil {
			.OnStep()
		}
	}

	 := make(map[string]modsum.Checksums, .TotalModules)
	var  []CommitRecord

	for ,  := range .Layers {
		if len() > 0 && .CommitMessage != "" {
			,  := commitLayerUpdates(, , , )
			if  != nil {
				return nil, 
			}
			if  != nil {
				 = append(, *)
				(StepEvent{
					Kind:    StepCommit,
					Layer:   .Index,
					Commit:  .ID,
					Message: .Message,
				})
			}
		}

		var  []vcs.FileEntry
		 :=  < len(.Layers)-1
		if  {
			,  = .ListFiles(, "")
			if  != nil {
				return nil, fmt.Errorf("list tracked files for layer %d: %w", .Index, )
			}
		}

		 := .FS()
		for ,  := range .Modules {
			if  := .Tag(, .Tag, vcs.TagOptions{Message: .TagMessage});  != nil {
				return nil, fmt.Errorf("tag %s: %w", .Tag, )
			}
			(StepEvent{
				Kind:   StepTag,
				Layer:  .Index,
				Module: .Path,
				Tag:    .Tag,
			})

			if  {
				,  := modsum.ComputeFS(, .Dir, .Path, .TargetVersion, )
				if  != nil {
					return nil, fmt.Errorf("compute checksums for %s@%s: %w", .Path, .TargetVersion, )
				}
				[.Path] = 
				(StepEvent{
					Kind:   StepChecksum,
					Layer:  .Index,
					Module: .Path,
					Tag:    .Tag,
				})
			}
		}
	}

	,  := .Publish()
	if  != nil {
		return nil, 
	}
	.PushHint = .VCS.PushHint(.Remote, )
	(StepEvent{
		Kind:    StepPublish,
		Commit:  .FinalID,
		Message: fmt.Sprintf("published %d tags", len(.Tags)),
	})

	if .Push {
		if  := .VCS.Push(, .Remote, .Ref, .Tags);  != nil {
			return nil, 
		}
		(StepEvent{
			Kind:    StepPush,
			Message: "pushed to remote",
		})
	}

	return &Result{
		Publish: ,
		Commits: ,
		Pushed:  .Push,
		Remote:  .Remote,
	}, nil
}

func (
	 context.Context,
	 vcs.Session,
	 LayerPlan,
	 map[string]modsum.Checksums,
) (*CommitRecord, error) {
	 := .FS()
	var  []string

	for ,  := range .Modules {
		if len(.Deps) == 0 {
			continue
		}
		 := make(map[string]modsum.Checksums, len(.Deps))
		for ,  := range .Deps {
			if ,  := [];  {
				[] = 
			}
		}
		if len() == 0 {
			continue
		}

		 := moduleFile(.Dir, "go.mod")
		 := moduleFile(.Dir, "go.sum")

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

		,  := modsum.RewriteModule(, , , )
		if  != nil {
			return nil, fmt.Errorf("update %s: %w", .Path, )
		}
		if .ModChanged {
			if  := .WriteFile(, .GoMod);  != nil {
				return nil, fmt.Errorf("write %s: %w", , )
			}
			 = append(, )
		}
		if .SumChanged {
			if  := .WriteFile(, .GoSum);  != nil {
				return nil, fmt.Errorf("write %s: %w", , )
			}
			 = append(, )
		}
	}

	if len() == 0 {
		return nil, nil
	}

	slices.Sort()
	,  := .Commit(, , vcs.CommitOptions{
		Message: .CommitMessage,
	})
	if  != nil {
		return nil, fmt.Errorf("commit layer %d updates: %w", .Index, )
	}
	return &CommitRecord{
		Layer:   .Index,
		ID:      ,
		Message: .CommitMessage,
		Files:   ,
	}, nil
}

func (,  string) string {
	if  == "" ||  == "." {
		return 
	}
	return path.Join(, )
}