// Timber Survey: a read-only inventory of a disk, sorted by whether a folder
// can be grown again. It prints one sheet and changes nothing.
package main

import (
	"encoding/json"
	"fmt"
	"io"
	"math"
	"os"
	"path/filepath"
	"regexp"
	"runtime"
	"sort"
	"strconv"
	"strings"
	"syscall"
	"time"
)

const (
	usage  = "timber-survey [tract] [--min SIZE]. Reads only. Removes nothing."
	tagSig = "Signature: 8a477f597d28d172789f06886806bc55"
	thin   = "no lockfile: regrows, not identically"
)

// rule is one row of the proof table: what must sit beside a timber-named folder.
type rule struct {
	manifests []string // any one of these, a regular file beside the folder, proves it
	missing   string   // the reason printed when no manifest is there
	locks     []string // when none of these is beside it, the proof is thin
	kind      string   // the Kind for a rule that needs no manifest
	// more is a further proof; it returns why the proof failed, or "".
	more func(dir, name string, side map[string]os.FileInfo) string
}

var (
	pkg   = []string{"package.json"}
	py    = []string{"pyproject.toml", "requirements.txt", "uv.lock", "Pipfile"}
	rules = map[string]rule{
		"node_modules": {manifests: pkg, locks: []string{"package-lock.json", "bun.lock", "bun.lockb", "yarn.lock", "pnpm-lock.yaml"}},
		".next":        {manifests: pkg},
		"target":       {manifests: []string{"Cargo.toml"}, locks: []string{"Cargo.lock"}},
		"dist":         {manifests: pkg, more: builtAndIgnored},
		"build":        {manifests: pkg, more: builtAndIgnored},
		".venv":        {manifests: py, missing: "no Python manifest beside it"},
		"venv":         {manifests: py, missing: "no Python manifest beside it"},
		"Pods":         {manifests: []string{"Podfile"}, locks: []string{"Podfile.lock"}},
		"__pycache__":  {kind: "interpreter"},
		"DerivedData":  {kind: "location", more: inXcode},
	}
	sizeRe = regexp.MustCompile(`^([0-9]+(?:\.[0-9]+)?)([BKMGT]?)$`)
)

// prove applies the rule to the folder dir/name. It returns the Kind and a note,
// or ok false with the reason as the note.
func (r rule) prove(dir, name string, side map[string]os.FileInfo) (kind, note string, ok bool) {
	kind = r.kind
	if len(r.manifests) > 0 {
		if kind = present(side, r.manifests); kind == "" {
			if r.missing != "" {
				return "", r.missing, false
			}
			return "", "no " + r.manifests[0] + " beside it", false
		}
	}
	if r.more != nil {
		if why := r.more(dir, name, side); why != "" {
			return "", why, false
		}
	}
	if len(r.locks) > 0 && present(side, r.locks) == "" {
		note = thin
	}
	return kind, note, true
}

// present returns the first of names that is a regular file among the entries, or "".
func present(side map[string]os.FileInfo, names []string) string {
	for _, n := range names {
		if fi, ok := side[n]; ok && fi.Mode().IsRegular() {
			return n
		}
	}
	return ""
}

func builtAndIgnored(dir, name string, side map[string]os.FileInfo) string {
	var p struct{ Scripts map[string]any }
	b, err := os.ReadFile(filepath.Join(dir, "package.json"))
	if err == nil {
		err = json.Unmarshal(b, &p)
	}
	if s, _ := p.Scripts["build"].(string); err != nil || strings.TrimSpace(s) == "" {
		return "no build script in package.json"
	}
	if present(side, []string{".gitignore"}) != "" {
		g, _ := os.ReadFile(filepath.Join(dir, ".gitignore"))
		for _, line := range strings.Split(string(g), "\n") {
			switch strings.TrimSpace(line) {
			case name, "/" + name, name + "/", "/" + name + "/":
				return ""
			}
		}
	}
	return "not named in .gitignore"
}

func inXcode(dir, name string, _ map[string]os.FileInfo) string {
	if strings.HasSuffix(filepath.Join(dir, name), "/Library/Developer/Xcode/DerivedData") {
		return ""
	}
	return "not in Library/Developer/Xcode"
}

