package main

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

// The rule. All integers, milliseconds, no floating point anywhere.
const (
	Ceiling  int64 = 1_800_000 // 30 minutes, stated and never reached
	First    int64 = 900_000   // grant 1
	MinGrant int64 = 10_000    // a grant is made only if strictly greater
	Window   int64 = 60_000    // asking opens this long before the deadline
)

// Grant returns grant number n: First halved n-1 times, rounded down.
func Grant(n int) int64 {
	if n < 1 || n > 63 {
		return 0
	}
	return First >> (n - 1)
}

// MaxGrants is how many grants the rule can ever make, computed from the constants.
func MaxGrants() int {
	n := 0
	for Grant(n+1) > MinGrant {
		n++
	}
	return n
}

// Total is the sum of grants 1 to k.
func Total(k int) int64 {
	var t int64
	for n := 1; n <= k; n++ {
		t += Grant(n)
	}
	return t
}

// SumAll is the sum of every grant integer halving could ever produce.
func SumAll() int64 {
	var t int64
	for n := 1; Grant(n) > 0; n++ {
		t += Grant(n)
	}
	return t
}

// Shortfall is what of the ceiling can never be granted.
func Shortfall() int64 { return Ceiling - SumAll() }

func ms(n int64) time.Duration { return time.Duration(n) * time.Millisecond }

// millis renders r milliseconds as seconds with up to three decimals, trailing zeros removed.
func millis(r int64) string {
	s := fmt.Sprintf("%d.%03d", r/1000, r%1000)
	return strings.TrimSuffix(strings.TrimRight(s, "0"), ".")
}

func unit(num, word string) string {
	if num == "1" {
		return num + " " + word
	}
	return num + " " + word + "s"
}

// Words is the one wording of a duration, used everywhere.
func Words(d int64) string {
	m, r := d/60_000, d%60_000
	if m == 0 {
		return unit(millis(r), "second")
	}
	w := unit(fmt.Sprint(m), "minute")
	if r != 0 {
		w += " " + unit(millis(r), "second")
	}
	return w
}

// Clock prints HH:MM:SS, with .mmm (trailing zeros removed) only when the milliseconds are not zero.
func Clock(t time.Time) string {
	s := t.Format("15:04:05")
	if m := int64(t.Nanosecond()) / 1e6; m != 0 {
		s += strings.TrimRight(fmt.Sprintf(".%03d", m), "0")
	}
	return s
}

// Day prints a date as "Tue 2026-10-13".
func Day(t time.Time) string { return t.Format("Mon 2006-01-02") }

// Answer is the one answer to a request made while asking is open, given k grants so far
// and deadline d. The live run and the dry run both use it.
func Answer(k int, d time.Time) (granted bool, g int64, nd time.Time, lines []string) {
	g = Grant(k + 1)
	if g <= MinGrant {
		return false, 0, d, []string{fmt.Sprintf(
			"Not granted. The next grant would be %s, under the %d second minimum. Remaining that can ever be granted: %s.",
			Words(g), MinGrant/1000, Words(Ceiling-Total(k)))}
	}
	nd = d.Add(ms(g))
	return true, g, nd, []string{
		fmt.Sprintf("Granted %s. Remaining that can ever be granted: %s.", Words(g), Words(Ceiling-Total(k+1))),
		"Bedtime is now " + Clock(nd) + ".",
	}
}
