package main

import (
	"io/fs"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"syscall"
	"testing"
	"time"
)

func day(s string) time.Time {
	t, err := time.Parse(isoLayout, s)
	if err != nil {
		panic(err)
	}
	return t
}

// The ten dates of the card, each checked by hand there.
func TestPloughDay(t *testing.T) {
	for _, c := range []struct {
		rest       string
		n          int
		thr, plows string
	}{
		{"2026-10-13", 1, "2027-01-13", "2027-03-25"},
		{"2026-10-13", 2, "2027-04-13", "2027-06-24"},
		{"2026-12-25", 1, "2027-03-25", "2027-03-25"},
		{"2026-12-26", 1, "2027-03-26", "2027-06-24"},
		{"2026-11-30", 1, "2027-02-28", "2027-03-25"},
		{"2028-02-29", 4, "2029-02-28", "2029-03-25"},
		{"2026-06-24", 4, "2027-06-24", "2027-06-24"},
		{"2026-06-25", 4, "2027-06-25", "2027-09-29"},
		{"2026-09-30", 1, "2026-12-30", "2027-03-25"},
		{"2026-03-26", 2, "2026-09-26", "2026-09-29"},
	} {
		if got := iso(threshold(day(c.rest), c.n)); got != c.thr {
			t.Errorf("threshold(%s, %d) = %s, want %s", c.rest, c.n, got, c.thr)
		}
		if got := iso(ploughDay(day(c.rest), c.n)); got != c.plows {
			t.Errorf("ploughDay(%s, %d) = %s, want %s", c.rest, c.n, got, c.plows)
		}
	}
}

func TestAddMonthsClamp(t *testing.T) {
	for _, c := range []struct {
		from string
		k    int
		want string
	}{
		{"2027-01-31", 1, "2027-02-28"},
		{"2028-01-31", 1, "2028-02-29"},
		{"2027-03-31", 1, "2027-04-30"},
		{"2026-11-30", 3, "2027-02-28"},
		{"2026-12-15", 1, "2027-01-15"},
		{"2026-10-13", 120, "2036-10-13"},
		{"2027-08-31", 3, "2027-11-30"},
	} {
		f := day(c.from)
		y, m, d := addMonths(f.Year(), f.Month(), f.Day(), c.k)
		if got := iso(mkday(y, m, d)); got != c.want {
			t.Errorf("addMonths(%s, %d) = %s, want %s", c.from, c.k, got, c.want)
		}
	}
	if n := daysBetween(day("2027-03-24"), day("2027-03-25")); n != 1 {
		t.Errorf("daysBetween across a day = %d", n)
	}
	if n := daysBetween(day("2027-01-05"), day("2027-06-24")); n != 170 {
		t.Errorf("daysBetween(5 Jan, 24 Jun) = %d, want 170", n)
	}
}

// field builds a small tree: a directory, files, a read-only file, a script, a
// symlink out of it and a fifo.
func field(t *testing.T) (root, outside string) {
	t.Helper()
	base := t.TempDir()
	t.Cleanup(func() { unlockAll(base) })
	root, outside = filepath.Join(base, "field"), filepath.Join(base, "outside.txt")
	must(t, os.MkdirAll(filepath.Join(root, "sub"), 0o755))
	must(t, os.WriteFile(outside, []byte("hi\n"), 0o600))
	must(t, os.WriteFile(filepath.Join(root, "a.txt"), []byte("a\n"), 0o644))
	must(t, os.WriteFile(filepath.Join(root, "run.sh"), []byte("#!/bin/sh\n"), 0o755))
	must(t, os.WriteFile(filepath.Join(root, "sub", "ro"), []byte("ro\n"), 0o444))
	must(t, os.Symlink(outside, filepath.Join(root, "link")))
	must(t, syscall.Mkfifo(filepath.Join(root, "pipe"), 0o644))
	return root, outside
}

func unlockAll(dir string) {
	filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error {
		if err == nil && d.Type()&fs.ModeSymlink == 0 {
			os.Chmod(p, 0o755)
		}
		return nil
	})
}

func must(t *testing.T, err error) {
	t.Helper()
	if err != nil {
		t.Fatal(err)
	}
}

func modeAt(t *testing.T, p string) uint32 {
	t.Helper()
	fi, err := os.Lstat(p)
	must(t, err)
	return modeOf(fi)
}

