package hgvcs

import (
	
	
	
	
	
	
	
	
	

	
)

// Name is the backend identifier for Mercurial.
const Name = "hg"

const (
	defaultRev              = "."
	defaultTagCommitMessage = "chore: add release tags"
	syntheticTipTag         = "tip"
	hgtagsFile              = ".hgtags"
)

// Config holds Mercurial-specific options decoded from goship.json’s "vcs" object.
type Config struct {
	// Program overrides the hg executable name or path passed to exec.LookPath
	// (default "hg").
	Program string `json:"program,omitzero"`
	// TagCommitMessage is the commit message used for the single batched
	// .hgtags commit created during Publish.
	TagCommitMessage string `json:"tagCommitMessage,omitzero"`
}

func ( Config) () string {
	return cmp.Or(.TagCommitMessage, defaultTagCommitMessage)
}

// Opener returns a vcs.Opener for the Mercurial backend using cfg.
func ( Config) vcs.Opener {
	return vcs.Opener{
		Name: Name,
		Open: func( context.Context,  string) (vcs.VCS, error) {
			return Open(, , )
		},
	}
}

// Repo implements vcs.VCS for a Mercurial repository.
type Repo struct {
	root    string
	program string
	cfg     Config
}

// Open locates the Mercurial repository containing dir.
func ( context.Context,  string,  Config) (vcs.VCS, error) {
	,  := exec.LookPath(cmp.Or(.Program, Name))
	if  != nil {
		return nil, fmt.Errorf("hg binary not found: %w", )
	}
	,  := runHg(, , , "root")
	if  != nil {
		return nil, fmt.Errorf("not a mercurial repository: %w", )
	}
	return &Repo{
		root:    filepath.Clean(strings.TrimSpace()),
		program: ,
		cfg:     ,
	}, nil
}

// Name returns "hg".
func ( *Repo) () string { return Name }

// Root returns the absolute path to the repository root.
func ( *Repo) () string { return .root }

// ResolveRev resolves rev ("" defaults to ".").
func ( *Repo) ( context.Context,  string) (vcs.Revision, error) {
	 = cmp.Or(, defaultRev)
	,  := runHg(, .program, .root, "log", "-r", , "-T", "{node}\n{branch}\n{activebookmark}")
	if  != nil {
		return vcs.Revision{}, fmt.Errorf("resolve hg revision %q: %w", , )
	}
	 := strings.Split(strings.TrimRight(, "\r\n"), "\n")
	if len() == 0 || strings.TrimSpace([0]) == "" {
		return vcs.Revision{}, fmt.Errorf("resolve hg revision %q: empty output", )
	}
	 := vcs.Revision{ID: strings.TrimSpace([0])}
	if len() > 1 {
		.Label = strings.TrimSpace([1])
	}
	if len() > 2 && strings.TrimSpace([2]) != "" {
		 := strings.TrimSpace([2])
		.Ref = 
		.Label = 
	}
	return , nil
}

// Tags returns all non-synthetic tags in the repository (excluding "tip").
func ( *Repo) ( context.Context) ([]string, error) {
	,  := runHg(, .program, .root, "tags", "-q")
	if  != nil {
		return nil, fmt.Errorf("list hg tags: %w", )
	}
	var  []string
	for  := range strings.Lines() {
		if  = strings.TrimSpace();  != "" &&  != "tip" {
			 = append(, )
		}
	}
	return , nil
}

// ChangedFiles returns repo-relative slash paths changed between baseRev and
// targetRev under dir.
func ( *Repo) ( context.Context, , ,  string) ([]string, error) {
	 := []string{"status", "--rev", , "--rev", , "--no-status", "-0"}
	if  := vcs.CleanRelDir();  != "" {
		 = append(, )
	}
	,  := runHgBytes(, .program, .root, ...)
	if  != nil {
		return nil, fmt.Errorf("hg status %s..%s: %w", , , )
	}
	var  []string
	for  := range bytes.SplitSeq(, []byte{0}) {
		if len() > 0 {
			 = append(, filepath.ToSlash(string()))
		}
	}
	return , nil
}

// ListFiles returns all tracked files at rev under dir.
func ( *Repo) ( context.Context, ,  string) ([]vcs.FileEntry, error) {
	return listFiles(, .program, .root, , )
}

// ReadFile returns the contents of slashPath at rev.
func ( *Repo) ( context.Context, ,  string) ([]byte, error) {
	 := vcs.CleanRelPath()
	,  := runHgBytes(, .program, .root, "cat", "-r", , "--", )
	if  != nil {
		return nil, fmt.Errorf("hg cat %s@%s: %w", , , )
	}
	return , nil
}

// Export extracts the tracked tree at rev into destDir using a single
// "hg archive" invocation.
func ( *Repo) ( context.Context, ,  string) error {
	if ,  := runHg(, .program, .root, "archive", "-r", , "-t", "files", );  != nil {
		return fmt.Errorf("hg archive %s: %w", , )
	}
	return nil
}

// Begin creates an isolated temporary Mercurial clone updated to rev.ID.
func ( *Repo) ( context.Context,  vcs.Revision) (vcs.Session, error) {
	,  := os.MkdirTemp("", "goship-hg-clone-*")
	if  != nil {
		return nil, fmt.Errorf("create temp hg clone dir: %w", )
	}
	if ,  := runHg(, .program, .root, "clone", "--noupdate", .root, );  != nil {
		_ = os.RemoveAll()
		return nil, fmt.Errorf("hg clone: %w", )
	}
	if ,  := runHg(, .program, , "update", "-r", .ID);  != nil {
		_ = os.RemoveAll()
		return nil, fmt.Errorf("hg update %s: %w", .ID, )
	}
	,  := runHg(, .program, .root, "config", "ui.username")
	return &session{
		repo:     ,
		dir:      ,
		rev:      ,
		head:     .ID,
		username: strings.TrimSpace(),
	}, nil
}

// Push pushes commits and tags to remote (empty uses Mercurial’s "default").
func ( *Repo) ( context.Context, ,  string,  []string) error {
	 := []string{"push"}
	if  != "" {
		 = append(, )
	}
	if ,  := runHg(, .program, .root, ...);  != nil {
		return fmt.Errorf("hg push: %w", )
	}
	return nil
}

// PushHint formats an hg push command hint.
func ( *Repo) ( string,  vcs.PublishResult) string {
	if  != "" {
		return "hg push " + 
	}
	return "hg push"
}

func ( context.Context, , , ,  string) ([]vcs.FileEntry, error) {
	 := []string{"files", "-r", , "-0"}
	if  := vcs.CleanRelDir();  != "" {
		 = append(, )
	}
	,  := runHgBytes(, , , ...)
	if  != nil {
		return nil, fmt.Errorf("hg files -r %s: %w", , )
	}
	var  []vcs.FileEntry
	for  := range bytes.SplitSeq(, []byte{0}) {
		if len() == 0 {
			continue
		}
		 = append(, vcs.FileEntry{
			Path: filepath.ToSlash(string()),
			Mode: fs.FileMode(0o644),
		})
	}
	return , nil
}

func ( context.Context, ,  string,  ...string) (string, error) {
	,  := runHgBytes(, , , ...)
	return string(), 
}

func ( context.Context, ,  string,  ...string) ([]byte, error) {
	return vcs.RunCmd(, , nil, []string{"HGPLAIN=1"}, , ...)
}