using System.Text.Json;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Hosting;

namespace ZB.MOM.WW.OtOpcUa.Driver.AbCip;

/// <summary>
///     Static factory registration helper for <see cref="AbCipDriver"/>. Server's Program.cs
///     calls <see cref="Register"/> once at startup; the bootstrapper then
///     materialises AB CIP DriverInstance rows from the central config DB into live driver
///     instances. Mirrors <c>GalaxyProxyDriverFactoryExtensions</c>.
/// </summary>
public static class AbCipDriverFactoryExtensions
{
    public const string DriverTypeName = "AbCip";

    /// <summary>
    /// Registers the AB CIP driver factory with the driver registry.
    /// </summary>
    /// <param name="registry">The driver factory registry to register with.</param>
    public static void Register(DriverFactoryRegistry registry)
    {
        ArgumentNullException.ThrowIfNull(registry);
        registry.Register(DriverTypeName, CreateInstance);
    }

    /// <summary>
    /// Creates an instance of the AB CIP driver from configuration.
    /// </summary>
    /// <param name="driverInstanceId">The unique identifier for this driver instance.</param>
    /// <param name="driverConfigJson">The driver configuration as a JSON string.</param>
    /// <returns>A configured <see cref="AbCipDriver"/> instance.</returns>
    internal static AbCipDriver CreateInstance(string driverInstanceId, string driverConfigJson)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(driverInstanceId);
        var options = ParseOptions(driverInstanceId, driverConfigJson);
        return new AbCipDriver(options, driverInstanceId);
    }

    /// <summary>
    ///     Deserialise an AB CIP driver-config JSON document into <see cref="AbCipDriverOptions"/>.
    ///     Shared by <see cref="CreateInstance"/> (first construction) and
    ///     <see cref="AbCipDriver.InitializeAsync"/> / <see cref="AbCipDriver.ReinitializeAsync"/>
    ///     so a reinitialize with a changed config JSON (new device, new tag, changed timeout)
    ///     actually takes effect rather than being silently discarded.
    /// </summary>
    /// <param name="driverInstanceId">The unique identifier for this driver instance.</param>
    /// <param name="driverConfigJson">The driver configuration as a JSON string.</param>
    /// <returns>Parsed driver options.</returns>
    internal static AbCipDriverOptions ParseOptions(string driverInstanceId, string driverConfigJson)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(driverInstanceId);
        ArgumentException.ThrowIfNullOrWhiteSpace(driverConfigJson);

        var dto = JsonSerializer.Deserialize<AbCipDriverConfigDto>(driverConfigJson, JsonOptions)
            ?? throw new InvalidOperationException(
                $"AB CIP driver config for '{driverInstanceId}' deserialised to null");

        return new AbCipDriverOptions
        {
            Devices = dto.Devices is { Count: > 0 }
                ? [.. dto.Devices.Select(d => new AbCipDeviceOptions(
                    HostAddress: d.HostAddress ?? throw new InvalidOperationException(
                        $"AB CIP config for '{driverInstanceId}' has a device missing HostAddress"),
                    PlcFamily: ParseEnum<AbCipPlcFamily>(d.PlcFamily, "device", driverInstanceId, "PlcFamily",
                        fallback: AbCipPlcFamily.ControlLogix),
                    DeviceName: d.DeviceName,
                    AllowPacking: d.AllowPacking,
                    ConnectionSize: d.ConnectionSize))]
                : [],
            // v3: the deploy artifact (Wave C) populates RawTags with the cluster's authored raw AbCip
            // tags (RawPath + TagConfig blob + WriteIdempotent + DeviceName). The driver maps each entry
            // through AbCipTagDefinitionFactory.FromTagConfig at Initialize; the legacy pre-declared DTO
            // tag path (structured Tags[] → BuildTag) is retired.
            RawTags = dto.RawTags is { Count: > 0 } ? [.. dto.RawTags] : [],
            Probe = new AbCipProbeOptions
            {
                Enabled = dto.Probe?.Enabled ?? true,
                Interval = TimeSpan.FromMilliseconds(dto.Probe?.IntervalMs ?? 5_000),
                Timeout = PositiveTimeoutOrDefault(dto.Probe?.TimeoutMs, 2_000),
                ProbeTagPath = dto.Probe?.ProbeTagPath,
            },
            Timeout = PositiveTimeoutOrDefault(dto.TimeoutMs, 2_000),
            EnableControllerBrowse = dto.EnableControllerBrowse ?? false,
            EnableAlarmProjection = dto.EnableAlarmProjection ?? false,
            AlarmPollInterval = TimeSpan.FromMilliseconds(dto.AlarmPollIntervalMs ?? 1_000),
            EnableDeclarationOnlyUdtGrouping = dto.EnableDeclarationOnlyUdtGrouping ?? false,
        };
    }

    /// <summary>
    ///     Maps an operator-supplied timeout (ms) to a positive <see cref="TimeSpan"/>, substituting
    ///     <paramref name="defaultMs"/> for a null / zero / negative value. libplctag's managed
    ///     <c>Tag.Timeout</c> setter throws <see cref="ArgumentOutOfRangeException"/> for a
    ///     non-positive value, which would otherwise fault tag creation on every read/write; clamping
    ///     here keeps a misconfigured <c>TimeoutMs: 0</c> running on the default bound instead. (Driver
    ///     timeout hardening, sibling of the S7 R2-01 read-leg fix.)
    /// </summary>
    /// <param name="ms">The operator-supplied timeout in milliseconds, or null.</param>
    /// <param name="defaultMs">The default applied when <paramref name="ms"/> is null or non-positive.</param>
    /// <returns>A strictly positive timeout.</returns>
    private static TimeSpan PositiveTimeoutOrDefault(int? ms, int defaultMs) =>
        TimeSpan.FromMilliseconds(ms is int v and > 0 ? v : defaultMs);

    private static T ParseEnum<T>(string? raw, string? tagName, string driverInstanceId, string field,
        T? fallback = null) where T : struct, Enum
    {
        if (string.IsNullOrWhiteSpace(raw))
        {
            if (fallback.HasValue) return fallback.Value;
            throw new InvalidOperationException(
                $"AB CIP tag '{tagName ?? "<unnamed>"}' in '{driverInstanceId}' missing {field}");
        }
        return Enum.TryParse<T>(raw, ignoreCase: true, out var v)
            ? v
            : throw new InvalidOperationException(
                $"AB CIP tag '{tagName}' has unknown {field} '{raw}'. " +
                $"Expected one of {string.Join(", ", Enum.GetNames<T>())}");
    }

    private static readonly JsonSerializerOptions JsonOptions = new()
    {
        PropertyNameCaseInsensitive = true,
        ReadCommentHandling = JsonCommentHandling.Skip,
        AllowTrailingCommas = true,
    };

    internal sealed class AbCipDriverConfigDto
    {
        /// <summary>
        /// Gets or sets the timeout in milliseconds for operations.
        /// </summary>
        public int? TimeoutMs { get; init; }

        /// <summary>
        /// Gets or sets whether controller browsing is enabled.
        /// </summary>
        public bool? EnableControllerBrowse { get; init; }

        /// <summary>
        /// Gets or sets whether alarm projection is enabled.
        /// </summary>
        public bool? EnableAlarmProjection { get; init; }

        /// <summary>
        /// Gets or sets whether declaration-only UDT grouping is enabled.
        /// </summary>
        public bool? EnableDeclarationOnlyUdtGrouping { get; init; }

        /// <summary>
        /// Gets or sets the alarm poll interval in milliseconds.
        /// </summary>
        public int? AlarmPollIntervalMs { get; init; }

        /// <summary>
        /// Gets or sets the list of devices to connect to.
        /// </summary>
        public List<AbCipDeviceDto>? Devices { get; init; }

        /// <summary>
        /// Gets or sets the authored raw tags (RawPath + TagConfig blob + WriteIdempotent + DeviceName)
        /// the deploy artifact delivers. The driver maps each through the tag-definition factory at Initialize.
        /// </summary>
        public List<RawTagEntry>? RawTags { get; init; }

        /// <summary>
        /// Gets or sets the probe configuration.
        /// </summary>
        public AbCipProbeDto? Probe { get; init; }
    }

    internal sealed class AbCipDeviceDto
    {
        /// <summary>
        /// Gets or sets the host address of the device.
        /// </summary>
        public string? HostAddress { get; init; }

        /// <summary>
        /// Gets or sets the PLC family.
        /// </summary>
        public string? PlcFamily { get; init; }

        /// <summary>
        /// Gets or sets the device name.
        /// </summary>
        public string? DeviceName { get; init; }

        /// <summary>
        /// Gets or sets whether packing is allowed.
        /// </summary>
        public bool? AllowPacking { get; init; }

        /// <summary>
        /// Gets or sets the connection size.
        /// </summary>
        public int? ConnectionSize { get; init; }
    }

    internal sealed class AbCipProbeDto
    {
        /// <summary>
        /// Gets or sets whether probing is enabled.
        /// </summary>
        public bool? Enabled { get; init; }

        /// <summary>
        /// Gets or sets the probe interval in milliseconds.
        /// </summary>
        public int? IntervalMs { get; init; }

        /// <summary>
        /// Gets or sets the probe timeout in milliseconds.
        /// </summary>
        public int? TimeoutMs { get; init; }

        /// <summary>
        /// Gets or sets the probe tag path.
        /// </summary>
        public string? ProbeTagPath { get; init; }
    }
}