// tagged reports whether a folder declares itself a cache (Cache Directory Tagging Specification).
func tagged(dir string, ents []os.FileInfo) bool {
	for _, fi := range ents {
		if fi.Name() != "CACHEDIR.TAG" || !fi.Mode().IsRegular() {
			continue
		}
		f, err := os.Open(filepath.Join(dir, fi.Name()))
		if err != nil {
			return false
		}
		defer f.Close()
		b := make([]byte, len(tagSig))
		_, err = io.ReadFull(f, b)
		return err == nil && string(b) == tagSig
	}
	return false
}

type row struct {
	size    uint64
	touched time.Time
	kind    string
	path    string
	note    string
}

// tree is one walked tract: everything the sheet prints except the volume and the clock.
type tree struct {
	tract            string
	min              uint64
	timber, standing []row
	unread, entries  int
}

type survey struct {
	tree
	dev  uint64
	seen map[[2]uint64]bool
	tick func(entries int)
}

// node is what a folder reports upward: its size, its size excluding timber, its standing rows.
type node struct {
	size, ex uint64
	rows     []row
}

func walk(tract string, min uint64, tick func(int)) (*tree, error) {
	self, err := os.Stat(tract)
	if err != nil {
		return nil, err
	}
	if !self.IsDir() {
		return nil, fmt.Errorf("%s is not a folder", tract)
	}
	s := &survey{tree: tree{tract: tract, min: min}, dev: devOf(self), seen: map[[2]uint64]bool{}, tick: tick}
	s.standing = s.classify(tract, self, s.list(tract), true).rows
	bySize(s.timber)
	bySize(s.standing)
	return &s.tree, nil
}

// list reads a folder and lstats each entry. A folder that cannot be read is counted, never hidden.
func (s *survey) list(dir string) []os.FileInfo {
	des, err := os.ReadDir(dir)
	if err != nil {
		s.unread++
	}
	out := make([]os.FileInfo, 0, len(des))
	for _, d := range des {
		if fi, err := d.Info(); err == nil {
			out = append(out, fi)
		}
	}
	s.entries += len(out)
	if s.tick != nil {
		s.tick(s.entries)
	}
	return out
}

// blocks is the space an entry holds on disk; a file with several hard links counts once per survey.
func (s *survey) blocks(fi os.FileInfo) uint64 {
	st := fi.Sys().(*syscall.Stat_t)
	if !fi.IsDir() && uint64(st.Nlink) > 1 {
		k := [2]uint64{uint64(st.Dev), uint64(st.Ino)}
		if s.seen[k] {
			return 0
		}
		s.seen[k] = true
	}
	return uint64(st.Blocks) * 512
}

func devOf(fi os.FileInfo) uint64 { return uint64(fi.Sys().(*syscall.Stat_t).Dev) }

// enter reports whether the walk may go into a folder: same device, and on a Mac not the volume mounts.
func (s *survey) enter(path string, fi os.FileInfo) bool {
	if devOf(fi) != s.dev {
		return false
	}
	return runtime.GOOS != "darwin" || (path != "/System/Volumes" && path != "/Volumes")
}

// measure sizes a folder's contents without judging anything inside it.
func (s *survey) measure(dir string, ents []os.FileInfo) uint64 {
	var n uint64
	for _, fi := range ents {
		if !fi.IsDir() {
			n += s.blocks(fi)
			continue
		}
		if p := filepath.Join(dir, fi.Name()); s.enter(p, fi) {
			n += s.blocks(fi) + s.measure(p, s.list(p))
		}
	}
	return n
}

// classify walks a folder that is neither timber-named nor tagged and decides its standing rows.
// The tract is never a row itself: it returns its children's rows.
func (s *survey) classify(dir string, self os.FileInfo, ents []os.FileInfo, tract bool) node {
	n := node{size: s.blocks(self)}
	n.ex = n.size
	side := make(map[string]os.FileInfo, len(ents))
	for _, fi := range ents {
		side[fi.Name()] = fi
	}
	var best node
	var rows []row
	for _, fi := range ents {
		if !fi.IsDir() {
			b := s.blocks(fi)
			n.size, n.ex = n.size+b, n.ex+b
			continue
		}
		if !s.enter(filepath.Join(dir, fi.Name()), fi) {
			continue
		}
		c := s.child(dir, self, ents, side, fi)
		n.size, n.ex = n.size+c.size, n.ex+c.ex
		if tract {
			rows = append(rows, c.rows...)
		}
		if c.ex > best.ex {
			best = c
		}
	}
	switch {
	case tract:
		n.rows = rows
	case n.ex < s.min:
	case best.ex >= s.min && 2*best.ex >= n.ex && n.ex-best.ex < s.min:
		n.rows = best.rows // one child holds the weight and the rest is small: the listing moves down
	default:
		note := ""
		if n.size > n.ex {
			note = "timber inside not counted"
		}
		n.rows = []row{{n.ex, newest(self, ents, false), "folder", dir, note}}
	}
	return n
}

