package main

import (
	"bytes"
	"crypto/rand"
	"fmt"
	"os"
	"path/filepath"
	"regexp"
	"strings"
	"testing"
	"time"
)

const mb = 1 << 20

// put writes n real bytes to path, making its folders.
func put(t *testing.T, path string, n int) {
	t.Helper()
	b := make([]byte, n)
	rand.Read(b)
	write(t, path, b)
}

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

// fixture lays out one folder per acceptance case under root/main, and a two-folder tract under root/n.
func fixture(t *testing.T, root string) {
	m := func(p string) string { return filepath.Join(root, "main", p) }
	txt := func(p, s string) { write(t, m(p), []byte(s)) }
	pj := `{"name": "x", "scripts": {"build": "tsc"}}` + "\n"

	txt("a-locked/package.json", pj) // (a), and (h) a node_modules nested inside it
	txt("a-locked/bun.lock", "{}\n")
	txt("a-locked/src/index.js", "export {}\n")
	put(t, m("a-locked/node_modules/left-pad/index.js"), 3*mb)
	put(t, m("a-locked/node_modules/left-pad/node_modules/dep/index.js"), 3*mb)
	txt("b-unlocked/package.json", pj) // (b)
	put(t, m("b-unlocked/node_modules/x/index.js"), 3*mb)
	// (c)
	put(t, m("c-orphan/node_modules/x/index.js"), 3*mb)
	// (d), and a shared target dir with no Cargo.toml, proved by its tag
	txt("d-cargo/Cargo.toml", "[package]\nname = \"d\"\n")
	txt("d-cargo/Cargo.lock", "version = 3\n")
	put(t, m("d-cargo/target/debug/d"), 3*mb)
	txt("d-shared/target/CACHEDIR.TAG", tagSig+"\n# This file is a cache directory tag.\n")
	put(t, m("d-shared/target/release/x"), 3*mb)
	txt("e1-dist/package.json", pj) // (e)
	txt("e1-dist/.gitignore", "node_modules\ndist\n")
	put(t, m("e1-dist/dist/app.js"), 3*mb)
	txt("e2-dist/package.json", pj)
	put(t, m("e2-dist/dist/app.js"), 3*mb)
	txt("f1-venv/pyproject.toml", "[project]\nname = \"f\"\n") // (f)
	put(t, m("f1-venv/.venv/lib/x.so"), 3*mb)
	put(t, m("f2-venv/.venv/lib/x.so"), 3*mb)
	put(t, m("g-xcode/Library/Developer/Xcode/DerivedData/App/Build/x"), 3*mb) // (g)
	// (i)
	if err := os.MkdirAll(m("i-symlink"), 0o755); err != nil {
		t.Fatal(err)
	}
	if err := os.Symlink(m("j-sixteen"), m("i-symlink/link")); err != nil {
		t.Fatal(err)
	}
	for k := 0; k < 16; k++ { // (j)
		put(t, m(fmt.Sprintf("j-sixteen/part-%02d/x", k)), 2*mb)
	}
	put(t, m("k-one-big/big/x"), 10*mb) // (k)
	put(t, m("k-one-big/notes.bin"), 512<<10)
	txt("l-modules/package.json", pj) // (l)
	txt("l-modules/package-lock.json", "{}\n")
	put(t, m("l-modules/node_modules/x/index.js"), 3*mb)
	txt("m1-tag/cache/CACHEDIR.TAG", tagSig+"\n") // (m)
	put(t, m("m1-tag/cache/x"), 3*mb)
	txt("m2-bad-tag/cache/CACHEDIR.TAG", strings.Replace(tagSig, "8a47", "8a48", 1)+"\n")
	put(t, m("m2-bad-tag/cache/x"), 3*mb)
	put(t, m("o-six-four/six/x"), 6*mb) // (o)
	put(t, m("o-six-four/four/x"), 4*mb)
	txt("q-quote/it's here/package.json", pj) // a quote and a space in the path
	txt("q-quote/it's here/bun.lock", "{}\n")
	put(t, m("q-quote/it's here/node_modules/x/index.js"), 3*mb)
	put(t, m("r-hardlink/one/x"), 3*mb) // one file, two names
	if err := os.MkdirAll(m("r-hardlink/two"), 0o755); err != nil {
		t.Fatal(err)
	}
	if err := os.Link(m("r-hardlink/one/x"), m("r-hardlink/two/x")); err != nil {
		t.Fatal(err)
	}
	put(t, filepath.Join(root, "n", "x", "x"), 10*mb) // (n)
	put(t, filepath.Join(root, "n", "y", "y"), 10*mb)
}

