package server

import (
	"context"
	"regexp"
	"strconv"

	"gitlab.com/Timfa/bluegit/internal/gitrepo"
	"gitlab.com/Timfa/bluegit/internal/readcache"
	"gitlab.com/Timfa/bluegit/internal/store"
)

// De leescache zit tussen de pagina's en git. Toegang is al gecontroleerd
// voordat een handler hier komt (guard/repoView); de cache weet niets van
// rechten en geeft alleen terug wat git voor dezelfde repo zou geven.
// Sleutels op een commit-SHA zijn onveranderlijk. Alles op een ref-naam
// staat in de refs-ruimte en verdwijnt bij elke ref-wijziging (AfterPush).

// ReadCache is de actieve cache, of nil.
func (s *Server) ReadCache() *readcache.Cache {
	s.cacheMu.RLock()
	defer s.cacheMu.RUnlock()
	return s.rcache
}

// SetReadCache zet of wist de cache.
func (s *Server) SetReadCache(c *readcache.Cache) {
	s.cacheMu.Lock()
	s.rcache = c
	s.cacheMu.Unlock()
}

var fullSHA = regexp.MustCompile(`^[0-9a-f]{40}([0-9a-f]{24})?$`)

func cachedRead[T any](s *Server, repoID int64, refs bool, key string, fn func() (T, error)) (T, error) {
	c := s.ReadCache()
	var v T
	if c != nil && c.GetJSON(repoID, refs, key, &v) {
		return v, nil
	}
	gen := c.Gen(repoID)
	v, err := fn()
	if err == nil && c != nil {
		c.PutJSONAt(repoID, refs, key, v, gen)
	}
	return v, err
}

func (s *Server) gdir(repo store.Repo) string {
	return gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
}

func (s *Server) cRefs(ctx context.Context, repo store.Repo) (map[string]string, error) {
	return cachedRead(s, repo.ID, true, "refs", func() (map[string]string, error) {
		return gitrepo.Refs(ctx, s.Git, s.gdir(repo))
	})
}

// revKey kiest de cachesleutel voor rev: de commit-SHA als die bekend is,
// anders de naam in de refs-ruimte.
func (s *Server) revKey(ctx context.Context, repo store.Repo, rev string) (refs bool, key string) {
	if fullSHA.MatchString(rev) {
		return false, rev
	}
	if s.ReadCache() == nil {
		return true, rev
	}
	if m, err := s.cRefs(ctx, repo); err == nil {
		for _, full := range []string{"refs/heads/" + rev, "refs/tags/" + rev, rev} {
			if sha, ok := m[full]; ok && fullSHA.MatchString(sha) {
				return false, sha
			}
		}
	}
	return true, rev
}

func (s *Server) cBranches(ctx context.Context, repo store.Repo) ([]string, error) {
	return cachedRead(s, repo.ID, true, "branches", func() ([]string, error) {
		return gitrepo.Branches(ctx, s.Git, s.gdir(repo))
	})
}

func (s *Server) cBranchTips(ctx context.Context, repo store.Repo) ([]gitrepo.BranchTip, error) {
	return cachedRead(s, repo.ID, true, "tips", func() ([]gitrepo.BranchTip, error) {
		return gitrepo.BranchTips(ctx, s.Git, s.gdir(repo))
	})
}

func (s *Server) cTags(ctx context.Context, repo store.Repo) ([]string, error) {
	return cachedRead(s, repo.ID, true, "tags", func() ([]string, error) {
		return gitrepo.Tags(ctx, s.Git, s.gdir(repo))
	})
}

func (s *Server) cListTags(ctx context.Context, repo store.Repo) ([]gitrepo.TagInfo, error) {
	return cachedRead(s, repo.ID, true, "listtags", func() ([]gitrepo.TagInfo, error) {
		return gitrepo.ListTags(ctx, s.Git, s.gdir(repo))
	})
}

func (s *Server) cAheadBehind(ctx context.Context, repo store.Repo, base, branch string) (int, int, error) {
	_, kb := s.revKey(ctx, repo, base)
	_, kr := s.revKey(ctx, repo, branch)
	refs := !fullSHA.MatchString(kb) || !fullSHA.MatchString(kr)
	v, err := cachedRead(s, repo.ID, refs, "ab:"+kb+":"+kr, func() ([2]int, error) {
		a, b, err := gitrepo.AheadBehind(ctx, s.Git, s.gdir(repo), base, branch)
		return [2]int{a, b}, err
	})
	return v[0], v[1], err
}

