package main

import (
	"fmt"
	"io"
	"os"
	"strings"
	"syscall"
	"time"
)

// State is one night: its target instant, how many grants were given, and the deadline D.
type State struct {
	Target time.Time // the night's HH:MM on the night's date
	HHMM   string
	K      int
	D      time.Time
}

func (s State) Night() string { return s.Target.Format("2006-01-02") }

// Select picks the night a start at `now` belongs to: yesterday's night if its grants still
// run past now, else today's night if its target (plus any grants) is still ahead, else tomorrow's.
// A night is resumed whenever the ledger holds grants for it, so restarting never returns a grant.
func Select(now time.Time, hour, minute int, hhmm string, nights []*Night) State {
	y, m, d := now.Date()
	for day := -1; day <= 1; day++ {
		c := time.Date(y, m, d+day, hour, minute, 0, 0, now.Location())
		k := Grants(nights, c.Format("2006-01-02"), hhmm)
		end := c.Add(ms(Total(k)))
		if end.After(now) || day == 1 {
			return State{Target: c, HHMM: hhmm, K: k, D: end}
		}
	}
	panic("unreachable")
}

func plural(n int, word string) string {
	if n == 1 {
		return fmt.Sprintf("%d %s", n, word)
	}
	return fmt.Sprintf("%d %ss", n, word)
}

// Opening is the lines a run starts with: the resume line when grants were given, then four lines.
func Opening(s State) []string {
	var out []string
	bed := s.HHMM
	if s.K > 0 {
		out = append(out, fmt.Sprintf("Resuming tonight. %s given, %s in total. Bedtime is %s.",
			plural(s.K, "grant"), Words(Total(s.K)), Clock(s.D)))
		bed = Clock(s.D)
	}
	next := "No further grant can be made."
	if g := Grant(s.K + 1); g > MinGrant {
		word := "next"
		if s.K == 0 {
			word = "first"
		}
		next = fmt.Sprintf("The %s grant is %s.", word, Words(g))
	}
	return append(out,
		fmt.Sprintf("Bedtime is %s on %s.", bed, Day(s.D)),
		fmt.Sprintf("Asking for five more minutes opens at %s, one minute before.", Clock(s.D.Add(-ms(Window)))),
		"Each grant is half the one before. "+next,
		fmt.Sprintf("The most that can ever be granted in total is %s.", Words(Ceiling)),
	)
}

// Schedule is the dry run's body: heading, opening, and every remaining grant, from Answer.
func Schedule(s State) []string {
	out := append([]string{"Schedule of extensions, night of " + Day(s.Target) + "."}, Opening(s)...)
	out = append(out, "")
	k, d := s.K, s.D
	for {
		ok, _, nd, lines := Answer(k, d)
		if !ok {
			break
		}
		k, d = k+1, nd
		out = append(out, fmt.Sprintf("%d. %s", k, lines[0]), "   "+lines[1])
	}
	n := MaxGrants() + 1
	return append(out,
		fmt.Sprintf("No grant %d: it would be %s, under the %d second minimum.", n, Words(Grant(n)), MinGrant/1000),
		"The last possible bedtime is "+Clock(s.Target.Add(ms(Total(MaxGrants()))))+".",
		fmt.Sprintf("Halving rounds down to the millisecond. %d milliseconds of the %s can never be granted.", Shortfall(), Words(Ceiling)),
	)
}

// Request reports whether a typed line is the one request this counter takes.
func Request(line string) bool {
	s := strings.Join(strings.Fields(strings.ToLower(line)), " ")
	s = strings.TrimRight(s, ".!?")
	return s == "five more minutes" || s == "5 more minutes"
}

// Env is everything the live run touches, so a test can replace the clock and the action.
type Env struct {
	Now    func() time.Time
	Wait   func(sim time.Duration) <-chan time.Time // waits real time for up to this much simulated time
	Out    io.Writer
	Lines  <-chan string
	Sigs   <-chan os.Signal
	Act    func() Outcome
	Ledger string
	Lock   bool
}

// Live waits for the clock, answers requests, then acts. It returns the exit code.
func Live(e Env, s State) int {
	say := func(l string) { fmt.Fprintln(e.Out, l) }
	note := func(at time.Time, event, det string) {
		if err := Append(e.Ledger, Line(at, s.Night(), s.HHMM, event, det)); err != nil {
			fmt.Fprintln(os.Stderr, "The ledger could not be written:", err)
		}
	}
	resumed := "no"
	if s.K > 0 {
		resumed = "yes"
	}
	note(e.Now(), "start", fmt.Sprintf("deadline=%s granted_ms=%d resumed=%s", Clock(s.D), Total(s.K), resumed))

	open := false
	opens := func() time.Time { return s.D.Add(-ms(Window)) }
	notice := func(now time.Time) {
		if !now.Before(opens()) && !open {
			open = true
			say(fmt.Sprintf("Asking is open from %s until %s.", Clock(opens()), Clock(s.D)))
		}
	}
	ask := func(at time.Time, result string, g int64) {
		note(at, "ask", fmt.Sprintf("result=%s grant_ms=%d total_ms=%d deadline=%s", result, g, Total(s.K), Clock(s.D)))
	}
	handle := func(line string, now time.Time) {
		notice(now)
		switch {
		case !Request(line):
			say("That is not a request this counter takes. The request is five more minutes.")
		case !open:
			say("Not yet. Asking opens at " + Clock(opens()) + ".")
			ask(now, "early", 0)
		default:
			ok, g, nd, lines := Answer(s.K, s.D)
			for _, l := range lines {
				say(l)
			}
			if !ok {
				ask(now, "declined", 0)
				return
			}
			s.K, s.D = s.K+1, nd
			ask(now, "granted", g)
			open = !now.Before(opens())
		}
	}
	stop := func(sig os.Signal) int {
		say("Stopped. Nothing was done.")
		note(e.Now(), "end", "action=interrupted")
		if sig == syscall.SIGTERM {
			return 143
		}
		return 130
	}

	lines := e.Lines
	take := func(l string, ok bool) {
		if !ok {
			lines = nil // input ended; the clock still decides
		} else if now := e.Now(); now.Before(s.D) {
			handle(l, now) // a request at or after the deadline is not answered: the action comes first
		}
	}
	for {
		select { // a stop that has arrived is honoured before anything else
		case sig := <-e.Sigs:
			return stop(sig)
		default:
		}
		now := e.Now()
		if !now.Before(s.D) {
			return fire(e, s, say, note)
		}
		notice(now)
		select { // a request that has arrived is answered before the clock is waited on
		case l, ok := <-lines:
			take(l, ok)
			continue
		default:
		}
		boundary := s.D
		if !open {
			boundary = opens()
		}
		select {
		case sig := <-e.Sigs:
			return stop(sig)
		case l, ok := <-lines:
			take(l, ok)
		case <-e.Wait(boundary.Sub(now)):
		}
	}
}

// fire acts at the deadline. Nothing comes before the action but its two lines.
func fire(e Env, s State, say func(string), note func(time.Time, string, string)) int {
	say("Bedtime.")
	if e.Lock {
		say("Locking.")
	} else {
		say("Sleeping.")
	}
	o := e.Act()
	det := "action=" + o.Action
	if len(o.Failed) > 0 {
		det += " failed=" + strings.Join(o.Failed, ",")
	}
	code := 0
	if o.Action == "none" {
		say("Neither suspend nor lock was available here. Nothing was done.")
		code = 3
	}
	note(o.At, "end", det)
	return code
}
