package main

import (
	"errors"
	"fmt"
	"io/fs"
	"os"
	"regexp"
	"strconv"
	"strings"
	"syscall"
	"time"
)

const header = "Observations. One line per run. Durations in seconds, measured, not estimated.\n" +
	"Runs that did not finish with exit 0 are kept apart and not judged.\n"

var (
	lineRe = regexp.MustCompile(`^\d{4}-\d{2}-\d{2} \d{2}:\d{2}\. [^.]*\. (\d+\.\d{3}) seconds, exit (\d+)\. In ([^\t]*)\t(.*)$`)
	bare   = regexp.MustCompile(`^[A-Za-z0-9_./:=+,@%-]+$`)
	flat   = strings.NewReplacer("\t", " ", "\n", " ", "\r", " ")
)

// key is what makes two runs "the same command": the working directory and the
// argument list, rendered the way a person would type it.
type key struct{ cwd, argv string }

func newKey(cwd string, args []string) key {
	words := make([]string, len(args))
	for i, a := range args {
		a = flat.Replace(a)
		if !bare.MatchString(a) {
			a = "'" + strings.ReplaceAll(a, "'", `'\''`) + "'"
		}
		words[i] = a
	}
	return key{flat.Replace(cwd), strings.Join(words, " ")}
}

// history is what the log says about one key.
type history struct {
	ok     []int64 // the window: the last 20 exit 0 durations in milliseconds, oldest first
	total  int     // every exit 0 run of the key on record, window or not
	failed int     // every other run of the key on record
}

func readHistory(path string, k key) (history, error) {
	data, err := os.ReadFile(path)
	if errors.Is(err, fs.ErrNotExist) {
		return history{}, nil
	}
	if err != nil {
		return history{}, err
	}
	return parseHistory(string(data), k), nil
}

// parseHistory reads only lines that match the observation format. Anything else,
// the header among it, is skipped and left where it is.
func parseHistory(text string, k key) history {
	var h history
	for _, line := range strings.Split(text, "\n") {
		m := lineRe.FindStringSubmatch(line)
		if m == nil || flat.Replace(m[3]) != k.cwd || flat.Replace(m[4]) != k.argv {
			continue
		}
		ms, err1 := strconv.ParseInt(strings.Replace(m[1], ".", "", 1), 10, 64)
		code, err2 := strconv.Atoi(m[2])
		switch {
		case err1 != nil || err2 != nil:
		case code != 0:
			h.failed++
		default:
			h.total++
			h.ok = append(h.ok, ms)
		}
	}
	if len(h.ok) > window {
		h.ok = h.ok[len(h.ok)-window:]
	}
	return h
}

func logLine(end time.Time, ms int64, code int, k key) string {
	return fmt.Sprintf("%s. %s. %d.%03d seconds, exit %d. In %s\t%s\n",
		end.Format("2006-01-02 15:04"), capital(speakClock(roundClock(end))), ms/1000, ms%1000, code, k.cwd, k.argv)
}

// appendRun adds one line with one O_APPEND write, under an exclusive flock held
// for the size check and the write, so the header is written once and two runs
// finishing together never interleave.
func appendRun(path, line string) error {
	f, err := os.OpenFile(path, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0o600)
	if err != nil {
		return err
	}
	defer f.Close()
	if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil {
		return err
	}
	st, err := f.Stat()
	if err != nil {
		return err
	}
	last := make([]byte, 1)
	if st.Size() == 0 {
		line = header + line
	} else if _, err := f.ReadAt(last, st.Size()-1); err == nil && last[0] != '\n' {
		line = "\n" + line // a hand edit left no final newline: keep both lines whole
	}
	_, err = f.WriteString(line)
	return err
}