// TestSurvey builds the fixture (in TIMBER_FIXTURE when set, so the CLI checks can reuse it) and checks every case.
func TestSurvey(t *testing.T) {
	root := os.Getenv("TIMBER_FIXTURE")
	if root == "" {
		root = t.TempDir()
	}
	fixture(t, root)
	tract := filepath.Join(root, "main")
	tr, err := walk(tract, mb, nil)
	if err != nil {
		t.Fatal(err)
	}
	got := map[string]row{}
	list := map[string]string{}
	for name, rs := range map[string][]row{"timber": tr.timber, "standing": tr.standing} {
		for _, r := range rs {
			rel, _ := filepath.Rel(tract, r.path)
			got[rel], list[rel] = r, name
		}
	}
	want := []struct{ name, path, list, note string }{
		{"a manifest and lockfile", "a-locked/node_modules", "timber", ""},
		{"b no lockfile", "b-unlocked/node_modules", "timber", thin},
		{"c orphan node_modules", "c-orphan/node_modules", "standing", "no package.json beside it"},
		{"d Cargo.toml and target", "d-cargo/target", "timber", ""},
		{"d shared target by its tag", "d-shared/target", "timber", "self-declared cache"},
		{"e dist built and ignored", "e1-dist/dist", "timber", ""},
		{"e dist not ignored", "e2-dist/dist", "standing", "not named in .gitignore"},
		{"f venv beside pyproject", "f1-venv/.venv", "timber", ""},
		{"f venv alone", "f2-venv/.venv", "standing", "no Python manifest beside it"},
		{"g DerivedData by location", "g-xcode/Library/Developer/Xcode/DerivedData", "timber", ""},
		{"j sixteen small folders", "j-sixteen", "standing", ""},
		{"k one big subfolder", "k-one-big/big", "standing", ""},
		{"l project of node_modules", "l-modules/node_modules", "timber", ""},
		{"m valid tag", "m1-tag/cache", "timber", "self-declared cache"},
		{"m altered tag", "m2-bad-tag/cache", "standing", ""},
		{"o six and four", "o-six-four", "standing", ""},
		{"quote in path", "q-quote/it's here/node_modules", "timber", ""},
		{"hard link counted once", "r-hardlink/one", "standing", ""},
	}
	for _, w := range want {
		t.Run(w.name, func(t *testing.T) {
			r, ok := got[w.path]
			if !ok || list[w.path] != w.list || r.note != w.note {
				t.Errorf("%s: got list %q note %q, want %q %q", w.path, list[w.path], r.note, w.list, w.note)
			}
		})
	}
	// Exactly these rows and no others: (h) no nested row, (i) the symlink adds nothing,
	// (j) (k) (l) (o) one row each, the hard link is not counted twice.
	if len(got) != len(want) {
		t.Errorf("got %d rows, want %d: %v", len(got), len(want), list)
	}
	if s := got["a-locked/node_modules"].size; s < 6*mb || s > 7*mb {
		t.Errorf("(h) nested node_modules should be inside its parent's size, got %d", s)
	}
	if s := got["j-sixteen"].size; s > 33*mb {
		t.Errorf("(i) j-sixteen counted the symlink's target twice: %d", s)
	}

	n, err := walk(filepath.Join(root, "n"), mb, nil)
	if err != nil || len(n.standing) != 2 || filepath.Base(n.standing[0].path) != "x" || filepath.Base(n.standing[1].path) != "y" {
		t.Errorf("(n) want rows x and y and none for the tract, got %+v", n.standing)
	}

	sheet := func(tr *tree, at time.Time) string {
		var b bytes.Buffer
		printSheet(&b, tr, volumeOf(tract), at)
		return b.String()
	}
	at := time.Date(2026, 10, 13, 9, 41, 0, 0, time.Local)
	one, two := sheet(tr, at), sheet(tr, at.AddDate(0, 0, 40))
	a, b := strings.Split(one, "\n"), strings.Split(two, "\n")
	for i := range a {
		if a[i] != b[i] && !strings.HasPrefix(a[i], "Surveyed:") {
			t.Errorf("sheets 40 days apart differ outside Surveyed: %q / %q", a[i], b[i])
		}
	}
	if !strings.HasSuffix(one, "\nNot for timber.\n") || strings.Count(one, "Not for timber.") != 1 {
		t.Error("the closer must be the last line, once")
	}
	standingAt := strings.Index(one, "\nSTANDING.")
	cmd := regexp.MustCompile(`(?m)^rm .*$`).FindAllString(one, -1)
	if len(cmd) != len(tr.timber) || strings.Contains(one[standingAt:], "\nrm ") {
		t.Errorf("want %d felling commands, all before STANDING, got %d", len(tr.timber), len(cmd))
	}
	quoted := "rm -rf -- '" + tract + "/q-quote/it'\\''s here/node_modules'"
	if !strings.Contains(one, quoted+"\n") {
		t.Errorf("missing %s", quoted)
	}

	big, _ := walk(tract, 900<<30, nil)
	none := sheet(big, at)
	if !strings.Contains(none, "No timber found above 900 G.") || !strings.Contains(none, "No standing items above 900 G.") || strings.Contains(none, "Not for timber.") {
		t.Errorf("empty sheet wrong:\n%s", none)
	}
}

func TestHuman(t *testing.T) {
	for n, want := range map[uint64]string{0: "0 B", 512: "512 B", 1500: "1.5 K", 500 << 20: "500 M", 900 << 30: "900 G", 1048550: "1 M", 44344123392: "41.3 G"} {
		if got := human(n); got != want {
			t.Errorf("human(%d) = %q, want %q", n, got, want)
		}
	}
	for s, want := range map[string]uint64{"500M": 500 << 20, "2G": 2 << 30, "1500": 1500, "1k": 1024} {
		if got, ok := parseSize(s); !ok || got != want {
			t.Errorf("parseSize(%q) = %d", s, got)
		}
	}
	for _, s := range []string{"abc", "", "0", "-1", "1e3", "inf"} {
		if _, ok := parseSize(s); ok {
			t.Errorf("parseSize(%q) should fail", s)
		}
	}
}
