// Command tomorrow logs the outcome of anything that repeats and prints the
// chance that the next one is a yes, by Laplace's rule of succession.
package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/fs"
	"os"
	"os/exec"
	"os/signal"
	"path/filepath"
	"sort"
	"strconv"
	"strings"
	"syscall"
	"time"
)

const (
	method   = "Method: rule of succession (Laplace, 1814). Each trial counted as independent."
	footnote = "* No event has been assigned certainty."
	nothing  = "Nothing has happened yet. Record something: tomorrow record walk yes"

	errName  = "tomorrow: event names are 1 to 24 characters: lowercase letters, digits, dot, underscore and hyphen."
	errRun   = "tomorrow: run needs a command after --."
	errWord  = "tomorrow: record takes yes or no."
	errStart = "tomorrow: nothing was run. The command did not start, so no outcome was recorded."
)

const help = `tomorrow: log what repeats, read the odds of the next one.

  tomorrow run <event> -- <command> [args...]   run it, record yes on exit 0
  tomorrow record <event> <yes|no>              record an outcome by hand
  tomorrow table                                print the odds of the next one
  tomorrow help                                 print this text

Event names: 1 to 24 lowercase letters, digits, dots, underscores and hyphens,
starting with a letter or digit.
Commands start without a shell. For pipes, write: -- sh -c '...'
Log: $TOMORROW_LOG, else $XDG_STATE_HOME/tomorrow/log.jsonl,
else $HOME/.local/state/tomorrow/log.jsonl. It is plain text.

normal is dead
`

// entry is one line of the log. The field order here is the order on disk.
type entry struct {
	At    string `json:"at"`
	Event string `json:"event"`
	Ok    bool   `json:"ok"`
	How   string `json:"how"`
	Ms    *int64 `json:"ms,omitempty"`
}

type trial struct {
	event string
	ok    bool
}

func main() { os.Exit(cli(os.Args[1:])) }

func cli(args []string) int {
	word := "table"
	if len(args) > 0 {
		word, args = args[0], args[1:]
	}
	switch word {
	case "table":
		return table()
	case "run":
		return run(args)
	case "record":
		return record(args)
	case "help", "-h", "--help":
		fmt.Print(help)
		return 0
	}
	fmt.Fprintf(os.Stderr, "tomorrow: unknown command %q. Try: tomorrow help\n", word)
	return 2
}

func validName(s string) bool {
	if len(s) < 1 || len(s) > 24 {
		return false
	}
	for i := 0; i < len(s); i++ {
		c := s[i]
		switch {
		case c >= 'a' && c <= 'z', c >= '0' && c <= '9':
		case i > 0 && (c == '.' || c == '_' || c == '-'):
		default:
			return false
		}
	}
	return true
}

func logPath() (string, error) {
	p := os.Getenv("TOMORROW_LOG")
	if p == "" {
		if d := os.Getenv("XDG_STATE_HOME"); d != "" {
			p = filepath.Join(d, "tomorrow", "log.jsonl")
		} else if h := os.Getenv("HOME"); h != "" {
			p = filepath.Join(h, ".local", "state", "tomorrow", "log.jsonl")
		} else {
			return "", errors.New("no log path: set TOMORROW_LOG or HOME")
		}
	}
	return filepath.Abs(p)
}

// parseLine accepts a JSON object with a string "event" that passes the name
// rule and a boolean "ok". Keys match exactly; everything else is ignored.
func parseLine(line string) (trial, bool) {
	var m map[string]json.RawMessage
	var event string
	var ok *bool
	if json.Unmarshal([]byte(line), &m) != nil ||
		json.Unmarshal(m["event"], &event) != nil ||
		json.Unmarshal(m["ok"], &ok) != nil ||
		ok == nil || !validName(event) {
		return trial{}, false
	}
	return trial{event, *ok}, true
}

// load returns the valid trials in file order and how many lines it skipped.
// A missing log is an empty one. The file is only read, never changed.
func load(path string) ([]trial, int, error) {
	b, err := os.ReadFile(path)
	if errors.Is(err, fs.ErrNotExist) {
		return nil, 0, nil
	}
	if err != nil || len(b) == 0 {
		return nil, 0, err
	}
	var trials []trial
	skipped := 0
	for _, line := range strings.Split(strings.TrimSuffix(string(b), "\n"), "\n") {
		if t, ok := parseLine(line); ok {
			trials = append(trials, t)
		} else {
			skipped++
		}
	}
	return trials, skipped, nil
}

// appendEntry adds one line with a single O_APPEND write, so parallel
// processes never interleave.
func appendEntry(path string, e entry) error {
	line, err := json.Marshal(e)
	if err != nil {
		return err
	}
	if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
		return err
	}
	f, err := os.OpenFile(path, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0o600)
	if err != nil {
		return err
	}
	line = append(line, '\n')
	// A hand-edited log can lose its final newline. Start a fresh line
	// instead of joining the last one.
	last := []byte{0}
	if fi, err := f.Stat(); err == nil && fi.Size() > 0 {
		if _, err := f.ReadAt(last, fi.Size()-1); err == nil && last[0] != '\n' {
			line = append([]byte{'\n'}, line...)
		}
	}
	if _, err := f.Write(line); err != nil {
		f.Close()
		return err
	}
	return f.Close()
}

// pct is the displayed odds, e.g. "66.7%".
func pct(s, t int) string {
	p := tenths(s, t)
	return fmt.Sprintf("%d.%d%%", p/10, p%10)
}

func summary(event string, ok bool, s, t int) string {
	word := "no"
	if ok {
		word = "yes"
	}
	return fmt.Sprintf("tomorrow: %s: %s. %d of %d. Tomorrow %s.", event, word, s, t, pct(s, t))
}

