using System;
using System.Globalization;
using System.IO;
namespace CarpaNet.BuildTasks;
///
/// Disk-based cache for resolved lexicon JSON files.
/// Each NSID is stored as {nsid}.json with a companion {nsid}.meta file containing the timestamp.
///
internal sealed class LexiconCache
{
private readonly string _cacheDir;
private readonly TimeSpan _ttl;
public LexiconCache(string cacheDir, double ttlHours = 24)
{
_cacheDir = cacheDir;
_ttl = TimeSpan.FromHours(ttlHours);
}
///
/// Gets the cache directory path.
///
public string CacheDirectory => _cacheDir;
///
/// Tries to retrieve a cached lexicon for the given NSID.
/// Returns null if not cached or expired.
///
public string? TryGet(string nsid)
{
var jsonPath = GetJsonPath(nsid);
var metaPath = GetMetaPath(nsid);
if (!File.Exists(jsonPath) || !File.Exists(metaPath))
return null;
// Check TTL
var metaContent = File.ReadAllText(metaPath).Trim();
if (!DateTimeOffset.TryParse(metaContent, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var cachedAt))
return null;
if (DateTimeOffset.UtcNow - cachedAt > _ttl)
return null;
return File.ReadAllText(jsonPath);
}
///
/// Stores a lexicon JSON in the cache.
///
public void Store(string nsid, string lexiconJson)
{
Directory.CreateDirectory(_cacheDir);
var jsonPath = GetJsonPath(nsid);
var metaPath = GetMetaPath(nsid);
File.WriteAllText(jsonPath, lexiconJson);
File.WriteAllText(metaPath, DateTimeOffset.UtcNow.ToString("O", CultureInfo.InvariantCulture));
}
///
/// Gets the path where the cached JSON file would be stored for the given NSID.
///
public string GetJsonPath(string nsid) => Path.Combine(_cacheDir, nsid + ".json");
///
/// Gets the path of the metadata file for the given NSID.
///
public string GetMetaPath(string nsid) => Path.Combine(_cacheDir, nsid + ".meta");
///
/// Checks whether a valid (non-expired) cache entry exists for the given NSID.
///
public bool IsCached(string nsid) => TryGet(nsid) != null;
///
/// Gets the path for the authority manifest JSON file.
///
public string GetAuthorityJsonPath(string authority) => Path.Combine(_cacheDir, "_authority." + SanitizeCacheKey(authority) + ".json");
///
/// Gets the path for the authority manifest meta file.
///
public string GetAuthorityMetaPath(string authority) => Path.Combine(_cacheDir, "_authority." + SanitizeCacheKey(authority) + ".meta");
///
/// Stores an authority manifest (list of discovered NSIDs) in the cache.
///
public void StoreAuthorityManifest(string authority, List nsids)
{
Directory.CreateDirectory(_cacheDir);
var jsonPath = GetAuthorityJsonPath(authority);
var metaPath = GetAuthorityMetaPath(authority);
var json = "[" + string.Join(",", nsids.ConvertAll(n => "\"" + n + "\"")) + "]";
File.WriteAllText(jsonPath, json);
File.WriteAllText(metaPath, DateTimeOffset.UtcNow.ToString("O", CultureInfo.InvariantCulture));
}
///
/// Tries to retrieve a cached authority manifest.
/// Returns the list of NSIDs if the manifest is fresh (within TTL), null if expired or missing.
///
public List? TryGetAuthorityManifest(string authority)
{
var jsonPath = GetAuthorityJsonPath(authority);
var metaPath = GetAuthorityMetaPath(authority);
if (!File.Exists(jsonPath) || !File.Exists(metaPath))
return null;
var metaContent = File.ReadAllText(metaPath).Trim();
if (!DateTimeOffset.TryParse(metaContent, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var cachedAt))
return null;
if (DateTimeOffset.UtcNow - cachedAt > _ttl)
return null;
var json = File.ReadAllText(jsonPath);
var nsids = new List();
using var doc = System.Text.Json.JsonDocument.Parse(json);
foreach (var element in doc.RootElement.EnumerateArray())
{
var nsid = element.GetString();
if (nsid != null)
nsids.Add(nsid);
}
return nsids;
}
///
/// Sanitizes a cache key for use in filenames by replacing invalid characters.
///
private static string SanitizeCacheKey(string key) => key.Replace(':', '_');
}