using System.Runtime.CompilerServices;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Engine;
namespace Febe.Web.Engine;
///
/// The commands the interface sends to the engine (spec §7.8, §4.2). The real implementation is
/// ; the demo has its own; without an engine refuses politely.
/// What the engine shows is (Febe.Core).
///
public interface IEngineControl
{
/// «Metti in pausa».
Task PauseAsync(CancellationToken ct);
/// «Riprendi».
Task ResumeAsync(CancellationToken ct);
/// «Controlla ora», with the confirmation token outside the active window.
Task CheckNowAsync(long accountId, string? confirmationToken, CancellationToken ct);
/// «Rileggi l'elenco» of the profiles Alberto follows.
Task RequestFollowingListAsync(CancellationToken ct);
/// Accounts were added, removed or changed: the engine brings its queue in step.
Task NotifyAccountsChangedAsync(CancellationToken ct);
///
/// «Riattiva» a recipe suspended after three problems in a row (unknown formats, targets not found). False when it
/// was not suspended or there is no engine.
///
Task ResumeRecipeAsync(RecipeKind recipe, CancellationToken ct) => Task.FromResult(false);
}
/// The commands of the interface on the real engine.
public sealed class EngineHostControl(EngineHost host) : IEngineControl
{
public Task PauseAsync(CancellationToken ct) => host.PauseAsync(ct);
public Task ResumeAsync(CancellationToken ct) => host.ResumeAsync(ct);
public Task CheckNowAsync(long accountId, string? confirmationToken, CancellationToken ct) =>
host.CheckNowAsync(accountId, confirmationToken, ct);
public Task RequestFollowingListAsync(CancellationToken ct) => host.RequestFollowingListAsync(ct);
public Task NotifyAccountsChangedAsync(CancellationToken ct) => host.NotifyAccountsChangedAsync(ct);
public Task ResumeRecipeAsync(RecipeKind recipe, CancellationToken ct) => host.ResumeRecipeAsync(recipe, ct);
}
///
/// When the browser was last used by Alberto: «Riprendi» after a verification becomes active only after he used the
/// browser (mockup 11). The Browser page («Ho finito») and the desktop window report it.
///
public sealed class BrowserUseTracker
{
private long _lastUsedTicks;
public DateTimeOffset? LastUsedAt
{
get
{
var ticks = Interlocked.Read(ref _lastUsedTicks);
return ticks == 0 ? null : new DateTimeOffset(ticks, TimeSpan.Zero);
}
}
public void MarkUsed(DateTimeOffset at) => Interlocked.Exchange(ref _lastUsedTicks, at.UtcTicks);
}
/// No engine in this process (it has not been wired yet, or the configuration stopped it): «Motore spento».
public sealed class OfflineEngine(IClock clock) : IEngineMonitor, IEngineControl
{
private const string Off = "Il motore non è in funzione.";
public Task GetSnapshotAsync(CancellationToken ct = default) =>
Task.FromResult(SnapshotParts.Build(clock, EngineMode.Off, "Motore spento", [Off], "Motore spento", CautionProfile.Prudent));
public async IAsyncEnumerable SubscribeAsync([EnumeratorCancellation] CancellationToken ct = default)
{
await Task.Delay(Timeout.Infinite, ct).ConfigureAwait(false);
yield break;
}
public Task PauseAsync(CancellationToken ct) => Task.CompletedTask;
public Task ResumeAsync(CancellationToken ct) => Task.FromResult(new ResumeResult(false, Off));
public Task CheckNowAsync(long accountId, string? confirmationToken, CancellationToken ct) =>
Task.FromResult(new CheckNowResult(CheckNowStatus.Refused, Off + " Il controllo non parte."));
public Task RequestFollowingListAsync(CancellationToken ct) => Task.CompletedTask;
public Task NotifyAccountsChangedAsync(CancellationToken ct) => Task.CompletedTask;
}
/// Pieces for building snapshots outside (offline engine, demo).
public static class SnapshotParts
{
/// The four main budgets in the order of the Attività page.
public static readonly ActionKind[] Main = [ActionKind.ProfileOpen, ActionKind.StoryView, ActionKind.BackfillPage, ActionKind.DataDownload];
/// Every category in the order of the table of spec §7.5.
public static readonly ActionKind[] All =
[ActionKind.Home, ActionKind.ProfileOpen, ActionKind.StoryView, ActionKind.BackfillPage, ActionKind.SinglePost, ActionKind.FollowingListPage, ActionKind.DataDownload];
/// A minimal snapshot: no sessions, empty budgets.
public static EngineSnapshot Build(IClock clock, EngineMode mode, string headline, IReadOnlyList details, string sidebar, CautionProfile profile)
{
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(profile);
var now = clock.Now;
var zone = clock.LocalZone;
var day = LocalCalendar.Today(now, zone);
var (start, end) = LocalCalendar.DayBounds(day, zone);
var budgets = All.Select(k => Budget(profile, k, 0, 0, null)).ToList();
return new EngineSnapshot
{
At = now,
Mode = mode,
Headline = headline,
Details = details,
SidebarLine = sidebar,
Profile = profile.Kind,
ProfileLine = $"Profilo «{ItalianText.Profile(profile.Kind)}»",
Today = new DayStrip(day, start, end, now, "Nessuna sessione oggi", []),
MainBudgets = [.. Main.Select(k => budgets.First(b => b.Kind == k))],
AllBudgets = budgets,
ProfilesOpenedToday = budgets.First(b => b.Kind == ActionKind.ProfileOpen),
Queue = [],
RecentActions = [],
SuspendedRecipes = [],
Breaker = BreakerState.Normal,
};
}
/// A budget as the interface shows it, with the same wording as the real monitor.
/// Profile with the limits.
/// Category.
/// Used today (bytes for data).
/// Used in the last hour (ignored for data).
/// «Fermo dalle 16:32» while the engine is stopped; null otherwise.
public static BudgetView Budget(CautionProfile profile, ActionKind kind, long usedToday, long usedLastHour, string? stoppedNote)
{
ArgumentNullException.ThrowIfNull(profile);
var data = kind == ActionKind.DataDownload;
long limitToday = data ? profile.DataPerDayBytes : profile.Budgets[kind].PerDay;
long? limitHour = data ? null : profile.Budgets[kind].PerHour;
var status = new BudgetStatus(kind, usedToday, limitToday, data ? null : usedLastHour, limitHour);
string note;
if (stoppedNote is not null && !data)
{
note = stoppedNote;
}
else if (status.DailyReached)
{
note = "Tetto di oggi raggiunto: riprende domani";
}
else if (status.HourlyReached)
{
note = "Tetto orario raggiunto: riprende entro un'ora";
}
else if (status.DailyRatio >= BudgetStatus.AmberThreshold)
{
note = "Quasi al limite per oggi";
}
else if (status.HourlyRatio >= BudgetStatus.AmberThreshold)
{
note = "Quasi al limite di quest'ora";
}
else if (data)
{
note = "Restano " + ItalianText.Bytes(Math.Max(0, limitToday - usedToday));
}
else
{
note = $"In questa ora {ItalianText.Number(usedLastHour)} di {ItalianText.Number(limitHour ?? 0)}";
}
return new BudgetView(
kind,
ItalianText.CategoryLabel(kind),
usedToday,
limitToday,
status.UsedLastHour,
limitHour,
status.IsAmber,
Math.Clamp(status.DailyRatio, 0, 1),
data ? ItalianText.Bytes(usedToday) : ItalianText.Number(usedToday),
"di " + (data ? ItalianText.Bytes(limitToday) : ItalianText.Number(limitToday)),
note);
}
}