// Command tipin attaches correction slips to a text file without ever editing it.
package main

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"os"
	"sort"
	"strconv"
	"strings"
	"time"
	"unicode/utf8"
)

const maxNote = 500

const usage = `tipin FILE LINE TEXT...     tip in a slip at line LINE (TEXT is the correction)
tipin show FILE             print the file, numbered, with the slips at the foot
tipin print FILE [N]        print the slips as a cut-out slip (all, or slip N)
tipin check [DIR]           find every slip file under DIR (default .): orphans, bare copies, slips that no longer fit, files that are not slip files
tipin drop FILE N           withdraw slip N (it stays in the sidecar, marked)
`

// errUsage makes main print the usage and exit 2.
var errUsage = errors.New("usage")

func main() {
	out := bufio.NewWriter(os.Stdout)
	code, err := run(os.Args[1:], out, os.Stderr)
	out.Flush()
	var r refusal
	switch {
	case errors.Is(err, errUsage):
		fmt.Fprint(os.Stderr, usage)
		code = 2
	case errors.As(err, &r):
		fmt.Fprintln(os.Stderr, r)
		code = 1
	case err != nil:
		fmt.Fprintln(os.Stderr, "Something failed. Nothing was changed.")
		code = 1
	}
	os.Exit(code)
}

func run(args []string, out io.Writer, errw io.Writer) (int, error) {
	if len(args) == 0 {
		return 2, errUsage
	}
	cmd := args[0]
	if cmd == "help" {
		fmt.Fprint(out, usage)
		return 2, nil
	}
	if cmd == "check" {
		if len(args) > 2 {
			return 2, errUsage
		}
		dir := "."
		if len(args) == 2 {
			dir = args[1]
		}
		return check(dir, out, errw)
	}
	if cmd != "show" && cmd != "print" && cmd != "drop" {
		if len(args) < 3 {
			return 2, errUsage
		}
		return 0, add(args[0], args[1], args[2:], out)
	}
	if len(args) < 2 || (cmd == "show" && len(args) != 2) || (cmd == "print" && len(args) > 3) || (cmd == "drop" && len(args) != 3) {
		return 2, errUsage
	}
	book := args[1]
	if strings.HasSuffix(book, ".tipin") {
		return 1, refuse("That is a slip file, not a book.")
	}
	switch cmd {
	case "show":
		return 0, show(book, out, errw)
	case "print":
		n := ""
		if len(args) == 3 {
			n = args[2]
		}
		return 0, printSlips(book, n, out, errw)
	}
	return 0, drop(book, args[2], out)
}

func add(book, lineArg string, words []string, out io.Writer) error {
	if strings.HasSuffix(book, ".tipin") {
		return refuse("That is a slip file, not a book.")
	}
	note := strings.Join(words, " ")
	if !utf8.ValidString(note) || strings.IndexFunc(note, isControl) >= 0 {
		return refuse("A slip is one line of plain words.")
	}
	note = strings.TrimSpace(note)
	if note == "" {
		return refuse("A slip needs words.")
	}
	if utf8.RuneCountInString(note) > maxNote {
		return refuse("A slip holds at most 500 characters.")
	}
	b, err := readBook(book)
	if err != nil {
		return err
	}
	line, err := strconv.Atoi(lineArg)
	if err != nil || line < 1 || line > len(b.Lines) {
		return refuse("%s has %s. There is no line %s.", clean(book), plural(len(b.Lines), "line", "lines"), clean(lineArg))
	}
	path := sidecarPath(book)
	sc, err := readSidecar(path)
	if err != nil {
		return err
	}
	if sc == nil {
		sc = &Sidecar{Next: 1, Slips: []Slip{}}
	}
	s := b.anchor(line)
	s.N = sc.Next
	s.Date = today()
	s.Note = note
	sc.Slips = append(sc.Slips, s)
	sc.Next++
	if err := writeSidecar(path, sc); err != nil {
		return err
	}
	name := clean(book)
	fmt.Fprintf(out, "Slip %d tipped in at line %d of %s. %s was not touched.\n", s.N, line, name, name)
	fmt.Fprintf(out, "Slips are kept in %s. Carry it with the file.\n", clean(path))
	fmt.Fprintf(out, "%s.\n", plural(live(sc), "slip", "slips"))
	return nil
}

