package scheduler

import (
	"time"

	"github.com/nomadcode/nomadcode-core/internal/workflow"
)

// IsAuthoringStale reports whether an authoring observation timestamp
// indicates a stale state. For running authoring tasks, pass the parsed
// authoring_run_updated_at value; for queued tasks, pass task.UpdatedAt.
// thresholdSec is the AUTHORING_STALE_AFTER_SEC config value (default 1200).
// Returns false when observedAt is zero or thresholdSec is non-positive.
func IsAuthoringStale(observedAt time.Time, thresholdSec int) bool {
	if observedAt.IsZero() || thresholdSec <= 0 {
		return false
	}
	return time.Since(observedAt) > time.Duration(thresholdSec)*time.Second
}

// ParseAuthoringRunUpdatedAt parses the authoring_run_updated_at RFC3339
// string from task metadata. Returns zero time on missing or parse error.
func ParseAuthoringRunUpdatedAt(meta map[string]any) time.Time {
	v, ok := meta[workflow.MetadataKeyAuthoringRunUpdatedAt]
	if !ok {
		return time.Time{}
	}
	s, ok := v.(string)
	if !ok || s == "" {
		return time.Time{}
	}
	t, err := time.Parse(time.RFC3339, s)
	if err != nil {
		return time.Time{}
	}
	return t
}
