package main

import (
	"bytes"
	"cmp"
	"encoding/json"
	"errors"
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
	"slices"
	"strings"
	"sync"
	"time"
	"unicode/utf8"
)

const (
	maxRunes = 500
	maxNotes = 100
)

var (
	errEmpty   = errors.New("empty note")
	errTooLong = errors.New("note over 500 characters")
	errFull    = errors.New("box full")
)

// Box is the suggestion box: the files on disk, and the count snapshot that
// lives only in memory.
type Box struct {
	mu     sync.Mutex
	dir    string
	sched  Schedule
	window time.Duration
	now    func() time.Time

	count  int       // the snapshot shown on the page
	stamp  time.Time // the instant the snapshot is as of
	lastAt time.Time // the last snapshot instant, or the start

	nKey   string // the opened box whose count at opening is known
	nCount int

	live          bool // timers armed; false in tests, which call tick directly
	wakeAt, dueAt time.Time
	tickT, dueT   *time.Timer
}

type boxFile struct {
	name, key string
	opened    bool
	mtime     time.Time
}

// openBox places the files found in dir and takes the startup snapshot.
func openBox(dir string, s Schedule, window time.Duration, now func() time.Time) (*Box, error) {
	if err := os.MkdirAll(dir, 0o700); err != nil {
		return nil, err
	}
	b := &Box{dir: dir, sched: s, window: window, now: now}
	t := now()
	next := keyOf(s.next(t))
	files, err := b.files()
	if err != nil {
		return nil, err
	}
	for _, f := range files {
		if !f.opened && f.key != next && !s.past(f.key, t) {
			return nil, fmt.Errorf("%s is keyed for an opening that is not the next one (%s). Not started.", filepath.Join(dir, f.name), next)
		}
		// Opened under an earlier hour on the same day: the next opening's
		// rename would replace it.
		if f.opened && f.key == next {
			return nil, fmt.Errorf("%s is keyed for the next opening (%s), which would replace it. Not started.", filepath.Join(dir, f.name), next)
		}
	}
	if err := b.sweep(t); err != nil {
		return nil, err
	}
	n, err := b.trueCount(t)
	if err != nil {
		return nil, err
	}
	b.count, b.stamp, b.lastAt = n, t, t
	return b, nil
}

// files lists the box files in dir by name: YYYY-MM-DD.json and
// YYYY-MM-DD.opened.json. Anything else is ignored. Sorted by key.
func (b *Box) files() ([]boxFile, error) {
	ents, err := os.ReadDir(b.dir)
	if err != nil {
		return nil, err
	}
	var out []boxFile
	for _, e := range ents {
		key, opened := strings.CutSuffix(e.Name(), ".opened.json")
		if !opened {
			var ok bool
			if key, ok = strings.CutSuffix(e.Name(), ".json"); !ok {
				continue
			}
		}
		if _, err := time.Parse("2006-01-02", key); err != nil || !e.Type().IsRegular() {
			continue
		}
		info, err := e.Info()
		if err != nil {
			continue
		}
		out = append(out, boxFile{e.Name(), key, opened, info.ModTime()})
	}
	return out, nil
}

// sweep shows every past-key box as opened (stamped now, renamed), makes sure
// the next box has a file, and deletes opened boxes whose window has ended.
func (b *Box) sweep(t time.Time) error {
	nextAt := b.sched.next(t)
	next := keyOf(nextAt)
	files, err := b.files()
	if err != nil {
		return err
	}
	for _, f := range files {
		if f.opened || !b.sched.past(f.key, t) {
			continue
		}
		p := filepath.Join(b.dir, f.name)
		// First shown: the window counts from this mtime. If the server stops
		// between the two steps, the next start does both again.
		if err := os.Chtimes(p, t, t); err != nil {
			return err
		}
		if err := os.Rename(p, filepath.Join(b.dir, f.key+".opened.json")); err != nil {
			return err
		}
	}
	p := filepath.Join(b.dir, next+".json")
	if _, err := os.Stat(p); errors.Is(err, fs.ErrNotExist) {
		if err := b.write(p, nil, nextAt); err != nil {
			return err
		}
	}
	return b.expire(t)
}

