package memvcs

import (
	
	
	
	
	
	
	
	
	

	
)

// Name is the backend identifier for the in-memory VCS.
const Name = "mem"

// Commit represents an immutable revision stored in a memvcs Repo.
type Commit struct {
	ID      string
	Parent  string
	Message string
	Files   map[string][]byte
}

// PushRecord records a Push call made against a memvcs Repo.
type PushRecord struct {
	Remote string
	Ref    string
	Tags   []string
}

// Repo is a pure in-memory implementation of vcs.VCS.
type Repo struct {
	mu      sync.Mutex
	root    string
	seq     int
	headRef string
	refs    map[string]string // ref -> commit ID
	commits map[string]Commit // commit ID -> Commit
	tags    map[string]string // tag -> commit ID
	pushes  []PushRecord
}

// New creates an in-memory Repo initialized with a single commit on branch
// "main" containing initialFiles (repo-relative slash paths).
func ( map[string][]byte) *Repo {
	 := &Repo{
		root:    "/mem",
		headRef: "main",
		refs:    make(map[string]string),
		commits: make(map[string]Commit),
		tags:    make(map[string]string),
	}
	.commitLocked("initial commit", cloneFiles())
	return 
}

func ( *Repo) ( string,  map[string][]byte) string {
	.seq++
	 := fmt.Sprintf("mem-%04d", .seq)
	 := .refs[.headRef]
	.commits[] = Commit{
		ID:      ,
		Parent:  ,
		Message: ,
		Files:   ,
	}
	.refs[.headRef] = 
	return 
}

// CommitFiles adds a new commit on the current branch (useful in tests).
func ( *Repo) ( string,  map[string][]byte) string {
	.mu.Lock()
	defer .mu.Unlock()

	 := cloneFiles(.commits[.refs[.headRef]].Files)
	for ,  := range  {
		[cleanPath()] = bytes.Clone()
	}
	return .commitLocked(, )
}

// AddTag creates a tag pointing at rev (or current head if empty).
func ( *Repo) (,  string) {
	.mu.Lock()
	defer .mu.Unlock()

	.tags[] = cmp.Or(, .refs[.headRef])
}

// Pushes returns a copy of all Push calls recorded by this Repo.
func ( *Repo) () []PushRecord {
	.mu.Lock()
	defer .mu.Unlock()
	return slices.Clone(.pushes)
}

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

// Root returns the synthetic root path "/mem".
func ( *Repo) () string { return .root }

// ResolveRev resolves rev (empty resolves the current branch).
func ( *Repo) ( context.Context,  string) (vcs.Revision, error) {
	.mu.Lock()
	defer .mu.Unlock()

	if  == "" ||  == .headRef {
		return vcs.Revision{
			ID:    .refs[.headRef],
			Ref:   .headRef,
			Label: .headRef,
		}, nil
	}
	if ,  := .refs[];  {
		return vcs.Revision{ID: , Ref: , Label: }, nil
	}
	if ,  := .tags[];  {
		return vcs.Revision{ID: }, nil
	}
	if ,  := .commits[];  {
		return vcs.Revision{ID: }, nil
	}
	return vcs.Revision{}, fmt.Errorf("memvcs: unknown revision %q", )
}

// Tags returns all tags in sorted order.
func ( *Repo) ( context.Context) ([]string, error) {
	.mu.Lock()
	defer .mu.Unlock()

	return slices.Sorted(maps.Keys(.tags)), nil
}

// ChangedFiles returns repo-relative slash paths whose contents differ between
// baseRev and targetRev under dir.
func ( *Repo) ( context.Context, , ,  string) ([]string, error) {
	.mu.Lock()
	defer .mu.Unlock()

	,  := .resolveIDLocked()
	if ! {
		return nil, fmt.Errorf("memvcs: unknown base revision %q", )
	}
	,  := .resolveIDLocked()
	if ! {
		return nil, fmt.Errorf("memvcs: unknown target revision %q", )
	}

	 := .commits[].Files
	 := .commits[].Files
	 := dirPrefix()

	 := make(map[string]bool)
	for  := range  {
		[] = true
	}
	for  := range  {
		[] = true
	}

	var  []string
	for  := range  {
		if  != "" && !strings.HasPrefix(, ) {
			continue
		}
		,  := []
		,  := []
		if  !=  || !bytes.Equal(, ) {
			 = append(, )
		}
	}
	slices.Sort()
	return , nil
}

// ListFiles returns all tracked files at rev under dir.
func ( *Repo) ( context.Context, ,  string) ([]vcs.FileEntry, error) {
	.mu.Lock()
	defer .mu.Unlock()

	,  := .resolveIDLocked()
	if ! {
		return nil, fmt.Errorf("memvcs: unknown revision %q", )
	}
	return listFromMap(.commits[].Files, ), nil
}

// ReadFile reads slashPath at rev.
func ( *Repo) ( context.Context, ,  string) ([]byte, error) {
	.mu.Lock()
	defer .mu.Unlock()

	,  := .resolveIDLocked()
	if ! {
		return nil, fmt.Errorf("memvcs: unknown revision %q", )
	}
	,  := .commits[].Files[cleanPath()]
	if ! {
		return nil, fs.ErrNotExist
	}
	return bytes.Clone(), nil
}

// Begin starts an isolated in-memory transaction rooted at rev.
func ( *Repo) ( context.Context,  vcs.Revision) (vcs.Session, error) {
	.mu.Lock()
	defer .mu.Unlock()

	,  := .commits[.ID]
	if ! {
		return nil, fmt.Errorf("memvcs: unknown revision %q", .ID)
	}
	return &session{
		repo:      ,
		rev:       ,
		head:      .ID,
		workFiles: cloneFiles(.Files),
		headFiles: cloneFiles(.Files),
		staged:    make(map[string]Commit),
		tags:      make(map[string]string),
	}, nil
}

// Push records a push operation in memory.
func ( *Repo) ( context.Context, ,  string,  []string) error {
	.mu.Lock()
	defer .mu.Unlock()

	.pushes = append(.pushes, PushRecord{
		Remote: cmp.Or(, "default"),
		Ref:    ,
		Tags:   slices.Clone(),
	})
	return nil
}

// PushHint returns a descriptive hint for memvcs.
func ( *Repo) ( string,  vcs.PublishResult) string {
	return fmt.Sprintf("mem push %s (%d tags)", cmp.Or(, "default"), len(.Tags))
}

func ( *Repo) ( string) (string, bool) {
	if  == "" {
		return .refs[.headRef], true
	}
	if ,  := .commits[];  {
		return , true
	}
	if ,  := .tags[];  {
		return , true
	}
	if ,  := .refs[];  {
		return , true
	}
	return "", false
}

func ( map[string][]byte,  string) []vcs.FileEntry {
	 := dirPrefix()
	var  []vcs.FileEntry
	for  := range  {
		if  != "" && !strings.HasPrefix(, ) {
			continue
		}
		 = append(, vcs.FileEntry{
			Path: ,
			Mode: fs.FileMode(0o644),
		})
	}
	slices.SortFunc(, func(,  vcs.FileEntry) int {
		return strings.Compare(.Path, .Path)
	})
	return 
}

func ( map[string][]byte) map[string][]byte {
	 := make(map[string][]byte, len())
	for ,  := range  {
		[cleanPath()] = bytes.Clone()
	}
	return 
}

func ( string) string {
	return vcs.CleanRelPath()
}

func ( string) string {
	return vcs.DirPrefix()
}