using System.Globalization; using Febe.Core.Abstractions; using Febe.Core.Domain; using Febe.Core.Pacing; using Febe.Core.Storage; namespace Febe.Core.Engine; /// /// The active window of one day (spec §7.2): the engine works only inside it. A window belongs to the local day it /// starts on and may end after midnight (e.g. 06:30–00:30). /// public sealed record ActiveWindow(DateOnly Day, DateTimeOffset Start, DateTimeOffset End) { public TimeSpan Length => End - Start; public bool Contains(DateTimeOffset instant) => instant >= Start && instant < End; } /// /// Plans the active window of every day: the profile's start and end, each shifted every day by a random amount within /// ± the profile's jitter (a normal draw with σ = jitter/2 truncated to ± jitter, never uniform), only on active /// weekdays. The shifts of a day are derived from a seed drawn once from the engine's random source and persisted, so /// they are deterministic per day and a restart never redraws them. /// public sealed class DayPlanner { private const double ShiftSigma = 0.5; private static readonly TimeSpan MinimumLength = TimeSpan.FromMinutes(30); private readonly ISettingsStore _settings; private readonly IRandomSource _random; private readonly Func _profile; private readonly SemaphoreSlim _seedGate = new(1, 1); private ulong? _seed; public DayPlanner(ISettingsStore settings, IRandomSource random, Func profile, TimeZoneInfo zone) { _settings = settings ?? throw new ArgumentNullException(nameof(settings)); _random = random ?? throw new ArgumentNullException(nameof(random)); _profile = profile ?? throw new ArgumentNullException(nameof(profile)); Zone = zone ?? throw new ArgumentNullException(nameof(zone)); } public TimeZoneInfo Zone { get; } /// The window of a local day, or null when the weekday is not active. public async Task GetWindowAsync(DateOnly day, CancellationToken ct = default) { var profile = _profile(); if (!profile.ActiveDays.Contains(day.DayOfWeek)) { return null; } var seed = await GetSeedAsync(ct).ConfigureAwait(false); return Compute(day, profile, seed, Zone); } /// The window containing (today's, or yesterday's when it crosses midnight); null at night. public async Task GetWindowAtAsync(DateTimeOffset instant, CancellationToken ct = default) { var today = LocalCalendar.Today(instant, Zone); foreach (var day in new[] { today.AddDays(-1), today }) { var window = await GetWindowAsync(day, ct).ConfigureAwait(false); if (window is not null && window.Contains(instant)) { return window; } } return null; } /// The window containing , or the next one to start; null only without active days. public async Task GetNextWindowAsync(DateTimeOffset instant, CancellationToken ct = default) { var today = LocalCalendar.Today(instant, Zone); for (var offset = -1; offset <= 8; offset++) { var window = await GetWindowAsync(today.AddDays(offset), ct).ConfigureAwait(false); if (window is not null && window.End > instant) { return window; } } return null; } /// The window of a day from a seed: pure, used by the planner and by tests. public static ActiveWindow Compute(DateOnly day, CautionProfile profile, ulong seed, TimeZoneInfo zone) { ArgumentNullException.ThrowIfNull(profile); var (startShift, endShift) = Shifts(seed, day); var endDay = profile.WindowEnd > profile.WindowStart ? day : day.AddDays(1); var baseStart = LocalCalendar.FromLocal(day.ToDateTime(profile.WindowStart), zone); var baseEnd = LocalCalendar.FromLocal(endDay.ToDateTime(profile.WindowEnd), zone); var start = baseStart + (profile.WindowJitter * startShift); var end = baseEnd + (profile.WindowJitter * endShift); if (end - start < MinimumLength) { end = start + MinimumLength; } // Whole seconds: easier to read and to compare with stored times (milliseconds). return new ActiveWindow(day, TruncateToSecond(start), TruncateToSecond(end)); } /// Daily shifts of start and end as fractions of the jitter, in [-1, 1]. internal static (double Start, double End) Shifts(ulong seed, DateOnly day) { var random = new SplitMixRandom(seed ^ ((ulong)day.DayNumber * 0x9E3779B97F4A7C15UL)); return (TruncatedNormal(random), TruncatedNormal(random)); } private static double TruncatedNormal(IRandomSource random) { for (var attempt = 0; attempt < 64; attempt++) { var value = random.Normal(0, ShiftSigma); if (value is >= -1 and <= 1) { return value; } } return 0; } private static DateTimeOffset TruncateToSecond(DateTimeOffset value) => new(value.Ticks - (value.Ticks % TimeSpan.TicksPerSecond), value.Offset); private async Task GetSeedAsync(CancellationToken ct) { if (_seed is { } known) { return known; } await _seedGate.WaitAsync(ct).ConfigureAwait(false); try { if (_seed is { } again) { return again; } var text = await _settings.GetAsync(EngineSettingKeys.WindowSeed, ct).ConfigureAwait(false); if (!ulong.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var seed)) { var high = (ulong)(_random.NextDouble() * uint.MaxValue); var low = (ulong)(_random.NextDouble() * uint.MaxValue); seed = (high << 32) | low; await _settings.SetAsync(EngineSettingKeys.WindowSeed, seed.ToString(CultureInfo.InvariantCulture), ct).ConfigureAwait(false); } _seed = seed; return seed; } finally { _seedGate.Release(); } } } /// SplitMix64: a tiny deterministic generator for values derived from a stored seed. internal sealed class SplitMixRandom(ulong seed) : IRandomSource { private ulong _state = seed; public double NextDouble() => (Next() >> 11) * (1.0 / (1UL << 53)); private ulong Next() { var z = _state += 0x9E3779B97F4A7C15UL; z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9UL; z = (z ^ (z >> 27)) * 0x94D049BB133111EBUL; return z ^ (z >> 31); } }