// expire deletes opened boxes whose window has ended and notes the earliest
// window end still to come.
func (b *Box) expire(t time.Time) error {
	nextAt := b.sched.next(t)
	files, err := b.files()
	if err != nil {
		return err
	}
	b.dueAt = time.Time{}
	for _, f := range files {
		if !f.opened || !b.sched.past(f.key, t) {
			continue
		}
		end := f.mtime.Add(b.window)
		if !t.Before(end) {
			if err := os.Remove(filepath.Join(b.dir, f.name)); err != nil && !errors.Is(err, fs.ErrNotExist) {
				return err
			}
			continue
		}
		if b.dueAt.IsZero() || end.Before(b.dueAt) {
			b.dueAt = end
		}
	}
	return os.Chtimes(b.dir, nextAt, nextAt)
}

// write replaces a box file atomically: temp file in the same directory,
// fsync, rename, mode 0600, then file and directory times set to the opening.
func (b *Box) write(p string, notes []string, at time.Time) error {
	if notes == nil {
		notes = []string{}
	}
	var buf bytes.Buffer
	enc := json.NewEncoder(&buf)
	enc.SetEscapeHTML(false)
	enc.SetIndent("", "  ")
	if err := enc.Encode(notes); err != nil {
		return err
	}
	f, err := os.CreateTemp(b.dir, ".put-*") // created 0600
	if err != nil {
		return err
	}
	_, 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(f.Name(), p)
	}
	if err != nil {
		os.Remove(f.Name())
		return err
	}
	if err := os.Chtimes(p, at, at); err != nil {
		return err
	}
	return os.Chtimes(b.dir, at, at)
}

func readNotes(p string) ([]string, error) {
	data, err := os.ReadFile(p)
	if errors.Is(err, fs.ErrNotExist) {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}
	var notes []string
	if err := json.Unmarshal(data, &notes); err != nil {
		return nil, fmt.Errorf("%s is not a JSON array of strings", p)
	}
	return notes, nil
}

func (b *Box) trueCount(t time.Time) (int, error) {
	notes, err := readNotes(filepath.Join(b.dir, keyOf(b.sched.next(t))+".json"))
	return len(notes), err
}

// flatten collapses every whitespace run to one space and trims.
func flatten(s string) string {
	return strings.Join(strings.Fields(strings.ToValidUTF8(s, "�")), " ")
}

// sortNotes orders by lower-cased byte order, ties by the raw string:
// "sorted by character code", so "Über" comes after "zebra".
func sortNotes(n []string) {
	slices.SortFunc(n, func(a, b string) int {
		return cmp.Or(strings.Compare(strings.ToLower(a), strings.ToLower(b)), strings.Compare(a, b))
	})
}

// add puts one note into the next box.
func (b *Box) add(raw string) error {
	note := flatten(raw)
	if note == "" {
		return errEmpty
	}
	if utf8.RuneCountInString(note) > maxRunes {
		return errTooLong
	}
	b.mu.Lock()
	defer b.mu.Unlock()
	t := b.now()
	b.catchUp(t)
	at := b.sched.next(t)
	p := filepath.Join(b.dir, keyOf(at)+".json")
	notes, err := readNotes(p)
	if err != nil {
		return err
	}
	if len(notes) >= maxNotes {
		return errFull
	}
	notes = append(notes, note)
	sortNotes(notes)
	return b.write(p, notes, at)
}

// tick is one wake of the chain: the snapshot, then the file checks.
func (b *Box) tick() {
	b.mu.Lock()
	defer b.mu.Unlock()
	b.tickAt(b.now())
}

func (b *Box) tickAt(t time.Time) {
	at := b.sched.lastInstant(t)
	if at.After(b.lastAt) { // idempotent: a second wake for the same instant takes nothing
		count, err := b.trueCount(t)
		if op := b.sched.prev(t); op.After(b.lastAt) {
			// An opening passed while running. The snapshot still in force is
			// the count shown at opening, if this is the only opening missed.
			if !b.sched.prev(op.Add(-time.Nanosecond)).After(b.lastAt) {
				b.nKey, b.nCount = keyOf(op), b.count
			}
			if at.Equal(op) {
				count, err = 0, nil // the new box is known to be empty
			}
		}
		if err == nil { // ponytail: an unreadable file keeps the old snapshot and its true stamp
			b.count, b.stamp = count, at
		}
		b.lastAt = at
	}
	b.sweep(t) // ponytail: no log to report to; the next tick retries and the page shows read errors
	b.arm(t)
}

