using System.Collections; using System.Reflection; using System.Security.Cryptography; using System.Text.Json; using System.Text.Json.Nodes; using PlotLine.Models; namespace PlotLine.Services; public static class BookBackupGraph { public static readonly JsonSerializerOptions Json = new() { PropertyNameCaseInsensitive = true }; internal static readonly HashSet Common = new(StringComparer.Ordinal) { "StoryIntelligenceIllustrationDemands", "Characters", "CharacterAliases", "CharacterImages", "CharacterAttributeTypes", "CharacterRelationships", "Locations", "LocationAliases", "LocationRelationships", "FloorPlans", "FloorPlanFloors", "FloorPlanBlocks", "FloorPlanTransitions", "StoryMaps", "MapFeatures", "MapRelationships", "MapReferenceImages", "PlotLines", "PlotThreads", "StoryAssets", "AssetAliases", "AssetStates", "AssetDependencies", "SceneMetricTypes", "TimelineSettings", "TimelineMetricSettings", "GenreMetricPresets", "GenreMetricPresetMetrics" }; internal static readonly Dictionary Aliases = new() { ["TimelineSettings"] = "ProjectTimelineSettings", ["TimelineMetricSettings"] = "ProjectTimelineMetricSettings", ["AssetCustodyCharacters"] = "AssetCustodyEventCharacters" }; internal static string Table(string collection) => Aliases.GetValueOrDefault(collection, collection); internal static object[] Rows(ProjectBackupExport b, string c) => ((IEnumerable)typeof(ProjectBackupData).GetProperty(c)!.GetValue(b.Data)!).Cast().ToArray(); internal static object? Value(object row, string field) => row.GetType().GetProperty(field)?.GetValue(row); internal static string? Identity(string c) => ProjectBackupGraphValidation.Entities.FirstOrDefault(e => e.Collection == c)?.Identity; internal static void SetRows(ProjectBackupExport b, string c, IEnumerable rows) { var p = typeof(ProjectBackupData).GetProperty(c)!; var type = p.PropertyType.GetGenericArguments()[0]; var list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(type))!; foreach (var r in rows) list.Add(r); p.SetValue(b.Data, list); } public static string Hash(object value) => Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(value))); public static ProjectBackupExport Clone(ProjectBackupExport b) => JsonSerializer.Deserialize(JsonSerializer.Serialize(b), Json)!; public static ProjectBackupExport Select(ProjectBackupExport source, IEnumerable selected, Guid origin = default) { var b = Clone(source); var books = selected.Distinct().ToHashSet(); if (books.Count == 0 || books.Any(id => !b.Data.Books.Any(x => x.BookID == id))) throw new ArgumentException("Choose books contained in this backup."); SetRows(b, "Books", b.Data.Books.Where(x => books.Contains(x.BookID))); var schema = ProjectBackupGraphValidation.Entities; // Ownership is rooted in books. Shared definitions stay complete; book-specific children follow their parent. var owned = new HashSet { "Books" }; bool changed = true; while (changed) { changed = false; foreach (var e in schema) if (!Common.Contains(e.Collection) && e.Links.Any(l => owned.Contains(l.TargetCollection))) changed |= owned.Add(e.Collection); } var priority = new[] { "BookID", "ChapterID", "ReviewCandidateID", "ReviewCandidateGenerationID", "CharacterEnrichmentRunID", "WholeBookPlotSynthesisRunID", "ImportSessionID", "BuildID", "WritingPlanID", "ScenarioID", "StoryMemoryCharacterID", "StoryMemoryLocationID", "StoryMemoryAssetID", "StoryIntelligenceRunID", "SceneResultID", "SceneID" }; for (var pass = 0; pass < schema.Length; pass++) { var removed = false; foreach (var e in schema.Where(e => owned.Contains(e.Collection) && e.Collection != "Books")) { var owners = e.Links.Where(l => owned.Contains(l.TargetCollection)).OrderBy(l => Array.IndexOf(priority, l.Column) < 0 ? 999 : Array.IndexOf(priority, l.Column)).ToArray(); if (owners.Length == 0) continue; var rows = Rows(b, e.Collection); var keep = rows.Where(row => { var owner = owners.FirstOrDefault(l => Value(row, l.Column) != null); return owner == null || Rows(b, owner.TargetCollection).Any(target => Equals(Value(target, owner.TargetColumn), Value(row, owner.Column))); }).ToArray(); if (keep.Length != rows.Length) { SetRows(b, e.Collection, keep); removed = true; } } if (!removed) break; } var scenes = b.Data.Scenes.Select(s => s.SceneID).ToHashSet(); if (source.Data.SceneDependencies.Any(d => scenes.Contains(d.SourceSceneID) != scenes.Contains(d.TargetSceneID))) throw new ArgumentException("These books have a cross-book scene dependency. Include the connected books to preserve it."); if (source.Data.MapJourneyNotes.Any(n => scenes.Contains(n.FromSceneID) != scenes.Contains(n.ToSceneID))) throw new ArgumentException("A saved map journey connects these books. Include the connected books to preserve it."); b.Recovery.ExternalReferences = b.Recovery.ExternalReferences.Where(r => Identity(r.Collection) is string identity && Rows(b, r.Collection).Any(owner => Equals(Value(owner, identity), r.OwnerID))).ToList(); // Never turn an excluded source number into a destination reference. Refuse rather than dropping canonical links. foreach (var entity in schema.Where(e => Common.Contains(e.Collection) && e.Identity != null)) foreach (var link in entity.Links.Where(l => owned.Contains(l.TargetCollection))) { var allowed = Rows(b, link.TargetCollection).Select(r => Value(r, link.TargetColumn)).ToHashSet(); foreach (var row in Rows(b, entity.Collection)) if (Value(row, link.Column) is object value && !allowed.Contains(value)) { var property = row.GetType().GetProperty(link.Column)!; if (Value(row, entity.Identity!) is not int id || origin == Guid.Empty) throw new ArgumentException("A common definition requires another book. Include the related books."); if (!b.Recovery.ExternalReferences.Any(r => r.Collection == entity.Collection && r.OwnerID == id && r.Field == link.Column && r.BindingRequired)) { b.Recovery.ExternalReferences.RemoveAll(r => r.Collection == entity.Collection && r.OwnerID == id && r.Field == link.Column); b.Recovery.ExternalReferences.Add(new(entity.Collection, id, link.Column, $"{origin:N}/{link.TargetCollection}/{value}", Nullable.GetUnderlyingType(property.PropertyType) == null)); } if (Nullable.GetUnderlyingType(property.PropertyType) != null) property.SetValue(row, null); } } var retainedPresets = new List(); foreach (var preset in b.Data.TimelineViewPresets.ToArray()) { SetRows(b, "TimelineViewPresets", [preset]); if (ProjectBackupTimelineState.Validate(b) == null) retainedPresets.Add(preset); else if (ProjectBackupTimelineState.Validate(source) != null) throw new ArgumentException("A source timeline preset is invalid; repair it before backing up."); } SetRows(b, "TimelineViewPresets", retainedPresets); var error = ProjectBackupMapValidation.Validate(b) ?? ProjectBackupGraphValidation.Validate(b, true); if (error != null) throw new ArgumentException("The selection has a dependency outside these books. Include the related books. " + error); b.Recovery.NativeReviews = b.Recovery.NativeReviews.Where(r => books.Contains(r.BookID)).ToList(); b.Recovery.IntentAssessments = b.Recovery.IntentAssessments.Where(r => scenes.Contains(r.SceneID)).ToList(); SetRows(b, "ProjectAccess", []); SetRows(b, "UserFiles", []); ProjectBackupFiles.Prune(b); return b; } public static string StoredHash(string collection, object row) { var fields = ProjectBackupStoredFieldContract.Columns(collection); if (fields.Length == 0) return Hash(row); var node = JsonSerializer.SerializeToNode(row)!.AsObject(); foreach (var key in node.Select(p => p.Key).ToArray()) if (!fields.Contains(key, StringComparer.OrdinalIgnoreCase)) node.Remove(key); foreach(var property in row.GetType().GetProperties().Where(p=>node.ContainsKey(p.Name))){var value=property.GetValue(row);if(value is DateTime date)node[property.Name]=JsonSerializer.SerializeToNode(DateTime.SpecifyKind(date,DateTimeKind.Unspecified));else if(value is decimal number)node[property.Name]=JsonNode.Parse(number.ToString("G29",System.Globalization.CultureInfo.InvariantCulture));} return Hash(node); } internal static void Merge(ProjectBackupExport destination, ProjectBackupExport incoming) { foreach (var p in typeof(ProjectBackupData).GetProperties()) { if (p.Name is "ProjectAccess" or "UserFiles" or "GenreMetricPresets" or "GenreMetricPresetMetrics" or "TimelineSettings") continue; var original = Rows(destination, p.Name); var next = Rows(incoming, p.Name); var key = Identity(p.Name); if (key != null) { var keys = original.ToDictionary(r => Value(r, key)!); foreach (var row in next) if (keys.TryGetValue(Value(row, key)!, out var prior) && StoredHash(p.Name, prior) != StoredHash(p.Name, row)) throw new ArgumentException("A destination identity conflict was detected; nothing was overwritten."); next = next.Where(r => !keys.ContainsKey(Value(r, key)!)).ToArray(); } if (p.Name == "TimelineMetricSettings") next = next.Where(r => !original.Any(o => Equals(Value(o, "ProjectID"), Value(r, "ProjectID")) && Equals(Value(o, "MetricTypeID"), Value(r, "MetricTypeID")))).ToArray(); SetRows(destination, p.Name, original.Concat(next).DistinctBy(r => StoredHash(p.Name, r))); } destination.Recovery.ExternalReferences.AddRange(incoming.Recovery.ExternalReferences); destination.Recovery.NativeReviews.AddRange(incoming.Recovery.NativeReviews); destination.Recovery.IntentAssessments.AddRange(incoming.Recovery.IntentAssessments); } public static void RemapState(ProjectBackupExport b, Dictionary> maps, int user) { int Id(string type, int old) => maps.TryGetValue(type, out var rows) && rows.TryGetValue(old, out var value) ? value : throw new ArgumentException("Recovery state has an unresolved " + type + " reference."); string Key(string key) => key.StartsWith("checklist-", StringComparison.Ordinal) && int.TryParse(key[10..], out var old) ? maps.TryGetValue("SceneChecklistItems", out var ids) && ids.TryGetValue(old, out var mapped) ? "checklist-" + mapped : "historical-" + key : key; var manuscripts = new Dictionary<(Guid, int), Guid>(); foreach (var review in b.Recovery.NativeReviews) { var original = review.CreatedUtc;var sourceUser=review.UserID; review.BookID = Id("Books", review.BookID); review.UserID = user; var originalReview = review.ReviewID; review.ReviewID = Guid.NewGuid(); var manuscriptKey = (review.ManuscriptID, review.BookID); if (!manuscripts.TryGetValue(manuscriptKey, out var manuscript)) manuscripts[manuscriptKey] = manuscript = Guid.NewGuid(); review.ManuscriptID = manuscript; review.CreatedUtc = DateTime.UtcNow; var result = JsonNode.Parse(review.ResultJson)!.AsObject(); if(result["RecoverySourceUserID"]==null)result["RecoverySourceUserID"]=sourceUser;result["RecoverySourceReviewID"] = originalReview; result["RecoveryOriginalCreatedUtc"] = original; result["RequestId"] = review.ReviewID; result["ReviewPath"] = "/native-companion/reviews/" + review.ReviewID; review.ResultJson = result.ToJsonString(); if (review.SourceJson != null) { var capture = JsonSerializer.Deserialize(review.SourceJson, Json) ?? throw new ArgumentException("Invalid review source"); capture.BookId = review.BookID; capture.ManuscriptId = review.ManuscriptID; capture.SessionId = Guid.Empty; capture.RequestId = review.ReviewID; review.SourceJson = JsonSerializer.Serialize(capture); } } b.Recovery.ExternalReferences = b.Recovery.ExternalReferences.Select(r => r with { OwnerID = Id(Table(r.Collection), r.OwnerID), BindingRequired = false }).ToList(); foreach (var assessment in b.Recovery.IntentAssessments) { var sourceUser=assessment.UserID;assessment.UserID = user; assessment.SceneID = Id("Scenes", assessment.SceneID); var originalHash = assessment.InputHash; assessment.InputHash = Hash(new { assessment.InputHash, ImportedScene = assessment.SceneID, SourceUser=sourceUser }); var rows = JsonNode.Parse(assessment.ResultsJson)!.AsArray(); foreach (var item in rows) { var record = item!.AsObject(); record["Key"] = Key(record["Key"]!.GetValue()); record["RecoverySourceInputHash"] = originalHash;if(record["RecoverySourceUserID"]==null)record["RecoverySourceUserID"]=sourceUser; } assessment.ResultsJson = rows.ToJsonString(); var decisions = JsonSerializer.Deserialize>(assessment.DecisionsJson) ?? []; assessment.DecisionsJson = JsonSerializer.Serialize(decisions.ToDictionary(p => Key(p.Key), p => p.Value)); } } public static string Validate(BookBackupPackage package) { if (package.Snapshot.FormatVersion != "1.4") throw new ArgumentException("Current book backup requires a complete recovery snapshot."); if (package.Format != "PlotDirector.BookBackup" || package.FormatVersion != "2.0" || package.SourceProjectKey == Guid.Empty) throw new ArgumentException("Unsupported book backup version."); var expected = Hash(new { package.SourceProjectKey, package.Snapshot, package.Identities, package.Warnings }); if (!string.Equals(expected, package.Integrity, StringComparison.Ordinal)) throw new ArgumentException("Backup integrity check failed."); return ProjectBackupMapValidation.Validate(package.Snapshot) ?? ProjectBackupGraphValidation.Validate(package.Snapshot, true) ?? ProjectBackupFiles.Validate(package.Snapshot) ?? ""; } }