package main

import (
	"bytes"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
	"testing"
	"time"
	"unicode/utf8"
)

// The acceptance flows, run through the real binary on copies of real files.

var (
	bin        string
	transcript bytes.Buffer
)

func TestMain(m *testing.M) {
	dir, err := os.MkdirTemp("", "tipin-bin")
	if err != nil {
		panic(err)
	}
	bin = filepath.Join(dir, "tipin")
	if out, err := exec.Command("go", "build", "-o", bin, ".").CombinedOutput(); err != nil {
		fmt.Fprintf(os.Stderr, "go build: %v\n%s", err, out)
		os.Exit(1)
	}
	code := m.Run()
	os.RemoveAll(dir)
	if os.MkdirAll("out", 0o755) == nil {
		os.WriteFile(filepath.Join("out", "transcript.txt"), transcript.Bytes(), 0o644)
	}
	os.Exit(code)
}

type res struct {
	out, err string
	code     int
}

// snap is every file under dir with its bytes, mode and mtime.
func snap(t *testing.T, dir string) string {
	t.Helper()
	var b strings.Builder
	filepath.Walk(dir, func(p string, info os.FileInfo, err error) error {
		if err != nil || info.IsDir() {
			return nil
		}
		data, _ := os.ReadFile(p)
		sum := sha256.Sum256(data)
		fmt.Fprintf(&b, "%s %s %v %d\n", p, hex.EncodeToString(sum[:]), info.Mode(), info.ModTime().UnixNano())
		return nil
	})
	return b.String()
}

// tip runs the binary in dir. Every run is audited: no escape, no em dash, no stack trace,
// and a refusal, a usage error or a check leaves every file under dir as it was.
func tip(t *testing.T, dir string, args ...string) res {
	t.Helper()
	return runTip(t, dir, true, args...)
}

// tipq is tip without the transcript, for the large tables.
func tipq(t *testing.T, dir string, args ...string) res {
	t.Helper()
	return runTip(t, dir, false, args...)
}

func runTip(t *testing.T, dir string, record bool, args ...string) res {
	t.Helper()
	before := snap(t, dir)
	cmd := exec.Command(bin, args...)
	cmd.Dir = dir
	var o, e bytes.Buffer
	cmd.Stdout, cmd.Stderr = &o, &e
	err := cmd.Run()
	r := res{o.String(), e.String(), 0}
	if x, ok := err.(*exec.ExitError); ok {
		r.code = x.ExitCode()
	} else if err != nil {
		t.Fatal(err)
	}
	all := r.out + r.err
	if strings.ContainsAny(all, "\x1b\u2014") || strings.Contains(all, "goroutine 1 [") {
		t.Fatalf("tipin %q printed an escape, an em dash or a stack trace:\n%s", args, all)
	}
	if (r.code != 0 || (len(args) > 0 && args[0] == "check") || strings.Contains(r.err, "Nothing was changed.")) && snap(t, dir) != before {
		t.Fatalf("tipin %q changed files although it should not have", args)
	}
	if record {
		fmt.Fprintf(&transcript, "[%s] $ tipin %s\n%s", t.Name(), shellWords(args), r.out)
		if r.err != "" {
			fmt.Fprintf(&transcript, "(stderr) %s", r.err)
		}
		fmt.Fprintf(&transcript, "(exit %d)\n\n", r.code)
	}
	return r
}

func shellWords(args []string) string {
	q := make([]string, len(args))
	for i, a := range args {
		q[i] = strconv.Quote(a)
		if a != "" && !strings.ContainsAny(a, " \t\n\"'\\$\x1b\x0c") {
			q[i] = a
		}
	}
	return strings.Join(q, " ")
}

func put(t *testing.T, path string, data []byte) {
	t.Helper()
	if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(path, data, 0o644); err != nil {
		t.Fatal(err)
	}
}

func sha(data []byte) string { s := sha256.Sum256(data); return hex.EncodeToString(s[:]) }

func want(t *testing.T, r res, code int, out string) {
	t.Helper()
	if r.code != code || r.out != out {
		t.Fatalf("exit %d, want %d\ngot:\n%s\nwant:\n%s\nstderr: %s", r.code, code, r.out, out, r.err)
	}
}

// verbatim checks that show printed every line of the book unaltered after a gutter of width g.
func verbatim(t *testing.T, show string, book []byte, g int) {
	t.Helper()
	lines := splitLines(book)
	got := strings.Split(show, "\n")
	for i, l := range lines {
		if len(got[i]) < g || got[i][g:] != string(l) {
			t.Fatalf("show line %d is not the book's line: %q", i+1, got[i])
		}
	}
}

func foot(show string) string { return show[strings.LastIndex(show, "\n________________\n"):] }

