package main

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

type clock struct{ t time.Time }

func (c *clock) now() time.Time { return c.t }

func mustOpen(t *testing.T, dir, opens string, window time.Duration, c *clock) *Box {
	t.Helper()
	s, err := parseOpens(opens)
	if err != nil {
		t.Fatal(err)
	}
	b, err := openBox(dir, s, window, c.now)
	if err != nil {
		t.Fatal(err)
	}
	return b
}

func mustView(t *testing.T, b *Box) frontView {
	t.Helper()
	v, err := b.view()
	if err != nil {
		t.Fatal(err)
	}
	return v
}

func put(t *testing.T, b *Box, notes ...string) {
	t.Helper()
	for _, n := range notes {
		if err := b.add(n); err != nil {
			t.Fatalf("add(%q): %v", n, err)
		}
	}
}

func readJSON(t *testing.T, p string) []string {
	t.Helper()
	n, err := readNotes(p)
	if err != nil {
		t.Fatal(err)
	}
	return n
}

func exists(p string) bool { _, err := os.Stat(p); return err == nil }

func writeFile(t *testing.T, p, body string) {
	t.Helper()
	if err := os.WriteFile(p, []byte(body), 0o600); err != nil {
		t.Fatal(err)
	}
}

func TestSortOrder(t *testing.T) {
	n := []string{"zebra", "Über den Plan", "mango", "apple", "Apple", "10 more chairs", "(bracket)"}
	sortNotes(n)
	want := []string{"(bracket)", "10 more chairs", "Apple", "apple", "mango", "zebra", "Über den Plan"}
	if !slices.Equal(n, want) {
		t.Errorf("got %q, want %q", n, want)
	}
}

func TestFlattenAndLimits(t *testing.T) {
	if got := flatten("  apple  pie\n\n\tfriday \r\n"); got != "apple pie friday" {
		t.Errorf("flatten = %q", got)
	}
	c := &clock{time.Date(2026, 10, 14, 10, 0, 0, 0, berlin(t))}
	b := mustOpen(t, t.TempDir(), "Fri 16:00", 24*time.Hour, c)
	// 500 runes after flattening is accepted, even when the typed text is longer.
	put(t, b, strings.Repeat("x", 500)+"\n\n\n      ", strings.Repeat("é", 500), strings.Repeat("a ", 250))
	for in, want := range map[string]error{
		"   \n\t ":                       errEmpty,
		strings.Repeat("é", 501):         errTooLong,
		"<b>" + strings.Repeat("y", 498): errTooLong,
	} {
		if err := b.add(in); !errors.Is(err, want) {
			t.Errorf("add(%d runes) = %v, want %v", len(in), err, want)
		}
	}
	for i := 3; i < maxNotes; i++ {
		put(t, b, "note number "+strings.Repeat("i", i))
	}
	if err := b.add("one more"); !errors.Is(err, errFull) {
		t.Errorf("101st note: %v, want errFull", err)
	}
	if n := readJSON(t, filepath.Join(b.dir, "2026-10-16.json")); len(n) != maxNotes {
		t.Errorf("%d notes stored", len(n))
	}
}

func TestSnapshotOnlyOnTick(t *testing.T) {
	loc := berlin(t)
	dir := t.TempDir()
	c := &clock{time.Date(2026, 10, 14, 14, 0, 0, 0, loc)}
	b := mustOpen(t, dir, "Fri 16:00", 24*time.Hour, c)
	put(t, b, "first", "second", "third")
	if v := mustView(t, b); v.Count != "0 notes inside." || v.Stamp != "Count as of 14:00." {
		t.Errorf("count moved without a tick: %q %q", v.Count, v.Stamp)
	}
	// A restart: the startup snapshot carries the real minute and the true count.
	c.t = time.Date(2026, 10, 14, 14, 37, 45, 0, loc)
	b = mustOpen(t, dir, "Fri 16:00", 24*time.Hour, c)
	if v := mustView(t, b); v.Count != "3 notes inside." || v.Stamp != "Count as of 14:37." {
		t.Errorf("startup snapshot: %q %q", v.Count, v.Stamp)
	}
	c.t = c.t.Add(10 * time.Minute)
	put(t, b, "fourth")
	if v := mustView(t, b); v.Count != "3 notes inside." {
		t.Errorf("count moved on a post: %q", v.Count)
	}
	c.t = time.Date(2026, 10, 14, 15, 0, 0, 4e6, loc) // the timer fires a little late
	b.tick()
	if v := mustView(t, b); v.Count != "4 notes inside." || v.Stamp != "Count as of 15:00." {
		t.Errorf("hourly tick: %q %q", v.Count, v.Stamp)
	}
	b.tick() // a second wake for the same instant takes nothing
	if b.stamp.Format("15:04:05") != "15:00:00" {
		t.Errorf("stamp is %v, want the scheduled instant", b.stamp)
	}
}

