package jjvcs

import (
	
	
	
	
	
	
	
	
	

	
)

// Name is the backend identifier for Jujutsu.
const Name = "jj"

const (
	defaultRev    = "@"
	defaultRemote = "origin"
)

// Config holds Jujutsu-specific options decoded from goship.json’s "vcs" object.
type Config struct {
	// Program overrides the jj executable name or path passed to exec.LookPath
	// (default "jj").
	Program string `json:"program,omitzero"`
	// GitProgram overrides the git executable name or path passed to
	// exec.LookPath when writing or pushing tags in the underlying Git store
	// (default "git").
	GitProgram string `json:"gitProgram,omitzero"`
	// Annotated creates annotated Git tags in the underlying Git store when
	// true (default true) or lightweight tags when false.
	Annotated *bool `json:"annotated,omitzero"`
	// Sign signs Git tag objects when true.
	Sign *bool `json:"sign,omitzero"`
}

func ( Config) () bool {
	return .Annotated == nil || *.Annotated
}

// Opener returns a vcs.Opener for the Jujutsu 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 Jujutsu repository.
type Repo struct {
	root       string
	gitDir     string
	program    string
	gitProgram string
	cfg        Config
}

// Open locates the Jujutsu repository containing dir.
func ( context.Context,  string,  Config) (vcs.VCS, error) {
	,  := exec.LookPath(cmp.Or(.Program, Name))
	if  != nil {
		return nil, fmt.Errorf("jj binary not found: %w", )
	}
	var  string
	if .GitProgram != "" {
		,  = exec.LookPath(.GitProgram)
		if  != nil {
			return nil, fmt.Errorf("git binary not found: %w", )
		}
	} else if ,  := exec.LookPath("git");  == nil {
		 = 
	} else {
		 = "git"
	}
	,  := runJJ(, , , "root")
	if  != nil {
		return nil, fmt.Errorf("not a jujutsu repository: %w", )
	}
	 := filepath.Clean(strings.TrimSpace())
	,  := resolveGitDir(, , )
	return &Repo{
		root:       ,
		gitDir:     ,
		program:    ,
		gitProgram: ,
		cfg:        ,
	}, nil
}

func ( context.Context, ,  string) (string, error) {
	,  := runJJ(, , , "git", "root")
	if  == nil && strings.TrimSpace() != "" {
		return filepath.Clean(strings.TrimSpace()), nil
	}
	// Fallback to colocated .git or internal .jj/repo/store/git.
	for ,  := range []string{
		filepath.Join(, ".git"),
		filepath.Join(, ".jj", "repo", "store", "git"),
	} {
		if ,  := os.Stat();  == nil {
			return , nil
		}
	}
	return "", fmt.Errorf("could not locate jj git store")
}

// Name returns "jj".
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)
	 := `commit_id ++ "\n" ++ local_bookmarks.map(|b| b.name()).join(",")`
	,  := runJJ(, .program, .root, "log", "-r", , "--no-graph", "-T", )
	if  != nil {
		return vcs.Revision{}, fmt.Errorf("resolve jj revision %q: %w", , )
	}
	 := strings.Split(strings.TrimRight(, "\r\n"), "\n")
	if len() == 0 || strings.TrimSpace([0]) == "" {
		return vcs.Revision{}, fmt.Errorf("resolve jj revision %q: empty output", )
	}
	 := vcs.Revision{ID: strings.TrimSpace([0])}
	if len() > 1 {
		for  := range strings.SplitSeq(strings.TrimSpace([1]), ",") {
			if  = strings.TrimSpace();  != "" {
				.Ref = 
				.Label = 
				break
			}
		}
	}
	return , nil
}

// Tags returns all tags in the repository.
func ( *Repo) ( context.Context) ([]string, error) {
	,  := runJJ(, .program, .root, "tag", "list", "-T", `name ++ "\n"`)
	if  != nil {
		return nil, fmt.Errorf("list jj tags: %w", )
	}
	var  []string
	for  := range strings.Lines() {
		if  = strings.TrimSpace();  != "" {
			 = append(, )
		}
	}
	return , nil
}

