namespace Titano.Uploader.Watching;
/// Size and last-write time of a file at one check.
public readonly record struct FileObservation(string Path, long Size, DateTime ModifiedUtc);
///
/// Decides when a file in a watch folder has stopped growing: it is reported once its size and write time were
/// identical in consecutive checks, then forgotten (the caller enqueues it).
///
public sealed class StableFileTracker
{
public const int RequiredChecks = 2;
private readonly Dictionary _seen = new(StringComparer.OrdinalIgnoreCase);
/// Files seen but not yet stable.
public int PendingCount => _seen.Count;
///
/// Records a complete scan: returns the files that are now stable and forgets files missing from the scan.
///
public IReadOnlyList Check(IEnumerable scan)
{
var present = new HashSet(StringComparer.OrdinalIgnoreCase);
var stable = new List();
foreach (var o in scan)
{
present.Add(o.Path);
if (Observe(o)) stable.Add(o);
}
foreach (var path in _seen.Keys.Where(p => !present.Contains(p)).ToList()) _seen.Remove(path);
return stable;
}
/// Records one observation; true when the file just became stable.
public bool Observe(FileObservation o)
{
var count = _seen.TryGetValue(o.Path, out var last) && last.Size == o.Size && last.Modified == o.ModifiedUtc ? last.Count + 1 : 1;
if (count >= RequiredChecks)
{
_seen.Remove(o.Path);
return true;
}
_seen[o.Path] = (o.Size, o.ModifiedUtc, count);
return false;
}
}