using System.Text.Json;
using System.Text.Json.Serialization;
using FileAccess = Godot.FileAccess;

namespace ReactorMaintenance.Godot.Data;

public static class CampaignRepository
{
    public static CampaignManifest LoadDefault()
    {
        var json = FileAccess.GetFileAsString(c_DefaultManifestPath);
        if (string.IsNullOrWhiteSpace(json))
            return CreateFallback();

        var manifest = JsonSerializer.Deserialize<CampaignManifest>(json, s_Options);
        return manifest is { Levels.Count: > 0 } ? manifest : CreateFallback();
    }

    private static CampaignManifest CreateFallback()
    {
        return new() {
            Levels = [
                new() {
                    Id = "fallback",
                    Name = "Fallback Reactor",
                    FlavorText = "A placeholder level loaded because the campaign manifest was unavailable.",
                    LevelPath = "res://Data/Levels/fallback.json"
                }
            ]
        };
    }

    private const string c_DefaultManifestPath = "res://Data/default_campaign_manifest.json";

    private static readonly JsonSerializerOptions s_Options = new() {
        PropertyNameCaseInsensitive = true,
        Converters = { new JsonStringEnumConverter() }
    };
}