using System.IO;
using ClaudeDo.Data;
using ClaudeDo.Installer.Core;

namespace ClaudeDo.Installer.Steps;

public sealed class WriteInstallManifestStep : IInstallStep
{
    public string Name => "Write Install Manifest";

    public Task<StepResult> ExecuteAsync(InstallContext ctx, IProgress<string> progress, CancellationToken ct)
    {
        if (string.IsNullOrWhiteSpace(ctx.InstalledVersion))
            return Task.FromResult(StepResult.Fail("Installed version is not set — DownloadAndExtractStep must run first."));

        try
        {
            var dataDir = Path.GetDirectoryName(Paths.Expand(ctx.DbPath));

            var manifest = new InstallManifest(
                Version: ctx.InstalledVersion,
                InstallDir: ctx.InstallDirectory,
                WorkerDir: Path.Combine(ctx.InstallDirectory, "worker"),
                InstalledAt: DateTimeOffset.UtcNow,
                DataDir: dataDir);

            InstallManifestStore.Write(ctx.InstallDirectory, manifest);
            progress.Report($"Wrote {InstallManifestStore.ManifestPath(ctx.InstallDirectory)}");
            return Task.FromResult(StepResult.Ok());
        }
        catch (Exception ex)
        {
            return Task.FromResult(StepResult.Fail(ex.Message));
        }
    }
}
