package main

import (
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"
)

func at(s string) time.Time {
	t, err := time.ParseInLocation("2006-01-02T15:04:05", s, time.UTC)
	if err != nil {
		panic(err)
	}
	return t
}

func granted(date, target string, k int) []*Night {
	text := ""
	for i := 0; i < k; i++ {
		text += Line(at(date+"T23:00:00"), date, target, "ask", "result=granted grant_ms=1 total_ms=1 deadline=x")
	}
	return Parse(text)
}

func TestSelectTargetAndResume(t *testing.T) {
	cases := []struct {
		name, now, target string
		h, m              int
		nights            []*Night
		night, d          string
		k                 int
	}{
		{"nothing granted, c ahead", "2026-10-13T22:00:00", "23:00", 23, 0, nil, "2026-10-13", "2026-10-13T23:00:00", 0},
		{"c passed, nothing granted: tomorrow", "2026-10-13T23:30:00", "23:00", 23, 0, nil, "2026-10-14", "2026-10-14T23:00:00", 0},
		{"c passed, c+g ahead: resume", "2026-10-13T23:10:00", "23:00", 23, 0, granted("2026-10-13", "23:00", 2), "2026-10-13", "2026-10-13T23:22:30", 2},
		{"c+g passed: tomorrow", "2026-10-13T23:30:00", "23:00", 23, 0, granted("2026-10-13", "23:00", 2), "2026-10-14", "2026-10-14T23:00:00", 0},
		{"after midnight: resume yesterday", "2026-10-14T00:05:00", "23:50", 23, 50, granted("2026-10-13", "23:50", 2), "2026-10-13", "2026-10-14T00:12:30", 2},
	}
	for _, c := range cases {
		s := Select(at(c.now), c.h, c.m, c.target, c.nights)
		if s.Night() != c.night || !s.D.Equal(at(c.d)) || s.K != c.k {
			t.Errorf("%s: night %s D %s k %d", c.name, s.Night(), s.D, s.K)
		}
	}
	if s := Select(at("2026-10-14T00:05:00"), 23, 50, "23:50", granted("2026-10-13", "23:50", 2)); Grant(s.K+1) != 225000 {
		t.Errorf("midnight resume: next grant is not number 3")
	}
}

const freshSchedule = `Schedule of extensions, night of Tue 2026-10-13.
Bedtime is 23:00 on Tue 2026-10-13.
Asking for five more minutes opens at 22:59:00, one minute before.
Each grant is half the one before. The first grant is 15 minutes.
The most that can ever be granted in total is 30 minutes.

1. Granted 15 minutes. Remaining that can ever be granted: 15 minutes.
   Bedtime is now 23:15:00.
2. Granted 7 minutes 30 seconds. Remaining that can ever be granted: 7 minutes 30 seconds.
   Bedtime is now 23:22:30.
3. Granted 3 minutes 45 seconds. Remaining that can ever be granted: 3 minutes 45 seconds.
   Bedtime is now 23:26:15.
4. Granted 1 minute 52.5 seconds. Remaining that can ever be granted: 1 minute 52.5 seconds.
   Bedtime is now 23:28:07.5.
5. Granted 56.25 seconds. Remaining that can ever be granted: 56.25 seconds.
   Bedtime is now 23:29:03.75.
6. Granted 28.125 seconds. Remaining that can ever be granted: 28.125 seconds.
   Bedtime is now 23:29:31.875.
7. Granted 14.062 seconds. Remaining that can ever be granted: 14.063 seconds.
   Bedtime is now 23:29:45.937.
No grant 8: it would be 7.031 seconds, under the 10 second minimum.
The last possible bedtime is 23:29:45.937.
Halving rounds down to the millisecond. 11 milliseconds of the 30 minutes can never be granted.`

func TestDryRunScheduleFresh(t *testing.T) {
	s := Select(at("2026-10-13T21:00:00"), 23, 0, "23:00", nil)
	if got := strings.Join(Schedule(s), "\n"); got != freshSchedule {
		t.Fatalf("schedule:\n%s", got)
	}
}

