using Febe.Core.Abstractions; using Febe.Core.Domain; namespace Febe.Core.Engine; /// What the «Con queste impostazioni» panel needs (spec §4.4, mockup 05). public sealed record AccountPlanInput { /// The account with the settings being edited (not yet saved). public required Account Account { get; init; } /// All the other accounts, to compute the load on the daily budgets (the edited account is ignored here by id). public IReadOnlyList OtherAccounts { get; init; } = []; /// The effective caution profile (settings applied). public required CautionProfile Profile { get; init; } /// Posts of this account already in the library (for the backfill estimate). public int ArchivedPosts { get; init; } public EngineOptions Options { get; init; } = EngineOptions.Default; /// /// Start of the gradual start in force (motore.avvio-graduale-dal) and the current time: the warning about /// halved budgets is given only while the ramp lasts. Null (unknown) keeps the warning. /// public DateTimeOffset? GradualStartSince { get; init; } public DateTimeOffset? Now { get; init; } } /// A line of the panel: «Nuovi post» — «controllati ogni 3 ore circa, tra le 7:30 e le 23:30». public sealed record PlanLine(string Title, string Text); /// The consequences of an account's settings, with real numbers (spec §4.5). public sealed record AccountPlanEstimate { public required IReadOnlyList Lines { get; init; } /// Warnings: requested accounts and frequencies exceed what the budgets allow (checks get sparser, not forced). public required IReadOnlyList Warnings { get; init; } /// The engine contacts this account at all (not paused, not «Solo archivio», reachable). public bool Contacted { get; init; } /// Profile checks as wished by the frequency. public TimeSpan? ProfileCheckWanted { get; init; } /// Profile checks as they will really happen (sparser when the budget is short). public TimeSpan? ProfileCheckEvery { get; init; } /// Planned interval between story checks (null with stories off). public TimeSpan? StoryInterval { get; init; } public double? StoryChecksPerDay { get; init; } /// Profile openings per day caused by this account (after thinning). public double ProfileOpensPerDay { get; init; } /// Profile openings per day asked by all the accounts together (before thinning). public double TotalProfileOpensPerDay { get; init; } /// Daily budget of profiles opened (full, without gradual start or halving). public int DailyProfileBudget { get; init; } /// Share of the daily profile budget taken by this account, 0–1. public double ShareOfDailyBudget { get; init; } /// All the accounts together ask more than the budget allows. public bool OverBudget { get; init; } public int? BackfillRemainingPosts { get; init; } /// Days the backfill needs (null when the number of posts is not known yet). public int? BackfillDays { get; init; } } /// /// The «Con queste impostazioni» calculator (spec §4.4): a pure function the web layer can call at every change. /// The numbers are estimates from medians; they say «circa». /// public static class AccountPlanCalculator { /// Mean of the next-check jitter (log-normal, median 1, σ 0.25, truncated to [0.6, 1.8]). private const double MeanCheckJitter = 1.03; /// Mean of the story jitter (median 0.75, σ 0.25, truncated to [0.45, 1]). private const double MeanStoryJitter = 0.74; public static AccountPlanEstimate Calculate(AccountPlanInput input) { ArgumentNullException.ThrowIfNull(input); var account = input.Account; var profile = input.Profile; var options = input.Options; var window = CautionProfileRules.WindowLength(profile.WindowStart, profile.WindowEnd); var windowText = $"tra le {Clock(profile.WindowStart)} e le {Clock(profile.WindowEnd)}"; var lines = new List(); var warnings = new List(); var all = input.OtherAccounts.Where(a => a.Id == 0 || a.Id != account.Id).Append(account).ToList(); var contactable = all.Where(CheckPolicy.IsContactable).ToList(); var totalDemand = contactable.Sum(a => ProfileOpensPerDay(a, window, options)); var budget = profile.Budgets.TryGetValue(ActionKind.ProfileOpen, out var b) ? b.PerDay : 0; var overBudget = budget > 0 && totalDemand > budget; var thinning = overBudget ? totalDemand / budget : 1.0; var contacted = CheckPolicy.IsContactable(account); var own = contacted ? ProfileOpensPerDay(account, window, options) : 0; TimeSpan? wanted = null; TimeSpan? every = null; TimeSpan? storyInterval = null; double? storyChecks = null; if (!contacted) { lines.Add(new PlanLine("Controlli", NotContactedText(account))); } else { // New posts. if (CheckPolicy.WantsProfileChecks(account)) { wanted = account.IsFollowed ? CheckPolicy.ProfileCheckInterval(account) : CheckPolicy.VisitInterval(account, window, options.MinimumStoryChecksPerDay); every = TimeSpan.FromTicks((long)(wanted.Value.Ticks * MeanCheckJitter * thinning)); var text = account.IsFollowed ? $"scoperti dal giro dei profili che segui, di norma entro {Minutes(profile.PauseMin)}–{Minutes(profile.PauseMax)} minuti dalla pubblicazione, {windowText}. Il profilo si riapre solo per riconciliare, {ItalianText.Every(Round(every.Value))} circa." : $"controllati {ItalianText.Every(Round(every.Value))} circa, {windowText}."; lines.Add(new PlanLine("Nuovi post", text)); } else { lines.Add(new PlanLine("Nuovi post", "non scaricati con queste impostazioni.")); } // Stories. if (CheckPolicy.WantsStories(account)) { storyInterval = CheckPolicy.StoryInterval(account, window, options.MinimumStoryChecksPerDay); storyChecks = Math.Max(options.MinimumStoryChecksPerDay, 1 + (window / (storyInterval.Value * MeanStoryJitter))); var how = account.IsFollowed && options.SweepCoversFollowedStories ? "a ogni giro dei profili che segui e" : string.Empty; lines.Add(new PlanLine( "Storie", $"controllate {how} almeno {ItalianText.Number(options.MinimumStoryChecksPerDay)} volte al giorno; fra due controlli passano al massimo {ItalianText.Duration(storyInterval.Value)} circa. Restano 24 ore, quindi nessuna dovrebbe scadere prima di essere vista." .Replace(" ", " ", StringComparison.Ordinal))); } else { lines.Add(new PlanLine("Storie", "spente.")); } } // History. var (backfillText, remaining, days) = Backfill(input, all); lines.Add(new PlanLine("Storico", backfillText)); // Weight on the daily budget. var ownAfter = own / thinning; var share = budget > 0 ? ownAfter / budget : 0; lines.Add(new PlanLine( "Carico", contacted ? $"circa {ItalianText.Decimal(ownAfter, ownAfter < 10 ? 1 : 0)} aperture del profilo al giorno, su {ItalianText.Number(budget)} disponibili ogni giorno per tutti gli account." : "nessuno.")); if (overBudget) { warnings.Add( $"Con {ItalianText.Count(contactable.Count, "account", "account")} e queste frequenze servirebbero circa {ItalianText.Number((long)Math.Ceiling(totalDemand))} aperture di profili al giorno, " + $"ma il tetto è {ItalianText.Number(budget)}: i controlli si diradano ({(thinning < 1.15 ? "un po' più radi" : $"circa {ItalianText.Decimal(thinning, 1)} volte più radi")}), non si forzano."); } var sessionsPerDay = SessionsPerDay(profile, window); var homeBudget = profile.Budgets.TryGetValue(ActionKind.Home, out var home) ? home.PerDay : 0; if (contactable.Any(a => a.IsFollowed) && homeBudget > 0 && sessionsPerDay * options.SweepProbability > homeBudget) { warnings.Add($"Il tetto della home ({ItalianText.Number(homeBudget)} al giorno) è più basso del numero di sessioni: alcuni giri dei seguiti salteranno e i nuovi post arriveranno più tardi."); } var rampOver = input.GradualStartSince is { } since && input.Now is { } at && at - since >= TimeSpan.FromDays(profile.RampUpDays); if (profile.GradualStart && profile.RampUpDays > 0 && !rampOver) { warnings.Add($"Con l'avvio graduale, nei primi {ItalianText.Count(profile.RampUpDays, "giorno", "giorni")} dopo il collegamento i tetti partono dalla metà: tutto è più lento."); } return new AccountPlanEstimate { Lines = lines, Warnings = warnings, Contacted = contacted, ProfileCheckWanted = wanted, ProfileCheckEvery = every, StoryInterval = storyInterval, StoryChecksPerDay = storyChecks, ProfileOpensPerDay = ownAfter, TotalProfileOpensPerDay = totalDemand, DailyProfileBudget = budget, ShareOfDailyBudget = share, OverBudget = overBudget, BackfillRemainingPosts = remaining, BackfillDays = days, }; } /// Profile openings per day an account asks for (visits, reconciliations, tagged tab). public static double ProfileOpensPerDay(Account account, TimeSpan window, EngineOptions? options = null) { ArgumentNullException.ThrowIfNull(account); options ??= EngineOptions.Default; if (!CheckPolicy.IsContactable(account)) { return 0; } double visits; if (CheckPolicy.WantsProfileChecks(account)) { var interval = account.IsFollowed ? CheckPolicy.ProfileCheckInterval(account) : CheckPolicy.VisitInterval(account, window, options.MinimumStoryChecksPerDay); visits = ChecksPerDay(interval * MeanCheckJitter, window); } else if (!account.IsFollowed && CheckPolicy.WantsStories(account)) { visits = ChecksPerDay(CheckPolicy.StoryInterval(account, window, options.MinimumStoryChecksPerDay) * MeanStoryJitter, window); } else { visits = 0; } return (account.ContentTypes & ContentTypes.Tagged) != 0 ? visits * 2 : visits; } /// Checks a day at an interval, counting the morning catch-up after the night. public static double ChecksPerDay(TimeSpan interval, TimeSpan window) { if (interval <= TimeSpan.Zero) { return 0; } if (interval >= TimeSpan.FromHours(24)) { return 24 / interval.TotalHours; } return 1 + (window / interval); } /// Sessions a day with median session length and median pause. public static double SessionsPerDay(CautionProfile profile, TimeSpan window) { ArgumentNullException.ThrowIfNull(profile); var session = Math.Sqrt(profile.SessionMin.TotalMinutes * profile.SessionMax.TotalMinutes); var pause = Math.Sqrt(profile.PauseMin.TotalMinutes * profile.PauseMax.TotalMinutes); return window.TotalMinutes / (session + pause); } private static (string Text, int? Remaining, int? Days) Backfill(AccountPlanInput input, List all) { var account = input.Account; var profile = input.Profile; if (account.BackfillCompletedAt is { } done && account.State != AccountState.Backfilling) { return ($"completato il {ItalianText.Day(DateOnly.FromDateTime(done.UtcDateTime))}.", 0, 0); } if (account.Limits.Depth == HistoryDepth.FromDate && account.Limits.FromDate is { } from) { return ($"dipende da quanti post ci sono dopo il {ItalianText.Day(DateOnly.FromDateTime(from.UtcDateTime))}: lo saprò strada facendo.", null, null); } if (account.State is not (AccountState.Backfilling or AccountState.UpToDate) || !CheckPolicy.WantsProfileChecks(account)) { return ("nessuno storico da scaricare con queste impostazioni.", null, null); } int? target = account.Limits.Depth == HistoryDepth.LastPosts ? account.Limits.LastPosts is { } last ? Math.Min(last, account.PostCount ?? last) : account.PostCount : account.PostCount; if (target is null) { return ("il numero dei post non è ancora noto: lo saprò dopo il primo controllo del profilo.", null, null); } var remaining = Math.Max(0, target.Value - input.ArchivedPosts); if (remaining == 0) { return ("tutto già in libreria.", 0, 0); } var sharing = Math.Max(1, all.Count(a => a.State == AccountState.Backfilling && a.BackfillCompletedAt is null && CheckPolicy.IsContactable(a))); var pagesPerDay = profile.Budgets.TryGetValue(ActionKind.BackfillPage, out var pages) ? pages.PerDay : 0; var byBudget = pagesPerDay * input.Options.PostsPerBackfillPage / (double)sharing; var perDay = Math.Min(Math.Min(account.Limits.BackfillPostsPerDay, profile.BackfillPostsPerAccountPerDay), byBudget); if (perDay <= 0) { return ("fermo: il limite di storico al giorno è zero.", remaining, null); } var days = (int)Math.Ceiling(remaining / perDay); var text = $"mancano {ItalianText.Count(remaining, "post", "post")}, servono circa {ItalianText.Count(days, "giorno", "giorni")} ({ItalianText.Number((long)Math.Floor(perDay))} post al giorno" + (sharing switch { <= 1 => string.Empty, 2 => ", a turno con un altro account", _ => $", a turno con altri {ItalianText.Number(sharing - 1)} account" }) + ")."; return (text, remaining, days); } private static string NotContactedText(Account account) => account.State switch { AccountState.ArchiveOnly => "«Solo archivio»: Febe non contatta questo account.", AccountState.Paused => "in pausa: Febe non controlla questo account finché non lo riattivi.", AccountState.Unreachable => "non raggiungibile: Febe non lo contatta finché non lo verifichi.", _ => "Febe non contatta questo account.", }; private static string Clock(TimeOnly time) => time.Hour.ToString(System.Globalization.CultureInfo.InvariantCulture) + ":" + time.Minute.ToString("00", System.Globalization.CultureInfo.InvariantCulture); private static string Minutes(TimeSpan span) => ItalianText.Number((long)Math.Round(span.TotalMinutes)); /// Rounds an interval for display: to 5 minutes under 2 hours, to half an hour above. private static TimeSpan Round(TimeSpan interval) => interval < TimeSpan.FromHours(2) ? TimeSpan.FromMinutes(Math.Max(5, Math.Round(interval.TotalMinutes / 5) * 5)) : TimeSpan.FromMinutes(Math.Round(interval.TotalMinutes / 30) * 30); }