// retire is the retention wake: it only deletes, and takes no snapshot.
func (b *Box) retire() {
	b.mu.Lock()
	defer b.mu.Unlock()
	t := b.now()
	b.expire(t)
	b.arm(t)
}

// arm sets the tick chain (next full hour or next opening, whichever is
// first) and the retention wake (earliest window end).
func (b *Box) arm(t time.Time) {
	if !b.live {
		return
	}
	b.wakeAt = hourFloor(t).Add(time.Hour)
	if o := b.sched.next(t); o.Before(b.wakeAt) {
		b.wakeAt = o
	}
	if b.tickT != nil {
		b.tickT.Stop()
	}
	b.tickT = time.AfterFunc(b.wakeAt.Sub(t), b.tick)
	if b.dueT != nil {
		b.dueT.Stop()
	}
	if !b.dueAt.IsZero() {
		b.dueT = time.AfterFunc(b.dueAt.Sub(t), b.retire)
	}
}

// catchUp runs an overdue wake before a request is answered: timers run on
// the monotonic clock and fire late after the host machine has slept.
func (b *Box) catchUp(t time.Time) {
	if b.live && !t.Before(b.wakeAt) {
		b.tickAt(t)
	} else if b.live && !b.dueAt.IsZero() && !t.Before(b.dueAt) {
		b.expire(t)
		b.arm(t)
	}
}

func (b *Box) start() {
	b.mu.Lock()
	defer b.mu.Unlock()
	b.live = true
	b.arm(b.now())
}

type frontView struct {
	Plate, Count, Stamp string
	Sheet               *sheetView
}

type sheetView struct {
	Header, Total, AtOpening, Earlier string
	Notes                             []string
}

func countLine(n int) string { return plural(n, "note", "notes") + " inside." }

// view is what GET / shows: the opened sheet, if any, and the box.
func (b *Box) view() (frontView, error) {
	b.mu.Lock()
	defer b.mu.Unlock()
	t := b.now()
	b.catchUp(t)
	v := frontView{
		Plate: b.sched.plate(),
		Count: countLine(b.count),
		Stamp: "Count as of " + b.stamp.Format("15:04") + ".",
	}
	var err error
	v.Sheet, err = b.sheet(t)
	return v, err
}

func (b *Box) sheet(t time.Time) (*sheetView, error) {
	files, err := b.files()
	if err != nil {
		return nil, err
	}
	var shown []boxFile
	for _, f := range files {
		if f.opened && b.sched.past(f.key, t) && t.Before(f.mtime.Add(b.window)) {
			shown = append(shown, f)
		}
	}
	if len(shown) == 0 {
		return nil, nil // no file, no sheet
	}
	latest := shown[len(shown)-1]
	var notes []string
	earlier := 0
	for i, f := range shown {
		n, err := readNotes(filepath.Join(b.dir, f.name))
		if err != nil {
			return nil, err
		}
		if i < len(shown)-1 && len(n) > 0 {
			earlier++
		}
		notes = append(notes, n...)
	}
	sortNotes(notes)
	s := &sheetView{
		Header: "Suggestion box. Opened " + b.sched.atKey(latest.key, t.Location()).Format("Monday 2 January 2006, 15:04") + ".",
		Total:  plural(len(notes), "note", "notes") + ".",
		Notes:  notes,
	}
	if len(notes) == 0 {
		s.Total = "The box was opened. It was empty."
	}
	if b.nKey == latest.key {
		s.AtOpening = fmt.Sprintf("Count shown on the page at opening: %d.", b.nCount)
	}
	if earlier > 0 {
		s.Earlier = "Includes notes from " + plural(earlier, "earlier opening", "earlier openings") + "."
	}
	return s, nil
}
