using System.Security.Cryptography; using System.Text; using System.Text.Json; using PlotLine.Models; namespace PlotLine.Services; // Only public geographical names enter this interface. Never pass descriptions, aliases or manuscript text. public interface IGeocodingProvider { string Name { get; } bool Enabled { get; } TimeSpan MinimumInterval { get; } Task> SearchAsync(GeographicQuery query, CancellationToken cancellationToken); } public sealed class GeographicRules { private readonly Dictionary roots = new(StringComparer.OrdinalIgnoreCase); private static readonly HashSet Types = new(StringComparer.OrdinalIgnoreCase) { "Country", "Region", "State", "County", "City", "Town", "Village" }; public GeographicRules(string referenceDirectory) { using var countries = JsonDocument.Parse(File.ReadAllText(Path.Combine(referenceDirectory, "countries.json"))); foreach (var country in countries.RootElement.GetProperty("3166-1").EnumerateArray()) { var root = new GeographicRoot(country.GetProperty("alpha_2").GetString()!); foreach (var key in new[] { "name", "official_name", "common_name", "alpha_3" }) if (country.TryGetProperty(key, out var name)) roots[name.GetString()!] = root; } using var subdivisions = JsonDocument.Parse(File.ReadAllText(Path.Combine(referenceDirectory, "subdivisions.json"))); foreach (var region in subdivisions.RootElement.GetProperty("3166-2").EnumerateArray()) { var code = region.GetProperty("code").GetString()!; var root = new GeographicRoot(code[..2], code); // Explicit ISO codes and country-qualified names avoid ambiguous bare region names (e.g. Georgia). roots[code] = root; roots[$"{region.GetProperty("name").GetString()}, {code[..2]}"] = root; } roots["UK"] = roots["United Kingdom"] = new("GB"); roots["USA"] = roots["US"] = roots["United States"] = new("US"); roots["England"] = new("GB", "GB-ENG"); roots["Scotland"] = new("GB", "GB-SCT"); roots["Wales"] = new("GB", "GB-WLS"); roots["Northern Ireland"] = new("GB", "GB-NIR"); // Georgia alone may mean either the country or US state; require an explicit country identifier. roots.Remove("Georgia"); } public GeographicRoot? Root(string name) => roots.GetValueOrDefault(name.Trim()); public GeographicQuery? Query(IReadOnlyList chain) { if (chain.Count == 0 || chain.Count > 100 || !Types.Contains(chain[0].LocationTypeName ?? "")) return null; if (chain[^1].ParentLocationID is not null) return null; var root = Root(chain[^1].LocationName); if (root is null) return null; // Premises and arbitrary fictional intermediate parents must never be sent to a provider. if (chain.Any(l => !Types.Contains(l.LocationTypeName ?? ""))) return null; return new(chain[0].LocationName, root.CountryCode, root.SubdivisionCode, chain.Skip(1).Reverse().Select(l => l.LocationName).ToArray()); } public static string CacheKey(GeographicQuery query, string source = "") => Convert.ToHexString(SHA256.HashData( Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new { Source = query.RelaxedContext ? source+":context-fallback" : source, Name = query.Name.Trim().ToUpperInvariant(), query.CountryCode, query.SubdivisionCode, Ancestors = query.Ancestors.Select(x => x.Trim().ToUpperInvariant()).ToArray() })))); public static IReadOnlyList Candidates(GeographicQuery query, IEnumerable candidates) => candidates.Where(c => c.CountryCode.Equals(query.CountryCode, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(c.Provider) && !string.IsNullOrWhiteSpace(c.PlaceID) && !string.IsNullOrWhiteSpace(c.Attribution) && double.IsFinite(c.Latitude) && double.IsFinite(c.Longitude) && c.Latitude is >= -90 and <= 90 && c.Longitude is >= -180 and <= 180) .DistinctBy(c => (c.Provider, c.PlaceID)).Take(10).ToList(); // A provider ranking or a single returned result alone does not establish uniqueness. // Conservative initial adapter contract: all matches require author confirmation. }