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

namespace ClaudeDo.Installer.Core;

public sealed record InstallManifest(
    string Version,
    string InstallDir,
    string WorkerDir,
    DateTimeOffset InstalledAt,
    string? DataDir = null);

public static class InstallManifestStore
{
    public const string FileName = "install.json";

    private static readonly JsonSerializerOptions JsonOptions = new()
    {
        WriteIndented = true,
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
    };

    public static string ManifestPath(string installDir) => Path.Combine(installDir, FileName);

    public static InstallManifest? TryRead(string installDir)
    {
        var path = ManifestPath(installDir);
        if (!File.Exists(path)) return null;

        try
        {
            var json = File.ReadAllText(path);
            return JsonSerializer.Deserialize<InstallManifest>(json, JsonOptions);
        }
        catch
        {
            return null;
        }
    }

    public static void Write(string installDir, InstallManifest manifest)
    {
        Directory.CreateDirectory(installDir);
        var json = JsonSerializer.Serialize(manifest, JsonOptions);
        File.WriteAllText(ManifestPath(installDir), json);
    }
}
