using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using Chronos.Core.Naming;
namespace Chronos.Core.Archiving;
///
/// Why frames of a sequence keep their file names in a Reorganize (owner review 2, R7), nothing of them touched; or, for
/// , why the whole sequence stays as it is.
///
public enum RenameBlock
{
/// Photos adopted in place, outside originals/: they belong to a tree someone else keeps.
InPlace,
/// Photos whose SHA-256 is not known yet (never verified): a verify hashes them first.
Unhashed,
/// Photos whose file is not there.
Missing,
///
/// The sequence's sidecar cannot be read, is of a newer format this build does not rewrite, or belongs to another
/// sequence: the sequence keeps its folder, title and file names, and so does every folder it is inside (0 frames).
///
Unreadable,
}
///
/// Frames of a sequence that keep their names, and why; or, for (0 frames), why the
/// whole sequence stays as it is.
///
public sealed record RenameBlocked(RenameBlock Reason, int Frames);
///
/// One file of a Reorganize: a frame's photo, or a companion that follows it (), from its name to its
/// new one; both relative to the sequence folder, forward slashes.
///
public sealed record FileRename(Guid FrameId, string From, string To, bool Companion = false);
///
/// The file renames of one sequence: every move, companions included, in frame order; how many frames get a new name; the
/// first of them () as samples; and the frames that keep their names.
///
public sealed record FileRenamePlan(IReadOnlyList Moves, int Frames, IReadOnlyList Samples, IReadOnlyList Blocked)
{
public static FileRenamePlan None { get; } = new([], 0, [], []);
/// A digest of every move in order (frame, old and new name, companion or not): two plans with the same one rename the same files the same way.
public string Digest()
{
var text = new StringBuilder();
foreach (var move in Moves) text.Append(CultureInfo.InvariantCulture, $"{move.FrameId:N}|{move.From}|{move.To}|{move.Companion}\n");
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString())));
}
}
///
/// Plans the new file names of a sequence's frames from a file template (Reorganize, owner review 2, R7; BRIEF §7.1, §12.5).
/// Frames are named in index order with the context an upload in capture order is filed with (,
/// which says where filing gave other names); a name already given, or held by a file that stays (a frame left alone, a file
/// no frame lists), gets _2, _3… as filing does, so the same frames, template and folder always give the same
/// names. Only photos under originals/ whose SHA-256 is known and
/// whose file is there are renamed, each within its folder; the XMP companions of a photo follow it
/// (; one named by a stem two frames share follows the first). The sidecar's frame order never
/// changes.
///
public static class FileRenames
{
/// Renamed frames a plan shows as samples.
public const int SampleCount = 3;
private const string Originals = ArchiveLayout.OriginalsFolder + "/";
/// The sequence title the names use ({title}): the new one when the same Reorganize retitles it.
/// Every file in the folders of the sequence's frames, relative to the sequence folder ().
public static FileRenamePlan Plan(SequenceManifest manifest, string? title, PathTemplate template, IReadOnlyCollection present)
{
ArgumentNullException.ThrowIfNull(manifest);
ArgumentNullException.ThrowIfNull(template);
ArgumentNullException.ThrowIfNull(present);
var onDisk = new HashSet(present, StringComparer.OrdinalIgnoreCase);
int inPlace = 0, unhashed = 0, missing = 0;
var eligible = new List();
// Companions are claimed in frame order by every frame, renamed or not: one a frame left alone claims stays with it.
var claimed = new HashSet(StringComparer.OrdinalIgnoreCase);
var companions = new Dictionary>();
// By the name they give without ".xmp": a photo's path without its extension, or its whole path.
var xmp = onDisk.Where(f => f.EndsWith(FrameCompanions.Extension, StringComparison.OrdinalIgnoreCase))
.ToLookup(f => f[..^FrameCompanions.Extension.Length], StringComparer.OrdinalIgnoreCase);
foreach (var frame in manifest.Frames)
{
var own = xmp[Stem(frame.File)].Concat(xmp[frame.File]).Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.Ordinal)
.Where(c => FrameCompanions.Names(c, frame.File) && claimed.Add(c)).ToList();
if (!frame.File.StartsWith(Originals, StringComparison.OrdinalIgnoreCase)) inPlace++;
else if (frame.Sha256 is null) unhashed++;
else if (!onDisk.Contains(frame.File)) missing++;
else
{
eligible.Add(frame);
companions[frame.Id] = own;
}
}
// What stays where it is: files no renamed frame or companion moves away from, and every frame left alone.
var moving = new HashSet(eligible.Select(f => f.File).Concat(companions.Values.SelectMany(c => c)), StringComparer.OrdinalIgnoreCase);
var taken = new HashSet(onDisk.Where(f => !moving.Contains(f)), StringComparer.OrdinalIgnoreCase);
foreach (var frame in manifest.Frames.Where(f => !companions.ContainsKey(f.Id))) taken.Add(frame.File);
var moves = new List();
var samples = new List();
var renamed = 0;
var names = new UniqueNames(taken);
foreach (var frame in eligible)
{
var own = companions[frame.Id];
var tails = own.ConvertAll(c => FrameCompanions.Tail(c, frame.File));
var directory = frame.File[..(frame.File.LastIndexOf('/') + 1)];
var file = names.Claim(directory + template.ExpandFile(FrameNaming.Context(frame, manifest, title)),
candidate => tails.TrueForAll(t => !taken.Contains(Stem(candidate) + t)));
foreach (var tail in tails) taken.Add(Stem(file) + tail);
if (string.Equals(file, frame.File, StringComparison.Ordinal)) continue;
var move = new FileRename(frame.Id, frame.File, file);
moves.Add(move);
if (samples.Count < SampleCount) samples.Add(move);
renamed++;
for (var c = 0; c < own.Count; c++)
{
var to = Stem(file) + tails[c];
if (!string.Equals(to, own[c], StringComparison.Ordinal)) moves.Add(new FileRename(frame.Id, own[c], to, Companion: true));
}
}
var blocked = new List();
if (inPlace > 0) blocked.Add(new RenameBlocked(RenameBlock.InPlace, inPlace));
if (unhashed > 0) blocked.Add(new RenameBlocked(RenameBlock.Unhashed, unhashed));
if (missing > 0) blocked.Add(new RenameBlocked(RenameBlock.Missing, missing));
return new FileRenamePlan(moves, renamed, samples, blocked);
}
///
/// Every file in the folders that hold the sequence's frames (originals/ as a rule), relative to the sequence
/// folder; hidden files included, so no name a file holds is ever given.
///
public static IReadOnlyList ListPresent(SequencePaths sequence, SequenceManifest manifest)
{
ArgumentNullException.ThrowIfNull(sequence);
ArgumentNullException.ThrowIfNull(manifest);
var files = new List();
foreach (var prefix in manifest.Frames.Select(f => f.File[..(f.File.LastIndexOf('/') + 1)]).Distinct(StringComparer.OrdinalIgnoreCase))
{
var directory = prefix.Length == 0 ? sequence.Folder : sequence.File(prefix.TrimEnd('/'));
// Listed as the trash lists companions (FrameCompanions), so both find the same XMP files.
files.AddRange(FrameCompanions.List(directory).Select(n => prefix + n));
}
return files;
}
/// A file's path without its extension (originals/2026-09-28_0001).
private static string Stem(string file) => file[..^Path.GetExtension(file).Length];
}