using System.Text.RegularExpressions;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;

namespace ZB.MOM.WW.OtOpcUa.Configuration.Validation;

/// <summary>
///     Managed-code pre-publish validator per decision #91. Complements the structural checks in
///     <c>sp_ValidateDraft</c> — this layer owns schema validation for JSON columns, UNS segment
///     regex, EquipmentId derivation, cross-cluster checks, and anything else that's uncomfortable
///     to express in T-SQL. Returns every failing rule in one pass (decision: surface all errors,
///     not just the first, so operators fix in bulk).
/// </summary>
public static class DraftValidator
{
    private static readonly Regex UnsSegment = new(@"^[a-z0-9-]{1,32}$", RegexOptions.Compiled);
    private const string UnsDefaultSegment = "_default";
    private const int MaxPathLength = 200;

    /// <summary>
    ///     Validates a draft snapshot and returns all validation errors found in a single pass.
    /// </summary>
    /// <param name="draft">The draft snapshot to validate.</param>
    public static IReadOnlyList<ValidationError> Validate(DraftSnapshot draft)
    {
        var errors = new List<ValidationError>();

        ValidateUnsSegments(draft, errors);
        ValidatePathLength(draft, errors);
        ValidateEquipmentUuidImmutability(draft, errors);
        ValidateSameClusterNamespaceBinding(draft, errors);
        ValidateReservationPreflight(draft, errors);
        ValidateEquipmentIdDerivation(draft, errors);
        ValidateDriverNamespaceCompatibility(draft, errors);

        return errors;
    }

    private static bool IsValidSegment(string? s) =>
        s is not null && (UnsSegment.IsMatch(s) || s == UnsDefaultSegment);

    private static void ValidateUnsSegments(DraftSnapshot draft, List<ValidationError> errors)
    {
        foreach (var a in draft.UnsAreas)
            if (!IsValidSegment(a.Name))
                errors.Add(new("UnsSegmentInvalid",
                    $"UnsArea.Name '{a.Name}' does not match [a-z0-9-]{{1,32}} or '_default'",
                    a.UnsAreaId));

        foreach (var l in draft.UnsLines)
            if (!IsValidSegment(l.Name))
                errors.Add(new("UnsSegmentInvalid",
                    $"UnsLine.Name '{l.Name}' does not match [a-z0-9-]{{1,32}} or '_default'",
                    l.UnsLineId));

        foreach (var e in draft.Equipment)
            if (!IsValidSegment(e.Name))
                errors.Add(new("UnsSegmentInvalid",
                    $"Equipment.Name '{e.Name}' does not match [a-z0-9-]{{1,32}} or '_default'",
                    e.EquipmentId));
    }

    /// <summary>Cluster.Enterprise + Site + area + line + equipment + 4 slashes ≤ 200 chars.</summary>
    private static void ValidatePathLength(DraftSnapshot draft, List<ValidationError> errors)
    {
        // Use actual Enterprise/Site lengths when the snapshot carries them (populated by
        // DraftValidationService from the ServerCluster row). Fall back to a conservative
        // 32-char upper bound per segment when not supplied — over-penalises short values
        // but never under-penalises long ones, which is acceptable for the fallback case.
        var enterpriseLen = draft.Enterprise?.Length ?? 32;
        var siteLen = draft.Site?.Length ?? 32;

        var areaById = draft.UnsAreas.ToDictionary(a => a.UnsAreaId);
        var lineById = draft.UnsLines.ToDictionary(l => l.UnsLineId);

        foreach (var eq in draft.Equipment.Where(e => e.UnsLineId is not null))
        {
            if (!lineById.TryGetValue(eq.UnsLineId!, out var line)) continue;
            if (!areaById.TryGetValue(line.UnsAreaId, out var area)) continue;

            var len = enterpriseLen + siteLen + area.Name.Length + line.Name.Length + eq.Name.Length + 4;
            if (len > MaxPathLength)
                errors.Add(new("PathTooLong",
                    $"Equipment path exceeds {MaxPathLength} chars (approx {len})",
                    eq.EquipmentId));
        }
    }

