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

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

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

    /// <summary>Registers the TwinCAT driver factory with the provided 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 a TwinCAT driver instance from the provided configuration.</summary>
    /// <param name="driverInstanceId">The driver instance identifier.</param>
    /// <param name="driverConfigJson">The driver configuration as JSON.</param>
    /// <returns>The constructed <see cref="TwinCATDriver"/> instance.</returns>
    internal static TwinCATDriver CreateInstance(string driverInstanceId, string driverConfigJson)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(driverInstanceId);
        var options = ParseOptions(driverConfigJson, driverInstanceId);
        return new TwinCATDriver(options, driverInstanceId);
    }

    /// <summary>
    ///     Parse a TwinCAT driver-config JSON document into a <see cref="TwinCATDriverOptions"/>.
    ///     Shared by <see cref="CreateInstance"/> (constructor-time) and
    ///     <see cref="TwinCATDriver.InitializeAsync"/> / <see cref="TwinCATDriver.ReinitializeAsync"/>
    ///     so a config generation pushed via Reinitialize is actually applied.
    /// </summary>
    /// <param name="driverConfigJson">The JSON configuration string.</param>
    /// <param name="driverInstanceId">The driver instance identifier.</param>
    /// <returns>The parsed <see cref="TwinCATDriverOptions"/>.</returns>
    internal static TwinCATDriverOptions ParseOptions(string driverConfigJson, string driverInstanceId)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(driverConfigJson);

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

        return new TwinCATDriverOptions
        {
            Devices = dto.Devices is { Count: > 0 }
                ? [.. dto.Devices.Select(d => new TwinCATDeviceOptions(
                    HostAddress: d.HostAddress ?? throw new InvalidOperationException(
                        $"TwinCAT config for '{driverInstanceId}' has a device missing HostAddress"),
                    DeviceName: d.DeviceName))]
                : [],
            // v3: the deploy artifact (Wave C) populates rawTags with the cluster's authored raw TwinCAT
            // tags (RawPath + TagConfig blob + WriteIdempotent + owning DeviceName). The driver maps each
            // through TwinCATTagDefinitionFactory at Initialize; the legacy pre-declared DTO tag path
            // (tags[] → BuildTag) is retired.
            RawTags = dto.RawTags is { Count: > 0 } ? [.. dto.RawTags] : [],
            Probe = new TwinCATProbeOptions
            {
                Enabled = dto.Probe?.Enabled ?? true,
                Interval = TimeSpan.FromMilliseconds(dto.Probe?.IntervalMs ?? 5_000),
                Timeout = TimeSpan.FromMilliseconds(dto.Probe?.TimeoutMs ?? 2_000),
            },
            Timeout = TimeSpan.FromMilliseconds(dto.TimeoutMs ?? 2_000),
            UseNativeNotifications = dto.UseNativeNotifications ?? true,
            EnableControllerBrowse = dto.EnableControllerBrowse ?? false,
            NotificationMaxDelayMs = dto.NotificationMaxDelayMs ?? 0,
        };
    }

    /// <summary>
    ///     Test-visible wrapper around <see cref="ParseOptions"/> for the regression suite —
    ///     keeps the public driver surface unchanged while letting tests assert that JSON
    ///     fields like <c>NotificationMaxDelayMs</c> and <c>Structure</c>-tag rejection are
    ///     honored end-to-end.
    /// </summary>
    /// <param name="driverConfigJson">The JSON configuration string.</param>
    /// <param name="driverInstanceId">The driver instance identifier.</param>
    /// <returns>The parsed <see cref="TwinCATDriverOptions"/>.</returns>
    public static TwinCATDriverOptions ParseOptionsForTests(string driverConfigJson, string driverInstanceId)
        => ParseOptions(driverConfigJson, driverInstanceId);

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

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

        /// <summary>Gets or sets a value indicating whether to use native notifications.</summary>
        public bool? UseNativeNotifications { get; init; }

        /// <summary>Gets or sets a value indicating whether to enable controller browsing.</summary>
        public bool? EnableControllerBrowse { get; init; }

        /// <summary>Gets or sets the maximum notification delay in milliseconds.</summary>
        public int? NotificationMaxDelayMs { get; init; }

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

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

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

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

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

    internal sealed class TwinCATProbeDto
    {
        /// <summary>Gets or sets a value indicating 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; }
    }
}
