package main

import (
	"fmt"
	"strings"
	"time"
)

const (
	quiet     = 2_000  // ms: a median under this says nothing before, and a run this quick nothing after
	clockMin  = 60_000 // ms: under this median nobody waits long enough for a clock time to matter
	clockRuns = 5      // a clock time is never spoken with fewer finished runs behind it
)

// speak says a duration of integer milliseconds. The form is chosen on the
// unrounded value; each form then rounds half up on the unit it speaks.
func speak(ms int64) string {
	switch {
	case ms < 1_000:
		return "under a second"
	case ms < 90_000:
		return plural((ms+500)/1_000, "second")
	case ms < 600_000:
		tens := (ms + 5_000) / 10_000
		return parts(tens/6, "minute", tens%6*10, "second")
	case ms < 5_400_000:
		return plural((ms+30_000)/60_000, "minute")
	default:
		fives := (ms + 150_000) / 300_000
		return parts(fives/12, "hour", fives%12*5, "minute")
	}
}

// speakEdge says a band edge: under 10 seconds always in tenths, never "under a second".
func speakEdge(ms int64) string {
	if ms < 10_000 {
		t := (ms + 50) / 100
		return fmt.Sprintf("%d.%d seconds", t/10, t%10)
	}
	return speak(ms)
}

func plural(n int64, unit string) string {
	if n == 1 {
		return "1 " + unit
	}
	return fmt.Sprintf("%d %ss", n, unit)
}

func parts(a int64, ua string, b int64, ub string) string {
	if b == 0 {
		return plural(a, ua)
	}
	return plural(a, ua) + " " + plural(b, ub)
}

var (
	hours   = [12]string{"twelve", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven"}
	minutes = [12]string{"", "five past", "ten past", "a quarter past", "twenty past", "twenty-five past", "half past",
		"twenty-five to", "twenty to", "a quarter to", "ten to", "five to"}
)

// roundClock rounds a wall clock time to the nearest five minutes, half up,
// carrying into the hour and the date.
func roundClock(t time.Time) time.Time {
	y, mo, d := t.Date()
	secs := t.Hour()*3600 + t.Minute()*60 + t.Second()
	return time.Date(y, mo, d, 0, 0, (secs+150)/300*300, 0, t.Location())
}

// speakClock says a time already rounded to five minutes, on a 12 hour clock.
func speakClock(t time.Time) string {
	h, m := t.Hour(), t.Minute()
	switch {
	case m == 0 && h == 12:
		return "noon"
	case m == 0 && h == 0:
		return "midnight"
	}
	s := hours[h%12] + " o'clock"
	if m > 30 {
		s = minutes[m/5] + " " + hours[(h+1)%12]
	} else if m > 0 {
		s = minutes[m/5] + " " + hours[h%12]
	}
	switch {
	case h >= 5 && h < 12:
		return s + " in the morning"
	case h >= 12 && h < 18:
		return s + " in the afternoon"
	case h >= 18 && h < 21:
		return s + " in the evening"
	}
	return s + " at night"
}

func capital(s string) string { return strings.ToUpper(s[:1]) + s[1:] }

// runs is the count phrase every statement carries.
func runs(h history) string {
	if h.total > window {
		return fmt.Sprintf("the last %d runs", window)
	}
	return fmt.Sprintf("%d runs", len(h.ok))
}

// before is what is said before the command runs. Nil means silence.
func before(h history, now time.Time) []string {
	n := len(h.ok)
	switch {
	case n == 0 && h.failed == 0:
		return []string{"No record. This is the first."}
	case n == 0 && h.failed == 1:
		return []string{"No finished run on record. 1 failed run is kept apart."}
	case n == 0:
		return []string{fmt.Sprintf("No finished run on record. %d failed runs are kept apart.", h.failed)}
	case n == 1:
		return []string{fmt.Sprintf("From 1 run on record: %s. Too few to call anything usual.", speak(h.ok[0]))}
	case n == 2:
		return []string{fmt.Sprintf("From 2 runs on record: %s, %s. Too few to call anything usual.", speak(h.ok[0]), speak(h.ok[1]))}
	}
	s := sorted(h.ok)
	med := halfUp(median(s))
	if med < quiet {
		return nil
	}
	count := runs(h)
	if low, high, ok := split(s); ok {
		return []string{fmt.Sprintf("Runs come in two kinds: %d near %s, %d near %s. From %s.",
			len(low), speak(halfUp(median(low))), len(high), speak(halfUp(median(high))), count)}
	}
	var out []string
	if least, most := speak(s[0]), speak(s[n-1]); least == most {
		every := "the " + count
		if h.total > window {
			every = count
		}
		out = append(out, fmt.Sprintf("Every one of %s took about %s.", every, least))
	} else {
		out = append(out, fmt.Sprintf("Usually about %s. Once took %s, once %s. From %s.", speak(med), least, most, count))
	}
	if n >= clockRuns && med >= clockMin {
		out = append(out, clockSentence(now, med, count))
	}
	return out
}

func clockSentence(now time.Time, ms int64, count string) string {
	t := roundClock(now.Add(time.Duration(ms) * time.Millisecond))
	s := "Expect to finish at about " + speakClock(t)
	day := func(t time.Time) string { return t.Format("2006-01-02") }
	switch day(t) {
	case day(now):
	case day(now.AddDate(0, 0, 1)):
		s += ", tomorrow"
	default:
		s += ", on " + t.Weekday().String()
	}
	return s + ". From " + count + "."
}

// after is what is said once the command has ended, without the blank line
// that precedes it. Nil means silence.
func after(h history, ms int64, code int, unwritten bool) []string {
	var out []string
	if code != 0 {
		out = append(out, fmt.Sprintf("Exit %d. Kept apart, not judged.", code))
	} else if len(h.ok) >= 3 && !(ms < quiet && halfUp(median(sorted(h.ok))) < quiet) {
		out = append(out, verdict(h, ms)...)
	}
	if unwritten {
		out = append(out, "The log could not be written.")
	}
	if code == 0 && h.total == 99 {
		out = append(out, "This was the 100th.")
	}
	return out
}

func verdict(h history, ms int64) []string {
	kind, count := h.ok, runs(h)
	if low, high, ok := split(h.ok); ok {
		kind = kindOf(ms, low, high)
		count = fmt.Sprintf("%d runs of that kind", len(kind))
	}
	lo, hi := band(kind)
	head := "That was not a usual one."
	if ms >= lo && ms <= hi {
		head = "That was a usual one."
	}
	return []string{head, evidence(ms, lo, hi, count)}
}

func evidence(ms, lo, hi int64, count string) string {
	b := speakEdge(lo) + " to " + speakEdge(hi)
	if speakEdge(lo) == speakEdge(hi) {
		b = "about " + speakEdge(lo)
	}
	return fmt.Sprintf("Took %s. The usual band is %s: the middle half of %s, plus a tenth of the median.", speak(ms), b, count)
}
