package main

import (
	"fmt"
	"slices"
	"strings"
	"testing"
	"time"
)

func secs(xs ...float64) []int64 {
	out := make([]int64, len(xs))
	for i, x := range xs {
		out[i] = halfUp(x * 1000)
	}
	return out
}

func eq(t *testing.T, what string, got, want any) {
	t.Helper()
	if fmt.Sprint(got) != fmt.Sprint(want) {
		t.Errorf("%s:\n got  %q\n want %q", what, got, want)
	}
}

func TestSpeak(t *testing.T) {
	for _, c := range []struct {
		s    float64
		want string
	}{
		{0.4, "under a second"}, {1, "1 second"}, {41, "41 seconds"}, {41.5, "42 seconds"},
		{89, "89 seconds"}, {89.6, "90 seconds"}, {90, "1 minute 30 seconds"},
		{190, "3 minutes 10 seconds"}, {599, "10 minutes"}, {2820, "47 minutes"},
		{5400, "1 hour 30 minutes"}, {8100, "2 hours 15 minutes"},
	} {
		eq(t, fmt.Sprint(c.s, "s"), speak(secs(c.s)[0]), c.want)
	}
}

func TestBandEdges(t *testing.T) {
	a := evidence(1000, 930, 1070, "5 runs")
	eq(t, "tenths", a, "Took 1 second. The usual band is 0.9 seconds to 1.1 seconds: the middle half of 5 runs, plus a tenth of the median.")
	b := evidence(400, 960, 1040, "5 runs")
	eq(t, "identical edges", b, "Took under a second. The usual band is about 1.0 seconds: the middle half of 5 runs, plus a tenth of the median.")
	for _, s := range []string{a, b} {
		if strings.Contains(s, "under a second to") {
			t.Errorf("said %q", s)
		}
	}
}

func TestClock(t *testing.T) {
	at := func(h, m int) time.Time { return time.Date(2026, 10, 13, h, m, 0, 0, time.UTC) }
	for _, c := range []struct {
		h, m int
		want string
	}{
		{12, 0, "noon"}, {0, 0, "midnight"}, {16, 12, "ten past four in the afternoon"},
		{23, 58, "midnight"}, {7, 45, "a quarter to eight in the morning"},
		{12, 30, "half past twelve in the afternoon"}, {0, 3, "five past twelve at night"},
		{17, 58, "six o'clock in the evening"},
	} {
		eq(t, fmt.Sprintf("%02d:%02d", c.h, c.m), speakClock(roundClock(at(c.h, c.m))), c.want)
	}
	eq(t, "23:58 carries the date", roundClock(at(23, 58)).Format("2006-01-02 15:04"), "2026-10-14 00:00")
	eq(t, "tomorrow", clockSentence(at(23, 50), 15*60_000, "5 runs"),
		"Expect to finish at about five past twelve at night, tomorrow. From 5 runs.")
	eq(t, "later", clockSentence(at(23, 50), 30*3_600_000, "5 runs"),
		"Expect to finish at about ten to six in the morning, on Thursday. From 5 runs.")
}