func TestPlanCounts(t *testing.T) {
	root, _ := field(t)
	sum := func(p *plan) int { return p.locked + p.unchanged + p.notyours + p.symlinks + p.other }

	p, err := planField(root, os.Getuid()+1)
	must(t, err)
	if p.entries != 7 || sum(p) != p.entries || p.notyours != 5 || p.symlinks != 1 || p.other != 1 || p.locked != 0 || len(p.rows) != 0 {
		t.Fatalf("fake uid: %+v", *p)
	}

	p, err = planField(root, os.Getuid())
	must(t, err)
	if sum(p) != p.entries || p.locked != 4 || p.unchanged != 1 || len(p.rows) != p.locked {
		t.Fatalf("own uid: %+v", *p)
	}
	want := map[string]string{".": "0755", "a.txt": "0644", "run.sh": "0755", "sub": "0755"}
	for _, r := range p.rows {
		if want[r.path] != r.mode {
			t.Errorf("row %s %s", r.mode, r.path)
		}
	}

	must(t, os.WriteFile(filepath.Join(root, "a\nb"), nil, 0o644))
	if _, err := planField(root, os.Getuid()); err == nil || !strings.Contains(err.Error(), "line break") {
		t.Fatalf("a name with a line break was not refused: %v", err)
	}
}

func TestRestoreIgnoresEscapingRows(t *testing.T) {
	root, outside := field(t)
	must(t, os.Symlink(filepath.Dir(outside), filepath.Join(root, "up")))
	e := &entry{n: 1, rows: []row{
		{"0777", "../outside.txt"},
		{"0777", outside},
		{"0777", "up/outside.txt"},
		{"777", "a.txt"},
		{"0644", "a.txt"},
		{"0755", "gone.txt"},
	}}
	must(t, os.Chmod(filepath.Join(root, "a.txt"), 0o444))
	restored, gone, ok := restore(root, e)
	if m := modeAt(t, outside); m != 0o600 {
		t.Fatalf("the outside file changed mode to %04o", m)
	}
	if m := modeAt(t, filepath.Join(root, "a.txt")); m != 0o644 || restored != 1 || gone != 1 || !ok {
		t.Fatalf("a.txt %04o, restored %d, gone %d, ok %v", m, restored, gone, ok)
	}
}

func TestLockAndRestoreExact(t *testing.T) {
	root, _ := field(t)
	p, err := planField(root, os.Getuid())
	must(t, err)
	if !lock(root, p.rows) {
		t.Fatal("lock failed")
	}
	if m := modeAt(t, filepath.Join(root, "run.sh")); m != 0o555 {
		t.Fatalf("run.sh locked as %04o", m)
	}
	ev := gather(root, time.Now().Add(-time.Hour), p.rows)
	if ev.writable != 0 || ev.total != 4 {
		t.Fatalf("evidence after lock: %+v", ev)
	}
	if n, _, _ := restore(root, &entry{rows: p.rows}); n != 4 {
		t.Fatalf("restored %d", n)
	}
	for path, want := range map[string]uint32{".": 0o755, "run.sh": 0o755, "a.txt": 0o644, "sub/ro": 0o444} {
		if m := modeAt(t, filepath.Join(root, path)); m != want {
			t.Errorf("%s came back as %04o, want %04o", path, m, want)
		}
	}
}

func book(bodies ...string) []byte {
	b := []byte(bookHeader)
	var es []*entry
	for i, body := range bodies {
		after := "-"
		if i > 0 {
			after = seal(es[i-1])
		}
		raw := []byte("entry " + strconv.Itoa(i+1) + "\nafter " + after + "\n" + body)
		es = append(es, &entry{raw: raw})
		b = append(b, raw...)
	}
	return b
}

const restedBody = "did rested\ndate 2026-10-13\nat 2026-10-13T08:45:31.482913000+03:00\nfield /srv/side-project\nseasons 1\nfrom 2027-03-25\nnote Resting. Nothing was deleted or moved.\n  0755 .\n  0644 src/a file.go\n"
const ploughedBody = "did ploughed\ndate 2027-03-25\nat 2027-03-25T09:00:00.000000000+02:00\nfield /srv/side-project\nof 1\nrestored 2\ngone 0\nchanged 1 2027-01-19T10:00:00.000000000+02:00 src/a file.go\nwritable 1 2\nnote Ploughed on the quarter day.\n"

