using System.IO.Pipelines;
using System.Text.RegularExpressions;
using CG.Web.MegaApiClient;
using CompatBot.EventHandlers.LogParsing.ArchiveHandlers;
using ResultNet;

namespace CompatBot.EventHandlers.LogParsing.SourceHandlers;

internal sealed partial class MegaHandler : BaseSourceHandler
{
    // mega.nz/#!8IJHBYyB!jw21m-GCs85uzj9E5XRysqyJCsNfZS0Zx4Eu9_zvuUM
    // mega.nz/file/8IJHBYyB#jw21m-GCs85uzj9E5XRysqyJCsNfZS0Zx4Eu9_zvuUM
    [GeneratedRegex(@"(?<mega_link>(https?://)?mega(\.co)?\.nz/(#(?<mega_id>[^/>\s]+)|file/(?<new_mega_id>[^/>\s]+)))", DefaultOptions)]
    private static partial Regex ExternalLink();
    private static readonly IProgress<double> Doodad = new Progress<double>(_ => { });

    public override async Task<Result<ISource>> FindHandlerAsync(DiscordMessage message, ICollection<IArchiveHandler> handlers)
    {
        if (message.Content is not {Length: >0})
            return Result.Failure<ISource>();

        var matches = ExternalLink().Matches(message.Content);
        if (matches is [])
            return Result.Failure<ISource>();

        var client = new MegaApiClient();
        await client.LoginAnonymousAsync();
        foreach (Match m in matches)
        {
            try
            {
                if (m.Groups["mega_link"].Value is not { Length: >0 } lnk
                    || !Uri.TryCreate(lnk, UriKind.Absolute, out var uri))
                    continue;
                
                var node = await client.GetNodeFromLinkAsync(uri).ConfigureAwait(false);
                if (node.Type is not NodeType.File)
                    continue;
                
                var buf = BufferPool.Rent(SnoopBufferSize);
                try
                {
                    await using var stream = await client.DownloadAsync(uri, Doodad, Config.Cts.Token).ConfigureAwait(false);
                    var read = await stream.ReadBytesAsync(buf).ConfigureAwait(false);
                    foreach (var handler in handlers)
                    {
                        var result = handler.CanHandle(node.Name, (int)node.Size, buf.AsSpan(0, read));
                        if (result.IsSuccess())
                            return Result.Success<ISource>(new MegaSource(client, uri, node, handler));
                        else if (result.Message is {Length: >0})
                            return result.Cast<ISource>();
                    }
                }
                finally
                {
                    BufferPool.Return(buf);
                }
            }
            catch (Exception e)
            {
                Config.Log.Warn(e, $"Error sniffing {m.Groups["mega_link"].Value}");
            }
        }
        return Result.Failure<ISource>();
    }

    private sealed class MegaSource : ISource
    {
        private readonly IMegaApiClient client;
        private readonly Uri uri;
        private readonly INode node;
        private readonly IArchiveHandler handler;

        public string SourceType => "Mega";
        public string FileName => node.Name;
        public long SourceFileSize => node.Size;
        public long SourceFilePosition => handler.SourcePosition;
        public long LogFileSize => handler.LogSize;

        internal MegaSource(IMegaApiClient client, Uri uri, INode node, IArchiveHandler handler)
        {
            this.client = client;
            this.uri = uri;
            this.node = node;
            this.handler = handler;
        }

        public async Task FillPipeAsync(PipeWriter writer, CancellationToken cancellationToken)
        {
            await using var stream = await client.DownloadAsync(uri, Doodad, cancellationToken).ConfigureAwait(false);
            await handler.FillPipeAsync(stream, writer, cancellationToken).ConfigureAwait(false);
        }

        public void Dispose() { }
    }
}