// Check 1.
func TestEndToEnd(t *testing.T) {
	dir := t.TempDir()
	doc := realFile(t, "doc.go")
	put(t, filepath.Join(dir, "notes.md"), doc)
	before := snap(t, dir)
	want(t, tip(t, dir, "notes.md", "3", "for Friday read Thursday"), 0,
		"Slip 1 tipped in at line 3 of notes.md. notes.md was not touched.\nSlips are kept in notes.md.tipin. Carry it with the file.\n1 slip.\n")
	if snap(t, dir) == before {
		t.Fatal("no sidecar written")
	}
	if a, _ := os.ReadFile(filepath.Join(dir, "notes.md")); !bytes.Equal(a, doc) {
		t.Fatal("book bytes changed")
	}
	if !strings.HasPrefix(snap(t, dir), before) {
		t.Fatal("book mtime changed")
	}
	raw, _ := os.ReadFile(filepath.Join(dir, "notes.md.tipin"))
	dec := json.NewDecoder(bytes.NewReader(raw))
	dec.Token()
	if k, _ := dec.Token(); k != "about" {
		t.Fatalf("first key %v", k)
	}
	var sc Sidecar
	if err := json.Unmarshal(raw, &sc); err != nil || len(sc.Slips) != 1 || sc.Slips[0].Edition != sha(doc) {
		t.Fatalf("sidecar: %v", err)
	}
	r := tip(t, dir, "show", "notes.md")
	verbatim(t, r.out, doc, 10)
	f := foot(r.out)
	if !strings.Contains(f, "ERRATA  notes.md  ed. "+sha(doc)[:12]+"  1 slip\n\n1. Line 3. for Friday read Thursday\n\nThe text above is as printed.\n") {
		t.Fatalf("foot:\n%s", f)
	}
	if !strings.Contains(r.out, "\n  3  [1]  "+string(splitLines(doc)[2])+"\n") {
		t.Fatal("no [1] in the gutter of line 3")
	}

	if _, err := exec.LookPath("tmux"); err != nil {
		t.Skip("check 1 tmux capture skipped: tmux is not installed")
	}
	sock := []string{"-L", "tipin-test", "-f", "/dev/null"}
	tm := func(a ...string) string {
		out, _ := exec.Command("tmux", append(append([]string{}, sock...), a...)...).Output()
		return string(out)
	}
	defer tm("kill-server")
	tm("new", "-d", "-x", "80", "-y", "40", "-s", "t", "-c", dir, "env", "PS1=$ ", "sh")
	tm("send-keys", "-t", "t", bin+" show notes.md | head -n 6; echo DONE", "Enter")
	pane := ""
	for i := 0; i < 50 && !strings.Contains(pane, "\nDONE"); i++ {
		time.Sleep(100 * time.Millisecond)
		pane = tm("capture-pane", "-p", "-t", "t")
	}
	fmt.Fprintf(&transcript, "[%s] tmux capture-pane -p\n%s\n", t.Name(), pane)
	if !strings.Contains(pane, "  3  [1]  // license") {
		t.Fatalf("tmux pane has no marker on line 3:\n%s", pane)
	}
}

// Check 2 (a) to (d).
func TestStates(t *testing.T) {
	doc := realFile(t, "doc.go")
	lines := splitLines(doc)
	blank := 0
	for i, n := 0, 0; i < len(lines); i++ {
		if len(lines[i]) == 0 {
			if n++; n == 3 {
				blank = i + 1
				break
			}
		}
	}
	text := 6
	if c := bytes.Count(doc, append(append([]byte("\n"), lines[text-1]...), '\n')); c != 1 || len(lines[text-1]) == 0 {
		t.Fatalf("line %d of doc.go is not a text line that occurs once", text)
	}
	t.Logf("third blank line of doc.go: %d; text line: %d", blank, text)
	setup := func() string {
		dir := t.TempDir()
		put(t, filepath.Join(dir, "notes.md"), doc)
		tip(t, dir, "notes.md", strconv.Itoa(blank), "for nothing read a blank line")
		tip(t, dir, "notes.md", strconv.Itoa(text), "for Package fmt read package fmt")
		return dir
	}
	edit := func(dir string, ls [][]byte) string {
		put(t, filepath.Join(dir, "notes.md"), joinLines(ls))
		r := tip(t, dir, "show", "notes.md")
		verbatim(t, r.out, joinLines(ls), 10)
		return foot(r.out)
	}
	differs := "Edition differs; line still fits."

	f := edit(setup(), withTop(lines, "Tipped in, first.", "Tipped in, second.", "Tipped in, third."))
	if !strings.Contains(f, fmt.Sprintf("1. Line %d, written at %d. for nothing read a blank line\n   %s\n", blank+3, blank, differs)) ||
		!strings.Contains(f, fmt.Sprintf("2. Line %d, written at %d. for Package fmt read package fmt\n   %s\n", text+3, text, differs)) {
		t.Fatalf("(a):\n%s", f)
	}

	ls := append([][]byte{}, lines...)
	ls[blank-2], ls[blank] = []byte("A new line above."), []byte("A new line below.")
	f = edit(setup(), ls)
	if !strings.Contains(f, fmt.Sprintf("1. No longer fits. Was line %d: \"\".\n", blank)) ||
		!strings.Contains(f, fmt.Sprintf("2. Line %d. for Package fmt read package fmt\n   %s\n", text, differs)) {
		t.Fatalf("(b):\n%s", f)
	}

	ls = append([][]byte{}, lines...)
	ls[text-1] = []byte("Package fmt implements formatted I/O, edited.")
	cd := fmt.Sprintf("2. No longer fits. Was line %d: \"%s\".\n   The slip said: for Package fmt read package fmt\n", text, quote(string(lines[text-1])))
	f = edit(setup(), ls)
	if !strings.Contains(f, fmt.Sprintf("1. Line %d. for nothing read a blank line\n   %s\n", blank, differs)) || !strings.Contains(f, cd) {
		t.Fatalf("(c):\n%s", f)
	}

	f = edit(setup(), without(lines, text))
	if !strings.Contains(f, fmt.Sprintf("1. Line %d, written at %d. for nothing read a blank line\n   %s\n", blank-1, blank, differs)) || !strings.Contains(f, cd) {
		t.Fatalf("(d):\n%s", f)
	}
}

