using Titano.Core.Model;
using Titano.Data.Jobs;
using Titano.Data.Repositories;
namespace Titano.Data.Processing;
///
/// Light analysis queued after work that brings sequences or frames into the index (card import, adoption, scan), so the
/// advisor's Auto values and recommended preset exist without any user action (BRIEF §1.1, §4.3). Nothing is queued
/// when the engine cannot run light analysis, and a sequence already waiting in a queued light analysis is not queued
/// again (that job runs after the changes that led here).
///
internal static class AnalysisFollowUp
{
/// Queues one light analysis of (labelled like the job that found them).
public static async Task QueueAsync(TitanoDatabase db, JobContext context, IReadOnlyCollection sequenceIds)
{
if (sequenceIds.Count == 0) return;
var waiting = (await db.Jobs.ListQueuedAsync([JobKind.LightAnalyse], 1000, context.Cancellation).ConfigureAwait(false))
.SelectMany(j => j.TargetIds).ToHashSet();
var targets = sequenceIds.Where(id => !waiting.Contains(id)).Distinct().ToList();
if (targets.Count == 0) return;
var request = ProcessingJobs.LightAnalysis(targets, context.Job.TargetLabel);
await context.EnqueueFollowUpAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority).ConfigureAwait(false);
}
/// Sequences of without a current light analysis (new, adopted, or with frames a scan added).
public static async Task> UnanalysedAsync(TitanoDatabase db, Guid archiveId, CancellationToken cancellationToken)
{
var ids = new List();
var query = new SequenceQuery { ArchiveId = archiveId, WithoutStatus = SequenceStatus.AnalyzedLight, Sort = SequenceSort.Oldest, Limit = 1000 };
do
{
var page = await db.Sequences.ListAsync(query, cancellationToken).ConfigureAwait(false);
ids.AddRange(page.Items.Select(s => s.Id));
query = query with { Cursor = page.NextCursor };
}
while (query.Cursor is not null);
return ids;
}
}