func TestOpeningSnapshotMonday0930(t *testing.T) {
	loc := berlin(t)
	dir := t.TempDir()
	c := &clock{time.Date(2026, 10, 18, 20, 10, 0, 0, loc)}
	b := mustOpen(t, dir, "Mon 09:30", 2*time.Hour, c)
	put(t, b, "lights in the hall", "a second kettle")
	c.t = time.Date(2026, 10, 19, 9, 0, 0, 0, loc)
	b.tick()
	c.t = time.Date(2026, 10, 19, 9, 30, 0, 2e6, loc)
	b.tick()
	v := mustView(t, b)
	if v.Count != "0 notes inside." || v.Stamp != "Count as of 09:30." {
		t.Errorf("opening snapshot: %q %q", v.Count, v.Stamp)
	}
	if v.Sheet == nil || v.Sheet.Header != "Suggestion box. Opened Monday 19 October 2026, 09:30." ||
		v.Sheet.Total != "2 notes." || v.Sheet.AtOpening != "Count shown on the page at opening: 2." {
		t.Fatalf("sheet: %+v", v.Sheet)
	}
	if !exists(filepath.Join(dir, "2026-10-19.opened.json")) || !exists(filepath.Join(dir, "2026-10-26.json")) {
		t.Error("opened file or next box file missing")
	}
}

func TestCountAtOpeningKeepsLastSnapshot(t *testing.T) {
	loc := berlin(t)
	dir := t.TempDir()
	c := &clock{time.Date(2026, 10, 16, 15, 10, 0, 0, loc)}
	b := mustOpen(t, dir, "Fri 16:00", 24*time.Hour, c)
	put(t, b, "the printer on two jams", "more chairs in room four", "fewer meetings on monday")
	c.t = time.Date(2026, 10, 16, 15, 12, 0, 0, loc)
	b = mustOpen(t, dir, "Fri 16:00", 24*time.Hour, c) // restart: snapshot 3
	put(t, b, "kettle")
	c.t = time.Date(2026, 10, 16, 16, 0, 0, 1e6, loc)
	b.tick()
	v := mustView(t, b)
	if v.Sheet == nil || v.Sheet.Total != "4 notes." || v.Sheet.AtOpening != "Count shown on the page at opening: 3." {
		t.Fatalf("sheet: %+v", v.Sheet)
	}
	if v.Count != "0 notes inside." || v.Stamp != "Count as of 16:00." {
		t.Errorf("new box: %q %q", v.Count, v.Stamp)
	}
	if !slices.Equal(v.Sheet.Notes, []string{"fewer meetings on monday", "kettle", "more chairs in room four", "the printer on two jams"}) {
		t.Errorf("order: %q", v.Sheet.Notes)
	}
}

func TestMtimeNormalised(t *testing.T) {
	loc := berlin(t)
	dir := t.TempDir()
	c := &clock{time.Date(2026, 10, 14, 11, 23, 0, 0, loc)}
	b := mustOpen(t, dir, "Fri 16:00", 24*time.Hour, c)
	c.t = c.t.Add(3 * time.Hour)
	put(t, b, "zebra crossing is unclear", "apple  pie\n\nfriday", "mango")
	opening := time.Date(2026, 10, 16, 16, 0, 0, 0, loc)
	for _, p := range []string{filepath.Join(dir, "2026-10-16.json"), dir} {
		info, err := os.Stat(p)
		if err != nil || !info.ModTime().Equal(opening) {
			t.Errorf("%s mtime %v, want %v", p, info.ModTime(), opening)
		}
	}
	data, _ := os.ReadFile(filepath.Join(dir, "2026-10-16.json"))
	if string(data) != "[\n  \"apple pie friday\",\n  \"mango\",\n  \"zebra crossing is unclear\"\n]\n" {
		t.Errorf("file:\n%s", data)
	}
}