var marker = regexp.MustCompile(`(?m)^ *(\d+)  \[1\]  `)

// Check 2 (e) through the binary: every blank and lone } line of print.go.
func TestTwinTableBinary(t *testing.T) {
	src := realFile(t, "print.go")
	b := newBook(src)
	blank, brace := twinLines(b)
	top := joinLines(withTop(b.Lines, "// tipin test line one", "// tipin test line two", "// tipin test line three"))
	dir := t.TempDir()
	book := filepath.Join(dir, "print.go")
	for _, n := range append(blank, brace...) {
		os.Remove(book + ".tipin")
		put(t, book, src)
		if r := tipq(t, dir, "print.go", strconv.Itoa(n), "for this line read the one above"); r.code != 0 {
			t.Fatalf("line %d: %s", n, r.err)
		}
		put(t, book, joinLines(without(b.Lines, n)))
		r := tipq(t, dir, "show", "print.go")
		if !strings.Contains(r.out, fmt.Sprintf("\n1. No longer fits. Was line %d: ", n)) || marker.MatchString(r.out) {
			t.Fatalf("line %d deleted: the slip still points somewhere:\n%s", n, foot(r.out))
		}
		put(t, book, top)
		r = tipq(t, dir, "show", "print.go")
		m := marker.FindAllStringSubmatch(r.out, -1)
		if !strings.Contains(r.out, fmt.Sprintf("\n1. Line %d, written at %d. ", n+3, n)) || len(m) != 1 || m[0][1] != strconv.Itoa(n+3) {
			t.Fatalf("line %d with three lines on top: %v\n%s", n, m, foot(r.out))
		}
	}
	fmt.Fprintf(&transcript, "[%s] %d blank and %d lone } lines of print.go: deleted, every slip no longer fits; three lines on top, every slip at its line plus 3.\n\n",
		t.Name(), len(blank), len(brace))
}