func drop(book, nArg string, out io.Writer) error {
	path := sidecarPath(book)
	sc, err := readSidecar(path)
	if err != nil {
		return err
	}
	n, _ := strconv.Atoi(nArg)
	i := find(sc, n)
	if i < 0 {
		return refuse("%s has no slip %s.", clean(book), clean(nArg))
	}
	if sc.Slips[i].Withdrawn != "" {
		return refuse("Slip %d is already withdrawn.", n)
	}
	sc.Slips[i].Withdrawn = today()
	if err := writeSidecar(path, sc); err != nil {
		return err
	}
	fmt.Fprintf(out, "Slip %d withdrawn. %s.\n", n, plural(live(sc), "slip", "slips"))
	return nil
}

// find returns the index of slip n, or -1.
func find(sc *Sidecar, n int) int {
	if sc == nil {
		return -1
	}
	for i, s := range sc.Slips {
		if s.N == n {
			return i
		}
	}
	return -1
}

func show(book string, out, errw io.Writer) error {
	b, err := readBook(book)
	if err != nil {
		return err
	}
	sc, err := readSidecar(sidecarPath(book))
	if err != nil {
		return err
	}
	slips := ordered(sc)
	markers := map[int][]string{}
	type placed struct {
		st   state
		line int
	}
	at := map[int]placed{}
	for _, s := range slips {
		if s.Withdrawn != "" {
			continue
		}
		st, l := locate(b, s)
		at[s.N] = placed{st, l}
		if st != gone {
			markers[l] = append(markers[l], strconv.Itoa(s.N))
		}
	}
	w := max(3, len(strconv.Itoa(len(b.Lines))))
	m := 0
	for _, ns := range markers {
		m = max(m, len(ns)+1+len(strings.Join(ns, ",")))
	}
	for i, l := range b.Lines {
		fmt.Fprintf(out, "%*d  ", w, i+1)
		if m > 0 {
			mk := ""
			if ns := markers[i+1]; ns != nil {
				mk = "[" + strings.Join(ns, ",") + "]"
			}
			fmt.Fprintf(out, "%-*s  ", m, mk)
		}
		out.Write(l)
		io.WriteString(out, "\n")
	}
	if len(slips) == 0 {
		fmt.Fprintf(errw, "No slips for %s.\n", clean(book))
		return nil
	}
	head := plural(live(sc), "slip", "slips")
	if wd := len(slips) - live(sc); wd > 0 {
		head += fmt.Sprintf(", %d withdrawn", wd)
	}
	fmt.Fprintf(out, "\n%s\nERRATA  %s  ed. %s  %s\n\n", strings.Repeat("_", 16), clean(book), b.Edition[:12], head)
	for _, s := range slips {
		ind := strings.Repeat(" ", len(strconv.Itoa(s.N))+2)
		p := at[s.N]
		switch {
		case s.Withdrawn != "":
			fmt.Fprintf(out, "%d. Withdrawn %s.\n", s.N, clean(s.Withdrawn))
		case p.st == gone:
			fmt.Fprintf(out, "%d. No longer fits. Was line %d: \"%s\".\n%sThe slip said: %s\n", s.N, s.Line, quote(s.Text), ind, clean(s.Note))
		case p.st == fits:
			fmt.Fprintf(out, "%d. Line %d. %s\n", s.N, p.line, clean(s.Note))
		default:
			fmt.Fprintf(out, "%d. Line %d%s. %s\n%sEdition differs; line still fits.\n", s.N, p.line, writtenAt(p.line, s.Line), clean(s.Note), ind)
		}
	}
	fmt.Fprint(out, "\nThe text above is as printed.\n")
	return nil
}

func writtenAt(now, was int) string {
	if now == was {
		return ""
	}
	return fmt.Sprintf(", written at %d", was)
}

// ordered returns the slips in slip number order.
func ordered(sc *Sidecar) []Slip {
	if sc == nil {
		return nil
	}
	s := append([]Slip(nil), sc.Slips...)
	sort.Slice(s, func(i, j int) bool { return s[i].N < s[j].N })
	return s
}

func live(sc *Sidecar) int {
	n := 0
	if sc != nil {
		for _, s := range sc.Slips {
			if s.Withdrawn == "" {
				n++
			}
		}
	}
	return n
}

func plural(n int, one, many string) string {
	if n == 1 {
		return "1 " + one
	}
	return fmt.Sprintf("%d %s", n, many)
}

func today() string { return time.Now().Format("2006-01-02") }

func isControl(r rune) bool { return r < 0x20 || r == 0x7f }

// clean turns each control character into one space, so no name or note can break a line.
func clean(s string) string {
	return strings.Map(func(r rune) rune {
		if isControl(r) {
			return ' '
		}
		return r
	}, s)
}

// quote is a quoted line: controls to spaces, cut at 60 runes.
func quote(s string) string {
	r := []rune(clean(s))
	if len(r) > 60 {
		return string(r[:60]) + "..."
	}
	return string(r)
}