// child sizes and judges one subfolder. Timber is recorded on the survey and reports no weight upward.
func (s *survey) child(dir string, self os.FileInfo, ents []os.FileInfo, side map[string]os.FileInfo, fi os.FileInfo) node {
	p := filepath.Join(dir, fi.Name())
	sub := s.list(p)
	r, named := rules[fi.Name()]
	tag := tagged(p, sub)
	if !named && !tag {
		return s.classify(p, fi, sub, false)
	}
	size := s.blocks(fi) + s.measure(p, sub)
	touched := newest(fi, sub, false)
	kind, note, ok := "", "", false
	if named {
		if kind, note, ok = r.prove(dir, fi.Name(), side); ok && len(r.manifests) > 0 {
			touched = newest(self, ents, true)
			if gi, err := os.Lstat(filepath.Join(dir, ".git", "index")); err == nil && gi.ModTime().After(touched) {
				touched = gi.ModTime()
			}
		}
	}
	if !ok && tag {
		kind, note, ok = "CACHEDIR.TAG", "self-declared cache", true
	}
	if ok {
		if size >= s.min {
			s.timber = append(s.timber, row{size, touched, kind, p, note})
		}
		return node{size: size}
	}
	// A timber name without proof: one child, never divided, standing if large, with its reason.
	c := node{size: size, ex: size}
	if size >= s.min {
		c.rows = []row{{size, touched, "folder", p, note}}
	}
	return c
}

// newest is the latest mtime among a folder's immediate entries (skipping timber-named
// folders for a project folder), or the folder's own mtime when nothing is left.
func newest(self os.FileInfo, ents []os.FileInfo, project bool) time.Time {
	var t time.Time
	for _, fi := range ents {
		if _, named := rules[fi.Name()]; project && named && fi.IsDir() {
			continue
		}
		if fi.ModTime().After(t) {
			t = fi.ModTime()
		}
	}
	if t.IsZero() {
		return self.ModTime()
	}
	return t
}

func bySize(rs []row) {
	sort.Slice(rs, func(i, j int) bool {
		if rs[i].size != rs[j].size {
			return rs[i].size > rs[j].size
		}
		return rs[i].path < rs[j].path
	})
}

type volume struct {
	pct  int
	free uint64
}

func volumeOf(path string) volume {
	var st syscall.Statfs_t
	if syscall.Statfs(path, &st) != nil {
		return volume{}
	}
	used, avail := uint64(st.Blocks)-uint64(st.Bfree), uint64(st.Bavail)
	// ponytail: Bsize is the block unit on macOS and equals the fragment size on common Linux filesystems.
	v := volume{free: avail * uint64(st.Bsize)}
	if used+avail > 0 {
		v.pct = int((used*100 + used + avail - 1) / (used + avail)) // rounded up, like df
	}
	return v
}

// human prints a size in base 1024 with one decimal, a trailing .0 dropped.
func human(n uint64) string {
	v, u := float64(n), 0
	for v >= 1024 && u < 4 {
		v, u = v/1024, u+1
	}
	if v = math.Round(v*10) / 10; v >= 1024 && u < 4 {
		v, u = v/1024, u+1
	}
	return strings.TrimSuffix(strconv.FormatFloat(v, 'f', 1, 64), ".0") + " " + "BKMGT"[u:u+1]
}

func parseSize(s string) (uint64, bool) {
	m := sizeRe.FindStringSubmatch(strings.ToUpper(s))
	if m == nil {
		return 0, false
	}
	v, _ := strconv.ParseFloat(m[1], 64)
	v *= math.Pow(1024, float64(strings.Index("BKMGT", m[2])))
	if v < 1 || v >= 1<<63 {
		return 0, false
	}
	return uint64(math.Round(v)), true
}

