using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using StellaOps.Feedser.Source.Common;
using StellaOps.Feedser.Source.Common.Fetch;
using StellaOps.Feedser.Source.Kisa.Configuration;
using StellaOps.Feedser.Source.Kisa.Internal;
using StellaOps.Feedser.Storage.Mongo;
using StellaOps.Feedser.Storage.Mongo.Advisories;
using StellaOps.Feedser.Storage.Mongo.Documents;
using StellaOps.Feedser.Storage.Mongo.Dtos;
using StellaOps.Plugin;

namespace StellaOps.Feedser.Source.Kisa;

public sealed class KisaConnector : IFeedConnector
{
    private static readonly JsonSerializerOptions SerializerOptions = new(JsonSerializerDefaults.Web)
    {
        PropertyNameCaseInsensitive = true,
        DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull,
    };

    private readonly KisaFeedClient _feedClient;
    private readonly KisaDetailParser _detailParser;
    private readonly SourceFetchService _fetchService;
    private readonly RawDocumentStorage _rawDocumentStorage;
    private readonly IDocumentStore _documentStore;
    private readonly IDtoStore _dtoStore;
    private readonly IAdvisoryStore _advisoryStore;
    private readonly ISourceStateRepository _stateRepository;
    private readonly KisaOptions _options;
    private readonly KisaDiagnostics _diagnostics;
    private readonly TimeProvider _timeProvider;
    private readonly ILogger<KisaConnector> _logger;

