package fossilvcs

import (
	
	
	
	
	

	
)

type preparedTag struct {
	name     string
	commitID string
}

type session struct {
	repo   *Repo
	dir    string
	rev    vcs.Revision
	head   string
	tags   []preparedTag
	closed bool
}

func ( *session) () fs.FS {
	return os.DirFS(.dir)
}

func ( *session) ( string,  []byte) error {
	return vcs.WriteDirFile(.dir, , )
}

func ( *session) ( context.Context) (string, error) {
	,  := runFossil(, .repo.program, .dir, "timeline", "-n", "1", "-F", "%H", "current")
	if  != nil {
		return "", 
	}
	for  := range strings.SplitSeq(, "\n") {
		 = strings.TrimSpace()
		if len() >= 10 {
			.head = 
			return .head, nil
		}
	}
	return .head, nil
}

func ( *session) ( context.Context,  string) ([]vcs.FileEntry, error) {
	return listFiles(, .repo.program, .dir, "current", )
}

func ( *session) ( context.Context,  []string,  vcs.CommitOptions) (string, error) {
	if len() == 0 {
		return .head, nil
	}
	 := append([]string{"add"}, ...)
	_, _ = runFossil(, .repo.program, .dir, ...)

	 := append(
		[]string{"commit", "--no-warnings", "--hash", "--nosync", "-m", .Message},
		...,
	)
	if ,  := runFossil(, .repo.program, .dir, ...);  != nil {
		return "", fmt.Errorf("fossil commit: %w", )
	}
	return .Head()
}

func ( *session) ( context.Context,  string,  vcs.TagOptions) error {
	,  := .Head()
	if  != nil {
		return 
	}
	.tags = append(.tags, preparedTag{name: , commitID: })
	return nil
}

func ( *session) ( context.Context) (vcs.PublishResult, error) {
	,  := .Head()
	if  != nil {
		return vcs.PublishResult{}, 
	}
	for ,  := range .tags {
		 := []string{"tag", "add"}
		if .repo.cfg.RawTags {
			 = append(, "--raw")
		}
		 = append(, .name, .commitID)
		if ,  := runFossil(, .repo.program, .dir, ...);  != nil {
			return vcs.PublishResult{}, fmt.Errorf("fossil tag add %s: %w", .name, )
		}
	}

	 := make([]string, len(.tags))
	for ,  := range .tags {
		[] = .name
	}
	return vcs.PublishResult{
		StartID: .rev.ID,
		FinalID: ,
		Ref:     .rev.Ref,
		Label:   .rev.Label,
		Tags:    ,
	}, nil
}

func ( *session) () error {
	if .closed {
		return nil
	}
	.closed = true
	_, _ = runFossil(context.Background(), .repo.program, .dir, "close", "--force")
	return os.RemoveAll(.dir)
}