using ClaudeDo.Data;
using ClaudeDo.Installer.Core;

namespace ClaudeDo.Installer.Steps;

public sealed class WriteConfigStep : IInstallStep
{
    public string Name => "Write Configuration";

    public Task<StepResult> ExecuteAsync(InstallContext ctx, IProgress<string> progress, CancellationToken ct)
    {
        try
        {
            // Expand ~ to the installing user's absolute path so the worker
            // service always finds the correct DB regardless of service account.
            var workerCfg = new InstallerWorkerConfig
            {
                DbPath = Paths.Expand(ctx.DbPath),
                SandboxRoot = Paths.Expand(ctx.SandboxRoot),
                LogRoot = Paths.Expand(ctx.LogRoot),
                WorktreeRootStrategy = ctx.WorktreeRootStrategy,
                CentralWorktreeRoot = Paths.Expand(ctx.CentralWorktreeRoot),
                QueueBackstopIntervalMs = ctx.QueueBackstopIntervalMs,
                SignalRPort = ctx.SignalRPort,
                ClaudeBin = ctx.ClaudeBin,
            };
            workerCfg.Save();
            progress.Report("Written worker.config.json");

            var uiCfg = new InstallerAppSettings
            {
                DbPath = Paths.Expand(ctx.UiDbPath),
                SignalRUrl = ctx.SignalRUrl,
                Language = ctx.Language,
            };
            uiCfg.Save();
            progress.Report("Written ui.config.json");

            return Task.FromResult(StepResult.Ok());
        }
        catch (Exception ex)
        {
            return Task.FromResult(StepResult.Fail(ex.Message));
        }
    }
}
