using System.Diagnostics;
using System.Runtime.InteropServices;

namespace BrikInstaller.Utils;

public static class BashUtils {
    public static string GetCommandOutput(string command) {
        string shell = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "cmd.exe" : "/bin/bash";
        string argPrefix = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "/c" : "-c";

        string formattedCommand = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) 
            ? command 
            : $"\"{command.Replace("\"", "\\\"")}\"";

        using var proc = new Process {
            StartInfo = new ProcessStartInfo {
                FileName = shell,
                Arguments = $"{argPrefix} {formattedCommand}",
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true,
                StandardOutputEncoding = System.Text.Encoding.UTF8
            }
        };

        try {
            proc.Start();
            string output = proc.StandardOutput.ReadToEnd();
            string error = proc.StandardError.ReadToEnd();
            proc.WaitForExit();

            return string.IsNullOrEmpty(output) ? error : output;
        } catch (Exception ex) {
            return $"Execution error : {ex.Message}";
        }
    }

    public static string GetBashCommandOutput(string command) {
        using var proc = new Process {
            StartInfo = new ProcessStartInfo {
                FileName = "/bin/bash",
                Arguments = $"-c \"{command}\"",
                UseShellExecute = false,
                RedirectStandardOutput = true,
                CreateNoWindow = true
            }
        };
        proc.Start();
        return proc.StandardOutput.ReadToEnd();
    }

    public static void OpenUrl(string url) {
        try {
            Process.Start(url);
        } catch {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
                url = url.Replace("&", "^&");
                Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
            } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) {
                Process.Start("xdg-open", url);
            } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) {
                Process.Start("open", url);
            } else {
                throw;
            }
        }
    }
}