package main

import (
	"errors"
	"fmt"
	"io"
	"io/fs"
	"os"
	"path/filepath"
	"sort"
	"strings"
)

type walked struct {
	path, rel string
	size      int64
}

type car struct {
	walked
	sc   *Sidecar
	live []Slip
}

func check(dir string, out, errw io.Writer) (int, error) {
	if info, err := os.Stat(dir); err != nil || !info.IsDir() {
		return 1, refuse("%s is not a directory.", clean(dir))
	}
	var books []walked // every regular file that is not a sidecar
	var cars []*car
	hasCar := map[string]bool{} // book path -> a sidecar sits beside it
	count := 0
	// "dir/." so that a DIR which is itself a symlink is walked; links inside it are not followed.
	root := dir + string(filepath.Separator) + "."
	err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
		if err != nil {
			if p == root {
				return err
			}
			fmt.Fprintf(errw, "Could not read %s.\n", clean(p))
			return nil
		}
		if d.IsDir() {
			if p != root && (d.Name() == ".git" || d.Name() == "node_modules") {
				return filepath.SkipDir
			}
			return nil
		}
		if !d.Type().IsRegular() {
			return nil
		}
		info, err := d.Info()
		if err != nil {
			return nil
		}
		count++
		rel, _ := filepath.Rel(dir, p)
		w := walked{p, rel, info.Size()}
		if strings.HasSuffix(d.Name(), ".tipin") {
			cars = append(cars, &car{walked: w})
			hasCar[strings.TrimSuffix(p, ".tipin")] = true
		} else {
			books = append(books, w)
		}
		return nil
	})
	if err != nil {
		return 1, refuse("%s cannot be read.", clean(dir))
	}
	sort.Slice(cars, func(i, j int) bool { return cars[i].rel < cars[j].rel })
	sort.Slice(books, func(i, j int) bool { return books[i].rel < books[j].rel })

	anyLive := false
	for _, c := range cars {
		data, err := os.ReadFile(c.path)
		if sc, ok := parseSidecar(data); err == nil && ok {
			c.sc = sc
			for _, s := range ordered(sc) {
				if s.Withdrawn == "" {
					c.live = append(c.live, s)
				}
			}
			anyLive = anyLive || len(c.live) > 0
		}
	}

	// The editions of the walked text files that could be a candidate or a bare copy.
	edition := map[string]string{}
	if anyLive {
		for _, f := range books {
			if f.size == 0 || f.size > maxBook || hasCar[f.path] {
				continue
			}
			if data, err := os.ReadFile(f.path); err == nil && isText(data) {
				edition[f.path] = editionHash(data)
			}
		}
	}

	var lines []string
	nBooks, nOrphans, nGone, nBad := 0, 0, 0, 0
	named := map[string]bool{}  // already a candidate of an orphan
	source := map[string]*car{} // edition -> the first book with live slips that has it
	for _, c := range cars {
		if c.sc == nil {
			nBad++
			lines = append(lines, "NOT A SLIP FILE  "+clean(c.rel))
			continue
		}
		if len(c.live) == 0 {
			continue
		}
		bookPath := strings.TrimSuffix(c.path, ".tipin")
		if _, err := os.Lstat(bookPath); errors.Is(err, fs.ErrNotExist) {
			nOrphans++
			lines = append(lines, orphan(c, dir, books, edition, named)...)
			continue
		}
		nBooks++
		var fit, differs, gones int
		b, err := readBook(bookPath)
		for _, s := range c.live {
			st := gone
			if err == nil {
				st, _ = locate(b, s)
			}
			switch st {
			case fits:
				fit++
			case moved:
				differs++
			default:
				gones++
			}
			if source[s.Edition] == nil {
				source[s.Edition] = c
			}
		}
		if err == nil && source[b.Edition] == nil {
			source[b.Edition] = c
		}
		nGone += gones
		var parts []string
		for _, p := range []struct {
			n    int
			what string
		}{{fit, "fits"}, {differs, "edition differs"}, {gones, "no longer fits"}} {
			if p.n > 0 {
				parts = append(parts, fmt.Sprintf("%d %s", p.n, p.what))
			}
		}
		lines = append(lines, fmt.Sprintf("%s  %s: %s", clean(strings.TrimSuffix(c.rel, ".tipin")),
			plural(len(c.live), "slip", "slips"), strings.Join(parts, ", ")))
	}

	nBare := 0
	for _, f := range books {
		c := source[edition[f.path]]
		if c == nil || named[f.path] {
			continue
		}
		nBare++
		book := strings.TrimSuffix(c.rel, ".tipin")
		lines = append(lines,
			fmt.Sprintf("BARE COPY  %s  same edition as %s, which has %s.", clean(f.rel), clean(book), plural(len(c.live), "slip", "slips")),
			fmt.Sprintf("        To carry the %s: cp %s %s", word(len(c.live)), shellQuote(c.path), shellQuote(f.path+".tipin")))
	}

	for _, l := range lines {
		fmt.Fprintln(out, l)
	}
	if len(lines) > 0 {
		fmt.Fprintln(out)
	}
	fmt.Fprintf(out, "Checked %s. %s\n", plural(count, "file", "files"), summary(anyLive, nBooks, nOrphans, nBare, nGone, nBad))
	if nOrphans+nBare+nGone+nBad > 0 {
		return 1, nil
	}
	return 0, nil
}

