using System.Globalization; using System.Text.Json; using Microsoft.Extensions.Options; using PlotLine.Models; namespace PlotLine.Services; public sealed class GeocodingOptions { public bool Enabled { get; set; } public string Provider { get; set; } = "Nominatim"; public string Endpoint { get; set; } = "https://nominatim.openstreetmap.org/search"; public string UserAgent { get; set; } = ""; public string WorkerHost { get; set; } = ""; public int MinimumIntervalSeconds { get; set; } = 15; } // Configuration comes from IOptionsMonitor: the JSON settings provider supports changes without redeployment. public sealed class NominatimGeocodingProvider(IOptionsMonitor options,IHttpClientFactory clients) : IGeocodingProvider { public string Name => "Nominatim:"+options.CurrentValue.Endpoint; public bool Enabled => options.CurrentValue is {Enabled:true,Provider:"Nominatim"} config && string.Equals(config.WorkerHost,Environment.MachineName,StringComparison.OrdinalIgnoreCase) && Valid(config); // All author-triggered multi-place batches use the stricter 4/minute ceiling, even when small. public TimeSpan MinimumInterval => TimeSpan.FromSeconds(Math.Clamp(options.CurrentValue.MinimumIntervalSeconds,15,86400)); private static bool Valid(GeocodingOptions config) => Uri.TryCreate(config.Endpoint,UriKind.Absolute,out var uri) && uri.Scheme=="https" && string.IsNullOrEmpty(uri.UserInfo) && string.IsNullOrEmpty(uri.Query) && config.UserAgent.StartsWith("PlotDirector/",StringComparison.Ordinal) && config.UserAgent.Length>=25 && (config.UserAgent.Contains("https://",StringComparison.Ordinal)||config.UserAgent.Contains('@')); public async Task> SearchAsync(GeographicQuery query,CancellationToken cancellationToken) { var config=options.CurrentValue; if(!Enabled)throw new InvalidOperationException("Geocoding is disabled or this host is not the designated worker."); // Only public place names and geographical ancestors, never descriptions or story content. var text=string.Join(", ",new[]{query.Name}.Concat(query.RelaxedContext?query.Ancestors.Take(1):query.Ancestors.Reverse())); var uri=config.Endpoint+"?format=jsonv2&addressdetails=1&namedetails=1&limit=10&dedupe=1&countrycodes=" +Uri.EscapeDataString(query.CountryCode.ToLowerInvariant())+"&accept-language=en&q="+Uri.EscapeDataString(text); using var request=new HttpRequestMessage(HttpMethod.Get,uri); request.Headers.UserAgent.ParseAdd(config.UserAgent); using var response=await clients.CreateClient("Geocoding").SendAsync(request,HttpCompletionOption.ResponseHeadersRead,cancellationToken); if(!response.IsSuccessStatusCode) throw new GeocodingHttpException((int)response.StatusCode, response.Headers.RetryAfter?.Delta ?? (response.Headers.RetryAfter?.Date-DateTimeOffset.UtcNow)); if(response.Content.Headers.ContentLength is >1_000_000)throw new InvalidDataException("Oversized provider response."); await using var stream=await response.Content.ReadAsStreamAsync(cancellationToken); using var buffer=new MemoryStream(); var chunk=new byte[8192];int read; while((read=await stream.ReadAsync(chunk,cancellationToken))>0){if(buffer.Length+read>1_000_000)throw new InvalidDataException("Oversized provider response.");buffer.Write(chunk,0,read);} using var json=JsonDocument.Parse(buffer.ToArray()); return Parse(query,json.RootElement); } public static IReadOnlyList Parse(GeographicQuery query,JsonElement response) { if(response.ValueKind!=JsonValueKind.Array)throw new InvalidDataException("Invalid provider response."); var candidates=new List(); var reliable=new HashSet(StringComparer.Ordinal); static string Normalize(string value)=>string.Join(' ',value.Trim().ToUpperInvariant().Split((char[]?)null,StringSplitOptions.RemoveEmptyEntries)); foreach(var row in response.EnumerateArray().Take(10)) { string Text(string field)=>row.TryGetProperty(field,out var value)?value.ToString():""; var type=Text("addresstype"); if(type is not ("country" or "state" or "region" or "county" or "city" or "town" or "village" or "hamlet" or "suburb" or "quarter" or "neighbourhood" or "administrative"))continue; if(!row.TryGetProperty("address",out var address))continue; var country=address.TryGetProperty("country_code",out var cc)?cc.GetString()?.ToUpperInvariant():null; if(country!=query.CountryCode)continue; var admin=address.EnumerateObject().Where(p=>p.Name is not ("postcode" or "country_code" or "house_number" or "road")) .Select(p=>p.Value.ToString()).Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); if(query.SubdivisionCode is not null && !admin.Contains(query.SubdivisionCode,StringComparer.OrdinalIgnoreCase))continue; if(!double.TryParse(Text("lat"),NumberStyles.Float,CultureInfo.InvariantCulture,out var lat) ||!double.TryParse(Text("lon"),NumberStyles.Float,CultureInfo.InvariantCulture,out var lon))continue; var identity=Text("osm_type")+":"+Text("osm_id"); if(identity is ":"||string.IsNullOrEmpty(Text("osm_id")))continue; var context=query.Ancestors.Skip(1).Select(Normalize).ToArray(); var exactName=Normalize(Text("name"))==Normalize(query.Name); var contextMatches=context.All(name=>admin.Any(a=>Normalize(a)==name)); // Require exact place name plus more identifying context than a country-only query. // A constituent/admin root or an additional matching ancestor supplies that context. if(exactName && contextMatches && (query.SubdivisionCode is not null || context.Length>0))reliable.Add(identity); candidates.Add(new("Nominatim",identity,Text("display_name"),lat,lon,country,admin, "© OpenStreetMap contributors · ODbL 1.0 · https://www.openstreetmap.org/copyright",false)); } var valid=GeographicRules.Candidates(query,candidates); // Ranked results alone are insufficient. Never auto-select a saturated result set or multiple candidates. if(!query.RelaxedContext && valid.Count==1 && response.GetArrayLength()<10 && reliable.Contains(valid[0].PlaceID)) return new[]{valid[0] with {UniqueWithinContext=true}}; return valid; } } public sealed class GeocodingHttpException(int statusCode,TimeSpan? retryAfter) : Exception { public int StatusCode { get; } = statusCode; public TimeSpan? RetryAfter { get; } = retryAfter; }