using ClaudeDo.Installer.Core;

namespace ClaudeDo.Installer.Checks;

public sealed record EnvironmentCheckReport(IReadOnlyList<CheckResult> Results)
{
    public bool HasBlockingError => Results.Any(r => r.Severity == CheckSeverity.Error && r.Status == CheckStatus.Failed);
}

public sealed class EnvironmentCheckService
{
    private readonly IReadOnlyList<IEnvironmentCheck> _checks;

    public EnvironmentCheckService(IEnumerable<IEnvironmentCheck> checks)
    {
        _checks = checks.ToList();
    }

    public async Task<EnvironmentCheckReport> RunAllAsync(InstallContext ctx, CancellationToken ct)
    {
        var tasks = _checks.Select(check => RunSafeAsync(check, ctx, ct)).ToArray();
        var results = await Task.WhenAll(tasks);
        return new EnvironmentCheckReport(results);
    }

    private static async Task<CheckResult> RunSafeAsync(IEnvironmentCheck check, InstallContext ctx, CancellationToken ct)
    {
        try
        {
            return await check.RunAsync(ctx, ct);
        }
        catch (Exception ex)
        {
            return CheckResult.Unknown(check.Id, check.Severity, string.Empty, ex.Message, ex.Message);
        }
    }
}
