using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using StellaOps.Feedser.Models;
using StellaOps.Feedser.Normalization.Cvss;
using StellaOps.Feedser.Normalization.Identifiers;
using StellaOps.Feedser.Normalization.Text;
using StellaOps.Feedser.Source.Common;
using StellaOps.Feedser.Storage.Mongo.Documents;
using StellaOps.Feedser.Storage.Mongo.Dtos;

namespace StellaOps.Feedser.Source.Osv.Internal;

internal static class OsvMapper
{
    private static readonly string[] SeverityOrder = { "none", "low", "medium", "high", "critical" };

    public static Advisory Map(
        OsvVulnerabilityDto dto,
        DocumentRecord document,
        DtoRecord dtoRecord,
        string ecosystem)
    {
        ArgumentNullException.ThrowIfNull(dto);
        ArgumentNullException.ThrowIfNull(document);
        ArgumentNullException.ThrowIfNull(dtoRecord);
        ArgumentException.ThrowIfNullOrEmpty(ecosystem);

        var recordedAt = dtoRecord.ValidatedAt;
        var fetchProvenance = new AdvisoryProvenance(OsvConnectorPlugin.SourceName, "document", document.Uri, document.FetchedAt);
        var mappingProvenance = new AdvisoryProvenance(OsvConnectorPlugin.SourceName, "mapping", dto.Id, recordedAt);

        var aliases = BuildAliases(dto);
        var references = BuildReferences(dto, recordedAt);
        var affectedPackages = BuildAffectedPackages(dto, ecosystem, recordedAt);
        var cvssMetrics = BuildCvssMetrics(dto, recordedAt, out var severity);

        var normalizedDescription = DescriptionNormalizer.Normalize(new[]
        {
            new LocalizedText(dto.Details, "en"),
            new LocalizedText(dto.Summary, "en"),
        });

        var title = string.IsNullOrWhiteSpace(dto.Summary) ? dto.Id : dto.Summary!.Trim();
        var summary = string.IsNullOrWhiteSpace(normalizedDescription.Text) ? dto.Summary : normalizedDescription.Text;
        var language = string.IsNullOrWhiteSpace(normalizedDescription.Language) ? null : normalizedDescription.Language;

        return new Advisory(
            dto.Id,
            title,
            summary,
            language,
            dto.Published?.ToUniversalTime(),
            dto.Modified?.ToUniversalTime(),
            severity,
            exploitKnown: false,
            aliases,
            references,
            affectedPackages,
            cvssMetrics,
            new[] { fetchProvenance, mappingProvenance });
    }

    private static IEnumerable<string> BuildAliases(OsvVulnerabilityDto dto)
    {
        var aliases = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
        {
            dto.Id,
        };

        if (dto.Aliases is not null)
        {
            foreach (var alias in dto.Aliases)
            {
                if (!string.IsNullOrWhiteSpace(alias))
                {
                    aliases.Add(alias.Trim());
                }
            }
        }

        if (dto.Related is not null)
        {
            foreach (var related in dto.Related)
            {
                if (!string.IsNullOrWhiteSpace(related))
                {
                    aliases.Add(related.Trim());
                }
            }
        }

        return aliases;
    }

    private static IReadOnlyList<AdvisoryReference> BuildReferences(OsvVulnerabilityDto dto, DateTimeOffset recordedAt)
    {
        if (dto.References is null || dto.References.Count == 0)
        {
            return Array.Empty<AdvisoryReference>();
        }

        var references = new List<AdvisoryReference>(dto.References.Count);
        foreach (var reference in dto.References)
        {
            if (string.IsNullOrWhiteSpace(reference.Url))
            {
                continue;
            }

            var kind = NormalizeReferenceKind(reference.Type);
            var provenance = new AdvisoryProvenance(OsvConnectorPlugin.SourceName, "reference", reference.Url, recordedAt);

            try
            {
                references.Add(new AdvisoryReference(reference.Url, kind, reference.Type, null, provenance));
            }
            catch (ArgumentException)
            {
                // ignore invalid URLs
            }
        }

        if (references.Count <= 1)
        {
            return references;
        }

        references.Sort(CompareReferences);

        var deduped = new List<AdvisoryReference>(references.Count);
        string? lastUrl = null;
        foreach (var reference in references)
        {
            if (lastUrl is not null && string.Equals(lastUrl, reference.Url, StringComparison.OrdinalIgnoreCase))
            {
                continue;
            }

            deduped.Add(reference);
            lastUrl = reference.Url;
        }

        return deduped;
    }

