namespace Febe.Core.Abstractions;
///
/// The only source of time for the engine (spec §5). Engine code never uses
/// DateTime.Now, DateTimeOffset.Now or Task.Delay directly, so it can run under a virtual clock.
///
public interface IClock
{
DateTimeOffset Now { get; }
/// The user's time zone (Alberto's): daily budgets and file names use it.
TimeZoneInfo LocalZone { get; }
Task Delay(TimeSpan time, CancellationToken ct);
}
/// The only source of randomness for the engine (spec §5).
public interface IRandomSource
{
/// Uniform value in [0, 1).
double NextDouble();
}
/// Real wall clock, used outside tests and simulation.
public sealed class SystemClock(TimeZoneInfo? zone = null) : IClock
{
public DateTimeOffset Now => DateTimeOffset.UtcNow;
public TimeZoneInfo LocalZone { get; } = zone ?? TimeZoneInfo.Local;
public Task Delay(TimeSpan time, CancellationToken ct) =>
time <= TimeSpan.Zero ? Task.CompletedTask : Task.Delay(time, ct);
}
/// Process-wide random source for production use.
public sealed class SystemRandom : IRandomSource
{
public double NextDouble() => Random.Shared.NextDouble();
}
/// Deterministic random source for tests and simulation (fixed seed).
public sealed class SeededRandom(int seed) : IRandomSource
{
private readonly Random _random = new(seed);
private readonly Lock _gate = new();
public double NextDouble()
{
lock (_gate)
{
return _random.NextDouble();
}
}
}