using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using AaLog.Cli.Output;

namespace AaLog.Cli.Filtering
{
    /// Client-side filtering applied after fetch. The aaLogReader library has its own
    /// LogRecordPostFilters facility, but rolling our own keeps the surface flat and
    /// avoids leaking library structs into the CLI argument layer.
    public static class RecordFilter
    {
        public static IReadOnlyList<LogRecordDto> Apply(
            IEnumerable<LogRecordDto> records,
            string componentPattern,
            string levelPattern,
            string messagePattern,
            bool useRegex)
        {
            Predicate<string> componentMatch = Build(componentPattern, useRegex);
            Predicate<string> levelMatch = Build(levelPattern, useRegex);
            Predicate<string> messageMatch = Build(messagePattern, useRegex);

            return records
                .Where(r => componentMatch(r.Component ?? string.Empty))
                .Where(r => levelMatch(r.Level ?? string.Empty))
                .Where(r => messageMatch(r.Message ?? string.Empty))
                .ToList();
        }

        private static Predicate<string> Build(string pattern, bool useRegex)
        {
            if (string.IsNullOrEmpty(pattern)) return _ => true;

            if (useRegex)
            {
                var rx = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
                return s => rx.IsMatch(s);
            }

            return s => s.IndexOf(pattern, StringComparison.OrdinalIgnoreCase) >= 0;
        }
    }
}
