using System.Diagnostics;
using YMhut.Box.Core.App;
using YMhut.Box.Core.Logging;

namespace YMhut.Box.WinUI.Services;

public interface IIndependentWindowHostLauncher
{
    Task LaunchAsync(IndependentWindowHostOptions options, CancellationToken cancellationToken = default);
}

public sealed class IndependentWindowHostLauncher(ILogService? logService = null) : IIndependentWindowHostLauncher
{
    public Task LaunchAsync(IndependentWindowHostOptions options, CancellationToken cancellationToken = default)
    {
        cancellationToken.ThrowIfCancellationRequested();
        var executable = RuntimeLayoutBootstrapper.InstalledExecutablePath;
        var startInfo = new ProcessStartInfo
        {
            FileName = executable,
            WorkingDirectory = RuntimeLayoutBootstrapper.InstalledWorkingDirectory,
            UseShellExecute = false
        };

        foreach (var argument in options.ToArguments())
        {
            startInfo.ArgumentList.Add(argument);
        }

        Process.Start(startInfo);
        _ = logService?.WriteAsync(
            "Information",
            "window-host",
            $"Independent window host launched: {options.Kind}",
            options.Title,
            cancellationToken);
        return Task.CompletedTask;
    }
}
