// Command bedtime puts the machine to sleep at the time you set, and lets you ask for five more minutes.
package main

import (
	"bufio"
	"errors"
	"fmt"
	"io/fs"
	"os"
	"os/signal"
	"runtime"
	"strconv"
	"strings"
	"syscall"
	"time"
)

const usage = `Usage: bedtime HH:MM [--dry-run] [--lock | --then "<command>"] [--clock-start YYYY-MM-DDTHH:MM:SS [--clock-speed N]], or bedtime log`

type opts struct {
	hhmm         string
	hour, minute int
	dry, lock    bool
	then         string
	clockStart   string
	speed        int64
}

// parseTime accepts H:MM or HH:MM, hour 0 to 23, minute 0 to 59.
func parseTime(s string) (h, m int, ok bool) {
	hs, ms, found := strings.Cut(s, ":")
	if !found || len(hs) < 1 || len(hs) > 2 || len(ms) != 2 || strings.Trim(hs+ms, "0123456789") != "" {
		return 0, 0, false
	}
	h, _ = strconv.Atoi(hs)
	m, _ = strconv.Atoi(ms)
	return h, m, h <= 23 && m <= 59
}

// parseArgs returns the options, or an exit message (empty meaning the usage line).
func parseArgs(args []string) (o opts, msg string, ok bool) {
	o.speed = 1
	speedSet := false
	var pos []string
	for i := 0; i < len(args); i++ {
		a := args[i]
		value := func() (string, bool) {
			if i+1 >= len(args) {
				return "", false
			}
			i++
			return args[i], true
		}
		var good bool
		switch a {
		case "--dry-run":
			o.dry, good = true, true
		case "--lock":
			o.lock, good = true, true
		case "--then":
			o.then, good = value()
			good = good && o.then != ""
		case "--clock-start":
			o.clockStart, good = value()
		case "--clock-speed":
			var v string
			v, good = value()
			n, err := strconv.ParseInt(v, 10, 64)
			o.speed, speedSet, good = n, true, good && err == nil && n >= 1
		default:
			if len(a) > 0 && a[0] == '-' {
				return o, "", false
			}
			pos, good = append(pos, a), true
		}
		if !good {
			return o, "", false
		}
	}
	if len(pos) != 1 || (o.lock && o.then != "") || (speedSet && o.clockStart == "") {
		return o, "", false
	}
	h, m, good := parseTime(pos[0])
	if !good {
		return o, "Bedtime must be given as HH:MM, 24-hour, for example 23:00.", false
	}
	o.hhmm, o.hour, o.minute = fmt.Sprintf("%02d:%02d", h, m), h, m
	return o, "", true
}

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

func run(args []string) int {
	if len(args) == 1 && (args[0] == "--help" || args[0] == "-h") {
		fmt.Println(usage)
		fmt.Println("At HH:MM the machine is put to sleep. One minute before, asking opens: type five more minutes.")
		fmt.Println("Each grant is half the one before. The first grant is 15 minutes. Nothing of 10 seconds or less is granted.")
		fmt.Println("The most that can ever be granted in total is 30 minutes. Restarting does not return a grant.")
		fmt.Println("Every start, request and end is appended to a plain ledger: $BEDTIME_LEDGER if set,")
		fmt.Println("else $XDG_STATE_HOME/bedtime/ledger.tsv, else ~/.local/state/bedtime/ledger.tsv. bedtime log prints it.")
		fmt.Println("normal is dead")
		return 0
	}
	if len(args) == 1 && args[0] == "log" {
		text, err := readLedger(LedgerPath())
		if err != nil {
			fmt.Fprintln(os.Stderr, "The ledger could not be read:", err)
			return 1
		}
		fmt.Print(Log(Parse(text)))
		return 0
	}
	o, msg, ok := parseArgs(args)
	if !ok {
		if msg == "" {
			msg = usage
		}
		fmt.Println(msg)
		return 2
	}
	if o.clockStart != "" && !o.dry && os.Getenv("BEDTIME_LEDGER") == "" {
		fmt.Println("A simulated clock needs its own ledger. Set BEDTIME_LEDGER.")
		return 2
	}

	now := func() time.Time { return time.Now().Round(0).Truncate(time.Millisecond) }
	if o.clockStart != "" {
		start, err := time.ParseInLocation("2006-01-02T15:04:05", o.clockStart, time.Local)
		if err != nil {
			fmt.Println(usage)
			return 2
		}
		real0 := time.Now()
		now = func() time.Time {
			return start.Add(time.Since(real0) * time.Duration(o.speed)).Truncate(time.Millisecond)
		}
		fmt.Printf("Clock: simulated from %s at %dx.\n", o.clockStart, o.speed)
	}

	path := LedgerPath()
	text, err := readLedger(path)
	if err != nil {
		fmt.Fprintln(os.Stderr, "The ledger could not be read:", err)
		return 1
	}
	s := Select(now(), o.hour, o.minute, o.hhmm, Parse(text))
	steps := Steps(runtime.GOOS, o.lock, o.then)

	if o.dry {
		for _, l := range Schedule(s) {
			fmt.Println(l)
		}
		fmt.Println()
		fmt.Println(Describe(steps))
		fmt.Println("Ledger: " + path)
		fmt.Println("Nothing was waited for, written or done.")
		return 0
	}

	for _, l := range Opening(s) {
		fmt.Println(l)
	}
	sigs := make(chan os.Signal, 2)
	signal.Notify(sigs, os.Interrupt, syscall.SIGTERM)
	lines := make(chan string)
	go func() {
		sc := bufio.NewScanner(os.Stdin)
		for sc.Scan() {
			lines <- sc.Text()
		}
		close(lines)
	}()
	return Live(Env{
		Now: now,
		Wait: func(sim time.Duration) <-chan time.Time {
			// never more than 200 ms of real time, so a laptop that slept and woke is noticed on the next poll
			return time.After(min(200*time.Millisecond, sim/time.Duration(o.speed)))
		},
		Out:    os.Stdout,
		Lines:  lines,
		Sigs:   sigs,
		Act:    func() Outcome { return RunSteps(steps, now) },
		Ledger: path,
		Lock:   o.lock,
	}, s)
}

func readLedger(path string) (string, error) {
	b, err := os.ReadFile(path)
	if errors.Is(err, fs.ErrNotExist) {
		return "", nil
	}
	return string(b), err
}
