package main

import (
	"fmt"
	"os"
	"time"
)

const (
	isoLayout = "2006-01-02"
	atLayout  = "2006-01-02T15:04:05.000000000Z07:00"
)

// A day is a calendar date held as midnight UTC, so a difference of days never
// meets daylight saving.
func mkday(y int, m time.Month, d int) time.Time { return time.Date(y, m, d, 0, 0, 0, 0, time.UTC) }

func daysIn(y int, m time.Month) int { return mkday(y, m+1, 0).Day() }

// addMonths adds k calendar months and clamps the day to the end of the target
// month (31 Jan plus 1 is 28 or 29 Feb). time.AddDate would roll into March.
func addMonths(y int, m time.Month, d, k int) (int, time.Month, int) {
	t := y*12 + int(m) - 1 + k
	ny, nm := t/12, time.Month(t%12+1)
	if last := daysIn(ny, nm); d > last {
		d = last
	}
	return ny, nm, d
}

// threshold is the rest date plus n seasons of three calendar months.
func threshold(rest time.Time, n int) time.Time {
	y, m, d := addMonths(rest.Year(), rest.Month(), rest.Day(), 3*n)
	return mkday(y, m, d)
}

var quarterDays = [...]struct {
	m time.Month
	d int
}{{time.March, 25}, {time.June, 24}, {time.September, 29}, {time.December, 25}}

// ploughDay is the first quarter day on or after the threshold.
func ploughDay(rest time.Time, n int) time.Time {
	t := threshold(rest, n)
	for _, q := range quarterDays {
		if day := mkday(t.Year(), q.m, q.d); !day.Before(t) {
			return day
		}
	}
	return mkday(t.Year()+1, time.March, 25)
}

func daysBetween(a, b time.Time) int { return int(b.Sub(a) / (24 * time.Hour)) }

func fmtDay(t time.Time) string { return t.Format("2 Jan 2006") }

// today is the local calendar date, or FALLOW_TODAY, which is announced on
// stderr so nothing is quietly faked. It never replaces a modification time.
func today() (time.Time, error) {
	if v, ok := os.LookupEnv("FALLOW_TODAY"); ok {
		t, err := time.Parse(isoLayout, v)
		if err != nil {
			return t, stop{2, "FALLOW_TODAY must be YYYY-MM-DD."}
		}
		fmt.Fprintf(os.Stderr, "Today is taken to be %s (FALLOW_TODAY).\n", v)
		return t, nil
	}
	n := time.Now()
	return mkday(n.Year(), n.Month(), n.Day()), nil
}

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