    private static string? NormalizeReferenceKind(string? type)
    {
        if (string.IsNullOrWhiteSpace(type))
        {
            return null;
        }

        return type.Trim().ToLowerInvariant() switch
        {
            "advisory" => "advisory",
            "exploit" => "exploit",
            "fix" or "patch" => "patch",
            "report" => "report",
            "article" => "article",
            _ => null,
        };
    }

    private static IReadOnlyList<AffectedPackage> BuildAffectedPackages(OsvVulnerabilityDto dto, string ecosystem, DateTimeOffset recordedAt)
    {
        if (dto.Affected is null || dto.Affected.Count == 0)
        {
            return Array.Empty<AffectedPackage>();
        }

        var packages = new List<AffectedPackage>(dto.Affected.Count);
        foreach (var affected in dto.Affected)
        {
            if (affected.Package is null)
            {
                continue;
            }

            var identifier = DetermineIdentifier(affected.Package, ecosystem);
            if (identifier is null)
            {
                continue;
            }

            var provenance = new[]
            {
                new AdvisoryProvenance(OsvConnectorPlugin.SourceName, "affected", identifier, recordedAt),
            };

            var ranges = BuildVersionRanges(affected, recordedAt, identifier);

            packages.Add(new AffectedPackage(
                AffectedPackageTypes.SemVer,
                identifier,
                platform: affected.Package.Ecosystem,
                versionRanges: ranges,
                statuses: Array.Empty<AffectedPackageStatus>(),
                provenance: provenance));
        }

        return packages;
    }

    private static IReadOnlyList<AffectedVersionRange> BuildVersionRanges(OsvAffectedPackageDto affected, DateTimeOffset recordedAt, string identifier)
    {
        if (affected.Ranges is null || affected.Ranges.Count == 0)
        {
            return Array.Empty<AffectedVersionRange>();
        }

        var ranges = new List<AffectedVersionRange>();
        foreach (var range in affected.Ranges)
        {
            if (!"semver".Equals(range.Type, StringComparison.OrdinalIgnoreCase)
                && !"ecosystem".Equals(range.Type, StringComparison.OrdinalIgnoreCase))
            {
                continue;
            }

            var provenance = new AdvisoryProvenance(OsvConnectorPlugin.SourceName, "range", identifier, recordedAt);
            if (range.Events is null || range.Events.Count == 0)
            {
                continue;
            }

            string? introduced = null;
            string? lastAffected = null;

            foreach (var evt in range.Events)
            {
                if (!string.IsNullOrWhiteSpace(evt.Introduced))
                {
                    introduced = evt.Introduced.Trim();
                    lastAffected = null;
                }

                if (!string.IsNullOrWhiteSpace(evt.LastAffected))
                {
                    lastAffected = evt.LastAffected.Trim();
                }

                if (!string.IsNullOrWhiteSpace(evt.Fixed))
                {
                    var fixedVersion = evt.Fixed.Trim();
                    ranges.Add(new AffectedVersionRange(
                        "semver",
                        introduced,
                        fixedVersion,
                        lastAffected,
                        rangeExpression: null,
                        provenance: provenance,
                        primitives: BuildSemVerPrimitives(introduced, fixedVersion, lastAffected)));
                    introduced = null;
                    lastAffected = null;
                }

                if (!string.IsNullOrWhiteSpace(evt.Limit))
                {
                    lastAffected = evt.Limit.Trim();
                }
            }

            if (introduced is not null || lastAffected is not null)
            {
                ranges.Add(new AffectedVersionRange(
                    "semver",
                    introduced,
                    fixedVersion: null,
                    lastAffected,
                    rangeExpression: null,
                    provenance: provenance,
                    primitives: BuildSemVerPrimitives(introduced, null, lastAffected)));
            }
        }

        return ranges.Count == 0
            ? Array.Empty<AffectedVersionRange>()
            : ranges;
    }

