using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.AbCip;
using ZB.MOM.WW.OtOpcUa.Driver.AbLegacy;
using ZB.MOM.WW.OtOpcUa.Driver.FOCAS;
using ZB.MOM.WW.OtOpcUa.Driver.Modbus;
using ZB.MOM.WW.OtOpcUa.Driver.S7;
using ZB.MOM.WW.OtOpcUa.Driver.TwinCAT;

namespace ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;

/// <summary>
///     Deploy-time TagConfig inspection dispatched by <c>DriverType</c> (R2-11, 05/CONV-2). Mirrors the
///     AdminUI <c>TagConfigValidator</c> shape: a case-insensitive map from the canonical driver-type string
///     to that driver's lightweight <c>Contracts</c> parser <c>Inspect()</c>, returning human-readable
///     warnings (present-but-invalid enum values that the lenient runtime silently defaults, plus
///     structurally-unparseable TagConfig). Unmapped drivers (Galaxy, OpcUaClient) are skipped exactly as in
///     the AdminUI validator. Never throws.
/// </summary>
public static class EquipmentTagConfigInspector
{
    private static readonly IReadOnlyDictionary<string, Func<string, IReadOnlyList<string>>> Inspectors =
        new Dictionary<string, Func<string, IReadOnlyList<string>>>(StringComparer.OrdinalIgnoreCase)
        {
            [DriverTypeNames.Modbus]   = ModbusTagDefinitionFactory.Inspect,
            [DriverTypeNames.S7]       = S7TagDefinitionFactory.Inspect,
            [DriverTypeNames.AbCip]    = AbCipTagDefinitionFactory.Inspect,
            [DriverTypeNames.AbLegacy] = AbLegacyTagDefinitionFactory.Inspect,
            [DriverTypeNames.TwinCAT]  = TwinCATTagDefinitionFactory.Inspect,
            [DriverTypeNames.FOCAS]    = FocasTagDefinitionFactory.Inspect,
        };

    /// <summary>Inspects a tag's <c>TagConfig</c> for the given driver type. Returns the driver's warnings,
    /// or an empty list when the driver type is unmapped (Galaxy/OpcUaClient) or the inputs are null.</summary>
    /// <param name="driverType">The bound driver's <c>DriverType</c> (canonical string, case-insensitive).</param>
    /// <param name="tagConfig">The equipment tag's <c>TagConfig</c> JSON.</param>
    /// <returns>The warnings; empty when the driver is unmapped or clean.</returns>
    public static IReadOnlyList<string> Inspect(string? driverType, string? tagConfig)
    {
        if (string.IsNullOrEmpty(driverType) || tagConfig is null) return Array.Empty<string>();
        return Inspectors.TryGetValue(driverType, out var inspect) ? inspect(tagConfig) : Array.Empty<string>();
    }

    /// <summary>Whether the given driver type has a mapped inspector (equipment-tag protocol drivers only).</summary>
    /// <param name="driverType">The bound driver's <c>DriverType</c>.</param>
    /// <returns><see langword="true"/> when an inspector is registered for the driver type.</returns>
    public static bool IsMapped(string? driverType) =>
        !string.IsNullOrEmpty(driverType) && Inspectors.ContainsKey(driverType);
}