func TestStrayPastFilesMerged(t *testing.T) {
	loc := berlin(t)
	dir := t.TempDir()
	writeFile(t, filepath.Join(dir, "2026-10-02.json"), `["b from two weeks ago"]`)
	writeFile(t, filepath.Join(dir, "2026-10-09.json"), `[]`)
	writeFile(t, filepath.Join(dir, "2026-10-16.json"), `["c last week", "a last week"]`)
	writeFile(t, filepath.Join(dir, "notes.txt"), `ignored`)
	c := &clock{time.Date(2026, 10, 17, 10, 0, 0, 0, loc)}
	b := mustOpen(t, dir, "Fri 16:00", 24*time.Hour, c)
	v := mustView(t, b)
	if v.Sheet == nil || v.Sheet.Header != "Suggestion box. Opened Friday 16 October 2026, 16:00." || v.Sheet.Total != "3 notes." ||
		v.Sheet.Earlier != "Includes notes from 1 earlier opening." || v.Sheet.AtOpening != "" {
		t.Fatalf("sheet: %+v", v.Sheet)
	}
	if !slices.Equal(v.Sheet.Notes, []string{"a last week", "b from two weeks ago", "c last week"}) {
		t.Errorf("notes: %q", v.Sheet.Notes)
	}
	c.t = c.t.Add(24 * time.Hour)
	b.tick()
	for _, k := range []string{"2026-10-02", "2026-10-09", "2026-10-16"} {
		if exists(filepath.Join(dir, k+".opened.json")) {
			t.Errorf("%s still there after the window", k)
		}
	}
	if !exists(filepath.Join(dir, "notes.txt")) || !exists(filepath.Join(dir, "2026-10-23.json")) {
		t.Error("an unrelated file or the next box was removed")
	}
}

func TestFutureKeyRefusesStart(t *testing.T) {
	loc := berlin(t)
	s, _ := parseOpens("Mon 09:30") // was Fri 16:00 while these files waited
	for _, key := range []string{"2026-10-16", "2026-10-23"} {
		dir := t.TempDir()
		writeFile(t, filepath.Join(dir, key+".json"), `["waiting for friday"]`)
		c := &clock{time.Date(2026, 10, 14, 12, 0, 0, 0, loc)}
		_, err := openBox(dir, s, 24*time.Hour, c.now)
		want := filepath.Join(dir, key+".json") + " is keyed for an opening that is not the next one (2026-10-19). Not started."
		if err == nil || err.Error() != want {
			t.Errorf("err = %v, want %q", err, want)
		}
		if exists(filepath.Join(dir, "2026-10-19.json")) {
			t.Error("a file was created before the refusal")
		}
	}
	// Once its date has passed, the same file is opened, not refused.
	dir := t.TempDir()
	writeFile(t, filepath.Join(dir, "2026-10-16.json"), `["waiting for friday"]`)
	c := &clock{time.Date(2026, 10, 17, 12, 0, 0, 0, loc)}
	b := mustOpen(t, dir, "Mon 09:30", 24*time.Hour, c)
	if v := mustView(t, b); v.Sheet == nil || v.Sheet.Total != "1 note." {
		t.Errorf("past key from an earlier setting: %+v", v.Sheet)
	}
	// Opened at 16:00, then restarted with a later hour the same day: the
	// 18:00 opening would rename a new box over it.
	dir = t.TempDir()
	writeFile(t, filepath.Join(dir, "2026-10-16.opened.json"), `["opened at four"]`)
	c = &clock{time.Date(2026, 10, 16, 16, 30, 0, 0, loc)}
	later, _ := parseOpens("Fri 18:00")
	_, err := openBox(dir, later, 24*time.Hour, c.now)
	want := filepath.Join(dir, "2026-10-16.opened.json") + " is keyed for the next opening (2026-10-16), which would replace it. Not started."
	if err == nil || err.Error() != want {
		t.Errorf("err = %v, want %q", err, want)
	}
}

