PlotDirector/PlotLine/Services/Context/ContextIntentDraft.cs
2026-12-02 20:51:53 +00:00

184 lines
8.2 KiB
C#

namespace PlotLine.Services.Context;
/// <summary>
/// Shared editing state for the Context and Writer presentations. This is an
/// unsaved author draft, never a source of story facts or manuscript positions.
/// Persistence adapters must authorise the scope and every linked identity again.
/// </summary>
public sealed class ContextIntentDraft
{
public sealed record Scope(int BookID, int ChapterID, int? SceneID = null);
public sealed record Link(string EntityKey, bool Covered);
public sealed record Evidence(Scope Source, string Passage, string? AcceptedRevision = null,
string? ParagraphIdentity = null);
public sealed record Item(Guid Key, int? SavedItemID, string Text, bool Completed,
bool Changed, string Notes, IReadOnlyList<Link> Links, IReadOnlyList<Evidence> Evidence);
public const int MaximumNotesLength = 4_000;
public const int MaximumLinks = 100;
public const int MaximumEvidence = 20;
private readonly List<Item> items = [];
public Scope Position { get; }
// Presentation callers cannot mutate the ordered backing list.
public IReadOnlyList<Item> Items => items.AsReadOnly();
public ContextIntentDraft(Scope position, IEnumerable<Item>? existing = null)
{
ValidateScope(position);
Position = position;
if (existing is null) return;
var rows = existing.Take(ContextIntentText.MaximumItems + 1).ToArray();
if (rows.Length > ContextIntentText.MaximumItems || rows.Select(x => x.Key).Distinct().Count() != rows.Length ||
rows.Where(x => x.SavedItemID.HasValue).Select(x => x.SavedItemID).Distinct().Count() != rows.Count(x => x.SavedItemID.HasValue))
throw new ArgumentException("Invalid or duplicate Intent items.");
foreach (var row in rows)
{
ValidateItem(row);
items.Add(Freeze(row));
}
}
public Guid Add(string text)
{
var row = New(text, false);
EnsureCapacity(1);
items.Add(row);
return row.Key;
}
// Apply the author's reviewed preview in one operation. Parsing alone never
// invokes this method, and a rejected batch must leave the whole draft intact.
public void AddPreview(IEnumerable<ContextIntentText.PreviewItem> reviewed)
{
var rows = reviewed.Take(ContextIntentText.MaximumItems + 1).Select(x => New(x.Text, x.RequestedCompleted)).ToArray();
EnsureCapacity(rows.Length);
items.AddRange(rows);
}
public void Edit(Guid key, string text, string notes, bool changed)
{
var index = Index(key);
var row = items[index] with { Text = text.Trim(), Notes = notes, Changed = changed };
ValidateItem(row);
items[index] = row;
}
public void Complete(Guid key, bool completed)
{
var index = Index(key);
items[index] = items[index] with { Completed = completed };
}
// Used by drag reorder and keyboard up/down alike. Completion does not sort.
public void Move(Guid key, int destination)
{
var index = Index(key);
if (destination < 0 || destination >= items.Count) throw new ArgumentException("Choose an item position within this checklist.");
var row = items[index];
items.RemoveAt(index);
items.Insert(destination, row);
}
public void Remove(Guid key) => items.RemoveAt(Index(key));
// Only a selected identity from an already authorised palette may be linked.
// A shared spelling is never an identity selection. Linking never completes.
public void LinkEntity(Guid key, string entityKey, IReadOnlyList<ContextIntentText.Entity> authorisedPalette)
{
var index = Index(key);
if (!authorisedPalette.Any(e => e.Key == entityKey)) throw new ArgumentException("Choose an available Story Element identity.");
var row = items[index];
if (row.Links.Any(link => link.EntityKey == entityKey)) return;
var updated = row with { Links = Array.AsReadOnly(row.Links.Append(new Link(entityKey, false)).ToArray()) };
ValidateItem(updated);
items[index] = updated;
}
public void CoverEntity(Guid key, string entityKey, bool covered)
{
var index = Index(key);
var row = items[index];
if (!row.Links.Any(link => link.EntityKey == entityKey)) throw new ArgumentException("Link the selected Story Element first.");
items[index] = row with { Links = Array.AsReadOnly(row.Links.Select(link => link.EntityKey == entityKey ? link with { Covered = covered } : link).ToArray()) };
}
public void UnlinkEntity(Guid key, string entityKey)
{
var index = Index(key);
items[index] = items[index] with { Links = Array.AsReadOnly(items[index].Links.Where(link => link.EntityKey != entityKey).ToArray()) };
}
// Evidence is an author-selected quote, not an inferred event. The future
// editor adapter supplies accepted revision/paragraph identities; these opaque
// values must never be interpreted as Word offsets or navigation commands.
public void AddEvidence(Guid key, Evidence evidence, bool complete)
{
var index = Index(key);
var row = items[index];
var updated = row with
{
Evidence = Array.AsReadOnly(row.Evidence.Append(evidence).ToArray()),
Completed = complete || row.Completed
};
ValidateItem(updated);
items[index] = updated;
}
public void RemoveEvidence(Guid key, int evidenceIndex)
{
var index = Index(key);
var row = items[index];
if (evidenceIndex < 0 || evidenceIndex >= row.Evidence.Count) throw new ArgumentException("Choose existing passage evidence.");
items[index] = row with { Evidence = Array.AsReadOnly(row.Evidence.Where((_, i) => i != evidenceIndex).ToArray()) };
}
private void ValidateItem(Item row)
{
if (row.Key == Guid.Empty || row.SavedItemID <= 0 || string.IsNullOrWhiteSpace(row.Text) ||
row.Text.Length > ContextIntentText.MaximumItemLength || row.Notes is null || row.Notes.Length > MaximumNotesLength ||
row.Links is null || row.Evidence is null || row.Links.Count > MaximumLinks || row.Evidence.Count > MaximumEvidence)
throw new ArgumentException("Check the Intent text, notes and attachment limits.");
if (row.Links.Any(link => string.IsNullOrWhiteSpace(link.EntityKey) || link.EntityKey.Length > 200) ||
row.Links.Select(link => link.EntityKey).Distinct(StringComparer.Ordinal).Count() != row.Links.Count)
throw new ArgumentException("Choose distinct Story Element identities.");
foreach (var evidence in row.Evidence)
{
ValidateScope(evidence.Source);
if (evidence.Source.BookID != Position.BookID || evidence.Source.ChapterID != Position.ChapterID ||
Position.SceneID.HasValue && evidence.Source.SceneID != Position.SceneID ||
string.IsNullOrWhiteSpace(evidence.Passage) || evidence.Passage.Length > ContextIntentText.MaximumPassageLength ||
evidence.AcceptedRevision?.Length > 200 || evidence.ParagraphIdentity?.Length > 200)
throw new ArgumentException("Choose a passage within this Intent scope.");
}
}
private static void ValidateScope(Scope position)
{
if (position.BookID <= 0 || position.ChapterID <= 0 || position.SceneID <= 0)
throw new ArgumentException("Choose a saved chapter and optional saved scene.");
}
private Item New(string text, bool completed)
{
var row = new Item(Guid.NewGuid(), null, text.Trim(), completed, false, "", [], []);
ValidateItem(row);
return Freeze(row);
}
private static Item Freeze(Item row) => row with
{
Links = Array.AsReadOnly(row.Links.ToArray()), Evidence = Array.AsReadOnly(row.Evidence.ToArray())
};
private void EnsureCapacity(int added)
{
if (added > ContextIntentText.MaximumItems - items.Count) throw new ArgumentException("Keep at most 200 items in one Intent scope.");
}
private int Index(Guid key)
{
var index = items.FindIndex(row => row.Key == key);
return index >= 0 ? index : throw new ArgumentException("Choose an existing Intent item.");
}
}