// ChangedFiles returns repo-relative slash paths changed between baseRev and
// targetRev under dir.
func ( *Repo) ( context.Context, , ,  string) ([]string, error) {
	 := []string{"diff", "--from", , "--to", , "--name-only"}
	if  := vcs.CleanRelDir();  != "" {
		 = append(, )
	}
	,  := runJJ(, .program, .root, ...)
	if  != nil {
		return nil, fmt.Errorf("jj diff %s..%s: %w", , , )
	}
	var  []string
	for  := range strings.Lines() {
		if  := filepath.ToSlash(strings.TrimSpace());  != "" {
			 = append(, )
		}
	}
	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()
	,  := runJJBytes(, .program, .root, "file", "show", "-r", , )
	if  != nil {
		return nil, fmt.Errorf("jj file show %s@%s: %w", , , )
	}
	return , nil
}

// Export extracts the tracked tree at rev into destDir using a single
// "git archive" invocation against the underlying Git store.
func ( *Repo) ( context.Context, ,  string) error {
	if .gitDir == "" {
		return fmt.Errorf("jj export %s: underlying git store not found", )
	}
	,  := .ResolveRev(, )
	if  != nil {
		return 
	}
	 := exec.CommandContext(, .gitProgram, "-c", "core.autocrlf=false", "--git-dir", .gitDir, "archive", "--format=tar", .ID)
	.Dir = .root
	,  := .StdoutPipe()
	if  != nil {
		return fmt.Errorf("jj git archive %s pipe: %w", , )
	}
	var  bytes.Buffer
	.Stderr = &
	if  := .Start();  != nil {
		return fmt.Errorf("start jj git archive %s: %w", , )
	}
	 := vcs.ExtractTar(, , "")
	 := .Wait()
	if  != nil {
		return fmt.Errorf("jj git archive %s: %w", , )
	}
	if  != nil {
		return fmt.Errorf("jj git archive %s: %w: %s", , , strings.TrimSpace(.String()))
	}
	return nil
}

// Begin creates an isolated temporary Jujutsu workspace rooted at rev.ID.
func ( *Repo) ( context.Context,  vcs.Revision) (vcs.Session, error) {
	,  := os.MkdirTemp("", "goship-jj-ws-*")
	if  != nil {
		return nil, fmt.Errorf("create temp jj workspace dir: %w", )
	}
	 := filepath.Base()
	if ,  := runJJ(, .program, .root, "workspace", "add", "--name", , "--revision", .ID, );  != nil {
		_ = os.RemoveAll()
		return nil, fmt.Errorf("jj workspace add: %w", )
	}
	return &session{
		repo:   ,
		dir:    ,
		wsName: ,
		rev:    ,
		head:   .ID,
	}, nil
}

// Push pushes the bookmark via jj git push and tags via git push.
func ( *Repo) ( context.Context, ,  string,  []string) error {
	 := []string{"git", "push"}
	if  != "" {
		 = append(, "--remote", )
	}
	if  != "" {
		 = append(, "--bookmark", )
	}
	if  != "" {
		if ,  := runJJ(, .program, .root, ...);  != nil {
			return fmt.Errorf("jj git push: %w", )
		}
	}
	if len() > 0 {
		if .gitDir == "" {
			return fmt.Errorf("jj push tags: underlying git store not found")
		}
		if  == "" {
			 = "origin"
		}
		 := []string{"--git-dir", .gitDir, "push", }
		for ,  := range  {
			 = append(, "refs/tags/"+)
		}
		if ,  := runGitBytes(, .gitProgram, .root, nil, ...);  != nil {
			return fmt.Errorf("push tags via git store: %w", )
		}
	}
	return nil
}

// PushHint formats a jj git push command hint.
func ( *Repo) ( string,  vcs.PublishResult) string {
	 := []string{"jj", "git", "push"}
	if  != "" {
		 = append(, "--remote", )
	}
	if .Label != "" {
		 = append(, "--bookmark", .Label)
	}
	return strings.Join(, " ")
}

func ( context.Context, , , ,  string) ([]vcs.FileEntry, error) {
	 := []string{"file", "list", "-r", }
	if  := vcs.CleanRelDir();  != "" {
		 = append(, )
	}
	,  := runJJ(, , , ...)
	if  != nil {
		return nil, fmt.Errorf("jj file list -r %s: %w", , )
	}
	var  []vcs.FileEntry
	for  := range strings.Lines() {
		if  := filepath.ToSlash(strings.TrimSpace());  != "" {
			 = append(, vcs.FileEntry{
				Path: ,
				Mode: fs.FileMode(0o644),
			})
		}
	}
	return , nil
}

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

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

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