// Check 3.
func TestOrphans(t *testing.T) {
	doc := realFile(t, "doc.go")
	orphanTree := func() string {
		dir := t.TempDir()
		put(t, filepath.Join(dir, "a", "notes.md"), doc)
		tip(t, dir, "a/notes.md", "3", "for Friday read Thursday")
		os.MkdirAll(filepath.Join(dir, "drafts"), 0o755)
		if err := os.Rename(filepath.Join(dir, "a", "notes.md"), filepath.Join(dir, "drafts", "notes-v2.md")); err != nil {
			t.Fatal(err)
		}
		return dir
	}
	// (i)
	dir := orphanTree()
	want(t, tip(t, dir, "check", "."), 1, "ORPHAN  a/notes.md.tipin  1 slip, no book.\n"+
		"        Same edition: drafts/notes-v2.md\n"+
		"        To reunite: mv 'a/notes.md.tipin' 'drafts/notes-v2.md.tipin'\n\nChecked 2 files. 1 orphan.\n")
	if out, err := exec.Command("sh", "-c", "cd '"+dir+"' && mv 'a/notes.md.tipin' 'drafts/notes-v2.md.tipin'").CombinedOutput(); err != nil {
		t.Fatalf("%v %s", err, out)
	}
	want(t, tip(t, dir, "check", "."), 0, "drafts/notes-v2.md  1 slip: 1 fits\n\nChecked 2 files. Every slip has its book.\n")

	// (iv)
	dir = t.TempDir()
	put(t, filepath.Join(dir, "x.tipin"), []byte("garbage"))
	put(t, filepath.Join(dir, "notes.md"), doc)
	want(t, tip(t, dir, "check", "."), 1, "NOT A SLIP FILE  x.tipin\n\nChecked 2 files. 1 not a slip file.\n")

	// (v)
	dir = orphanTree()
	put(t, filepath.Join(dir, "drafts", "notes-v3.md"), doc)
	want(t, tip(t, dir, "check", "."), 1, "ORPHAN  a/notes.md.tipin  1 slip, no book.\n"+
		"        Same edition: drafts/notes-v2.md\n"+
		"                      drafts/notes-v3.md\n"+
		"        Several candidates. Choose one.\n\nChecked 3 files. 1 orphan.\n")

	// Found by fit and not by edition.
	dir = orphanTree()
	v2 := filepath.Join(dir, "drafts", "notes-v2.md")
	put(t, v2, append([]byte("A line on top.\n"), doc...))
	r := tip(t, dir, "check", ".")
	if r.code != 1 || !strings.Contains(r.out, "        Every slip fits: drafts/notes-v2.md\n        To reunite: mv ") {
		t.Fatalf("fit candidate:\n%s", r.out)
	}

	if _, err := exec.LookPath("git"); err != nil {
		t.Skip("checks 3(ii) and 3(iii) skipped: git is not installed")
	}
	git := func(dir string, a ...string) string {
		t.Helper()
		cmd := exec.Command("git", append([]string{"-c", "user.name=tipin test", "-c", "user.email=test@example.invalid", "-c", "init.defaultBranch=main", "-c", "advice.detachedHead=false"}, a...)...)
		cmd.Dir = dir
		out, err := cmd.CombinedOutput()
		if err != nil {
			t.Fatalf("git %v: %v\n%s", a, err, out)
		}
		fmt.Fprintf(&transcript, "[%s] $ git %s\n%s\n", t.Name(), strings.Join(a, " "), out)
		return strings.TrimSpace(string(out))
	}
	// (ii)
	dir = t.TempDir()
	git(dir, "init", "-q")
	put(t, filepath.Join(dir, "notes.md"), doc)
	tip(t, dir, "notes.md", "3", "for Friday read Thursday")
	git(dir, "add", ".")
	git(dir, "commit", "-q", "-m", "book and slips")
	git(dir, "mv", "notes.md", "renamed.md")
	r = tip(t, dir, "check", ".")
	if r.code != 1 || !strings.Contains(r.out, "ORPHAN  notes.md.tipin  1 slip, no book.\n        Same edition: renamed.md\n        To reunite: mv 'notes.md.tipin' 'renamed.md.tipin'\n") {
		t.Fatalf("(ii):\n%s", r.out)
	}

	// (iii)
	dir = t.TempDir()
	git(dir, "init", "-q")
	book := filepath.Join(dir, "notes.md")
	put(t, book, doc)
	git(dir, "add", ".")
	git(dir, "commit", "-q", "-m", "book")
	first := git(dir, "rev-parse", "HEAD")
	tip(t, dir, "notes.md", "6", "for Package read package")
	git(dir, "add", ".")
	git(dir, "commit", "-q", "-m", "slip")
	withSlip := git(dir, "rev-parse", "HEAD")
	put(t, book, append([]byte("A line on top.\n"), doc...))
	git(dir, "commit", "-q", "-am", "a line on top")
	onTop := git(dir, "rev-parse", "HEAD")
	put(t, book, bytes.Replace(doc, []byte("Package fmt implements"), []byte("Package fmt provides"), 1))
	git(dir, "commit", "-q", "-am", "the slipped line rewritten")
	for _, c := range []struct{ rev, want string }{
		{withSlip, "\n1. Line 6. for Package read package\n"},
		{onTop, "\n1. Line 7, written at 6. for Package read package\n   Edition differs; line still fits.\n"},
		{"HEAD", "\n1. No longer fits. Was line 6: \"" + quote(string(splitLines(doc)[5])) + "\".\n"},
	} {
		git(dir, "checkout", c.rev, "--", "notes.md")
		if r := tip(t, dir, "show", "notes.md"); !strings.Contains(r.out, c.want) {
			t.Fatalf("(iii) %s:\n%s", c.rev, foot(r.out))
		}
	}
	git(dir, "checkout", "-q", first)
	if _, err := os.Stat(book + ".tipin"); err == nil {
		t.Fatal("the first commit should have no sidecar")
	}
	r = tip(t, dir, "show", "notes.md")
	if r.code != 0 || r.err != "No slips for notes.md.\n" || strings.Contains(r.out, "ERRATA") {
		t.Fatalf("(iii) no sidecar: %d %q", r.code, r.err)
	}
	verbatim(t, r.out, doc, 5)
}