    private static void ValidateEquipmentUuidImmutability(DraftSnapshot draft, List<ValidationError> errors)
    {
        var priorById = draft.PriorEquipment
            .GroupBy(e => e.EquipmentId)
            .ToDictionary(g => g.Key, g => g.First().EquipmentUuid);

        foreach (var eq in draft.Equipment)
        {
            if (priorById.TryGetValue(eq.EquipmentId, out var priorUuid) && priorUuid != eq.EquipmentUuid)
                errors.Add(new("EquipmentUuidImmutable",
                    $"EquipmentId '{eq.EquipmentId}' had UUID '{priorUuid}' in a prior generation; cannot change to '{eq.EquipmentUuid}'",
                    eq.EquipmentId));
        }
    }

    private static void ValidateSameClusterNamespaceBinding(DraftSnapshot draft, List<ValidationError> errors)
    {
        var nsById = draft.Namespaces.ToDictionary(n => n.NamespaceId);

        foreach (var di in draft.DriverInstances)
        {
            if (!nsById.TryGetValue(di.NamespaceId, out var ns))
            {
                errors.Add(new("NamespaceUnresolved",
                    $"DriverInstance '{di.DriverInstanceId}' references unknown NamespaceId '{di.NamespaceId}'",
                    di.DriverInstanceId));
                continue;
            }

            if (ns.ClusterId != di.ClusterId)
                errors.Add(new("BadCrossClusterNamespaceBinding",
                    $"DriverInstance '{di.DriverInstanceId}' is in cluster '{di.ClusterId}' but references namespace in cluster '{ns.ClusterId}'",
                    di.DriverInstanceId));
        }
    }

    private static void ValidateReservationPreflight(DraftSnapshot draft, List<ValidationError> errors)
    {
        var activeByKindValue = draft.ActiveReservations
            .ToDictionary(r => (r.Kind, r.Value), r => r.EquipmentUuid);

        foreach (var eq in draft.Equipment)
        {
            if (eq.ZTag is not null &&
                activeByKindValue.TryGetValue((ReservationKind.ZTag, eq.ZTag), out var ztagOwner) &&
                ztagOwner != eq.EquipmentUuid)
                errors.Add(new("BadDuplicateExternalIdentifier",
                    $"ZTag '{eq.ZTag}' is already reserved by EquipmentUuid '{ztagOwner}'",
                    eq.EquipmentId));

            if (eq.SAPID is not null &&
                activeByKindValue.TryGetValue((ReservationKind.SAPID, eq.SAPID), out var sapOwner) &&
                sapOwner != eq.EquipmentUuid)
                errors.Add(new("BadDuplicateExternalIdentifier",
                    $"SAPID '{eq.SAPID}' is already reserved by EquipmentUuid '{sapOwner}'",
                    eq.EquipmentId));
        }
    }

    /// <summary>Decision #125: EquipmentId = 'EQ-' + lowercase first 12 hex chars of the UUID.</summary>
    /// <param name="uuid">The equipment UUID to derive the ID from.</param>
    public static string DeriveEquipmentId(Guid uuid) =>
        "EQ-" + uuid.ToString("N")[..12].ToLowerInvariant();

    private static void ValidateEquipmentIdDerivation(DraftSnapshot draft, List<ValidationError> errors)
    {
        foreach (var eq in draft.Equipment)
        {
            var expected = DeriveEquipmentId(eq.EquipmentUuid);
            if (!string.Equals(eq.EquipmentId, expected, StringComparison.Ordinal))
                errors.Add(new("EquipmentIdNotDerived",
                    $"Equipment.EquipmentId '{eq.EquipmentId}' does not match the canonical derivation '{expected}'",
                    eq.EquipmentId));
        }
    }

