package main

import (
	"bytes"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strings"
	"testing"
)

// goroot is the real Go installation; its fmt sources are the test books.
func goroot(t testing.TB) string {
	t.Helper()
	out, err := exec.Command("go", "env", "GOROOT").Output()
	if err != nil {
		t.Fatalf("go env GOROOT: %v", err)
	}
	return strings.TrimSpace(string(out))
}

func realFile(t testing.TB, name string) []byte {
	t.Helper()
	data, err := os.ReadFile(filepath.Join(goroot(t), "src", "fmt", name))
	if err != nil {
		t.Fatal(err)
	}
	return data
}

func joinLines(ls [][]byte) []byte { return append(bytes.Join(ls, []byte("\n")), '\n') }

// without returns the lines with 1-based line n removed.
func without(ls [][]byte, n int) [][]byte {
	out := append([][]byte{}, ls[:n-1]...)
	return append(out, ls[n:]...)
}

// withTop returns the lines with new lines put first.
func withTop(ls [][]byte, top ...string) [][]byte {
	var out [][]byte
	for _, s := range top {
		out = append(out, []byte(s))
	}
	return append(out, ls...)
}

func TestSplitLines(t *testing.T) {
	for _, c := range []struct {
		in   string
		want []string
	}{
		{"", nil},
		{"a", []string{"a"}},
		{"a\n", []string{"a"}},
		{"a\n\n", []string{"a", ""}},
		{"a\r\nb\r\n", []string{"a", "b"}},
		{"a \r\n\tb", []string{"a ", "\tb"}},
	} {
		got := splitLines([]byte(c.in))
		if len(got) != len(c.want) {
			t.Fatalf("%q: %d lines, want %d", c.in, len(got), len(c.want))
		}
		for i := range got {
			if string(got[i]) != c.want[i] {
				t.Fatalf("%q line %d: %q, want %q", c.in, i+1, got[i], c.want[i])
			}
		}
	}
	if lineHash([]byte("a")) != lineHash([]byte("a\r")[:1]) || len(lineHash(nil)) != 16 {
		t.Fatal("lineHash")
	}
	crlf := newBook([]byte("x\r\ny\r\n"))
	lf := newBook([]byte("x\ny\n"))
	if crlf.Hashes[0] != lf.Hashes[0] || crlf.Edition == lf.Edition {
		t.Fatal("a \\r is not part of a line hash, but is part of the edition")
	}
}

func TestLocateSmall(t *testing.T) {
	book := []byte("func a() {\n}\n\nfunc b() {\n}\n\nfunc a() {\n}\n\n")
	b := newBook(book)
	s := b.anchor(2) // a lone } between "func a() {" and ""
	if s.Copies != 3 || s.Twins != 2 || s.Rank != 1 {
		t.Fatalf("anchor: copies %d twins %d rank %d", s.Copies, s.Twins, s.Rank)
	}
	if st, l := locate(b, s); st != fits || l != 2 {
		t.Fatalf("same edition: %v %d", st, l)
	}
	// Insert above: it moves with its rank.
	if st, l := locate(newBook(append([]byte("// x\n"), book...)), s); st != moved || l != 3 {
		t.Fatalf("moved: %v %d", st, l)
	}
	// Delete it: its twin must not take its place.
	if st, _ := locate(newBook(joinLines(without(b.Lines, 2))), s); st != gone {
		t.Fatal("deleted twin slid onto its neighbour")
	}
	one := b.anchor(4) // func b() {, once
	if one.Copies != 1 {
		t.Fatal("copies")
	}
	edited := bytes.Replace(book, []byte("func b() {"), []byte("func c() {"), 1)
	if st, _ := locate(newBook(edited), one); st != gone {
		t.Fatal("edited line still fits")
	}
	doubled := append(append([]byte{}, book...), []byte("func b() {\n")...)
	if st, _ := locate(newBook(doubled), one); st != gone {
		t.Fatal("a second copy appeared and the slip chose one")
	}
	noEOL := newBook([]byte("p\nq"))
	if st, l := locate(newBook([]byte("o\np\nq")), noEOL.anchor(2)); st != moved || l != 3 {
		t.Fatalf("no trailing newline: %v %d", st, l)
	}
	crlf := newBook([]byte("p\r\nq\r\n"))
	if st, l := locate(newBook([]byte("o\r\np\r\nq\r\n")), crlf.anchor(1)); st != moved || l != 2 {
		t.Fatalf("crlf: %v %d", st, l)
	}
}

var twinLine = regexp.MustCompile(`^\t*}$`)

// twinLines are the blank and lone closing brace lines of a real file, read from it.
func twinLines(b *Book) (blank, brace []int) {
	for i, l := range b.Lines {
		switch {
		case len(l) == 0:
			blank = append(blank, i+1)
		case twinLine.Match(l):
			brace = append(brace, i+1)
		}
	}
	return
}

// TestTwinTable is check 2(e) against locate: every blank and lone } line of print.go.
func TestTwinTable(t *testing.T) {
	b := newBook(realFile(t, "print.go"))
	blank, brace := twinLines(b)
	t.Logf("print.go: %d lines, %d blank, %d lone }, %d in all", len(b.Lines), len(blank), len(brace), len(blank)+len(brace))
	if len(blank) == 0 || len(brace) == 0 {
		t.Fatal("print.go has no twins to test")
	}
	top := withTop(b.Lines, "// tipin test line one", "// tipin test line two", "// tipin test line three")
	inserted := newBook(joinLines(top))
	for _, n := range append(blank, brace...) {
		s := b.anchor(n)
		if s.Copies < 2 {
			t.Fatalf("line %d is not a twin line", n)
		}
		if st, l := locate(newBook(joinLines(without(b.Lines, n))), s); st != gone {
			t.Fatalf("line %d deleted, slip landed on line %d", n, l)
		}
		if st, l := locate(inserted, s); st != moved || l != n+3 {
			t.Fatalf("line %d with three lines on top: %v at %d, want %d", n, st, l, n+3)
		}
	}
}
