using System.Text.Json;
using Chronos.Core.Diagnostics;
using Chronos.Core.IO;
namespace Chronos.Core.Archiving;
/// One file of a photo deletion: where it was in the sequence folder and where it went in the archive's trash.
/// Path relative to the sequence folder (forward slashes).
/// Path relative to the archive root (forward slashes), inside the trash entry.
public sealed record FrameRemovalMove(string From, string To);
///
/// Write-ahead record of a photo deletion (.chronos/remove.pending.json, owner review 2, R6): the trash entry the
/// photos move into, the frames leaving the sidecar and every file move. Written before the first move and removed once
/// sequence.json no longer lists the frames, so a crash in between is undone by : the files go
/// back to their places, the entry's record and folder go, and the sequence is as it was. Until the sidecar is written
/// the entry's record has its name, which the trash never lists, so half an entry can be
/// neither restored nor emptied.
///
/// The entry's record, relative to the archive root (its name once the deletion is complete).
/// The entry's folder, relative to the archive root.
public sealed record FrameRemovalJournal(string Record, string Folder, IReadOnlyList Frames, IReadOnlyList Moves)
{
/// The name a deletion's record has until its sidecar is written.
public static string PendingRecord(string record) => record + ".pending";
public static void Write(SequencePaths sequence, FrameRemovalJournal journal)
{
ArgumentNullException.ThrowIfNull(sequence);
Directory.CreateDirectory(sequence.MetaDirectory);
AtomicFile.WriteAllBytes(sequence.RemovalJournalPath, JsonSerializer.SerializeToUtf8Bytes(journal, ArchiveJson.Default.FrameRemovalJournal));
}
public static void Delete(SequencePaths sequence)
{
ArgumentNullException.ThrowIfNull(sequence);
if (File.Exists(sequence.RemovalJournalPath)) File.Delete(sequence.RemovalJournalPath);
}
///
/// Undoes a deletion a crash interrupted before its sidecar was written: while still lists a
/// frame of the journal, each file that reached the trash moves back (one whose place is taken again stays in the trash,
/// logged, and so does the entry then, listed under its record's own name), and the entry's record and its emptied
/// folder go. A deletion whose sidecar was written is complete: its record takes its own name, and the journal goes.
/// Returns whether a deletion was undone. The caller holds the lease.
///
public static bool Recover(SequencePaths sequence, SequenceManifest manifest)
{
ArgumentNullException.ThrowIfNull(sequence);
ArgumentNullException.ThrowIfNull(manifest);
if (!File.Exists(sequence.RemovalJournalPath)) return false;
FrameRemovalJournal? journal;
try
{
journal = JsonSerializer.Deserialize(AtomicFile.ReadAllBytes(sequence.RemovalJournalPath), ArchiveJson.Default.FrameRemovalJournal);
}
catch (JsonException)
{
journal = null; // torn while being written: nothing was moved yet
}
var undone = false;
var archive = sequence.Archive;
if (journal is not null && manifest.Frames.Any(f => journal.Frames.Contains(f.Id)))
{
var kept = 0;
foreach (var move in journal.Moves)
{
var trashed = archive.FromRelative(move.To);
var place = sequence.File(move.From);
if (!File.Exists(trashed)) continue;
if (File.Exists(place))
{
kept++;
Log.Warning("archive", $"{sequence.ArchiveRelative(move.From)} is there again; its deleted copy stays in {move.To}");
continue;
}
Directory.CreateDirectory(Path.GetDirectoryName(place)!);
File.Move(trashed, place, overwrite: false);
}
var record = archive.FromRelative(journal.Record);
if (kept == 0)
{
if (File.Exists(record)) File.Delete(record);
if (File.Exists(PendingRecord(record))) File.Delete(PendingRecord(record));
RemoveEmpty(archive.FromRelative(journal.Folder));
}
else
{
// What stays in the trash is listed, restorable and erasable like any entry.
Publish(record);
}
Log.Warning("archive", $"An interrupted photo deletion in {sequence.RelativeFolder} was undone");
undone = true;
}
else if (journal is not null)
{
Publish(archive.FromRelative(journal.Record));
}
Delete(sequence);
return undone;
}
/// Gives a deletion's record its own name (), once its photos are out of the sidecar.
public static void Publish(string record)
{
var pending = PendingRecord(record);
if (File.Exists(pending) && !File.Exists(record)) File.Move(pending, record, overwrite: false);
}
/// Removes and its subfolders when they hold no file.
public static void RemoveEmpty(string folder)
{
if (!Directory.Exists(folder)) return;
foreach (var child in Directory.EnumerateDirectories(folder)) RemoveEmpty(child);
if (!Directory.EnumerateFileSystemEntries(folder).Any()) Directory.Delete(folder);
}
}