namespace Chronos.Core.Import;
/// A run of consecutive frames forming one session: [Start, Start + Count).
public readonly record struct SessionRange(int Start, int Count)
{
public int End => Start + Count;
}
///
/// Splits a time-ordered run of captures into shooting sessions (BRIEF ยง13): a pause longer than the gap starts a
/// new session; a session with fewer than the minimum frames (test shots) merges into the previous one, or into the
/// next when it comes first. Breaks the user forced are never merged away; breaks the user removed never split.
///
public static class SessionSplitter
{
/// Capture times in ascending order.
/// For a frame index: true = the user starts a session there, false = the user joined it
/// to the previous frame, null = automatic.
public static IReadOnlyList Split(IReadOnlyList times, TimeSpan gap, int minimumFrames, Func? userBreak = null)
{
if (times.Count == 0) return [];
var groups = new List<(int Start, int Count, bool Forced)>();
var start = 0;
var forced = false;
for (var i = 1; i < times.Count; i++)
{
var decision = userBreak?.Invoke(i);
if (decision == false || (decision is null && times[i] - times[i - 1] <= gap)) continue;
groups.Add((start, i - start, forced));
start = i;
forced = decision == true;
}
groups.Add((start, times.Count - start, forced));
for (var i = 0; i < groups.Count && groups.Count > 1;)
{
var g = groups[i];
if (g.Count >= minimumFrames)
{
i++;
continue;
}
if (i > 0 && !g.Forced)
{
var previous = groups[i - 1];
groups[i - 1] = (previous.Start, previous.Count + g.Count, previous.Forced);
groups.RemoveAt(i);
}
else if (i == 0 && !groups[1].Forced)
{
groups[1] = (g.Start, g.Count + groups[1].Count, g.Forced);
groups.RemoveAt(0);
}
else
{
i++;
}
}
return groups.ConvertAll(g => new SessionRange(g.Start, g.Count));
}
}