type statsVal struct{ Commits, Branches, Tags int }

func (s *Server) cStats(ctx context.Context, repo store.Repo, rev string) (int, int, int, error) {
	// branches en tags hangen van refs af; dus altijd in de refs-ruimte
	v, err := cachedRead(s, repo.ID, true, "stats:"+rev, func() (statsVal, error) {
		c, b, t, err := gitrepo.Stats(ctx, s.Git, s.gdir(repo), rev)
		return statsVal{c, b, t}, err
	})
	return v.Commits, v.Branches, v.Tags, err
}

func (s *Server) cLastCommit(ctx context.Context, repo store.Repo, rev, path string) (gitrepo.Commit, error) {
	refs, k := s.revKey(ctx, repo, rev)
	return cachedRead(s, repo.ID, refs, "last:"+k+":"+path, func() (gitrepo.Commit, error) {
		return gitrepo.LastCommit(ctx, s.Git, s.gdir(repo), rev, path)
	})
}

func (s *Server) cTree(ctx context.Context, repo store.Repo, rev, rel string) ([]gitrepo.Entry, error) {
	refs, k := s.revKey(ctx, repo, rev)
	return cachedRead(s, repo.ID, refs, "tree:"+k+":"+rel, func() ([]gitrepo.Entry, error) {
		return gitrepo.Tree(ctx, s.Git, s.gdir(repo), rev, rel)
	})
}

func (s *Server) cTreeAll(ctx context.Context, repo store.Repo, rev string) ([]gitrepo.Entry, error) {
	refs, k := s.revKey(ctx, repo, rev)
	return cachedRead(s, repo.ID, refs, "treeall:"+k, func() ([]gitrepo.Entry, error) {
		return gitrepo.TreeAll(ctx, s.Git, s.gdir(repo), rev)
	})
}

func (s *Server) cTouch(ctx context.Context, repo store.Repo, rev string) (map[string]gitrepo.Commit, error) {
	refs, k := s.revKey(ctx, repo, rev)
	return cachedRead(s, repo.ID, refs, "touch:"+k, func() (map[string]gitrepo.Commit, error) {
		return gitrepo.Touch(ctx, s.Git, s.gdir(repo), rev)
	})
}

type blobVal struct {
	Text   string
	Binary bool
}

// cDoc is voor kleine documenten zoals de README; grote bestanden lezen
// we gewoon uit git.
func (s *Server) cDoc(ctx context.Context, repo store.Repo, rev, path string, max int) (string, bool, error) {
	refs, k := s.revKey(ctx, repo, rev)
	v, err := cachedRead(s, repo.ID, refs, "doc:"+strconv.Itoa(max)+":"+k+":"+path, func() (blobVal, error) {
		t, b, err := gitrepo.Blob(ctx, s.Git, s.gdir(repo), rev, path, max)
		return blobVal{t, b}, err
	})
	return v.Text, v.Binary, err
}

// refreshCache is de write-through na elke ref-wijziging: oude ref-data
// weg, daarna de overzichtspagina van de standaardbranch opnieuw vullen.
// refsChanged vergeet de ref-data meteen (dus nooit verouderd) en vult
// op de achtergrond opnieuw.
func (s *Server) refsChanged(repo store.Repo) {
	c := s.ReadCache()
	if c != nil {
		c.DropRefs(repo.ID)
	}
	s.dropGraph(repo)
	go s.refreshCache(repo)
}

func (s *Server) refreshCache(repo store.Repo) {
	ctx := context.Background()
	_, _ = s.repoGraph(ctx, repo)
	if s.ReadCache() == nil {
		return
	}
	_, _ = s.cRefs(ctx, repo)
	_, _ = s.cBranches(ctx, repo)
	_, _ = s.cBranchTips(ctx, repo)
	_, _ = s.cTags(ctx, repo)
	_, _ = s.cListTags(ctx, repo)
	rev := repo.DefaultBranch
	if rev == "" {
		return
	}
	_, _, _, _ = s.cStats(ctx, repo, rev)
	_, _ = s.cLastCommit(ctx, repo, rev, "")
	_, _ = s.cTouch(ctx, repo, rev)
	if entries, err := s.cTree(ctx, repo, rev, ""); err == nil {
		if readme, _ := findDocs(entries); readme != "" {
			_, _, _ = s.cDoc(ctx, repo, rev, readme, 200_000)
		}
	}
	_ = s.repoLanguage(ctx, repo, rev)
}
