using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AaLog.Cli.Filtering;
using AaLog.Cli.Output;
using CliFx;
using CliFx.Attributes;
using CliFx.Infrastructure;

namespace AaLog.Cli.Commands
{
    [Command("last", Description = "Fetch the most recent N records ending at 'now' (or --until).")]
    public sealed class LastCommand : ReadCommandBase, ICommand
    {
        [CommandOption("count", 'n', Description = "Number of records to fetch (most recent first). Default 50.")]
        public int Count { get; init; } = 50;

        [CommandOption("until", Description = "Anchor timestamp for the 'end' of the window (ISO-8601, local time). Defaults to now.")]
        public DateTime? Until { get; init; }

        public ValueTask ExecuteAsync(IConsole console)
        {
            var endTimestamp = Until ?? DateTime.Now;
            using var reader = LogReaderFactory.Open(LogDirectory);
            var raw = reader.GetRecordsByEndTimestampAndCount(endTimestamp, Count) ?? new List<aaLogReader.LogRecord>();

            // Library returns newest-first when fetched by end-timestamp; keep that for human reading.
            var dtos = raw.Select(LogRecordDto.From);
            var filtered = RecordFilter.Apply(dtos, Component, Level, Message, UseRegex);

            if (LlmJson)
            {
                var query = new
                {
                    command = "last",
                    count = Count,
                    until = endTimestamp.ToString("yyyy-MM-ddTHH:mm:ss"),
                    component = Component,
                    level = Level,
                    message = Message,
                    regex = UseRegex,
                    log_dir = reader.Options.LogDirectory,
                };
                OutputWriter.WriteLlmJson(console, query, filtered);
            }
            else
            {
                OutputWriter.WriteHuman(console, filtered);
            }
            return default;
        }
    }
}
