package main

import (
	"fmt"
	"testing"
	"time"
)

// nightLedger is the ledger the end to end run writes: a start, seven grants, a decline, an end.
func nightLedger() string {
	d := time.Date(2026, 10, 13, 23, 0, 0, 0, time.UTC)
	text := Line(d.Add(-2*time.Minute), "2026-10-13", "23:00", "start", "deadline=23:00:00 granted_ms=0 resumed=no")
	for k := 0; k < 8; k++ {
		ok, g, nd, _ := Answer(k, d)
		result, total := "declined", Total(k)
		if ok {
			result, total, d = "granted", Total(k+1), nd
		}
		text += Line(d, "2026-10-13", "23:00", "ask", fmt.Sprintf("result=%s grant_ms=%d total_ms=%d deadline=%s", result, g, total, Clock(d)))
	}
	text += "not a ledger line\n"
	return text + Line(d, "2026-10-13", "23:00", "end", "action=then")
}

func TestParseCountsANight(t *testing.T) {
	n := Parse(nightLedger())
	if len(n) != 1 || n[0].Starts != 1 || n[0].Asks != 8 || n[0].Grants != 7 || n[0].Added != 1785937 ||
		n[0].Ended != "then" || n[0].Slept != "23:29:45" {
		t.Fatalf("parsed %+v", *n[0])
	}
}

func TestLogLayout(t *testing.T) {
	want := "Night       Bedtime  Starts  Asks  Granted  Added                      Ended  Slept\n" +
		"2026-10-13  23:00    1       8     7        29 minutes 45.937 seconds  then   23:29:45\n" +
		"\nNights recorded: 1. Nights with at least one ask: 1.\n"
	if got := Log(Parse(nightLedger())); got != want {
		t.Fatalf("log:\n%s\nwant:\n%s", got, want)
	}
}

func TestStoppedNightAndEmptyLedger(t *testing.T) {
	n := Parse("2026-10-13T23:01:00.000+00:00\t2026-10-13\t23:00\tend\taction=interrupted\n")
	if n[0].Ended != "stopped" || n[0].Slept != "-" {
		t.Fatalf("stopped night: %+v", *n[0])
	}
	if Log(Parse("")) != "No nights recorded.\n" {
		t.Fatal("empty ledger")
	}
}
