using System.Text.Json;
using System.Text.Json.Nodes;
using Titano.Core.Archiving;
using Titano.Core.Diagnostics;
using Titano.Core.IO;
using Titano.Core.Model;
using Titano.Core.Project;
namespace Titano.Data.Archiving;
///
/// Keeps a project's frame positions (exclusions, hero, virtual-camera keyframes; BRIEF §5, §7) on their frames when the
/// index takes a sidecar in which frames were inserted before others: an upload or import of earlier photos, photos a
/// scan found, a sync download, a journalled batch completed after a crash. Positions name the frames in the indexed
/// order (what editors, renders and the API read), so the old order comes from the index rows. Only an insertion is
/// followed: when an indexed frame is no longer in the sidecar, positions cannot be mapped and stay as they are. The move
/// is part of the frames change, not a settings edit, so the settings version stays. Settings synced from another copy
/// arrive translated to this copy's frames (); their positions on
/// photos that were not here yet () take their place when the photos arrive,
/// wherever they land.
///
internal static class ProjectPositions
{
///
/// The index's copy of the project (the one in force) with its positions moved to the order of
/// and its pending frames placed; null when nothing changes. A project.json the
/// index has no copy of was written by another process against its own frames, so it is left to that writer.
///
public static async Task MoveAsync(TitanoRepositories db, Sequence indexed, SequenceManifest manifest,
CancellationToken cancellationToken)
{
// The sidecar's frames are the ones indexed: nothing was inserted.
if (indexed.FramesVersion == manifest.Versions.Frames) return null;
if (indexed.SettingsJson is not { } project) return null;
var rows = await db.Frames.ListPositionsAsync(indexed.Id, cancellationToken).ConfigureAwait(false);
var now = new Dictionary(manifest.Frames.Count);
foreach (var frame in manifest.Frames) now[frame.Id] = frame.I;
Dictionary? moves = [];
foreach (var row in rows)
{
if (!now.TryGetValue(row.FrameId, out var index))
{
moves = null;
break;
}
if (index != row.Index) moves[row.Index] = index;
}
return Placed(project, moves is null ? null : ProjectSettings.MoveFramePositions(project, moves), manifest);
}
///
/// The index's copy of the project with the pending frames whose photos now holds put in
/// place: frames appended in step with the index, which moves no position. Null when nothing changes.
///
public static PositionMove? Place(Sequence indexed, SequenceManifest manifest) =>
indexed.SettingsJson is { } project ? Placed(project, null, manifest) : null;
private static PositionMove? Placed(string before, string? moved, SequenceManifest manifest)
{
var current = moved ?? before;
// Most projects wait for no photo: the sidecar's photos are gathered only for those that do.
var placed = current.Contains("pendingFrames", StringComparison.OrdinalIgnoreCase)
? ProjectSettings.TranslateFramePositions(current, null, new FramePhotos(manifest.Frames.Select(f => (f.I, new FramePhoto(f.Sha256, f.Size, f.CapturedAt)))))
: null;
if ((placed ?? moved) is not { } after) return null;
// A hero that waited for its photo names a frame the Library shows too.
var hero = placed is not null && HeroOf(current) is null && HeroOf(placed) is { } index ? manifest.Frames.FirstOrDefault(f => f.I == index)?.Id : null;
return new PositionMove(before, after, hero);
}
private static int? HeroOf(string json)
{
try
{
return JsonNode.Parse(json, new JsonNodeOptions { PropertyNameCaseInsensitive = true }) is JsonObject project
&& project["heroFrame"] is JsonValue value && value.TryGetValue(out var hero)
? hero
: null;
}
catch (Exception ex) when (ex is JsonException or ArgumentException)
{
return null;
}
}
///
/// Mirrors moved positions into project.json once the index holds them, unless the file was written since
/// (it then belongs to that writer, whose next save mirrors the index again). A failed write leaves the index right.
///
public static void WriteProject(SequencePaths sequence, string before, string moved)
{
try
{
if (File.Exists(sequence.ProjectPath) && !SameJson(File.ReadAllText(sequence.ProjectPath), before)) return;
Directory.CreateDirectory(sequence.MetaDirectory);
AtomicFile.WriteAllText(sequence.ProjectPath, moved);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("archive", $"Project of {sequence.RelativeFolder} keeps its old frame positions on disk", ex);
}
}
/// Same JSON content whatever the layout (an index may store it normalised).
private static bool SameJson(string a, string b)
{
try
{
return JsonNode.DeepEquals(JsonNode.Parse(a), JsonNode.Parse(b));
}
catch (JsonException)
{
return false;
}
}
}
///
/// A project whose positions followed its frames: the index's copy before and after, and the frame a hero that waited
/// for its photo now names (the index's hero frame follows it); null when the hero frame stays.
///
internal sealed record PositionMove(string Before, string Moved, Guid? HeroFrameId)
{
/// The index row with the moved project.
public Sequence ApplyTo(Sequence row) => row with { SettingsJson = Moved, HeroFrameId = HeroFrameId ?? row.HeroFrameId };
}