    private static RangePrimitives BuildSemVerPrimitives(string? introduced, string? fixedVersion, string? lastAffected)
    {
        var semver = new SemVerPrimitive(
            introduced,
            IntroducedInclusive: true,
            fixedVersion,
            FixedInclusive: false,
            lastAffected,
            LastAffectedInclusive: true,
            ConstraintExpression: null);

        return new RangePrimitives(semver, null, null, null);
    }

    private static string? DetermineIdentifier(OsvPackageDto package, string ecosystem)
    {
        if (!string.IsNullOrWhiteSpace(package.Purl)
            && IdentifierNormalizer.TryNormalizePackageUrl(package.Purl, out var normalized))
        {
            return normalized;
        }

        if (!string.IsNullOrWhiteSpace(package.Name))
        {
            var name = package.Name.Trim();
            return string.IsNullOrWhiteSpace(package.Ecosystem)
                ? $"{ecosystem}:{name}"
                : $"{package.Ecosystem.Trim()}:{name}";
        }

        return null;
    }

    private static IReadOnlyList<CvssMetric> BuildCvssMetrics(OsvVulnerabilityDto dto, DateTimeOffset recordedAt, out string? severity)
    {
        severity = null;
        if (dto.Severity is null || dto.Severity.Count == 0)
        {
            return Array.Empty<CvssMetric>();
        }

        var metrics = new List<CvssMetric>(dto.Severity.Count);
        var bestRank = -1;

        foreach (var severityEntry in dto.Severity)
        {
            if (string.IsNullOrWhiteSpace(severityEntry.Score))
            {
                continue;
            }

            if (!CvssMetricNormalizer.TryNormalize(severityEntry.Type, severityEntry.Score, null, null, out var normalized))
            {
                continue;
            }

            var provenance = new AdvisoryProvenance(OsvConnectorPlugin.SourceName, "cvss", severityEntry.Type ?? "osv", recordedAt);
            metrics.Add(normalized.ToModel(provenance));

            var rank = Array.IndexOf(SeverityOrder, normalized.BaseSeverity);
            if (rank > bestRank)
            {
                bestRank = rank;
                severity = normalized.BaseSeverity;
            }
        }

        if (bestRank < 0 && dto.DatabaseSpecific.ValueKind == JsonValueKind.Object &&
            dto.DatabaseSpecific.TryGetProperty("severity", out var severityProperty))
        {
            var fallback = severityProperty.GetString();
            if (!string.IsNullOrWhiteSpace(fallback))
            {
                severity = SeverityNormalization.Normalize(fallback);
            }
        }

        return metrics;
    }

    private static int CompareReferences(AdvisoryReference? left, AdvisoryReference? right)
    {
        if (ReferenceEquals(left, right))
        {
            return 0;
        }

        if (left is null)
        {
            return 1;
        }

        if (right is null)
        {
            return -1;
        }

        var compare = StringComparer.OrdinalIgnoreCase.Compare(left.Url, right.Url);
        if (compare != 0)
        {
            return compare;
        }

        compare = CompareNullable(left.Kind, right.Kind);
        if (compare != 0)
        {
            return compare;
        }

        compare = CompareNullable(left.SourceTag, right.SourceTag);
        if (compare != 0)
        {
            return compare;
        }

        return left.Provenance.RecordedAt.CompareTo(right.Provenance.RecordedAt);
    }

    private static int CompareNullable(string? left, string? right)
    {
        if (left is null && right is null)
        {
            return 0;
        }

        if (left is null)
        {
            return 1;
        }

        if (right is null)
        {
            return -1;
        }

        return StringComparer.Ordinal.Compare(left, right);
    }
}