// Check 4.
func TestBareCopy(t *testing.T) {
	doc := realFile(t, "doc.go")
	dir := t.TempDir()
	put(t, filepath.Join(dir, "a", "notes.md"), doc)
	tip(t, dir, "a/notes.md", "3", "for Friday read Thursday")
	put(t, filepath.Join(dir, "b", "notes.md"), doc)
	edited := bytes.Replace(doc, []byte("Package fmt"), []byte("Package fmT"), 1)
	put(t, filepath.Join(dir, "c", "notes.md"), edited)
	want(t, tip(t, dir, "check", "."), 1, "a/notes.md  1 slip: 1 fits\n"+
		"BARE COPY  b/notes.md  same edition as a/notes.md, which has 1 slip.\n"+
		"        To carry the slip: cp 'a/notes.md.tipin' 'b/notes.md.tipin'\n\nChecked 4 files. 1 book with slips, 1 bare copy.\n")
	if out, err := exec.Command("sh", "-c", "cd '"+dir+"' && cp 'a/notes.md.tipin' 'b/notes.md.tipin'").CombinedOutput(); err != nil {
		t.Fatalf("%v %s", err, out)
	}
	want(t, tip(t, dir, "check", "."), 0, "a/notes.md  1 slip: 1 fits\nb/notes.md  1 slip: 1 fits\n\nChecked 5 files. Every slip has its book.\n")
	os.RemoveAll(filepath.Join(dir, "c"))
	r := tip(t, dir, "check", ".")
	if r.code != 0 || !strings.HasSuffix(r.out, "\nChecked 4 files. Every slip has its book.\n") {
		t.Fatalf("after cp:\n%s", r.out)
	}

	src := filepath.Join(goroot(t), "src")
	start := time.Now()
	out, err := exec.Command(bin, "check", src).Output()
	took := time.Since(start)
	fmt.Fprintf(&transcript, "[%s] $ tipin check $GOROOT/src\n%s(%.2f s, error %v)\n\n", t.Name(), out, took.Seconds(), err)
	if err != nil || !strings.HasSuffix(string(out), " files. No slips.\n") || took > 5*time.Second {
		t.Fatalf("GOROOT check: %v %q in %v", err, out, took)
	}
}

// Check 5.
func TestBookNeverTouched(t *testing.T) {
	dir := t.TempDir()
	book := filepath.Join(dir, "notes.md")
	put(t, book, realFile(t, "doc.go"))
	os.Chmod(book, 0o444)
	old := time.Date(2001, 2, 3, 4, 5, 6, 0, time.UTC)
	os.Chtimes(book, old, old)
	bookSnap := func() string { return snap(t, dir)[:strings.Index(snap(t, dir), "\n")] }
	b0 := bookSnap()
	tip(t, dir, "notes.md", "3", "for Friday read Thursday")
	tip(t, dir, "show", "notes.md")
	tip(t, dir, "print", "notes.md")
	tip(t, dir, "drop", "notes.md", "1")
	if bookSnap() != b0 {
		t.Fatal("the book changed")
	}

	if os.Geteuid() == 0 {
		t.Log("read-only directory part skipped: running as root")
	} else {
		ro := t.TempDir()
		put(t, filepath.Join(ro, "file"), []byte("one line\n"))
		os.Chmod(ro, 0o555)
		defer os.Chmod(ro, 0o755)
		r := tip(t, ro, "file", "1", "x")
		if r.code != 1 || r.err != "file.tipin cannot be written here. Nothing was changed.\n" {
			t.Fatalf("read-only dir: %d %q", r.code, r.err)
		}
		if names, _ := filepath.Glob(filepath.Join(ro, ".*")); len(names) != 0 {
			t.Fatalf("left behind: %v", names)
		}
	}

	pat := regexp.MustCompile(`O_WRONLY|O_RDWR|O_APPEND|WriteFile|Create\(|Remove`)
	srcs, _ := filepath.Glob("*.go")
	for _, f := range srcs {
		if strings.HasSuffix(f, "_test.go") {
			continue
		}
		data, _ := os.ReadFile(f)
		for i, l := range strings.Split(string(data), "\n") {
			if pat.MatchString(l) {
				fmt.Fprintf(&transcript, "[%s] grep %s:%d:%s\n", t.Name(), f, i+1, l)
				if !strings.Contains(l, "(tmp") {
					t.Fatalf("%s:%d writes or removes something other than the temp file: %s", f, i+1, l)
				}
			}
		}
	}
	transcript.WriteString("\n")
}

