package release

import (
	
	
	
	
	
	
	

	
	
	
	
	
	
)

// PlanOptions configures release planning.
type PlanOptions struct {
	VCS            vcs.VCS
	Workspace      workspace.Loader
	Rev            string
	Spec           version.Spec
	Overrides      map[string]string
	Filter         modgraph.FilterOptions
	ChangedOnly    bool
	WithDependents bool
	SkipExisting   bool
	Check          config.CheckMode
	CommitTemplate string
	TagTemplate    string
}

// PlanSpec holds all pure parameters needed to compute a Plan from a Snapshot.
type PlanSpec struct {
	Spec           version.Spec
	Overrides      map[string]string
	Filter         modgraph.FilterOptions
	ChangedOnly    bool
	WithDependents bool
	SkipExisting   bool
	Check          config.CheckMode
	CommitTemplate string
	TagTemplate    string
}

// ModulePlan describes the planned release of a single module.
type ModulePlan struct {
	Path            string              `json:"path"`
	Dir             string              `json:"dir"`
	PreviousTag     string              `json:"previousTag,omitzero"`
	PreviousVersion string              `json:"previousVersion,omitzero"`
	TargetVersion   string              `json:"targetVersion"`
	Tag             string              `json:"tag"`
	TagMessage      string              `json:"tagMessage,omitzero"`
	Deps            []string            `json:"deps,omitzero"`
	Changed         bool                `json:"changed"`
	ChangedFiles    int                 `json:"changedFiles,omitzero"`
	APIDiff         *apidiff.ModuleDiff `json:"apiDiff,omitzero"`
	Warnings        []string            `json:"warnings,omitzero"`
}

// LayerPlan describes a single topological layer of a release.
type LayerPlan struct {
	Index         int          `json:"index"`
	CommitMessage string       `json:"commitMessage,omitzero"`
	Modules       []ModulePlan `json:"modules"`
}

// Plan is the immutable, validated release execution plan.
type Plan struct {
	VCS          string        `json:"vcs"`
	Discovery    string        `json:"discovery"`
	Revision     vcs.Revision  `json:"revision"`
	Layers       []LayerPlan   `json:"layers"`
	Skipped      []SkippedInfo `json:"skipped,omitzero"`
	Warnings     []string      `json:"warnings,omitzero"`
	TotalModules int           `json:"totalModules"`
	TotalCommits int           `json:"totalCommits"`
	TotalTags    int           `json:"totalTags"`
}

// DepBump describes a single dependency version bump included in a commit.
type DepBump struct {
	Module  string
	Version string
	Tag     string
}

// CommitTemplateData is passed to CommitTemplate when rendering layer commit messages.
type CommitTemplateData struct {
	Layer       int
	Modules     []string
	Deps        []DepBump
	UpdatedDeps []string
	Revision    vcs.Revision
	VCS         string
}

// TagTemplateData is passed to TagTemplate when rendering tag messages.
type TagTemplateData struct {
	Module          string
	Dir             string
	Version         string
	Tag             string
	PreviousVersion string
	PreviousTag     string
	Revision        vcs.Revision
	VCS             string
	APIDiff         *apidiff.ModuleDiff
}

// BuildPlan collects a Snapshot and delegates to the pure PlanFromSnapshot.
func ( context.Context,  PlanOptions) (*Plan, error) {
	 := .Spec.Bump == version.BumpAuto ||
		.Check == config.CheckWarn ||
		.Check == config.CheckError
	,  := CollectSnapshot(, SnapshotOptions{
		VCS:       .VCS,
		Workspace: .Workspace,
		Rev:       .Rev,
		Filter:    .Filter,
		APIDiff:   ,
	})
	if  != nil {
		return nil, 
	}
	return PlanFromSnapshot(, PlanSpec{
		Spec:           .Spec,
		Overrides:      .Overrides,
		Filter:         .Filter,
		ChangedOnly:    .ChangedOnly,
		WithDependents: .WithDependents,
		SkipExisting:   .SkipExisting,
		Check:          .Check,
		CommitTemplate: .CommitTemplate,
		TagTemplate:    .TagTemplate,
	})
}

