namespace SilverOS.Welcome.Core.Apply;

internal static class ProcessResultExtensions
{
    /// <summary>
    /// Throws an <see cref="InvalidOperationException"/> with a scrubbed message when the
    /// process exited non-zero, so a failed privileged step surfaces to the wizard (and a
    /// failed apply does not proceed to bootstrap teardown) instead of failing silently.
    /// </summary>
    public static void EnsureSuccess(in this ProcessResult result, string operation)
    {
        if (result.ExitCode == 0) return;
        var firstLine = (result.StdErr ?? string.Empty)
            .Split('\n')
            .Select(l => l.Trim())
            .FirstOrDefault(l => l.Length > 0) ?? string.Empty;
        if (firstLine.Length > 200) firstLine = firstLine[..200];
        throw new InvalidOperationException($"{operation} failed (exit {result.ExitCode}): {firstLine}");
    }
}
