using Chronos.Core.Model;
using Chronos.Data.Repositories;
using Chronos.Data.Sync;
using Chronos.Protocol;
namespace Chronos.Data.Copies;
/// One photo a sequence keeps in two versions: each version's frame, file name and SHA-256.
public sealed record PhotoVersions(Guid FirstFrameId, string FirstFileName, string FirstSha256, Guid SecondFrameId, string SecondFileName, string SecondSha256)
{
/// The photo's capture instant (both versions share it).
public DateTime? CapturedAt { get; init; }
public long FirstSize { get; init; }
public long SecondSize { get; init; }
}
///
/// The two sides of a comparison as reads them (owner review 6, #73; design §4.2): a local
/// sequence's frames and tombstones, a server sequence's manifest with its frames' capture times, and the last-copy check
/// the planners make before anything goes to a trash.
///
public sealed class CopySides(ChronosDatabase db)
{
/// Frames whose file holds nothing usable: the other side's copy repairs them.
public const FrameFlags UnusableFlags = FrameFlags.Missing | FrameFlags.Corrupt;
/// Parameters per statement of .
private const int Batch = 500;
private readonly ChronosDatabase _db = db ?? throw new ArgumentNullException(nameof(db));
private readonly DbAccess _access = new(db.Database);
/// A local sequence: every frame row in index order and its tombstones ().
public async Task LocalAsync(Guid id, CancellationToken ct)
{
var frames = await Processing.SequenceFrames.ListAsync(_db, id, ct).ConfigureAwait(false);
var removals = await _db.FrameRemovals.ListBySequenceAsync(id, ct).ConfigureAwait(false);
return new CopySideInput(
[.. frames.Select(f => new CopyPhotoInput(f.Id, f.Index, f.FileName, f.Sha256, f.Size, f.CapturedAt, (f.Flags & UnusableFlags) != 0))],
SyncTombstones.ToDto(removals));
}
///
/// A server sequence: its manifest (content, flags, tombstones) with the capture times of its frame rows (the manifest
/// has none). A frame the listing no longer has keeps no capture time.
///
public async Task RemoteAsync(ISyncRemote remote, Guid id, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(remote);
var manifest = await remote.GetManifestAsync(id, ct).ConfigureAwait(false);
var rows = await remote.ListFramesAsync(id, ct).ConfigureAwait(false);
var captured = new Dictionary(rows.Count);
foreach (var row in rows) captured[row.Id] = row.CapturedAt;
return new CopySideInput(
[.. manifest.Frames.Select(f => new CopyPhotoInput(f.Id, f.Index, f.FileName, f.Sha256.Length == 0 ? null : f.Sha256, f.Size,
captured.GetValueOrDefault(f.Id), (f.Flags & (long)UnusableFlags) != 0))],
manifest.Removed ?? []);
}
///
/// The photos one sequence keeps in two versions (owner Q3, design §4.1 Versions): a sub-second capture instant holding
/// exactly two usable, hashed frames of different content, as a Union merge or Integrate leaves them. Read from the
/// frames themselves, so they stay listed after the pair that made them is gone; each pair once, in index order.
///
public async Task> VersionsAsync(Guid sequenceId, CancellationToken ct)
{
var frames = await Processing.SequenceFrames.ListAsync(_db, sequenceId, ct).ConfigureAwait(false);
var result = new List();
foreach (var group in frames.Where(f => (f.Flags & UnusableFlags) == 0 && f.Sha256 is { Length: > 0 } && f.CapturedAt is not null)
.GroupBy(f => CopyComparer.Millisecond(f.CapturedAt!.Value)))
{
if (group.Key % 1000 == 0) continue;
var versions = group.DistinctBy(f => f.Sha256!.ToLowerInvariant(), StringComparer.Ordinal).OrderBy(f => f.Index).ToList();
if (versions.Count != 2 || group.Count() != 2) continue;
result.Add(new PhotoVersions(versions[0].Id, versions[0].FileName, versions[0].Sha256!.ToLowerInvariant(),
versions[1].Id, versions[1].FileName, versions[1].Sha256!.ToLowerInvariant())
{
CapturedAt = versions[0].CapturedAt,
FirstSize = versions[0].Size,
SecondSize = versions[1].Size,
});
}
return [.. result.OrderBy(v => frames.First(f => f.Id == v.FirstFrameId).Index)];
}
///
/// The raw SHA-256 (lower-case) of that a usable frame (not Missing or Corrupt) of any sequence
/// of this index other than holds: what is not the last copy of its photo. Batched.
///
public async Task> HeldElsewhereAsync(IReadOnlyCollection sha256, IReadOnlyCollection except, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(sha256);
ArgumentNullException.ThrowIfNull(except);
var held = new HashSet(StringComparer.Ordinal);
var wanted = sha256.Where(s => !string.IsNullOrEmpty(s)).Select(s => s.ToLowerInvariant()).Distinct(StringComparer.Ordinal).ToList();
var excluded = except.Distinct().ToList();
foreach (var chunk in wanted.Chunk(Math.Max(1, Batch - excluded.Count)))
{
var p = new SqlParameters();
var not = excluded.Count == 0 ? string.Empty : $" AND sequence_id NOT IN ({string.Join(", ", excluded.Select(id => p.Add(id)))})";
var hashes = string.Join(", ", chunk.Select(sha => p.Add(sha)));
var rows = await _access.ListAsync(
$"SELECT DISTINCT sha256 FROM frames WHERE sha256 IN ({hashes}) AND (flags & {(int)UnusableFlags}) = 0{not}",
p.ToArray(), r => r.GetString(0), ct).ConfigureAwait(false);
foreach (var sha in rows) held.Add(sha.ToLowerInvariant());
}
return held;
}
}