// PlanFromSnapshot is a pure function that validates all preconditions and
// builds a layered release Plan from snap without performing any I/O.
func ( *Snapshot,  PlanSpec) (*Plan, error) {
	, ,  := parseTemplates(.CommitTemplate, .TagTemplate)
	if  != nil {
		return nil, 
	}

	, ,  := modgraph.Filter(.Modules, .Filter)
	if  != nil {
		return nil, 
	}
	if len() == 0 {
		return nil, modgraph.ErrNoModules
	}

	,  := modgraph.Build()
	if  != nil {
		return nil, 
	}

	 := toSkippedInfo()

	if .ChangedOnly {
		, ,  = filterChanged(, , .WithDependents, )
		if  != nil {
			return nil, 
		}
	}

	 := make(map[string]bool, len(.Tags))
	for ,  := range .Tags {
		[] = true
	}

	 := make(map[string]string, len(.Modules()))
	 := make(map[string]string, len(.Modules()))
	 := make(map[string][]string)
	 := make(map[string]bool, len(.Modules()))
	 := false

	for ,  := range .Modules() {
		 := changeFor(, )
		 := .Spec
		if .Bump == version.BumpAuto {
			switch {
			case .APIDiff != nil:
				.Bump = .APIDiff.SuggestedBump(.LatestVer)
			case .LatestVer == "":
				.Bump = version.BumpMinor
			default:
				.Bump = version.BumpPatch
			}
		}
		,  := version.Resolve(.Path, .Dir, .LatestVer, , .Overrides)
		if  != nil {
			return nil, 
		}
		 := version.TagFor(.Dir, )
		if [] {
			if !.SkipExisting {
				return nil, fmt.Errorf("tag %q already exists for module %s", , .Path)
			}
			 = true
			 = append(, SkippedInfo{
				Path:   .Path,
				Dir:    .Dir,
				Reason: fmt.Sprintf("tag %s already exists", ),
			})
			continue
		}
		if .APIDiff != nil && (.Check == config.CheckWarn || .Check == config.CheckError) {
			if  := .APIDiff.CheckCompatibility(.LatestVer, ); len() > 0 {
				if .Check == config.CheckError {
					return nil, fmt.Errorf("compatibility check failed for %s: %s", .Path, [0])
				}
				[.Path] = 
			}
		}
		[.Path] = 
		[.Path] = 
		[.Path] = true
	}

	if  {
		,  = .Subgraph()
		if  != nil {
			return nil, 
		}
		if len(.Modules()) == 0 {
			return nil, modgraph.ErrNoModules
		}
	}

	 := &Plan{
		VCS:       .VCS,
		Discovery: .Discovery,
		Revision:  .Revision,
		Skipped:   ,
	}

	for ,  := range .Layers() {
		,  := buildLayerPlan(
			, , , ,
			, , ,
			, ,
		)
		if  != nil {
			return nil, 
		}
		.TotalModules += len(.Modules)
		.TotalTags += len(.Modules)
		if .CommitMessage != "" {
			.TotalCommits++
		}
		for ,  := range .Modules {
			for ,  := range .Warnings {
				.Warnings = append(.Warnings, fmt.Sprintf("%s: %s", .Path, ))
			}
		}
		.Layers = append(.Layers, )
	}

	return , nil
}

func (
	 int,
	 []*modgraph.Module,
	 *Snapshot,
	 *modgraph.Graph,
	,  map[string]string,
	 map[string][]string,
	,  *template.Template,
) (LayerPlan, error) {
	 := LayerPlan{
		Index:   ,
		Modules: make([]ModulePlan, len()),
	}

	var  []string
	 := make(map[string]bool)

	for ,  := range  {
		 := changeFor(, )
		 := [.Path]
		 := [.Path]
		 = append(, .Path)

		var  []string
		for ,  := range .DepsOf(.Path) {
			 = append(, .Path)
			[.Path] = true
		}

		,  := renderTemplate(, TagTemplateData{
			Module:          .Path,
			Dir:             .Dir,
			Version:         ,
			Tag:             ,
			PreviousVersion: .LatestVer,
			PreviousTag:     .LatestTag,
			Revision:        .Revision,
			VCS:             .VCS,
			APIDiff:         .APIDiff,
		})
		if  != nil {
			return LayerPlan{}, fmt.Errorf("render tag template for %s: %w", .Path, )
		}

		.Modules[] = ModulePlan{
			Path:            .Path,
			Dir:             .Dir,
			PreviousTag:     .LatestTag,
			PreviousVersion: .LatestVer,
			TargetVersion:   ,
			Tag:             ,
			TagMessage:      ,
			Deps:            ,
			Changed:         .Changed,
			ChangedFiles:    .ChangedFiles,
			APIDiff:         .APIDiff,
			Warnings:        [.Path],
		}
	}

	if len() > 0 {
		 := slices.Sorted(maps.Keys())
		 := make([]DepBump, len())
		for ,  := range  {
			[] = DepBump{
				Module:  ,
				Version: [],
				Tag:     [],
			}
		}
		var  error
		.CommitMessage,  = renderTemplate(, CommitTemplateData{
			Layer:       ,
			Modules:     ,
			Deps:        ,
			UpdatedDeps: ,
			Revision:    .Revision,
			VCS:         .VCS,
		})
		if  != nil {
			return LayerPlan{}, fmt.Errorf("render commit template for layer %d: %w", , )
		}
	}

	return , nil
}

func (
	 *Snapshot,
	 *modgraph.Graph,
	 bool,
	 []SkippedInfo,
) (*modgraph.Graph, []SkippedInfo, error) {
	var  []string
	for ,  := range .Modules() {
		if changeFor(, ).Changed {
			 = append(, .Path)
		}
	}

	 := make(map[string]bool, len())
	if  {
		 = .TransitiveDependents()
	} else {
		for ,  := range  {
			[] = true
		}
	}

	for ,  := range .Modules() {
		if ![.Path] {
			 := changeFor(, )
			 = append(, SkippedInfo{
				Path:   .Path,
				Dir:    .Dir,
				Reason: fmt.Sprintf("unchanged since %s", .LatestTag),
			})
		}
	}

	,  := .Subgraph()
	if  != nil {
		return nil, nil, 
	}
	if len(.Modules()) == 0 {
		return nil, nil, modgraph.ErrNoModules
	}
	return , , nil
}

func (,  string) (,  *template.Template,  error) {
	,  = template.New("commit").Parse(cmp.Or(, config.DefaultCommitTemplate))
	if  != nil {
		return nil, nil, fmt.Errorf("parse commit template: %w", )
	}
	,  = template.New("tag").Parse(cmp.Or(, config.DefaultTagTemplate))
	if  != nil {
		return nil, nil, fmt.Errorf("parse tag template: %w", )
	}
	return , , nil
}

func ( *template.Template,  any) (string, error) {
	var  bytes.Buffer
	if  := .Execute(&, );  != nil {
		return "", 
	}
	return .String(), nil
}