// note appends one outcome and returns the sentence that reports it.
func note(event string, ok bool, ms *int64) (string, error) {
	how := "hand"
	if ms != nil {
		how = "run"
	}
	path, err := logPath()
	if err == nil {
		err = appendEntry(path, entry{time.Now().UTC().Format("2006-01-02T15:04:05Z"), event, ok, how, ms})
	}
	if err != nil {
		return "", fmt.Errorf("could not write the log: %w", err)
	}
	trials, _, err := load(path)
	if err != nil {
		return "", fmt.Errorf("could not read the log: %w", err)
	}
	s, t := 0, 0
	for _, tr := range trials {
		if tr.event == event {
			t++
			if tr.ok {
				s++
			}
		}
	}
	return summary(event, ok, s, t), nil
}

func run(args []string) int {
	if len(args) == 0 || !validName(args[0]) {
		fmt.Fprintln(os.Stderr, errName)
		return 2
	}
	if len(args) < 3 || args[1] != "--" {
		fmt.Fprintln(os.Stderr, errRun)
		return 2
	}
	cmd := exec.Command(args[2], args[3:]...)
	cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr

	// Notify, not Ignore: an ignored signal would be inherited by the child.
	// SIGHUP or SIGINT that arrived already ignored (nohup, a background job)
	// is left alone, so the child inherits it ignored as it would without us.
	sigs := make(chan os.Signal, 8)
	for _, s := range []os.Signal{syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGHUP} {
		if !signal.Ignored(s) {
			signal.Notify(sigs, s)
		}
	}
	defer signal.Stop(sigs)

	start := time.Now()
	if err := cmd.Start(); err != nil {
		fmt.Fprintln(os.Stderr, errStart, err)
		if errors.Is(err, exec.ErrNotFound) || errors.Is(err, fs.ErrNotExist) {
			return 127
		}
		return 126
	}
	go func() {
		// SIGINT and SIGQUIT already reach the child from the terminal.
		for s := range sigs {
			if s == syscall.SIGTERM || s == syscall.SIGHUP {
				cmd.Process.Signal(s)
			}
		}
	}()
	cmd.Wait()
	ms := time.Since(start).Milliseconds()

	ws := cmd.ProcessState.Sys().(syscall.WaitStatus)
	code := ws.ExitStatus()
	if ws.Signaled() {
		code = 128 + int(ws.Signal())
	}
	line, err := note(args[0], code == 0, &ms)
	if err != nil {
		line = "tomorrow: " + err.Error()
	}
	fmt.Fprintln(os.Stderr, line)
	return code
}

func record(args []string) int {
	if len(args) == 0 || !validName(args[0]) {
		fmt.Fprintln(os.Stderr, errName)
		return 2
	}
	if len(args) != 2 || (args[1] != "yes" && args[1] != "no") {
		fmt.Fprintln(os.Stderr, errWord)
		return 2
	}
	line, err := note(args[0], args[1] == "yes", nil)
	if err != nil {
		fmt.Fprintln(os.Stderr, "tomorrow: "+err.Error())
		return 1
	}
	fmt.Println(line)
	return 0
}

func table() int {
	path, err := logPath()
	var trials []trial
	skipped := 0
	if err == nil {
		trials, skipped, err = load(path)
	}
	if err != nil {
		fmt.Fprintln(os.Stderr, "tomorrow: could not read the log:", err)
		return 1
	}
	fmt.Print(render(time.Now().AddDate(0, 0, 1).Format("2006-01-02"), path, trials))
	switch {
	case skipped == 1:
		fmt.Fprintln(os.Stderr, "tomorrow: 1 line of the log could not be read. It was left as it is.")
	case skipped > 1:
		fmt.Fprintf(os.Stderr, "tomorrow: %d lines of the log could not be read. They were left as they are.\n", skipped)
	}
	return 0
}

// render is the whole table as printed: title, Record, Method, then either
// the rows and the footnote or the empty line.
func render(date, path string, trials []trial) string {
	var b strings.Builder
	fmt.Fprintf(&b, "Tomorrow Table for %s\nRecord: %s\n%s\n\n", date, path, method)
	if len(trials) == 0 {
		b.WriteString(nothing + "\n")
		return b.String()
	}
	byEvent := map[string][]bool{}
	for _, t := range trials {
		byEvent[t.event] = append(byEvent[t.event], t.ok)
	}
	names := make([]string, 0, len(byEvent))
	for n := range byEvent {
		names = append(names, n)
	}
	sort.Strings(names)

	rows := [][]string{{"Event", "Trials", "Yes", "Tomorrow*", "To 90%", "Last five"}}
	for _, n := range names {
		oks := byEvent[n]
		s, five := 0, ""
		for i, ok := range oks {
			c := "N"
			if ok {
				s++
				c = "Y"
			}
			if i >= len(oks)-5 {
				five += c
			}
		}
		t := len(oks)
		rows = append(rows, []string{n, strconv.Itoa(t), strconv.Itoa(s), pct(s, t), strconv.Itoa(toNinety(s, t)), five})
	}
	width := make([]int, len(rows[0]))
	for _, r := range rows {
		for i, c := range r {
			width[i] = max(width[i], len(c))
		}
	}
	for _, r := range rows {
		cells := make([]string, len(r))
		for i, c := range r {
			switch i {
			case 0:
				cells[i] = fmt.Sprintf("%-*s", width[i], c)
			case len(r) - 1:
				cells[i] = c // the last column is never padded
			default:
				cells[i] = fmt.Sprintf("%*s", width[i], c)
			}
		}
		b.WriteString(strings.Join(cells, "  ") + "\n")
	}
	b.WriteString("\n" + footnote + "\n")
	return b.String()
}