func commas(n int) string {
	s := strconv.Itoa(n)
	for i := len(s) - 3; i > 0; i -= 3 {
		s = s[:i] + "," + s[i:]
	}
	return s
}

func quote(path string) string { return "'" + strings.ReplaceAll(path, "'", `'\''`) + "'" }

// printSheet writes the sheet. It reads no clock: the survey time is given.
func printSheet(w io.Writer, t *tree, v volume, at time.Time) {
	p := func(f string, a ...any) { fmt.Fprintf(w, f+"\n", a...) }
	table := func(rs []row) {
		p("%-8s  %-12s  %-16s  %s", "Size", "Last touched", "Kind", "Path")
		for _, r := range rs {
			p("%-8s  %-12s  %-16s  %s", human(r.size), r.touched.Format("2006-01-02"), r.kind, r.path)
			if r.note != "" {
				p("          %s", r.note)
			}
		}
	}
	min := human(t.min)
	unread := "none."
	if t.unread == 1 {
		unread = "1 folder."
	} else if t.unread > 1 {
		unread = commas(t.unread) + " folders."
	}
	p("TIMBER SURVEY")
	p("Form 1, stand inventory, disk volume.")
	p("Issued by normal is dead.")
	p("")
	p("Tract:    %s", t.tract)
	p("Surveyed: %s", at.Format("2006-01-02 15:04"))
	p("Volume:   %d%% full, %s free.", v.pct, human(v.free))
	p("Basis:    blocks on disk, each hard link counted once. Nothing was removed.")
	p("Not read: %s", unread)
	p("")
	p("TIMBER. Will grow again.")
	p("")
	// Re-check at print time: a command is given only for a path that is still a real folder.
	var live []row
	var total uint64
	for _, r := range t.timber {
		if fi, err := os.Lstat(r.path); err == nil && fi.IsDir() {
			live, total = append(live, r), total+r.size
		}
	}
	if len(live) == 0 {
		p("No timber found above %s.", min)
	} else {
		table(live)
		stands := "stands"
		if len(live) == 1 {
			stands = "stand"
		}
		p("")
		p("Timber, %d %s over %s: %s.", len(live), stands, min, human(total))
		p("Free after felling all of it: at most %s.", human(v.free+total))
		p("")
		p("Felling commands (timber only). Run one at a time.")
		for _, r := range live {
			p("rm -rf -- %s", quote(r.path))
		}
	}
	p("")
	p("STANDING. Will not grow again. No commands are given.")
	p("")
	if len(t.standing) == 0 {
		p("No standing items above %s.", min)
		return
	}
	table(t.standing)
	p("Not for timber.")
}

func parseArgs(args []string) (tract string, min uint64, ok bool) {
	min = 500 << 20
	for i := 0; i < len(args); i++ {
		switch a := args[i]; {
		case a == "--min" && i+1 < len(args):
			i++
			if min, ok = parseSize(args[i]); !ok {
				return "", 0, false
			}
		case strings.HasPrefix(a, "--min="):
			if min, ok = parseSize(a[len("--min="):]); !ok {
				return "", 0, false
			}
		case strings.HasPrefix(a, "-") || tract != "":
			return "", 0, false
		default:
			tract = a
		}
	}
	if tract == "" {
		home, err := os.UserHomeDir()
		if err != nil {
			return "", 0, false
		}
		tract = home
	}
	return tract, min, true
}

func main() {
	tract, min, ok := parseArgs(os.Args[1:])
	if !ok {
		fmt.Fprintln(os.Stderr, usage)
		os.Exit(2)
	}
	at := time.Now()
	abs, _ := filepath.Abs(tract)
	var tick func(int)
	if fi, err := os.Stderr.Stat(); err == nil && fi.Mode()&os.ModeCharDevice != 0 {
		var last time.Time
		tick = func(n int) {
			if time.Since(last) >= 250*time.Millisecond {
				fmt.Fprintf(os.Stderr, "\rWalking. %s entries.", commas(n))
				last = time.Now()
			}
		}
	}
	t, err := walk(abs, min, tick)
	if err != nil {
		fmt.Fprintf(os.Stderr, "No such tract: %s.\n", tract)
		os.Exit(2)
	}
	if tick != nil {
		fmt.Fprintf(os.Stderr, "\rWalking. %s entries.\r\033[K", commas(t.entries))
	}
	printSheet(os.Stdout, t, volumeOf(abs), at)
}
