package jjvcs

import (
	
	
	
	
	
	

	
)

type preparedTag struct {
	name     string
	commitID string
	message  string
}

type session struct {
	repo   *Repo
	dir    string
	wsName 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) {
	return .head, nil
}

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

func ( *session) ( context.Context,  []string,  vcs.CommitOptions) (string, error) {
	if len() == 0 {
		return .head, nil
	}
	 := append([]string{"commit", "-m", .Message}, ...)
	if ,  := runJJ(, .repo.program, .dir, ...);  != nil {
		return "", fmt.Errorf("jj commit: %w", )
	}
	,  := runJJ(, .repo.program, .dir, "log", "-r", "@-", "--no-graph", "-T", "commit_id")
	if  != nil {
		return "", fmt.Errorf("resolve committed jj revision: %w", )
	}
	.head = strings.TrimSpace()
	return .head, nil
}

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

func ( *session) ( context.Context) (vcs.PublishResult, error) {
	if .rev.Ref != "" && .head != .rev.ID {
		if ,  := runJJ(, .repo.program, .repo.root, "bookmark", "set", .rev.Ref, "-r", .head);  != nil {
			return vcs.PublishResult{}, fmt.Errorf("update jj bookmark %s: %w", .rev.Ref, )
		}
	}

	if len(.tags) > 0 {
		if .repo.gitDir == "" {
			return vcs.PublishResult{}, fmt.Errorf("jj publish tags: underlying git store not found")
		}
		// Export JJ commits into the underlying Git store before tagging.
		_, _ = runJJ(, .repo.program, .repo.root, "git", "export")

		var  bytes.Buffer
		 := .repo.cfg.isAnnotated()
		 := .repo.cfg.Sign != nil && *.repo.cfg.Sign

		for ,  := range .tags {
			switch {
			case !:
				fmt.Fprintf(&, "create refs/tags/%s %s\n", .name, .commitID)
			case :
				if ,  := runGitBytes(, .repo.gitProgram, .repo.root, nil, "--git-dir", .repo.gitDir, "tag", "-a", "-s", "-m", .message, .name, .commitID);  != nil {
					return vcs.PublishResult{}, fmt.Errorf("create signed tag %s: %w", .name, )
				}
			default:
				,  := .makeAnnotatedTagObject(, )
				if  != nil {
					return vcs.PublishResult{}, 
				}
				fmt.Fprintf(&, "create refs/tags/%s %s\n", .name, )
			}
		}
		if .Len() > 0 {
			if ,  := runGitBytes(, .repo.gitProgram, .repo.root, .Bytes(), "--git-dir", .repo.gitDir, "update-ref", "--stdin");  != nil {
				return vcs.PublishResult{}, fmt.Errorf("atomic tag update in jj git store: %w", )
			}
		}
		_, _ = runJJ(, .repo.program, .repo.root, "git", "import")
	}

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

func ( *session) ( context.Context,  preparedTag) (string, error) {
	,  := runGitBytes(, .repo.gitProgram, .repo.root, nil, "--git-dir", .repo.gitDir, "var", "GIT_COMMITTER_IDENT")
	if  != nil {
		return "", fmt.Errorf("resolve committer identity: %w", )
	}
	var  bytes.Buffer
	fmt.Fprintf(&, "object %s\n", .commitID)
	.WriteString("type commit\n")
	fmt.Fprintf(&, "tag %s\n", .name)
	fmt.Fprintf(&, "tagger %s\n", strings.TrimSpace(string()))
	.WriteByte('\n')
	.WriteString(.message)
	if !strings.HasSuffix(.message, "\n") {
		.WriteByte('\n')
	}
	,  := runGitBytes(, .repo.gitProgram, .repo.root, .Bytes(), "--git-dir", .repo.gitDir, "mktag")
	if  != nil {
		return "", fmt.Errorf("create tag object for %s: %w", .name, )
	}
	return strings.TrimSpace(string()), nil
}

func ( *session) () error {
	if .closed {
		return nil
	}
	.closed = true
	_, _ = runJJ(context.Background(), .repo.program, .repo.root, "workspace", "forget", .wsName)
	return os.RemoveAll(.dir)
}