package fossilvcs

import (
	
	
	
	
	
	
	
	
	
	
	

	
)

// Name is the backend identifier for Fossil.
const Name = "fossil"

const defaultRev = "current"

// Config holds Fossil-specific options decoded from goship.json’s "vcs" object.
type Config struct {
	// Program overrides the fossil executable name or path passed to
	// exec.LookPath (default "fossil").
	Program string `json:"program,omitzero"`
	// RawTags passes --raw to "fossil tag add" instead of creating symbolic
	// (sym-*) tags.
	RawTags bool `json:"rawTags,omitzero"`
}

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

// Open locates the Fossil checkout containing dir.
func ( context.Context,  string,  Config) (vcs.VCS, error) {
	,  := exec.LookPath(cmp.Or(.Program, Name))
	if  != nil {
		return nil, fmt.Errorf("fossil binary not found: %w", )
	}
	,  := runFossil(, , , "status")
	if  != nil {
		return nil, fmt.Errorf("not a fossil checkout: %w", )
	}

	var ,  string
	for  := range strings.SplitSeq(, "\n") {
		, ,  := strings.Cut(, ":")
		if ! {
			continue
		}
		 = strings.TrimSpace()
		switch strings.TrimSpace() {
		case "local-root":
			 = filepath.Clean()
		case "repository":
			 = filepath.Clean()
		}
	}
	if  == "" ||  == "" {
		return nil, fmt.Errorf("could not determine fossil root and repository from status")
	}
	return &Repo{
		root:    ,
		repoDB:  ,
		program: ,
		cfg:     ,
	}, nil
}

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

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

// ResolveRev resolves rev ("" defaults to "current").
func ( *Repo) ( context.Context,  string) (vcs.Revision, error) {
	 = cmp.Or(, defaultRev)
	,  := runFossil(, .program, .root, "timeline", "-n", "1", "-F", "%H|%b", )
	if  != nil {
		return vcs.Revision{}, fmt.Errorf("resolve fossil revision %q: %w", , )
	}
	for  := range strings.Lines() {
		, ,  := strings.Cut(strings.TrimSpace(), "|")
		if  && len() >= 10 {
			return vcs.Revision{
				ID:    strings.TrimSpace(),
				Ref:   strings.TrimSpace(),
				Label: strings.TrimSpace(),
			}, nil
		}
	}
	return vcs.Revision{}, fmt.Errorf("resolve fossil revision %q: could not parse timeline output", )
}

// Tags returns all tags in the Fossil repository.
func ( *Repo) ( context.Context) ([]string, error) {
	,  := runFossil(, .program, .root, "tag", "list")
	if  != nil {
		return nil, fmt.Errorf("list fossil 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) {
	,  := runFossil(, .program, .root, "diff", "--brief", "--from", , "--to", )
	if  != nil {
		return nil, fmt.Errorf("fossil diff %s..%s: %w", , , )
	}
	 := vcs.DirPrefix()
	var  []string
	for  := range strings.Lines() {
		 := strings.Fields()
		if len() < 2 {
			continue
		}
		 := filepath.ToSlash([len()-1])
		if  != "" && !strings.HasPrefix(, ) {
			continue
		}
		 = 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()
	,  := runFossilBytes(, .program, .root, "cat", "-r", , )
	if  != nil {
		return nil, fmt.Errorf("fossil cat %s@%s: %w", , , )
	}
	return , nil
}

// Export extracts the tracked tree at rev into destDir using a single
// "fossil tarball" invocation.
func ( *Repo) ( context.Context, ,  string) error {
	const  = "goship-export"
	 := exec.CommandContext(, .program, "tarball", , "-", "--name", )
	.Dir = .root
	,  := .StdoutPipe()
	if  != nil {
		return fmt.Errorf("fossil tarball %s pipe: %w", , )
	}
	var  bytes.Buffer
	.Stderr = &
	if  := .Start();  != nil {
		return fmt.Errorf("start fossil tarball %s: %w", , )
	}
	,  := gzip.NewReader()
	if  != nil {
		_, _ = io.Copy(io.Discard, )
		_ = .Wait()
		return fmt.Errorf("decompress fossil tarball %s: %w: %s", , , strings.TrimSpace(.String()))
	}
	 := vcs.ExtractTar(, , +"/")
	 := .Close()
	_, _ = io.Copy(io.Discard, )
	 := .Wait()
	if  != nil {
		return fmt.Errorf("fossil tarball %s: %w", , )
	}
	if  != nil {
		return fmt.Errorf("fossil tarball %s gzip close: %w", , )
	}
	if  != nil {
		return fmt.Errorf("fossil tarball %s: %w: %s", , , strings.TrimSpace(.String()))
	}
	return nil
}

// Begin opens an isolated temporary Fossil checkout at rev.ID.
func ( *Repo) ( context.Context,  vcs.Revision) (vcs.Session, error) {
	,  := os.MkdirTemp("", "goship-fossil-checkout-*")
	if  != nil {
		return nil, fmt.Errorf("create temp fossil checkout dir: %w", )
	}
	if ,  := runFossil(, .program, , "open", .repoDB, .ID);  != nil {
		_ = os.RemoveAll()
		return nil, fmt.Errorf("fossil open %s: %w", .ID, )
	}
	if ,  := runFossil(, .program, .root, "user", "default");  == nil {
		if  := strings.TrimSpace();  != "" {
			_, _ = runFossil(, .program, , "user", "default", )
		}
	}
	return &session{
		repo: ,
		dir:  ,
		rev:  ,
		head: .ID,
	}, nil
}

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

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

func ( context.Context, , , ,  string) ([]vcs.FileEntry, error) {
	,  := runFossil(, , , "ls", "-r", )
	if  != nil {
		return nil, fmt.Errorf("fossil ls -r %s: %w", , )
	}
	 := vcs.DirPrefix()
	var  []vcs.FileEntry
	for  := range strings.Lines() {
		 := filepath.ToSlash(strings.TrimSpace())
		if  == "" {
			continue
		}
		if  != "" && !strings.HasPrefix(, ) {
			continue
		}
		 = append(, vcs.FileEntry{
			Path: ,
			Mode: fs.FileMode(0o644),
		})
	}
	return , nil
}

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

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