func TestFreshStart(t *testing.T) {
	dir := filepath.Join(t.TempDir(), "data")
	c := &clock{time.Date(2026, 10, 14, 12, 0, 0, 0, berlin(t))}
	b := mustOpen(t, dir, "Fri 16:00", 24*time.Hour, c)
	data, err := os.ReadFile(filepath.Join(dir, "2026-10-16.json"))
	if err != nil || strings.TrimSpace(string(data)) != "[]" {
		t.Errorf("next box file: %q %v", data, err)
	}
	fi, _ := os.Stat(filepath.Join(dir, "2026-10-16.json"))
	di, _ := os.Stat(dir)
	if fi.Mode().Perm() != 0o600 || di.Mode().Perm() != 0o700 {
		t.Errorf("modes %v %v", fi.Mode(), di.Mode())
	}
	if v := mustView(t, b); v.Sheet != nil {
		t.Errorf("a sheet on a fresh start: %+v", v.Sheet)
	}
}

func TestEmptyBoxOpened(t *testing.T) {
	loc := berlin(t)
	c := &clock{time.Date(2026, 10, 16, 15, 30, 0, 0, loc)}
	b := mustOpen(t, t.TempDir(), "Fri 16:00", 24*time.Hour, c)
	c.t = time.Date(2026, 10, 16, 16, 0, 0, 0, loc)
	b.tick()
	v := mustView(t, b)
	if v.Sheet == nil || v.Sheet.Total != "The box was opened. It was empty." || v.Sheet.AtOpening != "Count shown on the page at opening: 0." || len(v.Sheet.Notes) != 0 {
		t.Fatalf("sheet: %+v", v.Sheet)
	}
}

func TestPastFileStampedOnce(t *testing.T) {
	loc := berlin(t)
	dir := t.TempDir()
	writeFile(t, filepath.Join(dir, "2026-10-16.json"), `["kept while the server was off"]`)
	start := time.Date(2026, 10, 17, 9, 12, 0, 0, loc)
	c := &clock{start}
	mustOpen(t, dir, "Fri 16:00", 24*time.Hour, c)
	p := filepath.Join(dir, "2026-10-16.opened.json")
	info, err := os.Stat(p)
	if err != nil || !info.ModTime().Equal(start) || exists(filepath.Join(dir, "2026-10-16.json")) {
		t.Fatalf("not renamed and stamped with the start: %v %v", info, err)
	}
	c.t = start.Add(5 * time.Hour)
	b := mustOpen(t, dir, "Fri 16:00", 24*time.Hour, c)
	if info, _ := os.Stat(p); !info.ModTime().Equal(start) {
		t.Errorf("re-stamped on restart: %v", info.ModTime())
	}
	if v := mustView(t, b); v.Sheet == nil || v.Sheet.AtOpening != "" {
		t.Errorf("sheet: %+v (N must be unknown)", v.Sheet)
	}
}

func TestWindowAcrossRestart(t *testing.T) {
	loc := berlin(t)
	dir := t.TempDir()
	c := &clock{time.Date(2026, 10, 16, 15, 40, 0, 0, loc)}
	b := mustOpen(t, dir, "Fri 16:00", 24*time.Hour, c)
	put(t, b, "open the window")
	shown := time.Date(2026, 10, 16, 16, 0, 0, 3e6, loc)
	c.t = shown
	b.tick()
	c.t = shown.Add(12 * time.Hour)
	b = mustOpen(t, dir, "Fri 16:00", 24*time.Hour, c)
	if v := mustView(t, b); v.Sheet == nil || v.Sheet.AtOpening != "" {
		t.Fatalf("after a restart in the window: %+v", v.Sheet)
	}
	c.t = shown.Add(24*time.Hour - time.Second)
	b.retire()
	if !exists(filepath.Join(dir, "2026-10-16.opened.json")) {
		t.Fatal("deleted before the window ended")
	}
	c.t = shown.Add(24 * time.Hour)
	b.retire()
	if exists(filepath.Join(dir, "2026-10-16.opened.json")) || !exists(filepath.Join(dir, "2026-10-23.json")) {
		t.Fatal("window end: opened file kept or next box lost")
	}
	b = mustOpen(t, dir, "Fri 16:00", 24*time.Hour, c)
	if v := mustView(t, b); v.Sheet != nil {
		t.Fatalf("a sheet after the files were deleted: %+v", v.Sheet)
	}
	put(t, b, "next week")
	c.t = time.Date(2026, 10, 23, 16, 0, 0, 0, loc)
	b.tick()
	if v := mustView(t, b); v.Sheet == nil || v.Sheet.Total != "1 note." || v.Sheet.Earlier != "" {
		t.Fatalf("next opening: %+v", v.Sheet)
	}
}