// sheetsOf splits print output into 30 line sheets and checks the geometry of each.
func sheetsOf(t *testing.T, out string) [][]string {
	t.Helper()
	lines := strings.Split(strings.TrimSuffix(out, "\n"), "\n")
	if len(lines)%30 != 0 || len(lines) == 0 {
		t.Fatalf("%d lines, not whole sheets of 30", len(lines))
	}
	var sheets [][]string
	for i := 0; i < len(lines); i += 30 {
		s := lines[i : i+30]
		if s[0] != cutLine || s[29] != cutLine || utf8.RuneCountInString(cutLine) != 71 {
			t.Fatalf("sheet %d has no cut lines", i/30+1)
		}
		sheets = append(sheets, s)
	}
	for _, l := range lines {
		if utf8.RuneCountInString(l) > 72 {
			t.Fatalf("line of %d runes: %q", utf8.RuneCountInString(l), l)
		}
	}
	return sheets
}

var slipNo = regexp.MustCompile(`^ (\d+)\. Line `)

// everyOnce checks that each slip from 1 to n appears on exactly one sheet, and K of N headers.
func everyOnce(t *testing.T, sheets [][]string, n int) {
	t.Helper()
	seen := map[string]int{}
	for k, s := range sheets {
		h := fmt.Sprintf(" ERRATA, slip sheet %d of %d", k+1, len(sheets))
		if len(sheets) == 1 {
			h = " ERRATA"
		}
		if s[1] != h {
			t.Fatalf("sheet %d header %q, want %q", k+1, s[1], h)
		}
		for _, l := range s {
			if m := slipNo.FindStringSubmatch(l); m != nil {
				seen[m[1]]++
			}
		}
	}
	for i := 1; i <= n; i++ {
		if seen[strconv.Itoa(i)] != 1 {
			t.Fatalf("slip %d appears %d times", i, seen[strconv.Itoa(i)])
		}
	}
}

// words makes a note of exactly n runes from plain words.
func words(n int) string {
	s := strings.Repeat("for net thirty read net forty five ", n/35+1)
	s = strings.TrimSpace(s[:n])
	for utf8.RuneCountInString(s) < n {
		s += "x"
	}
	return s
}

