package gitgraph

import (
	"container/list"
	"context"
	"strings"
	"sync"
)

// DefaultMaxBytes is 8 MiB, ruim voor honderden grafieken.
const DefaultMaxBytes = 8 << 20

// Loader leest commits en refs uit git. Wordt alleen bij een miss aangeroepen.
type Loader func(ctx context.Context) ([]Commit, []Ref, error)

// Cache bewaart gelegde grafieken in het geheugen. Geen schijf-I/O.
type Cache struct {
	max int64

	mu    sync.Mutex
	lru   *list.List // voorkant = recent
	items map[string]*list.Element
	size  int64
	hits  int64
	miss  int64
}

type cached struct {
	key   string
	repo  int64
	graph *Graph
	bytes int64
}

// NewCache maakt een lege LRU-cache. max <= 0 gebruikt DefaultMaxBytes.
func NewCache(max int64) *Cache {
	if max <= 0 {
		max = DefaultMaxBytes
	}
	return &Cache{max: max, lru: list.New(), items: map[string]*list.Element{}}
}

// Get geeft een cached grafiek, of legt er één vanuit load. load wordt
// bij een hit niet aangeroepen.
func (c *Cache) Get(ctx context.Context, key, defaultBranch string, load Loader) (*Graph, error) {
	if c == nil {
		commits, refs, err := load(ctx)
		if err != nil {
			return nil, err
		}
		return Layout(commits, refs, defaultBranch), nil
	}
	if g, ok := c.lookup(key); ok {
		return g, nil
	}
	commits, refs, err := load(ctx)
	if err != nil {
		return nil, err
	}
	g := Layout(commits, refs, defaultBranch)
	c.put(key, repoIDFromKey(key), g)
	return g, nil
}

func repoIDFromKey(key string) int64 {
	var id int64
	for _, r := range key {
		if r == ':' {
			break
		}
		if r < '0' || r > '9' {
			return 0
		}
		id = id*10 + int64(r-'0')
	}
	return id
}

func (c *Cache) lookup(key string) (*Graph, bool) {
	c.mu.Lock()
	defer c.mu.Unlock()
	el, ok := c.items[key]
	if !ok {
		c.miss++
		return nil, false
	}
	c.lru.MoveToFront(el)
	c.hits++
	return el.Value.(*cached).graph, true
}

func (c *Cache) put(key string, repoID int64, g *Graph) {
	if c == nil || g == nil {
		return
	}
	n := estimateBytes(g)
	c.mu.Lock()
	defer c.mu.Unlock()
	if el, ok := c.items[key]; ok {
		c.size -= el.Value.(*cached).bytes
		c.lru.Remove(el)
		delete(c.items, key)
	}
	c.items[key] = c.lru.PushFront(&cached{key: key, repo: repoID, graph: g, bytes: n})
	c.size += n
	c.evictLocked()
}

func estimateBytes(g *Graph) int64 {
	n := 256
	for _, r := range g.Rows {
		n += 128 + len(r.SHA) + len(r.Subject) + len(r.Author) + len(r.Email)
		for _, lb := range r.Labels {
			n += 32 + len(lb.Name)
		}
	}
	n += len(g.Edges) * 40
	return int64(n)
}

func (c *Cache) evictLocked() {
	for c.size > c.max && c.lru.Len() > 1 {
		el := c.lru.Back()
		e := el.Value.(*cached)
		c.lru.Remove(el)
		delete(c.items, e.key)
		c.size -= e.bytes
	}
}

// Drop vergeet alle grafieken van één repository (na een push of verwijdering).
func (c *Cache) Drop(repoID int64) {
	if c == nil {
		return
	}
	prefix := strings.TrimSpace(strings.SplitN(Key(repoID, nil, "", 0), ":", 2)[0]) + ":"
	// Key always starts with "<id>:"
	_ = prefix
	c.mu.Lock()
	defer c.mu.Unlock()
	for key, el := range c.items {
		if el.Value.(*cached).repo == repoID {
			c.size -= el.Value.(*cached).bytes
			c.lru.Remove(el)
			delete(c.items, key)
		}
	}
}

// Stats is hits, misses en huidig geheugengebruik, voor metingen.
func (c *Cache) Stats() (hits, misses, entries int64, bytes int64) {
	if c == nil {
		return 0, 0, 0, 0
	}
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.hits, c.miss, int64(len(c.items)), c.size
}