func TestResumedOpeningLines(t *testing.T) {
	s := Select(at("2026-10-13T23:01:00"), 23, 0, "23:00", granted("2026-10-13", "23:00", 1))
	want := []string{
		"Resuming tonight. 1 grant given, 15 minutes in total. Bedtime is 23:15:00.",
		"Bedtime is 23:15:00 on Tue 2026-10-13.",
		"Asking for five more minutes opens at 23:14:00, one minute before.",
		"Each grant is half the one before. The next grant is 7 minutes 30 seconds.",
		"The most that can ever be granted in total is 30 minutes.",
	}
	if got := strings.Join(Opening(s), "\n"); got != strings.Join(want, "\n") {
		t.Fatalf("opening:\n%s", got)
	}
	rows := strings.Join(Schedule(s), "\n")
	if !strings.Contains(rows, "\n2. Granted 7 minutes 30 seconds.") || strings.Contains(rows, "\n1. ") ||
		!strings.Contains(rows, "The last possible bedtime is 23:29:45.937.") {
		t.Fatalf("resumed schedule:\n%s", rows)
	}
	s = Select(at("2026-10-14T00:05:00"), 23, 50, "23:50", granted("2026-10-13", "23:50", 2))
	if o := Opening(s); o[0] != "Resuming tonight. 2 grants given, 22 minutes 30 seconds in total. Bedtime is 00:12:30." ||
		o[1] != "Bedtime is 00:12:30 on Wed 2026-10-14." {
		t.Fatalf("midnight opening: %q", o[:2])
	}
	s = Select(at("2026-10-13T23:29:00"), 23, 0, "23:00", granted("2026-10-13", "23:00", 7))
	if o := Opening(s); o[3] != "Each grant is half the one before. No further grant can be made." {
		t.Fatalf("exhausted opening: %q", o[3])
	}
}

func TestRequestRecognition(t *testing.T) {
	for _, l := range []string{"five more minutes", "Five More Minutes!", "  5   more minutes?  ", "FIVE MORE MINUTES."} {
		if !Request(l) {
			t.Errorf("%q not recognised", l)
		}
	}
	for _, l := range []string{"give me an hour", "five more minute", "", "six more minutes"} {
		if Request(l) {
			t.Errorf("%q recognised", l)
		}
	}
}

// replyWriter answers each "Asking is open" line with a request, the way a person at the desk would.
type replyWriter struct {
	out   strings.Builder
	lines chan string
}

func (w *replyWriter) Write(p []byte) (int, error) {
	w.out.Write(p)
	if strings.HasPrefix(string(p), "Asking is open") {
		w.lines <- "five more minutes"
	}
	return len(p), nil
}

func TestLiveRunWithFakeClockAndFakeAction(t *testing.T) {
	now := at("2026-10-13T22:58:00")
	ledger := filepath.Join(t.TempDir(), "ledger.tsv")
	w := &replyWriter{lines: make(chan string, 16)}
	var acted time.Time
	code := Live(Env{
		Now: func() time.Time { return now },
		Wait: func(sim time.Duration) <-chan time.Time {
			now = now.Add(min(sim, 200*time.Millisecond))
			c := make(chan time.Time, 1)
			c <- now
			return c
		},
		Out:    w,
		Lines:  w.lines,
		Act:    func() Outcome { acted = now; return Outcome{Action: "then", At: now} },
		Ledger: ledger,
	}, Select(now, 23, 0, "23:00", nil))
	out := w.out.String()
	if code != 0 || strings.Count(out, "Asking is open") != 8 || strings.Count(out, "\nGranted") != 7 ||
		strings.Count(out, "Not granted") != 1 || !strings.HasSuffix(out, "Bedtime.\nSleeping.\n") {
		t.Fatalf("code %d, output:\n%s", code, out)
	}
	if !acted.Equal(at("2026-10-13T23:29:45").Add(937 * time.Millisecond)) {
		t.Fatalf("acted at %s", acted)
	}
	text, _ := os.ReadFile(ledger)
	got := Log(Parse(string(text)))
	if !strings.Contains(got, "2026-10-13  23:00    1       8     7        29 minutes 45.937 seconds  then   23:29:45\n") {
		t.Fatalf("log:\n%s", got)
	}
}
