package server

import (
	"context"
	"fmt"

	"gitlab.com/Timfa/bluegit/internal/ci"
	"gitlab.com/Timfa/bluegit/internal/store"
)

// pipeSnap is één pipeline in de volgorde waarin Steve jobs oppakt.
type pipeSnap struct {
	Jobs []store.Job
}

// queueRanks geeft elke startklare queued job zijn plek in Steves
// globale wachtrij. ci.concurrency beperkt hoeveel jobs tegelijk
// running worden; die lopende jobs houden hun slot en krijgen geen
// nummer. De wachtenden blijven 1, 2, 3, … tot er een slot vrijkomt.
// Een job die nog op een voorganger of een resourcegroep wacht, heeft
// geen plek: Steve slaat die over.
func (s *Server) queueRanks(ctx context.Context) map[int64]int {
	pipes, err := s.Store.ActivePipelines(ctx)
	if err != nil {
		return map[int64]int{}
	}
	snaps := make([]pipeSnap, 0, len(pipes))
	for _, p := range pipes {
		jobs, err := s.Store.JobsByPipeline(ctx, p.ID)
		if err != nil {
			continue
		}
		snaps = append(snaps, pipeSnap{Jobs: jobs})
	}
	return rankQueue(snaps)
}

func queueText(tr func(string, ...any) string, ranks map[int64]int, id int64) string {
	if ranks == nil {
		return ""
	}
	n := ranks[id]
	if n < 1 {
		return ""
	}
	return tr("pipe.queuePos", n)
}

// rankQueue nummert startklare jobs vanaf 1. Pipelines staan op id,
// jobs daarbinnen op positie. Jobs die al running zijn vullen een
// concurrency-slot en staan niet in de telling, zodat de eerstvolgende
// wachtende job #1 is, ook als Steve al vol zit.
func rankQueue(pipes []pipeSnap) map[int64]int {
	busy := map[string]bool{}
	for _, p := range pipes {
		for _, j := range p.Jobs {
			if j.Status == "running" && j.ResourceGroup != "" {
				busy[fmt.Sprintf("%d\t%s", j.RepoID, j.ResourceGroup)] = true
			}
		}
	}
	ranks := map[int64]int{}
	n := 0
	for _, p := range pipes {
		specs, status := ciSpecs(p.Jobs)
		for _, j := range p.Jobs {
			if j.Status != "queued" {
				continue
			}
			if j.ResourceGroup != "" && busy[fmt.Sprintf("%d\t%s", j.RepoID, j.ResourceGroup)] {
				continue
			}
			if ci.Gate(specs, status, specs[indexJob(p.Jobs, j.Name)]) != "ready" {
				continue
			}
			n++
			ranks[j.ID] = n
		}
	}
	return ranks
}

func ciSpecs(jobs []store.Job) ([]ci.Job, map[string]string) {
	specs := make([]ci.Job, len(jobs))
	status := map[string]string{}
	for i, j := range jobs {
		specs[i] = ci.Job{
			Name: j.Name, Stage: j.Stage, Needs: j.Needs, Optional: j.Optional,
			NeedsSet: j.NeedsSet, AllowFailure: j.AllowFailure, When: j.When,
		}
		status[j.Name] = j.Status
	}
	return specs, status
}

func indexJob(jobs []store.Job, name string) int {
	for i, j := range jobs {
		if j.Name == name {
			return i
		}
	}
	return 0
}
