using System.Diagnostics;
using ClaudeDo.Data.Environment;

namespace ClaudeDo.Worker.Lifecycle;

public static class ClaudeCliPreflight
{
    public sealed record Result(bool Ok, string Version, string Error, int ExitCode);

    public static async Task<Result> CheckAsync(string claudeBin, CancellationToken ct = default)
    {
        var resolved = ExecutableResolver.Resolve(claudeBin);
        if (resolved is null)
            return new Result(false, "", $"'{claudeBin}' not found on PATH.", -1);

        try
        {
            var psi = resolved.IsShim
                ? BuildShimPsi(resolved.Path)
                : new ProcessStartInfo
                {
                    FileName = resolved.Path,
                    Arguments = "--version",
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true,
                };
            using var proc = Process.Start(psi);
            if (proc is null) return new Result(false, "", "Process.Start returned null", -1);

            var stdoutTask = proc.StandardOutput.ReadToEndAsync(ct);
            var stderrTask = proc.StandardError.ReadToEndAsync(ct);
            await proc.WaitForExitAsync(ct);

            var stdout = (await stdoutTask).Trim();
            var stderr = (await stderrTask).Trim();
            return new Result(proc.ExitCode == 0, stdout, stderr, proc.ExitCode);
        }
        catch (Exception ex)
        {
            return new Result(false, "", ex.Message, -1);
        }
    }

    private static ProcessStartInfo BuildShimPsi(string shimPath)
    {
        var shim = ExecutableResolver.BuildShimStartInfo(shimPath, new[] { "--version" });
        return new ProcessStartInfo
        {
            FileName = shim.FileName,
            Arguments = shim.Arguments,
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            CreateNoWindow = true,
        };
    }
}