func TestChainDetectsEdit(t *testing.T) {
	good := book(restedBody, ploughedBody, restedBody)
	es, err := parseBook(good)
	must(t, err)
	if len(es) != 3 || verify(es) != "" {
		t.Fatalf("a good book: %d entries, %q", len(es), verify(es))
	}
	if r := es[0]; r.seasons != 1 || iso(r.from) != "2027-03-25" || len(r.rows) != 2 || r.rows[1].path != "src/a file.go" {
		t.Fatalf("rested entry read as %+v", r)
	}
	if c := es[1]; c.ev.changed != 1 || c.ev.newestPath != "src/a file.go" || c.ev.writable != 1 || c.ev.total != 2 {
		t.Fatalf("frozen evidence read as %+v", c.ev)
	}

	edited, _ := parseBook([]byte(strings.Replace(string(good), "seasons 1\n", "seasons 4\n", 1)))
	if got := verify(edited); got != "Entry 2 names a different entry 1 than the one in the book." {
		t.Fatalf("edit: %q", got)
	}
	parts := strings.SplitAfterN(string(good), "entry 2\n", 2)
	third := parts[1][strings.Index(parts[1], "entry 3\n"):]
	deleted, _ := parseBook([]byte(strings.TrimSuffix(parts[0], "entry 2\n") + third))
	if got := verify(deleted); got != "Entry numbering jumps from 1 to 3." {
		t.Fatalf("delete: %q", got)
	}
	tail, _ := parseBook(append(good, "note x\n"...))
	if verify(tail) != "" || seal(tail[2]) == seal(es[2]) {
		t.Fatal("a line added to the last entry must keep the chain and change the printed seal")
	}
	want := "The book cannot be read at line " + strconv.Itoa(strings.Count(string(good), "\n")+1) + "."
	if _, err := parseBook(append(good, "entry x\n"...)); err == nil || err.Error() != want {
		t.Fatalf("unreadable line: %v", err)
	}
}

func TestCropRotation(t *testing.T) {
	want := []string{"winter grain", "spring grain", "fallow", "winter grain", "spring grain"}
	for i, w := range want {
		if got := cropFor(i + 1); got != w {
			t.Errorf("crop %d = %q, want %q", i+1, got, w)
		}
	}
}

func TestStatusDirCarries(t *testing.T) {
	root, _ := field(t)
	copyDir, _ := field(t)
	p, err := planField(root, os.Getuid())
	must(t, err)
	k := len(p.rows)
	lock(root, p.rows)
	lock(copyDir, p.rows) // what cp -a carries
	if m := carries(copyDir, p.rows); m != k {
		t.Fatalf("a copy with the same modes: %d of %d", m, k)
	}
	must(t, os.Chmod(filepath.Join(copyDir, "run.sh"), 0o755))
	if m := carries(copyDir, p.rows); m != k-1 {
		t.Fatalf("one mode changed: %d of %d", m, k)
	}
	if m := carries(t.TempDir(), p.rows); m != 0 {
		t.Fatalf("an unrelated directory matched %d", m)
	}
	escaping := []row{{"0644", "../outside.txt"}}
	must(t, os.Chmod(filepath.Join(filepath.Dir(copyDir), "outside.txt"), 0o444))
	if m := carries(copyDir, escaping); m != 0 {
		t.Fatal("a row outside the directory matched")
	}
}

func TestPlural(t *testing.T) {
	for got, want := range map[string]string{
		plural(1, "entry", "entries"):    "1 entry",
		plural(0, "entry", "entries"):    "0 entries",
		plural(4812, "entry", "entries"): "4812 entries",
		tooEarly(day("2027-03-25"), 1):   "Not before 25 Mar 2027. 1 day to go.",
		tooEarly(day("2027-06-24"), 254): "Not before 24 Jun 2027. 254 days to go.",
		plural(1, "season", "seasons"):   "1 season",
		strings.Join(evidence{found: true, changed: 1, newest: day("2027-01-19"), newestPath: "src/main.go", writable: 1, total: 4812}.lines(), "|"): "Changed since rest: 1 entry. Newest: 19 Jan 2027, src/main.go.|Write permission: back on 1 of 4812 locked entries.",
		strings.Join(evidence{found: true, changed: 3, newest: day("2027-07-14"), newestPath: "src/main.go", total: 4812}.lines(), "|"):              "Changed since rest: 3 entries. Newest: 14 Jul 2027, src/main.go.|Write permission: held on all 4812 locked entries.",
		strings.Join(evidence{found: true}.lines(), "|"): "Changed since rest: none found.|Write permission: no entries were locked.",
		strings.Join(evidence{}.lines(), "|"):            "Not found at this path.",
	} {
		if got != want {
			t.Errorf("got %q, want %q", got, want)
		}
	}
}
