package alert

import (
	"strings"
	"time"
)

// PageDelayAnnotation names the rule annotation holding how long alertstore
// waits before the first phone call for a page-class alert.
//
// An annotation rather than a label, because a label joins the alert's
// identity: adding one to a rule changes the fingerprint of every alert it
// produces, and the fingerprint is what occurrence dedup and the aggregation
// key are built on. Nothing here needs to reach Alertmanager's routing or
// grouping, so it stays out of the identity and can be added to a live rule
// without renaming what that rule has been firing.
//
// A constant and not a setting, for the reason ResponseClassLabel is one: a
// configurable name puts a cross-repository contract behind a typo.
const PageDelayAnnotation = "page_delay"

// MaxPageDelay caps what a rule may ask for.
//
// Two independently reasonable numbers compose into an unreasonable one: a
// rule asking eight minutes and a later agent grant adding eight more would put
// the first call on a critical condition three quarters of an hour out. The cap
// is where that composition is bounded, so it binds the rule's own value too.
const MaxPageDelay = 10 * time.Minute

// PageDelay returns how long to wait before the first phone call, read from the
// annotations of the rule that fired.
//
// Absent, empty, unparseable, negative — all mean zero, which is what every
// alert does today: the first call goes out as soon as an owner is assigned.
// Failing to zero is the point. A typo in a rule annotation must not be able to
// silence a page; the worst it can do is lose a delay someone wanted.
//
// The value is a Go duration string (`5m`, `90s`). Day units are not accepted,
// and the cap would reject them anyway — nothing about waking someone for a
// page-class alert is measured in days.
func PageDelay(annotations map[string]string) time.Duration {
	raw := strings.TrimSpace(annotations[PageDelayAnnotation])
	if raw == "" {
		return 0
	}
	d, err := time.ParseDuration(raw)
	if err != nil || d <= 0 {
		return 0
	}
	if d > MaxPageDelay {
		return MaxPageDelay
	}
	return d
}