func TestMedianAndBand(t *testing.T) {
	eq(t, "odd median", median([]int64{1, 2, 9}), 2)
	eq(t, "even median", median([]int64{1, 2, 3, 9}), 2.5)
	for _, c := range []struct {
		runs   []int64
		lo, hi int64
	}{
		{secs(3, 1, 2), 800, 3200},                        // n=3: min and max, widened by 200
		{secs(50, 10, 40, 20, 30), 17000, 43000},          // n=5: 2nd and 4th, widened by 3000
		{secs(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 2450, 8550}, // n=10: 3rd and 8th, widened by 550
	} {
		lo, hi := band(c.runs)
		eq(t, fmt.Sprint("band ", c.runs), []int64{lo, hi}, []int64{c.lo, c.hi})
	}
}

// The worked example under The verdict in CARD.md.
func TestWorkedExample(t *testing.T) {
	runs := secs(250, 220, 380, 241, 266, 232, 258)
	lo, hi := band(runs)
	eq(t, "band", []int64{lo, hi}, []int64{207000, 291000})
	if _, _, ok := split(runs); ok {
		t.Error("split found")
	}
	h := history{ok: runs, total: 7}
	eq(t, "before", before(h, time.Date(2026, 10, 13, 16, 6, 0, 0, time.UTC)), []string{
		"Usually about 4 minutes 10 seconds. Once took 3 minutes 40 seconds, once 6 minutes 20 seconds. From 7 runs.",
		"Expect to finish at about ten past four in the afternoon. From 7 runs.",
	})
	eq(t, "after", after(h, 262318, 0, false), []string{
		"That was a usual one.",
		"Took 4 minutes 20 seconds. The usual band is 3 minutes 30 seconds to 4 minutes 50 seconds: the middle half of 7 runs, plus a tenth of the median.",
	})
	k := newKey("/tmp/proj", []string{"make", "build"})
	eq(t, "log line", logLine(time.Date(2026, 10, 13, 16, 10, 41, 0, time.UTC), 262318, 0, k),
		"2026-10-13 16:10. Ten past four in the afternoon. 262.318 seconds, exit 0. In /tmp/proj\tmake build\n")
}

func TestStatements(t *testing.T) {
	now := time.Date(2026, 10, 13, 9, 0, 0, 0, time.UTC)
	same := before(history{ok: secs(3.004, 3.005, 3.006), total: 3}, now)
	eq(t, "identical runs", same, []string{"Every one of the 3 runs took about 3 seconds."})
	if strings.Contains(strings.Join(same, " "), "Usually about") {
		t.Error("said Usually about")
	}
	eq(t, "first", before(history{}, now), []string{"No record. This is the first."})
	eq(t, "one failed", before(history{failed: 1}, now), []string{"No finished run on record. 1 failed run is kept apart."})
	eq(t, "two failed", before(history{failed: 2}, now), []string{"No finished run on record. 2 failed runs are kept apart."})
	eq(t, "one run", before(history{ok: secs(41), total: 1}, now), []string{"From 1 run on record: 41 seconds. Too few to call anything usual."})
	eq(t, "two runs", before(history{ok: secs(41, 44), total: 2}, now), []string{"From 2 runs on record: 41 seconds, 44 seconds. Too few to call anything usual."})
	eq(t, "two kinds", before(history{ok: secs(40, 12, 38, 11, 41, 12, 39, 42, 13, 40), total: 10}, now),
		[]string{"Runs come in two kinds: 4 near 12 seconds, 6 near 40 seconds. From 10 runs."})
	eq(t, "the last 20", before(history{ok: secs(3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3), total: 25}, now),
		[]string{"Every one of the last 20 runs took about 3 seconds."})
	eq(t, "quiet before", before(history{ok: secs(0.5, 0.6, 0.7), total: 3}, now), []string(nil))
	eq(t, "quiet after", after(history{ok: secs(0.5, 0.6, 0.7), total: 3}, 800, 0, false), []string(nil))
	eq(t, "slow run after quick ones", after(history{ok: secs(0.5, 0.6, 0.7), total: 3}, 9000, 0, false)[0], "That was not a usual one.")
	eq(t, "failed, even quick", after(history{}, 5, 2, false), []string{"Exit 2. Kept apart, not judged."})
	eq(t, "unwritten", after(history{}, 5, 0, true), []string{"The log could not be written."})
	eq(t, "verdict by kind", after(history{ok: secs(12, 12, 13, 40, 41, 42), total: 6}, 12500, 0, false), []string{
		"That was a usual one.",
		"Took 13 seconds. The usual band is 11 seconds to 14 seconds: the middle half of 3 runs of that kind, plus a tenth of the median.",
	})
}

func TestSplit(t *testing.T) {
	low, high, ok := split(secs(12, 12, 13, 40, 41, 42))
	eq(t, "two kinds", []any{ok, len(low), len(high)}, []any{true, 3, 3})
	if _, _, ok := split(secs(12, 14, 18, 24, 30, 40)); ok {
		t.Error("split found in a steady rise")
	}
}

func TestHundredth(t *testing.T) {
	quick := secs(0.1, 0.1, 0.1)
	for prior, want := range map[int]bool{98: false, 99: true, 100: false, 199: false} {
		got := slices.Contains(after(history{ok: quick, total: prior}, 100, 0, false), "This was the 100th.")
		eq(t, fmt.Sprint("prior ", prior), got, want)
	}
	eq(t, "quick 100th alone", after(history{ok: quick, total: 99}, 100, 0, false), []string{"This was the 100th."})
	eq(t, "a failed run is not the 100th", after(history{ok: quick, total: 99}, 100, 1, false), []string{"Exit 1. Kept apart, not judged."})

	k := newKey("/p", []string{"true"})
	end := time.Date(2026, 10, 13, 9, 0, 0, 0, time.UTC)
	var log strings.Builder
	log.WriteString(header)
	for i := 0; i < 99; i++ {
		log.WriteString(logLine(end, 1, 0, k))
		if i%30 == 0 {
			log.WriteString(logLine(end, 1, 1, k))
		}
	}
	h := parseHistory(log.String(), k)
	eq(t, "failed runs do not count", []int{h.total, h.failed, len(h.ok)}, []int{99, 4, 20})
	eq(t, "the 100th from a parsed log", slices.Contains(after(h, 1, 0, false), "This was the 100th."), true)
}

func TestKey(t *testing.T) {
	for _, c := range []struct {
		args []string
		want string
	}{
		{[]string{"make", "build"}, "make build"},
		{[]string{"echo", "a b"}, "echo 'a b'"},
		{[]string{"echo", "it's"}, `echo 'it'\''s'`},
		{[]string{"echo", "a\tb"}, "echo 'a b'"},
		{[]string{"echo", ""}, "echo ''"},
		{[]string{"sh", "-c", "sleep ${S:-3}"}, "sh -c 'sleep ${S:-3}'"},
	} {
		eq(t, fmt.Sprintf("%q", c.args), newKey("/a", c.args).argv, c.want)
	}
	eq(t, "tab in cwd", newKey("/a\tb", []string{"x"}).cwd, "/a b")
	if newKey("/a", []string{"make", "build"}) == newKey("/b", []string{"make", "build"}) {
		t.Error("two directories made one key")
	}
}

func TestLogRoundTrip(t *testing.T) {
	k := newKey("/tmp/proj", []string{"echo", "it's", "a\tb"})
	end := time.Date(2026, 10, 13, 7, 44, 0, 0, time.UTC)
	ok, failed := logLine(end, 262318, 0, k), logLine(end, 1500, 130, k)
	m := lineRe.FindStringSubmatch(strings.TrimSuffix(ok, "\n"))
	eq(t, "fields", m[1:], []string{"262.318", "0", "/tmp/proj", `echo 'it'\''s' 'a b'`})
	for _, line := range strings.Split(strings.TrimSuffix(header, "\n"), "\n") {
		if lineRe.MatchString(line) {
			t.Errorf("header line matched: %q", line)
		}
	}
	h := parseHistory(header+ok+"not an observation\n"+failed+logLine(end, 5, 0, newKey("/other", []string{"echo"})), k)
	eq(t, "parsed", []any{h.ok, h.total, h.failed}, []any{[]int64{262318}, 1, 1})
}
