package runnercfg

import (
	"sort"
	"sync"
	"time"
)

// JobInfo is één job in het overzicht.
type JobInfo struct {
	ID       int64     `json:"id"`
	Name     string    `json:"name"`
	Project  string    `json:"project"`
	Pipeline int64     `json:"pipeline"`
	Image    string    `json:"image"`
	Status   string    `json:"status"`
	Started  time.Time `json:"started_at"`
	Finished time.Time `json:"finished_at,omitempty"`
	URL      string    `json:"url,omitempty"`
}

// Tracker houdt actieve en recente jobs en de pauze bij. Veilig voor
// gelijktijdig gebruik.
type Tracker struct {
	mu     sync.Mutex
	active map[int64]JobInfo
	recent []JobInfo
	paused bool
	images map[string]time.Time
}

const recentMax = 25

// Start registreert een lopende job.
func (t *Tracker) Start(j JobInfo) {
	t.mu.Lock()
	defer t.mu.Unlock()
	if t.active == nil {
		t.active = map[int64]JobInfo{}
	}
	if j.Started.IsZero() {
		j.Started = time.Now()
	}
	j.Status = "running"
	t.active[j.ID] = j
	if j.Image != "" {
		if t.images == nil {
			t.images = map[string]time.Time{}
		}
		t.images[j.Image] = time.Now()
	}
}

// Finish zet een job bij de recente jobs.
func (t *Tracker) Finish(id int64, status string) {
	t.mu.Lock()
	defer t.mu.Unlock()
	j, ok := t.active[id]
	if !ok {
		return
	}
	delete(t.active, id)
	j.Status, j.Finished = status, time.Now()
	t.recent = append([]JobInfo{j}, t.recent...)
	if len(t.recent) > recentMax {
		t.recent = t.recent[:recentMax]
	}
}

// Active geeft de lopende jobs, oudste eerst.
func (t *Tracker) Active() []JobInfo {
	t.mu.Lock()
	defer t.mu.Unlock()
	out := make([]JobInfo, 0, len(t.active))
	for _, j := range t.active {
		out = append(out, j)
	}
	sort.Slice(out, func(i, k int) bool { return out[i].Started.Before(out[k].Started) })
	return out
}

// Recent geeft de laatst afgeronde jobs, nieuwste eerst.
func (t *Tracker) Recent() []JobInfo {
	t.mu.Lock()
	defer t.mu.Unlock()
	return append([]JobInfo(nil), t.recent...)
}

// SetPaused zet de pauze (drain): lopende jobs lopen af, nieuwe niet.
func (t *Tracker) SetPaused(on bool) {
	t.mu.Lock()
	t.paused = on
	t.mu.Unlock()
}

// Paused zegt of er geen nieuwe jobs opgepakt worden.
func (t *Tracker) Paused() bool {
	t.mu.Lock()
	defer t.mu.Unlock()
	return t.paused
}

// SafeToUpgrade: niets loopt meer.
func (t *Tracker) SafeToUpgrade() bool {
	t.mu.Lock()
	defer t.mu.Unlock()
	return len(t.active) == 0
}

// StaleImages geeft de images die het langst niet gebruikt zijn, boven keep.
func (t *Tracker) StaleImages(keep int) []string {
	t.mu.Lock()
	defer t.mu.Unlock()
	type iu struct {
		ref string
		at  time.Time
	}
	var all []iu
	inUse := map[string]bool{}
	for _, j := range t.active {
		inUse[j.Image] = true
	}
	for ref, at := range t.images {
		all = append(all, iu{ref, at})
	}
	sort.Slice(all, func(i, k int) bool { return all[i].at.After(all[k].at) })
	var out []string
	for i, x := range all {
		if i >= keep && !inUse[x.ref] {
			out = append(out, x.ref)
			delete(t.images, x.ref)
		}
	}
	return out
}
