using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RynthCore.Plugin.RynthOracle.Data;
///
/// One Infinite Leaftide Dynamic Stamp (dynstamps.csv): an NPC hand-in that puts a
/// "Dynamic_N_..." quest flag on the character. List from the players' "ExtraDyn" sheet
/// (10.13.2026, one sheet per area, the wiki's Dynamic Stamps page); NPCs that give no stamp
/// are left out. A stamp is a one-time flag: having it in /myquests means it's done.
///
internal sealed class DynamicStamp
{
public string Area = "";
/// Where in the area (a town, a dungeon, coordinates), or "".
public string Place = "";
public string Npc = "";
/// What the NPC gives back (the sheet's "X gives you Y"), or "".
public string Reward = "";
/// The quest flag, lower case (as QuestFlagStore keys it).
public string Stamp = "";
public string Note = "";
/// The NPC, else the place (a few sheet rows only name the spot).
public string Label => Npc.Length > 0 ? Npc : Place;
///
/// The stamp without the "!" the sheet copied from the server's "You've stamped {flag}!" line.
/// ACECustom names a stamp "Dynamic_1_" plus random letters, digits and ! @ # $ ^ &
/// (QuestManager.ComputeDynamicQuest), yet 238 of the 243 listed stamps end in "!".
///
public string Stem => Stamp.EndsWith('!') ? Stamp[..^1] : Stamp;
///
/// The flag this character has for the stamp, or null. Tried in order: the stamp as listed,
/// without the copied closing "!" (the server's flag, almost always), with "!" added (a few
/// rows lost a real one), its errand's delivery flag ("_d"), then, when the stem is at least
/// long, the one errand whose flag starts with it (a row cut
/// short). is the Dynamic flags of RynthILT's /qb list (Infinite
/// Leaftide): /myquests leaves out flags the server holds no quest text for, so a stamp that
/// isn't in /myquests is looked for there too, with the same rules.
///
public string? MatchedFlag(QuestFlagStore flags, IReadOnlySet? qbStamps = null)
{
string? mine = Match(k => flags.TryGet(k, out _), flags.Flags.Keys);
if (mine != null || qbStamps == null || qbStamps.Count == 0) return mine;
return Match(qbStamps.Contains, qbStamps);
}
/// The matching rules over one source (see ).
private string? Match(Func has, IEnumerable keys)
{
string stem = Stem;
if (has(Stamp)) return Stamp;
if (stem != Stamp && has(stem)) return stem;
if (stem == Stamp && has(Stamp + "!")) return Stamp + "!";
if (has(stem + DynamicStampList.DeliverySuffix)) return stem + DynamicStampList.DeliverySuffix;
if (stem.Length < MinPrefixLength) return null;
string? only = null;
foreach (string key in keys)
{
if (!key.StartsWith(stem, StringComparison.OrdinalIgnoreCase)) continue;
// An errand's own flag and its "_d" delivery flag are one stamp; two errands can't be told apart.
if (only != null && !DynamicStampList.ErrandOf(only).Equals(DynamicStampList.ErrandOf(key), StringComparison.OrdinalIgnoreCase))
return null;
if (only == null || key.Length < only.Length) only = key; // the errand's own flag over its "_d"
}
return only;
}
public bool Have(QuestFlagStore flags, IReadOnlySet? qbStamps = null) => MatchedFlag(flags, qbStamps) != null;
// Sheet areas that are groupings, not places on the map.
private static readonly HashSet NotPlaces = new(StringComparer.OrdinalIgnoreCase)
{
"Looking Around", "Odd Stamps", "Odd Stamps 2",
};
///
/// Where RynthNav should go for this stamp, best first (RynthNav takes the first that is on its
/// map): the coordinates in the note or the place, the place and its parts ("Mhoire Castle -
/// Great Hall" also tries "Mhoire Castle"), the NPC, then the area. Empty when there is nothing.
///
public List NavCandidates()
{
var list = new List();
void Add(string s)
{
s = s.Trim().Trim('.', ',', ';', ':').Trim();
if (s.Length >= 4 && !char.IsDigit(s[0]) && !list.Contains(s, StringComparer.OrdinalIgnoreCase)) list.Add(s);
}
foreach (string text in new[] { Note, Place })
if (NavTargets.FirstCoords(text) is string c && !list.Contains(c)) list.Add(c);
string place = NavTargets.WithoutCoords(Place);
place = System.Text.RegularExpressions.Regex.Replace(place, @"\b(at|in the|nearby)\b", " ", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
place = System.Text.RegularExpressions.Regex.Replace(place, @"\s+", " ").Trim();
Add(place);
foreach (string part in place.Split(new[] { " - ", " / ", "(", ")" }, StringSplitOptions.RemoveEmptyEntries))
Add(part);
Add(Npc);
if (!NotPlaces.Contains(Area)) Add(Area);
return list;
}
/// A truncated stamp shorter than this is matched exactly only (too many flags share a short stem).
public const int MinPrefixLength = 14;
}
internal static class DynamicStampList
{
/// Dynamic stamp quest flags start with this (lower case).
public const string FlagPrefix = "dynamic_";
///
/// A chain errand's second flag: the NPC the item is delivered to stamps the errand's flag
/// with this added (QuestManager.ComputeDynamicQuest, questName + "_d").
///
public const string DeliverySuffix = "_d";
/// The errand a Dynamic flag belongs to: the flag without its "_d" delivery suffix.
public static string ErrandOf(string flag) =>
flag.EndsWith(DeliverySuffix, StringComparison.OrdinalIgnoreCase) ? flag[..^DeliverySuffix.Length] : flag;
private static readonly List Sheet = Load();
///
/// The stamps: the wiki's Dynamic Stamps page when RynthILT has read it (2026-11-21, Silentkelpie: "the dynamic
/// stamp tab should be using" it), else the players' sheet shipped with RynthOracle.
///
public static List All { get; private set; } = Sheet;
/// The areas in list order (the wiki's towns and camps, or the sheet's Facility Hub, Looking Around, ...).
public static List Areas { get; private set; } = BuildAreas(Sheet);
/// Where the list comes from: "wiki" or "sheet".
public static string Source { get; private set; } = "sheet";
/// Goes up when the list is swapped.
public static int Revision { get; private set; }
///
/// Uses the wiki's Dynamic Stamps (QuestGuide.DynStamps) when there are any, else goes back to the sheet.
/// Pump thread. The wiki's coordinates go into the note, where RynthNav's candidates look first.
///
public static void UseWiki(IReadOnlyList? wiki)
{
if (wiki == null || wiki.Count == 0)
{
if (Source == "sheet") return;
All = Sheet;
Areas = BuildAreas(Sheet);
Source = "sheet";
Revision++;
return;
}
var list = new List(wiki.Count);
var seen = new HashSet(StringComparer.OrdinalIgnoreCase);
foreach (GuideDynStamp d in wiki)
{
string stamp = d.Stamp.Trim().ToLowerInvariant();
if (!stamp.StartsWith(FlagPrefix, StringComparison.Ordinal) || !seen.Add(stamp)) continue;
string note = d.Coords.Length > 0 && d.Note.Length > 0 ? d.Coords + " - " + d.Note : d.Coords + d.Note;
list.Add(new DynamicStamp { Area = d.Area, Place = d.Place, Npc = d.Npc, Reward = d.Reward, Stamp = stamp, Note = note });
}
if (list.Count == 0) { UseWiki(null); return; }
All = list;
Areas = BuildAreas(list);
Source = "wiki";
Revision++;
}
///
/// Dynamic stamps on this character that the list doesn't have (new or unlisted NPCs), so the
/// tab can show them and the count isn't only what the sheet knows.
///
public static List Unlisted(QuestFlagStore flags, IReadOnlySet? qbStamps = null)
{
// By errand: a listed stamp's "_d" delivery flag is that stamp, and an unlisted errand shows once.
var matched = new HashSet(StringComparer.OrdinalIgnoreCase);
foreach (DynamicStamp s in All)
if (s.MatchedFlag(flags, qbStamps) is string f) matched.Add(ErrandOf(f));
var extra = new HashSet(StringComparer.OrdinalIgnoreCase);
foreach (string key in flags.Flags.Keys)
if (key.StartsWith(FlagPrefix, StringComparison.OrdinalIgnoreCase) && !matched.Contains(ErrandOf(key)))
extra.Add(ErrandOf(key));
if (qbStamps != null)
foreach (string key in qbStamps)
if (key.StartsWith(FlagPrefix, StringComparison.OrdinalIgnoreCase) && !matched.Contains(ErrandOf(key)))
extra.Add(ErrandOf(key));
var list = extra.ToList();
list.Sort(StringComparer.OrdinalIgnoreCase);
return list;
}
///
/// Where this character's stamps come from, for the log: Dynamic flags in /myquests, Dynamic
/// flags in the /qb list, and the listed stamps matched from either.
///
public static (int InMyQuests, int InQb, int Matched) Counts(QuestFlagStore flags, IReadOnlySet? qbStamps)
{
int mine = flags.Flags.Keys.Count(k => k.StartsWith(FlagPrefix, StringComparison.OrdinalIgnoreCase));
int qb = qbStamps?.Count(k => k.StartsWith(FlagPrefix, StringComparison.OrdinalIgnoreCase)) ?? 0;
int matched = All.Count(s => s.Have(flags, qbStamps));
return (mine, qb, matched);
}
private static List Load()
{
var list = new List();
using StreamReader r = Csv.OpenEmbedded("dynstamps.csv");
Dictionary col = Csv.MapColumns(r.ReadLine() ?? "");
int cArea = Csv.Column(col, "Area"), cPlace = Csv.Column(col, "Place"), cNpc = Csv.Column(col, "Npc"),
cReward = Csv.Column(col, "Reward"), cStamp = Csv.Column(col, "Stamp"), cNote = Csv.Column(col, "Note");
var seen = new HashSet(StringComparer.OrdinalIgnoreCase);
while (r.ReadLine() is string line)
{
if (string.IsNullOrWhiteSpace(line)) continue;
string[] f = Csv.ParseLine(line);
string stamp = Csv.Field(f, cStamp).Trim().ToLowerInvariant();
if (!stamp.StartsWith(FlagPrefix, StringComparison.Ordinal) || !seen.Add(stamp)) continue;
list.Add(new DynamicStamp
{
Area = Csv.Field(f, cArea),
Place = Csv.Field(f, cPlace),
Npc = Csv.Field(f, cNpc),
Reward = Csv.Field(f, cReward),
Stamp = stamp,
Note = Csv.Field(f, cNote),
});
}
return list;
}
private static List BuildAreas(List all)
{
var areas = new List();
foreach (DynamicStamp s in all)
if (!areas.Contains(s.Area)) areas.Add(s.Area);
return areas;
}
}