using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Titano.Uploader.Sources;
/// The last session of a source, so later files within the gap join it (watch folders).
public sealed record SessionContinuation(string Key, DateTime LastCapture);
/// Session key per input frame (input order) and the session the next batch may continue.
public sealed record SessionAssignment(IReadOnlyList Keys, SessionContinuation? Last);
///
/// Splits frames of one source into shooting sessions with the card-import rules (BRIEF ยง13): a gap longer than
/// starts a session; sessions with fewer than frames (test shots) merge
/// into the previous session, or into the next one when they come first. The server turns each key into a sequence.
///
public static class SessionGrouper
{
/// SessionGapMinutes default.
public static readonly TimeSpan Gap = TimeSpan.FromMinutes(45);
/// MinimumSessionFrames default.
public const int MinimumFrames = 8;
/// Groups ; keys start with so sources never collide.
public static SessionAssignment Assign(IReadOnlyList captureTimes, string sourceTag, SessionContinuation? previous = null)
{
if (captureTimes.Count == 0) return new SessionAssignment([], previous);
var order = Enumerable.Range(0, captureTimes.Count).OrderBy(i => captureTimes[i]).ToArray();
// Split on gaps; a group that continues the previous batch keeps its key and is never "small".
var groups = new List();
var current = new Group { Continues = previous is not null && (captureTimes[order[0]] - previous.LastCapture).Duration() <= Gap };
for (var n = 0; n < order.Length; n++)
{
var i = order[n];
if (n > 0 && captureTimes[i] - captureTimes[order[n - 1]] > Gap)
{
groups.Add(current);
current = new Group();
}
current.Members.Add(i);
}
groups.Add(current);
var merged = new List();
foreach (var g in groups)
{
if (merged.Count > 0 && g.Members.Count < MinimumFrames) merged[^1].Members.AddRange(g.Members);
else merged.Add(g);
}
if (merged.Count > 1 && merged[0].Members.Count < MinimumFrames && !merged[0].Continues)
{
merged[0].Members.AddRange(merged[1].Members);
merged.RemoveAt(1);
}
var keys = new string[captureTimes.Count];
string? lastKey = null;
foreach (var g in merged)
{
var first = g.Members.Min(i => captureTimes[i]);
lastKey = g.Continues ? previous!.Key : Key(sourceTag, first);
foreach (var i in g.Members) keys[i] = lastKey;
}
var lastCapture = captureTimes[order[^1]];
if (previous is not null && previous.LastCapture > lastCapture && merged[^1].Continues) lastCapture = previous.LastCapture;
return new SessionAssignment(keys, new SessionContinuation(lastKey!, lastCapture));
}
/// Short stable tag for a source folder: 8 hex digits of the SHA-256 of its normalised path.
public static string SourceTag(string root)
{
var normalized = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)).ToUpperInvariant();
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(normalized)))[..8];
}
/// {tag}-{yyyyMMdd-HHmmss} of the session's first frame.
public static string Key(string sourceTag, DateTime firstCapture) =>
sourceTag + "-" + firstCapture.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture);
private sealed class Group
{
public List Members { get; } = [];
public bool Continues { get; init; }
}
}