package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
	"unicode/utf8"
)

const maxBook = 8 << 20

// refusal is a one-sentence message for stderr; the command exits 1.
type refusal string

func (r refusal) Error() string { return string(r) }

func refuse(format string, a ...any) error { return refusal(fmt.Sprintf(format, a...)) }

// sidecarPath is the book path as given plus ".tipin": the same directory, the same base name.
func sidecarPath(book string) string { return book + ".tipin" }

// readBook reads a book with os.ReadFile only; nothing here can write to it.
func readBook(name string) (*Book, error) {
	info, err := os.Stat(name)
	switch {
	case errors.Is(err, fs.ErrNotExist):
		return nil, refuse("There is no file %s.", clean(name))
	case err != nil:
		return nil, refuse("%s cannot be read.", clean(name))
	case info.IsDir():
		return nil, refuse("%s is a directory, not a file.", clean(name))
	case !info.Mode().IsRegular():
		return nil, refuse("%s is not a regular file.", clean(name))
	case info.Size() > maxBook:
		return nil, refuse("That file is larger than 8 MiB.")
	}
	data, err := os.ReadFile(name)
	if err != nil {
		return nil, refuse("%s cannot be read.", clean(name))
	}
	if len(data) > maxBook {
		return nil, refuse("That file is larger than 8 MiB.")
	}
	if !isText(data) {
		return nil, refuse("That does not look like a text file.")
	}
	return newBook(data), nil
}

func isText(data []byte) bool {
	head := data
	if len(head) > 8000 {
		head = head[:8000]
	}
	return bytes.IndexByte(head, 0) < 0
}

// readSidecar returns nil, nil when there is no sidecar.
func readSidecar(path string) (*Sidecar, error) {
	data, err := os.ReadFile(path)
	if errors.Is(err, fs.ErrNotExist) {
		return nil, nil
	}
	sc, ok := parseSidecar(data)
	if err != nil || !ok {
		return nil, refuse("%s is not a slip file this version can read. Nothing was changed.", clean(path))
	}
	return sc, nil
}

// parseSidecar accepts version 1 only, and only slips this program could have written.
func parseSidecar(data []byte) (*Sidecar, bool) {
	var sc Sidecar
	if json.Unmarshal(data, &sc) != nil || sc.Tipin != 1 || sc.Next < 1 {
		return nil, false
	}
	seen := map[int]bool{}
	for _, s := range sc.Slips {
		n := utf8.RuneCountInString(s.Note)
		if s.N < 1 || s.N >= sc.Next || seen[s.N] || s.Line < 1 || s.Copies < 1 ||
			s.Twins < 1 || s.Rank < 1 || s.Rank > s.Twins || n < 1 || n > maxNote {
			return nil, false
		}
		seen[s.N] = true
	}
	if sc.Slips == nil {
		sc.Slips = []Slip{}
	}
	return &sc, true
}

// writeSidecar writes a temp file beside the sidecar and renames it over; on failure nothing changes.
func writeSidecar(path string, sc *Sidecar) error {
	base := filepath.Base(path)
	book := base[:len(base)-len(".tipin")]
	sc.About = fmt.Sprintf("Errata slips for %s. They are kept apart so that %s is never edited. Read them with: tipin show %s", book, book, book)
	sc.Tipin = 1
	sc.Book = book
	var buf bytes.Buffer
	enc := json.NewEncoder(&buf)
	enc.SetEscapeHTML(false)
	enc.SetIndent("", "  ")
	if err := enc.Encode(sc); err != nil {
		return err
	}
	tmp := filepath.Join(filepath.Dir(path), "."+base+".tmp")
	fail := refuse("%s cannot be written here. Nothing was changed.", clean(path))
	f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
	if err != nil {
		return fail
	}
	_, err = f.Write(buf.Bytes())
	if err == nil {
		err = f.Sync()
	}
	if cerr := f.Close(); err == nil {
		err = cerr
	}
	if err == nil {
		err = os.Rename(tmp, path)
	}
	if err != nil {
		os.Remove(tmp)
		return fail
	}
	return nil
}