func word(n int) string {
	if n == 1 {
		return "slip"
	}
	return "slips"
}

// orphan reports a sidecar whose book is gone, with the file it most likely belongs to.
func orphan(c *car, dir string, books []walked, edition map[string]string, named map[string]bool) []string {
	lines := []string{fmt.Sprintf("ORPHAN  %s  %s, no book.", clean(c.rel), plural(len(c.live), "slip", "slips"))}
	label := "Same edition: "
	var found []walked
	for _, f := range books {
		e, ok := edition[f.path]
		if !ok {
			continue
		}
		for _, s := range c.live {
			if s.Edition == e {
				found = append(found, f)
				break
			}
		}
	}
	if len(found) == 0 {
		label = "Every slip fits: "
		for _, f := range books {
			if _, ok := edition[f.path]; !ok {
				continue
			}
			data, err := os.ReadFile(f.path)
			if err != nil {
				continue
			}
			b := newBook(data)
			all := true
			for _, s := range c.live {
				if st, _ := locate(b, s); st == gone {
					all = false
					break
				}
			}
			if all {
				found = append(found, f)
			}
		}
	}
	if len(found) == 0 {
		return append(lines, "        No candidate found.")
	}
	pad := strings.Repeat(" ", 8+len(label))
	for i, f := range found {
		named[f.path] = true
		lead := pad
		if i == 0 {
			lead = "        " + label
		}
		lines = append(lines, lead+clean(f.rel))
	}
	if len(found) > 1 {
		return append(lines, "        Several candidates. Choose one.")
	}
	return append(lines, fmt.Sprintf("        To reunite: mv %s %s", shellQuote(c.path), shellQuote(found[0].path+".tipin")))
}

func summary(anyLive bool, nBooks, nOrphans, nBare, nGone, nBad int) string {
	if nOrphans+nBare+nGone+nBad == 0 {
		if anyLive {
			return "Every slip has its book."
		}
		return "No slips."
	}
	var parts []string
	for _, p := range []struct {
		n         int
		one, many string
	}{
		{nBooks, "book with slips", "books with slips"},
		{nOrphans, "orphan", "orphans"},
		{nBare, "bare copy", "bare copies"},
		{nGone, "slip no longer fits", "slips no longer fit"},
		{nBad, "not a slip file", "not slip files"},
	} {
		if p.n > 0 {
			parts = append(parts, plural(p.n, p.one, p.many))
		}
	}
	return strings.Join(parts, ", ") + "."
}

// shellQuote quotes a path for a POSIX shell; a path holding control characters gets $'...' escapes.
func shellQuote(p string) string {
	if strings.IndexFunc(p, isControl) < 0 {
		return "'" + strings.ReplaceAll(p, "'", `'\''`) + "'"
	}
	var b strings.Builder
	b.WriteString("$'")
	for _, r := range p {
		switch {
		case r == '\'' || r == '\\':
			b.WriteByte('\\')
			b.WriteRune(r)
		case isControl(r):
			fmt.Fprintf(&b, "\\x%02x", r)
		default:
			b.WriteRune(r)
		}
	}
	b.WriteByte('\'')
	return b.String()
}