    public KisaConnector(
        KisaFeedClient feedClient,
        KisaDetailParser detailParser,
        SourceFetchService fetchService,
        RawDocumentStorage rawDocumentStorage,
        IDocumentStore documentStore,
        IDtoStore dtoStore,
        IAdvisoryStore advisoryStore,
        ISourceStateRepository stateRepository,
        IOptions<KisaOptions> options,
        KisaDiagnostics diagnostics,
        TimeProvider? timeProvider,
        ILogger<KisaConnector> logger)
    {
        _feedClient = feedClient ?? throw new ArgumentNullException(nameof(feedClient));
        _detailParser = detailParser ?? throw new ArgumentNullException(nameof(detailParser));
        _fetchService = fetchService ?? throw new ArgumentNullException(nameof(fetchService));
        _rawDocumentStorage = rawDocumentStorage ?? throw new ArgumentNullException(nameof(rawDocumentStorage));
        _documentStore = documentStore ?? throw new ArgumentNullException(nameof(documentStore));
        _dtoStore = dtoStore ?? throw new ArgumentNullException(nameof(dtoStore));
        _advisoryStore = advisoryStore ?? throw new ArgumentNullException(nameof(advisoryStore));
        _stateRepository = stateRepository ?? throw new ArgumentNullException(nameof(stateRepository));
        _options = (options ?? throw new ArgumentNullException(nameof(options))).Value ?? throw new ArgumentNullException(nameof(options));
        _options.Validate();
        _diagnostics = diagnostics ?? throw new ArgumentNullException(nameof(diagnostics));
        _timeProvider = timeProvider ?? TimeProvider.System;
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public string SourceName => KisaConnectorPlugin.SourceName;

    public async Task FetchAsync(IServiceProvider services, CancellationToken cancellationToken)
    {
        ArgumentNullException.ThrowIfNull(services);

        var cursor = await GetCursorAsync(cancellationToken).ConfigureAwait(false);
        var now = _timeProvider.GetUtcNow();
        _diagnostics.FeedAttempt();
        IReadOnlyList<KisaFeedItem> items;

        try
        {
            items = await _feedClient.LoadAsync(cancellationToken).ConfigureAwait(false);
            _diagnostics.FeedSuccess(items.Count);

            if (items.Count > 0)
            {
                _logger.LogInformation("KISA feed returned {ItemCount} advisories", items.Count);
            }
            else
            {
                _logger.LogDebug("KISA feed returned no advisories");
            }
        }
        catch (Exception ex)
        {
            _diagnostics.FeedFailure(ex.GetType().Name);
            _logger.LogError(ex, "KISA feed fetch failed");
            await _stateRepository.MarkFailureAsync(SourceName, now, _options.FailureBackoff, ex.Message, cancellationToken).ConfigureAwait(false);
            throw;
        }

        if (items.Count == 0)
        {
            await UpdateCursorAsync(cursor.WithLastFetch(now), cancellationToken).ConfigureAwait(false);
            return;
        }

        var pendingDocuments = cursor.PendingDocuments.ToHashSet();
        var pendingMappings = cursor.PendingMappings.ToHashSet();
        var knownIds = new HashSet<string>(cursor.KnownIds, StringComparer.OrdinalIgnoreCase);
        var processed = 0;
        var latestPublished = cursor.LastPublished ?? DateTimeOffset.MinValue;

        foreach (var item in items.OrderByDescending(static i => i.Published))
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (knownIds.Contains(item.AdvisoryId))
            {
                continue;
            }

            if (processed >= _options.MaxAdvisoriesPerFetch)
            {
                break;
            }

            var category = item.Category;
            _diagnostics.DetailAttempt(category);

            try
            {
                var existing = await _documentStore.FindBySourceAndUriAsync(SourceName, item.DetailApiUri.ToString(), cancellationToken).ConfigureAwait(false);
                var request = new SourceFetchRequest(KisaOptions.HttpClientName, SourceName, item.DetailApiUri)
                {
                    Metadata = KisaDocumentMetadata.CreateMetadata(item),
                    AcceptHeaders = new[] { "application/json", "text/json" },
                    ETag = existing?.Etag,
                    LastModified = existing?.LastModified,
                    TimeoutOverride = _options.RequestTimeout,
                };

                var result = await _fetchService.FetchAsync(request, cancellationToken).ConfigureAwait(false);
                if (result.IsNotModified)
                {
                    _diagnostics.DetailUnchanged(category);
                    _logger.LogDebug("KISA detail {Idx} unchanged ({Category})", item.AdvisoryId, category ?? "unknown");
                    knownIds.Add(item.AdvisoryId);
                    continue;
                }

                if (!result.IsSuccess || result.Document is null)
                {
                    _diagnostics.DetailFailure(category, "empty-document");
                    _logger.LogWarning("KISA detail fetch returned no document for {Idx}", item.AdvisoryId);
                    continue;
                }

                pendingDocuments.Add(result.Document.Id);
                pendingMappings.Remove(result.Document.Id);
                knownIds.Add(item.AdvisoryId);
                processed++;
                _diagnostics.DetailSuccess(category);
                _logger.LogInformation(
                    "KISA fetched detail for {Idx} (documentId={DocumentId}, category={Category})",
                    item.AdvisoryId,
                    result.Document.Id,
                    category ?? "unknown");

                if (_options.RequestDelay > TimeSpan.Zero)
                {
                    await Task.Delay(_options.RequestDelay, cancellationToken).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                _diagnostics.DetailFailure(category, ex.GetType().Name);
                _logger.LogError(ex, "KISA detail fetch failed for {Idx}", item.AdvisoryId);
                await _stateRepository.MarkFailureAsync(SourceName, now, _options.FailureBackoff, ex.Message, cancellationToken).ConfigureAwait(false);
                throw;
            }

            if (item.Published > latestPublished)
            {
                latestPublished = item.Published;
                _diagnostics.CursorAdvanced();
                _logger.LogDebug("KISA advanced published cursor to {Published:O}", latestPublished);
            }
        }

        var trimmedKnown = knownIds.Count > _options.MaxKnownAdvisories
            ? knownIds.OrderByDescending(id => id, StringComparer.OrdinalIgnoreCase)
                .Take(_options.MaxKnownAdvisories)
                .ToArray()
            : knownIds.ToArray();

        var updatedCursor = cursor
            .WithPendingDocuments(pendingDocuments)
            .WithPendingMappings(pendingMappings)
            .WithKnownIds(trimmedKnown)
            .WithLastPublished(latestPublished == DateTimeOffset.MinValue ? cursor.LastPublished : latestPublished)
            .WithLastFetch(now);

        await UpdateCursorAsync(updatedCursor, cancellationToken).ConfigureAwait(false);
        _logger.LogInformation("KISA fetch stored {Processed} new documents (knownIds={KnownCount})", processed, trimmedKnown.Length);
    }

    public async Task ParseAsync(IServiceProvider services, CancellationToken cancellationToken)
    {
        ArgumentNullException.ThrowIfNull(services);

        var cursor = await GetCursorAsync(cancellationToken).ConfigureAwait(false);
        if (cursor.PendingDocuments.Count == 0)
        {
            return;
        }

        var remainingDocuments = cursor.PendingDocuments.ToHashSet();
        var pendingMappings = cursor.PendingMappings.ToHashSet();
        var now = _timeProvider.GetUtcNow();

        foreach (var documentId in cursor.PendingDocuments)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var document = await _documentStore.FindAsync(documentId, cancellationToken).ConfigureAwait(false);
            if (document is null)
            {
                _diagnostics.ParseFailure(null, "document-missing");
                _logger.LogWarning("KISA document {DocumentId} missing during parse", documentId);
                remainingDocuments.Remove(documentId);
                pendingMappings.Remove(documentId);
                continue;
            }

            var category = GetCategory(document);
            if (!document.GridFsId.HasValue)
            {
                _diagnostics.ParseFailure(category, "missing-gridfs");
                _logger.LogWarning("KISA document {DocumentId} missing GridFS payload", document.Id);
                await _documentStore.UpdateStatusAsync(document.Id, DocumentStatuses.Failed, cancellationToken).ConfigureAwait(false);
                remainingDocuments.Remove(documentId);
                pendingMappings.Remove(documentId);
                continue;
            }

            _diagnostics.ParseAttempt(category);

            byte[] payload;
            try
            {
                payload = await _rawDocumentStorage.DownloadAsync(document.GridFsId.Value, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _diagnostics.ParseFailure(category, "download");
                _logger.LogError(ex, "KISA unable to download document {DocumentId}", document.Id);
                throw;
            }

            KisaParsedAdvisory parsed;
            try
            {
                var apiUri = new Uri(document.Uri);
                var pageUri = document.Metadata is not null && document.Metadata.TryGetValue("kisa.detailPage", out var pageValue)
                    ? new Uri(pageValue)
                    : apiUri;
                parsed = _detailParser.Parse(apiUri, pageUri, payload);
            }
            catch (Exception ex)
            {
                _diagnostics.ParseFailure(category, "parse");
                _logger.LogError(ex, "KISA failed to parse detail {DocumentId}", document.Id);
                await _documentStore.UpdateStatusAsync(document.Id, DocumentStatuses.Failed, cancellationToken).ConfigureAwait(false);
                remainingDocuments.Remove(documentId);
                pendingMappings.Remove(documentId);
                continue;
            }
            _diagnostics.ParseSuccess(category);
            _logger.LogDebug("KISA parsed detail for {DocumentId} ({Category})", document.Id, category ?? "unknown");

            var dtoBson = BsonDocument.Parse(JsonSerializer.Serialize(parsed, SerializerOptions));
            var dtoRecord = new DtoRecord(Guid.NewGuid(), document.Id, SourceName, "kisa.detail.v1", dtoBson, now);
            await _dtoStore.UpsertAsync(dtoRecord, cancellationToken).ConfigureAwait(false);
            await _documentStore.UpdateStatusAsync(document.Id, DocumentStatuses.PendingMap, cancellationToken).ConfigureAwait(false);

            remainingDocuments.Remove(documentId);
            pendingMappings.Add(document.Id);
        }

        var updatedCursor = cursor
            .WithPendingDocuments(remainingDocuments)
            .WithPendingMappings(pendingMappings);

        await UpdateCursorAsync(updatedCursor, cancellationToken).ConfigureAwait(false);
    }

    public async Task MapAsync(IServiceProvider services, CancellationToken cancellationToken)
    {
        ArgumentNullException.ThrowIfNull(services);

        var cursor = await GetCursorAsync(cancellationToken).ConfigureAwait(false);
        if (cursor.PendingMappings.Count == 0)
        {
            return;
        }

        var pendingMappings = cursor.PendingMappings.ToHashSet();

        foreach (var documentId in cursor.PendingMappings)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var document = await _documentStore.FindAsync(documentId, cancellationToken).ConfigureAwait(false);
            if (document is null)
            {
                _diagnostics.MapFailure(null, "document-missing");
                _logger.LogWarning("KISA document {DocumentId} missing during map", documentId);
                pendingMappings.Remove(documentId);
                continue;
            }

            var dtoRecord = await _dtoStore.FindByDocumentIdAsync(documentId, cancellationToken).ConfigureAwait(false);
            if (dtoRecord is null)
            {
                _diagnostics.MapFailure(null, "dto-missing");
                _logger.LogWarning("KISA DTO missing for document {DocumentId}", document.Id);
                await _documentStore.UpdateStatusAsync(document.Id, DocumentStatuses.Failed, cancellationToken).ConfigureAwait(false);
                pendingMappings.Remove(documentId);
                continue;
            }

            KisaParsedAdvisory? parsed;
            try
            {
                parsed = JsonSerializer.Deserialize<KisaParsedAdvisory>(dtoRecord.Payload.ToJson(), SerializerOptions);
            }
            catch (Exception ex)
            {
                _diagnostics.MapFailure(null, "dto-deserialize");
                _logger.LogError(ex, "KISA failed to deserialize DTO for document {DocumentId}", document.Id);
                await _documentStore.UpdateStatusAsync(document.Id, DocumentStatuses.Failed, cancellationToken).ConfigureAwait(false);
                pendingMappings.Remove(documentId);
                continue;
            }

            if (parsed is null)
            {
                _diagnostics.MapFailure(null, "dto-null");
                await _documentStore.UpdateStatusAsync(document.Id, DocumentStatuses.Failed, cancellationToken).ConfigureAwait(false);
                pendingMappings.Remove(documentId);
                continue;
            }

            try
            {
                var advisory = KisaMapper.Map(parsed, document, dtoRecord.ValidatedAt);
                await _advisoryStore.UpsertAsync(advisory, cancellationToken).ConfigureAwait(false);
                await _documentStore.UpdateStatusAsync(document.Id, DocumentStatuses.Mapped, cancellationToken).ConfigureAwait(false);
                pendingMappings.Remove(documentId);
                _diagnostics.MapSuccess(parsed.Severity);
                _logger.LogInformation("KISA mapped advisory {AdvisoryId} (severity={Severity})", parsed.AdvisoryId, parsed.Severity ?? "unknown");
            }
            catch (Exception ex)
            {
                _diagnostics.MapFailure(parsed.Severity, "map");
                _logger.LogError(ex, "KISA mapping failed for document {DocumentId}", document.Id);
                await _documentStore.UpdateStatusAsync(document.Id, DocumentStatuses.Failed, cancellationToken).ConfigureAwait(false);
                pendingMappings.Remove(documentId);
            }
        }

        var updatedCursor = cursor.WithPendingMappings(pendingMappings);
        await UpdateCursorAsync(updatedCursor, cancellationToken).ConfigureAwait(false);
    }

    private static string? GetCategory(DocumentRecord document)
    {
        if (document.Metadata is null)
        {
            return null;
        }

        return document.Metadata.TryGetValue("kisa.category", out var category)
            ? category
            : null;
    }

    private async Task<KisaCursor> GetCursorAsync(CancellationToken cancellationToken)
    {
        var state = await _stateRepository.TryGetAsync(SourceName, cancellationToken).ConfigureAwait(false);
        return state is null ? KisaCursor.Empty : KisaCursor.FromBson(state.Cursor);
    }

    private Task UpdateCursorAsync(KisaCursor cursor, CancellationToken cancellationToken)
    {
        var document = cursor.ToBsonDocument();
        var completedAt = cursor.LastFetchAt ?? _timeProvider.GetUtcNow();
        return _stateRepository.UpdateCursorAsync(SourceName, document, completedAt, cancellationToken);
    }
}
