namespace AmiReel.Services;

public static class UserFacingErrors
{
    public static string Summarize(Exception exception)
    {
        string message = exception.Message.Trim();
        if (string.IsNullOrWhiteSpace(message))
            return "An unexpected error occurred.";

        string[] lines = message
            .Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);

        if (lines.Length == 0)
            return "An unexpected error occurred.";

        if (!lines[0].StartsWith("Process exited with code", StringComparison.OrdinalIgnoreCase))
            return message;

        List<string> important = [];
        foreach (string line in lines.Skip(1))
        {
            if (IsNoise(line))
                continue;

            important.Add(line);
        }

        if (important.Count == 0)
            return lines[0];

        List<string> summary = [lines[0]];
        foreach (string line in important.TakeLast(3))
        {
            if (!summary.Contains(line, StringComparer.Ordinal))
                summary.Add(line);
        }

        return string.Join(Environment.NewLine, summary);
    }

    internal static bool IsNoise(string line)
    {
        return FfmpegOutputFilter.IsBoilerplateLine(line)
            || line.StartsWith("major_brand", StringComparison.OrdinalIgnoreCase)
            || line.StartsWith("minor_version", StringComparison.OrdinalIgnoreCase)
            || line.StartsWith("compatible_brands", StringComparison.OrdinalIgnoreCase)
            || line.StartsWith("encoder", StringComparison.OrdinalIgnoreCase)
            || line.StartsWith("[in#", StringComparison.OrdinalIgnoreCase)
            || line.StartsWith("[out#", StringComparison.OrdinalIgnoreCase)
            || line.StartsWith("Last message repeated", StringComparison.OrdinalIgnoreCase)
            || line.StartsWith("frame=", StringComparison.OrdinalIgnoreCase);
    }
}
