package main

import (
	"math"
	"slices"
)

const window = 20 // only the last 20 exit 0 runs of a key are read for statements

func sorted(xs []int64) []int64 {
	s := slices.Clone(xs)
	slices.Sort(s)
	return s
}

// median is the true median of a sorted list, unrounded: the mean of the two
// middle values for an even count.
func median(s []int64) float64 {
	n := len(s)
	if n%2 == 1 {
		return float64(s[n/2])
	}
	return float64(s[n/2-1]+s[n/2]) / 2
}

// halfUp converts to integer milliseconds, rounding half up.
func halfUp(x float64) int64 { return int64(math.Floor(x + 0.5)) }

// rank is the nearest-rank percentile num/den of a sorted list: index ceil(p*n)-1.
func rank(s []int64, num, den int) int64 { return s[(num*len(s)+den-1)/den-1] }

// band is the middle half of the runs, widened by a tenth of the median on each
// side, in integer milliseconds. The low edge is never below 0.
func band(runs []int64) (lo, hi int64) {
	s := sorted(runs)
	tenth := median(s) / 10
	return max(0, halfUp(float64(rank(s, 1, 4))-tenth)), halfUp(float64(rank(s, 3, 4)) + tenth)
}

// split finds two kinds of runs: the neighbouring pair in the sorted runs with the
// largest ratio, at least 2, with at least 3 runs on each side of the gap.
func split(runs []int64) (low, high []int64, ok bool) {
	s := sorted(runs)
	best, at := 0.0, 0
	for i := 3; i <= len(s)-3; i++ {
		if r := float64(max(s[i], 1)) / float64(max(s[i-1], 1)); r >= 2 && r > best {
			best, at = r, i
		}
	}
	if at == 0 {
		return nil, nil, false
	}
	return s[:at], s[at:], true
}

// kindOf picks the kind whose median is nearest to the run in ratio.
func kindOf(ms int64, low, high []int64) []int64 {
	far := func(m float64) float64 {
		a, b := max(float64(ms), 1), max(m, 1)
		return max(a, b) / min(a, b)
	}
	if far(median(low)) <= far(median(high)) {
		return low
	}
	return high
}
