package runnercfg

import (
	"math"
	"path/filepath"
	"runtime"

	"gitlab.com/Timfa/bluegit/internal/diskusage"
)

// Hardware is wat de runner van zijn machine ziet.
type Hardware struct {
	CPUs     int
	MemoryMB int
	DiskFree int // GB vrij op de werkmap
	DiskSize int // GB totaal
}

// Detect leest CPU's, het werkgeheugen en de schijf onder dir.
func Detect(dir string) Hardware {
	h := Hardware{CPUs: runtime.NumCPU(), MemoryMB: detectMemory()}
	for d := dir; d != ""; {
		if du, err := diskusage.Usage(d); err == nil {
			h.DiskFree = int(du.Free >> 30)
			h.DiskSize = int(du.Total >> 30)
			break
		}
		next := filepath.Dir(d)
		if next == d {
			break
		}
		d = next
	}
	return h
}

// Recommend geeft logische waarden voor deze hardware. Uitgangspunt: een
// CI-job wil ~2 kernen en ~2 GB; de host houdt 1 kern en 1 GB voor zichzelf,
// en per job ~10 GB schijf voor images, checkout en cache.
func Recommend(h Hardware) Settings {
	r := Defaults()
	cpu := h.CPUs
	if cpu < 1 {
		cpu = 1
	}
	mem := h.MemoryMB
	byCPU := int(math.Max(1, float64((cpu-1)/2)))
	byMem := 1
	if mem > 0 {
		byMem = int(math.Max(1, float64((mem-1024)/2048)))
	}
	byDisk := 64
	if h.DiskFree > 0 {
		byDisk = int(math.Max(1, float64(h.DiskFree/10)))
	}
	r.Concurrency = minInt(byCPU, byMem, byDisk, 8)
	if r.Concurrency < 1 {
		r.Concurrency = 1
	}
	share := float64(cpu-1) / float64(r.Concurrency)
	if share < 1 {
		share = 1
	}
	r.CPUs = math.Floor(share*2) / 2
	if mem > 0 {
		m := (mem - 1024) / r.Concurrency
		if m < 512 {
			m = 512
		}
		r.MemoryMB = m / 256 * 256
	}
	r.PidsLimit = 4096
	if h.DiskFree > 0 {
		r.MaxImages = minInt(maxInt(5, h.DiskFree/2), 50)
		r.MaxDiskGB = maxInt(5, h.DiskFree*6/10)
		r.PruneCacheGB = maxInt(2, h.DiskFree/10)
	}
	return r
}

func minInt(v ...int) int {
	m := v[0]
	for _, x := range v[1:] {
		if x < m {
			m = x
		}
	}
	return m
}

func maxInt(a, b int) int {
	if a > b {
		return a
	}
	return b
}