    private static void ValidateDriverNamespaceCompatibility(DraftSnapshot draft, List<ValidationError> errors)
    {
        var nsById = draft.Namespaces.ToDictionary(n => n.NamespaceId);

        foreach (var di in draft.DriverInstances)
        {
            if (!nsById.TryGetValue(di.NamespaceId, out var ns)) continue;

            var compat = ns.Kind switch
            {
                NamespaceKind.SystemPlatform => di.DriverType == "GalaxyMxGateway",
                NamespaceKind.Equipment      => di.DriverType != "GalaxyMxGateway",
                _                            => true,
            };

            if (!compat)
                errors.Add(new("DriverNamespaceKindMismatch",
                    $"DriverInstance '{di.DriverInstanceId}' ({di.DriverType}) is not allowed in {ns.Kind} namespace",
                    di.DriverInstanceId));
        }
    }

    /// <summary>
    ///     Phase 6.3 Stream A.2 + task #148 part 2 — managed pre-publish guard for cluster
    ///     topology vs. <see cref="ServerCluster.RedundancyMode"/>. The SQL
    ///     <c>CK_ServerCluster_RedundancyMode_NodeCount</c> CHECK already enforces the
    ///     (NodeCount, RedundancyMode) pair on the row itself, but it cannot see the
    ///     <see cref="ClusterNode.Enabled"/> flag on child nodes — an operator can toggle
    ///     nodes off (effective count = 1) while leaving RedundancyMode at Hot and the
    ///     constraint stays green. This check catches that drift before publish so the
    ///     runtime doesn't boot into a topology the <see cref="Enums.RedundancyMode"/> claims
    ///     is invalid.
    /// </summary>
    /// <remarks>
    ///     Called from the publish pipeline separately from <see cref="Validate"/> because the
    ///     cluster/nodes rows aren't generation-versioned — they don't belong on
    ///     <see cref="DraftSnapshot"/>. Returns every failing rule in one pass, same shape as
    ///     <see cref="Validate"/>.
    /// </remarks>
    /// <param name="cluster">The server cluster to validate.</param>
    /// <param name="clusterNodes">The cluster nodes to validate against the cluster configuration.</param>
    public static IReadOnlyList<ValidationError> ValidateClusterTopology(
        ServerCluster cluster,
        IReadOnlyList<ClusterNode> clusterNodes)
    {
        ArgumentNullException.ThrowIfNull(cluster);
        ArgumentNullException.ThrowIfNull(clusterNodes);

        var errors = new List<ValidationError>();
        var enabledNodes = clusterNodes.Count(n => n.Enabled);

        // Declared count must match declared mode (belt around the SQL CHECK).
        var declaredOk = (cluster.NodeCount, cluster.RedundancyMode) switch
        {
            (1, RedundancyMode.None) => true,
            (2, RedundancyMode.Warm) => true,
            (2, RedundancyMode.Hot) => true,
            _ => false,
        };
        if (!declaredOk)
            errors.Add(new("ClusterRedundancyModeInvalid",
                $"Cluster '{cluster.ClusterId}' declares NodeCount={cluster.NodeCount} + RedundancyMode={cluster.RedundancyMode}. " +
                $"Supported combinations: (1, None), (2, Warm), (2, Hot).",
                cluster.ClusterId));

        // Enabled-node count must match declared count. Disabling a node to 1 while leaving
        // mode at Hot/Warm would boot the runtime into InvalidTopology band.
        if (enabledNodes != cluster.NodeCount)
            errors.Add(new("ClusterEnabledNodeCountMismatch",
                $"Cluster '{cluster.ClusterId}' declares NodeCount={cluster.NodeCount} but has {enabledNodes} Enabled nodes. " +
                $"Toggle the missing node(s) back on or change RedundancyMode/NodeCount to match.",
                cluster.ClusterId));

        // v2: the v1 "exactly one Primary per cluster" invariant is gone. RedundancyRole was
        // dropped in Task 14d; in v2 the Akka cluster's role-leader-of-"driver" elects the
        // primary at runtime, so there is no static configuration to validate here.

        return errors;
    }
}