// Check 6.
func TestPrint(t *testing.T) {
	doc := realFile(t, "doc.go")
	lines := splitLines(doc)
	dir := t.TempDir()
	put(t, filepath.Join(dir, "notes.md"), doc)
	tip(t, dir, "notes.md", "3", "for Friday read Thursday")
	r := tip(t, dir, "print", "notes.md")
	s := sheetsOf(t, r.out)
	ed := sha(doc)[:12]
	if len(s) != 1 || s[0][1] != " ERRATA" || s[0][2] != " notes.md   ed. "+ed+"   printed "+today() ||
		s[0][27] != "" || s[0][28] != " This slip belongs to edition "+ed+" of notes.md and to no other." {
		t.Fatalf("sheet:\n%s", r.out)
	}

	// A long line with tabs, a 500 rune note.
	long := 0
	for i, l := range lines {
		if bytes.IndexByte(l, '\t') >= 0 && utf8.RuneCount(l) > 60 {
			long = i + 1
			break
		}
	}
	t.Logf("first line of doc.go over 60 runes with a tab: %d (%d runes)", long, utf8.RuneCount(lines[long-1]))
	dir = t.TempDir()
	put(t, filepath.Join(dir, "notes.md"), doc)
	tip(t, dir, "notes.md", strconv.Itoa(long), words(500))
	r = tip(t, dir, "print", "notes.md")
	s = sheetsOf(t, r.out)
	q := quote(string(lines[long-1]))
	unwrapped := strings.ReplaceAll(r.out, "\n    ", " ")
	if len(s) != 1 || !strings.Contains(unwrapped, fmt.Sprintf(" 1. Line %d: \"%s\" ", long, q)) || utf8.RuneCountInString(q) != 63 || strings.Contains(r.out, "\t") {
		t.Fatalf("long line:\n%s", r.out)
	}

	// A 40 rune book name.
	name := strings.Repeat("n", 37) + ".md"
	put(t, filepath.Join(dir, name), doc)
	tip(t, dir, name, "3", "for Friday read Thursday")
	s = sheetsOf(t, tip(t, dir, "print", name).out)
	if s[0][2] != " "+strings.Repeat("n", 27)+"...   ed. "+ed+"   printed "+today() {
		t.Fatalf("long name: %q", s[0][2])
	}

	// Nine slips of 400 characters.
	dir = t.TempDir()
	put(t, filepath.Join(dir, "notes.md"), doc)
	for i := 1; i <= 9; i++ {
		tipq(t, dir, "notes.md", strconv.Itoa(i*10), words(400))
	}
	r = tip(t, dir, "print", "notes.md")
	s = sheetsOf(t, r.out)
	if len(s) < 2 {
		t.Fatal("nine long slips fit on one sheet")
	}
	everyOnce(t, s, 9)

	// A form feed and an ESC inside line 3.
	dir = t.TempDir()
	ctl := bytes.Replace(doc, []byte("license that"), []byte("license\x0c\x1bthat"), 1)
	put(t, filepath.Join(dir, "notes.md"), ctl)
	tip(t, dir, "notes.md", "3", "for Friday read Thursday")
	r = runTip(t, dir, true, "print", "notes.md")
	if len(sheetsOf(t, r.out)) != 1 || !strings.Contains(r.out, `"// license  that can be`) {
		t.Fatalf("control characters:\n%s", r.out)
	}

	// A file name holding a newline.
	nl := "no\ntes.md"
	put(t, filepath.Join(dir, nl), doc)
	tip(t, dir, nl, "3", "for Friday read Thursday")
	if s = sheetsOf(t, tip(t, dir, "print", nl).out); s[0][2] != " no tes.md   ed. "+ed+"   printed "+today() {
		t.Fatalf("newline name: %q", s[0][2])
	}

	// 101 slips, the last a single 500 character word.
	dir = t.TempDir()
	put(t, filepath.Join(dir, "notes.md"), doc)
	for i := 1; i <= 100; i++ {
		tipq(t, dir, "notes.md", strconv.Itoa(i), words(400))
	}
	word := strings.Repeat("w", 500)
	tip(t, dir, "notes.md", "101", word)
	r = tip(t, dir, "print", "notes.md")
	s = sheetsOf(t, r.out)
	everyOnce(t, s, 101)
	if !strings.Contains(r.out, "\n      "+strings.Repeat("w", 66)+"\n") || strings.Contains(r.out, strings.Repeat("w", 67)) {
		t.Fatal("slip 101's note is not broken hard at 66 runes")
	}
	t.Logf("101 slips: %d sheets", len(s))

	// No longer fits, withdrawn, missing.
	dir = t.TempDir()
	book := filepath.Join(dir, "notes.md")
	put(t, book, doc)
	tip(t, dir, "notes.md", "3", "for Friday read Thursday")
	tip(t, dir, "notes.md", "6", "for Package read package")
	put(t, book, bytes.Replace(doc, []byte("Package fmt implements"), []byte("Package fmt provides"), 1))
	r = tip(t, dir, "print", "notes.md")
	if r.err != "1 slip not printed: it no longer fits.\n" || strings.Contains(r.out, " 2. ") || len(sheetsOf(t, r.out)) != 1 {
		t.Fatalf("no longer fits: %q", r.err)
	}
	if r = tip(t, dir, "print", "notes.md", "2"); r.code != 1 || r.err != "1 slip not printed: it no longer fits.\n" {
		t.Fatalf("print 2: %d %q", r.code, r.err)
	}
	put(t, book, doc)
	tip(t, dir, "drop", "notes.md", "1")
	r = tip(t, dir, "print", "notes.md")
	if r.err != "" || strings.Contains(r.out, " 1. Line") || !strings.Contains(r.out, " 2. Line 6:") {
		t.Fatalf("withdrawn: %q\n%s", r.err, r.out)
	}
	if r = tip(t, dir, "print", "notes.md", "1"); r.code != 1 || r.err != "Slip 1 is withdrawn.\n" {
		t.Fatalf("print 1: %q", r.err)
	}
	if r = tip(t, dir, "print", "notes.md", "7"); r.code != 1 || r.err != "notes.md has no slip 7.\n" {
		t.Fatalf("print 7: %q", r.err)
	}
}

