using System.Text.Json;
using System.Text.Json.Serialization;

namespace RioJoy.Core.Overlay;

/// <summary>
/// Loads and saves an <see cref="OverlayTemplate"/> as a <c>regions.json</c> — the
/// cockpit cell geometry extracted from the source artwork
/// (docs/reference/customBackground/riojoy.xcf). Same JSON conventions as
/// <see cref="Profiles.ConfigStore"/> (indented, enums as strings, null-skipping).
/// </summary>
public static class OverlayTemplateStore
{
    private static readonly JsonSerializerOptions Options = new()
    {
        WriteIndented = true,
        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
        Converters = { new JsonStringEnumConverter() },
    };

    public static string Serialize(OverlayTemplate template)
    {
        ArgumentNullException.ThrowIfNull(template);
        return JsonSerializer.Serialize(template, Options);
    }

    public static OverlayTemplate Deserialize(string json)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(json);
        return JsonSerializer.Deserialize<OverlayTemplate>(json, Options)
               ?? throw new JsonException("Overlay template JSON deserialized to null.");
    }

    public static void Save(OverlayTemplate template, string path)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(path);
        string? dir = Path.GetDirectoryName(Path.GetFullPath(path));
        if (!string.IsNullOrEmpty(dir))
            Directory.CreateDirectory(dir);
        File.WriteAllText(path, Serialize(template));
    }

    public static OverlayTemplate Load(string path)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(path);
        return Deserialize(File.ReadAllText(path));
    }
}
