package main

import (
	"regexp"
	"sort"
	"strings"
	"time"
)

// IOOut is one block device over the last sample interval.
type IOOut struct {
	Dev     string  `json:"dev"`
	Util    float64 `json:"util"`     // % of the time with at least one request in flight
	AwaitMs float64 `json:"await_ms"` // average time a request took, queueing included
	RBps    float64 `json:"rbps"`     // bytes read per second
	WBps    float64 `json:"wbps"`
}

// IOTracker turns the /proc/diskstats counters into per-interval figures.
type IOTracker struct {
	prev  map[string]DiskStat
	prevT time.Time
}

func NewIOTracker() *IOTracker { return &IOTracker{prev: map[string]DiskStat{}} }

// Update returns the devices that did any I/O since the previous call, busiest first (at most 8).
func (t *IOTracker) Update(now time.Time, stats []DiskStat) []IOOut {
	elapsed := now.Sub(t.prevT)
	next := make(map[string]DiskStat, len(stats))
	var out []IOOut
	for _, s := range stats {
		next[s.Name] = s
		p, ok := t.prev[s.Name]
		if !ok || t.prevT.IsZero() || elapsed <= 0 || s.IOMs < p.IOMs || s.Reads < p.Reads || s.Writes < p.Writes {
			continue // first reading, or the counters were reset (device re-added)
		}
		ios := (s.Reads - p.Reads) + (s.Writes - p.Writes)
		ms := float64(elapsed) / float64(time.Millisecond)
		o := IOOut{Dev: s.Name, Util: round1(clamp(100*float64(s.IOMs-p.IOMs)/ms, 0, 100))}
		if ios > 0 && s.ReadMs >= p.ReadMs && s.WriteMs >= p.WriteMs {
			o.AwaitMs = round1(float64((s.ReadMs-p.ReadMs)+(s.WriteMs-p.WriteMs)) / float64(ios))
		}
		sec := elapsed.Seconds()
		if s.SectorsRead >= p.SectorsRead {
			o.RBps = float64(int64(float64(s.SectorsRead-p.SectorsRead) * 512 / sec))
		}
		if s.SectorsWritten >= p.SectorsWritten {
			o.WBps = float64(int64(float64(s.SectorsWritten-p.SectorsWritten) * 512 / sec))
		}
		if ios == 0 && o.Util == 0 {
			continue
		}
		out = append(out, o)
	}
	t.prev, t.prevT = next, now
	sort.Slice(out, func(i, j int) bool {
		if out[i].Util != out[j].Util {
			return out[i].Util > out[j].Util
		}
		return out[i].Dev < out[j].Dev
	})
	if len(out) > 8 {
		out = out[:8]
	}
	return out
}

// Devices that are never interesting: loop images, RAM disks, CD drives, floppies.
func pseudoBlock(name string) bool {
	for _, p := range []string{"loop", "ram", "zram", "sr", "fd", "nbd"} {
		if strings.HasPrefix(name, p) {
			return true
		}
	}
	return false
}

var partitionRe = regexp.MustCompile(`^((s|h|v|xv)d[a-z]+\d+|nvme\d+n\d+p\d+|mmcblk\d+p\d+)$`)

// wholeDisk keeps whole devices, not their partitions (whose I/O is counted again on the disk).
// sysBlock is the list of /sys/block; when it could not be read a name pattern decides.
func wholeDisk(sysBlock map[string]bool) func(string) bool {
	return func(name string) bool {
		if pseudoBlock(name) {
			return false
		}
		if len(sysBlock) > 0 {
			return sysBlock[strings.ReplaceAll(name, "/", "!")]
		}
		return !partitionRe.MatchString(name)
	}
}