// Check 7.
func TestRefusals(t *testing.T) {
	doc := realFile(t, "doc.go")
	n := len(splitLines(doc))
	dir := t.TempDir()
	put(t, filepath.Join(dir, "notes.md"), doc)
	tip(t, dir, "notes.md", "3", "for Friday read Thursday")
	os.Mkdir(filepath.Join(dir, "folder"), 0o755)
	ls, err := os.ReadFile("/bin/ls")
	if err != nil {
		t.Fatal(err)
	}
	put(t, filepath.Join(dir, "ls"), ls)
	big := bytes.Repeat(doc, (8<<20)/len(doc)+1)
	put(t, filepath.Join(dir, "big.md"), big)
	put(t, filepath.Join(dir, "bad.md"), doc)
	put(t, filepath.Join(dir, "bad.md.tipin"), []byte("garbage\x00\xff"))
	plain := "A slip is one line of plain words.\n"
	for _, c := range []struct {
		args []string
		code int
		err  string
	}{
		{[]string{"notes.md", "0", "x"}, 1, fmt.Sprintf("notes.md has %d lines. There is no line 0.\n", n)},
		{[]string{"notes.md", strconv.Itoa(n + 1), "x"}, 1, fmt.Sprintf("notes.md has %d lines. There is no line %d.\n", n, n+1)},
		{[]string{"notes.md", "3", "  "}, 1, "A slip needs words.\n"},
		{[]string{"notes.md", "3", strings.Repeat("a", 501)}, 1, "A slip holds at most 500 characters.\n"},
		{[]string{"notes.md", "3", "a\nb"}, 1, plain},
		{[]string{"notes.md", "3", "a\x1bb"}, 1, plain},
		{[]string{"notes.md", "3", "words\t"}, 1, plain},
		{[]string{"missing.md", "1", "x"}, 1, "There is no file missing.md.\n"},
		{[]string{"folder", "1", "x"}, 1, "folder is a directory, not a file.\n"},
		{[]string{"notes.md.tipin", "1", "x"}, 1, "That is a slip file, not a book.\n"},
		{[]string{"show", "notes.md.tipin"}, 1, "That is a slip file, not a book.\n"},
		{[]string{"ls", "1", "x"}, 1, "That does not look like a text file.\n"},
		{[]string{"big.md", "1", "x"}, 1, "That file is larger than 8 MiB.\n"},
		{[]string{"bad.md", "1", "x"}, 1, "bad.md.tipin is not a slip file this version can read. Nothing was changed.\n"},
		{[]string{"drop", "bad.md", "1"}, 1, "bad.md.tipin is not a slip file this version can read. Nothing was changed.\n"},
		{[]string{"drop", "notes.md", "5"}, 1, "notes.md has no slip 5.\n"},
		{[]string{}, 2, usage},
		{[]string{"notes.md"}, 2, usage},
		{[]string{"show"}, 2, usage},
	} {
		r := tip(t, dir, c.args...)
		if r.code != c.code || r.err != c.err || r.out != "" {
			t.Fatalf("tipin %q: exit %d %q, want %d %q", c.args, r.code, r.err, c.code, c.err)
		}
	}
	if r := tip(t, dir, "help"); r.code != 2 || r.out != usage {
		t.Fatal("help")
	}

	// CRLF and no trailing newline both work.
	crlf := bytes.ReplaceAll(doc, []byte("\n"), []byte("\r\n"))
	put(t, filepath.Join(dir, "crlf.md"), crlf)
	tip(t, dir, "crlf.md", "3", "for Friday read Thursday")
	r := tip(t, dir, "show", "crlf.md")
	verbatim(t, r.out, crlf, 10)
	if !strings.Contains(r.out, "\n1. Line 3. for Friday read Thursday\n") || strings.Contains(r.out, "\r") {
		t.Fatal("crlf")
	}
	noEOL := bytes.TrimSuffix(doc, []byte("\n"))
	put(t, filepath.Join(dir, "noeol.md"), noEOL)
	tip(t, dir, "noeol.md", strconv.Itoa(n), "for package read Package")
	if r := tip(t, dir, "show", "noeol.md"); !strings.Contains(r.out, fmt.Sprintf("\n1. Line %d. for package read Package\n", n)) {
		t.Fatal("no trailing newline")
	}

	// Withdrawing the last live slip keeps the sidecar.
	want(t, tip(t, dir, "drop", "notes.md", "1"), 0, "Slip 1 withdrawn. 0 slips.\n")
	if r := tip(t, dir, "drop", "notes.md", "1"); r.err != "Slip 1 is already withdrawn.\n" {
		t.Fatal("drop twice")
	}
	if _, err := os.Stat(filepath.Join(dir, "notes.md.tipin")); err != nil {
		t.Fatal("sidecar removed")
	}
	f := foot(tip(t, dir, "show", "notes.md").out)
	if !strings.HasSuffix(f, "  0 slips, 1 withdrawn\n\n1. Withdrawn "+today()+".\n\nThe text above is as printed.\n") {
		t.Fatalf("foot:\n%s", f)
	}
}

// Check 8.
func TestNumbersStable(t *testing.T) {
	dir := t.TempDir()
	put(t, filepath.Join(dir, "notes.md"), realFile(t, "doc.go"))
	for _, l := range []string{"3", "6", "7"} {
		tip(t, dir, "notes.md", l, "for this read that")
	}
	want(t, tip(t, dir, "drop", "notes.md", "2"), 0, "Slip 2 withdrawn. 2 slips.\n")
	r := tip(t, dir, "notes.md", "8", "for are simpler read is simpler")
	if !strings.HasPrefix(r.out, "Slip 4 tipped in at line 8") || !strings.HasSuffix(r.out, "\n3 slips.\n") {
		t.Fatal(r.out)
	}
	sc, err := readSidecar(filepath.Join(dir, "notes.md.tipin"))
	if err != nil || len(sc.Slips) != 4 || sc.Next != 5 {
		t.Fatal("sidecar does not hold all four")
	}
	f := foot(tip(t, dir, "show", "notes.md").out)
	if !strings.Contains(f, "  3 slips, 1 withdrawn\n\n1. Line 3. for this read that\n2. Withdrawn "+today()+".\n3. Line 7. ") ||
		!strings.Contains(f, "\n4. Line 8. for are simpler read is simpler\n") {
		t.Fatalf("foot:\n%s", f)
	}
}
