using System.Text.Json;
using System.Text.Json.Serialization;
using ZB.MOM.WW.OtOpcUa.Core.Hosting;
using ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.PlcFamilies;

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

/// <summary>
///     Static factory registration helper for <see cref="AbLegacyDriver"/>. Server's Program.cs
///     calls <see cref="Register"/> once at startup; the bootstrapper (task #248) then
///     materialises AB Legacy DriverInstance rows from the central config DB into live
///     driver instances. Mirrors <c>GalaxyProxyDriverFactoryExtensions</c>.
/// </summary>
public static class AbLegacyDriverFactoryExtensions
{
    public const string DriverTypeName = "AbLegacy";

    public static void Register(DriverFactoryRegistry registry)
    {
        ArgumentNullException.ThrowIfNull(registry);
        registry.Register(DriverTypeName, CreateInstance);
    }

    internal static AbLegacyDriver CreateInstance(string driverInstanceId, string driverConfigJson)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(driverInstanceId);
        ArgumentException.ThrowIfNullOrWhiteSpace(driverConfigJson);

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

        var options = new AbLegacyDriverOptions
        {
            Devices = dto.Devices is { Count: > 0 }
                ? [.. dto.Devices.Select(d => new AbLegacyDeviceOptions(
                    HostAddress: d.HostAddress ?? throw new InvalidOperationException(
                        $"AB Legacy config for '{driverInstanceId}' has a device missing HostAddress"),
                    PlcFamily: ParseEnum<AbLegacyPlcFamily>(d.PlcFamily, driverInstanceId, "PlcFamily",
                        fallback: AbLegacyPlcFamily.Slc500),
                    DeviceName: d.DeviceName))]
                : [],
            Tags = dto.Tags is { Count: > 0 }
                ? [.. dto.Tags.Select(t => new AbLegacyTagDefinition(
                    Name: t.Name ?? throw new InvalidOperationException(
                        $"AB Legacy config for '{driverInstanceId}' has a tag missing Name"),
                    DeviceHostAddress: t.DeviceHostAddress ?? throw new InvalidOperationException(
                        $"AB Legacy tag '{t.Name}' in '{driverInstanceId}' missing DeviceHostAddress"),
                    Address: t.Address ?? throw new InvalidOperationException(
                        $"AB Legacy tag '{t.Name}' in '{driverInstanceId}' missing Address"),
                    DataType: ParseEnum<AbLegacyDataType>(t.DataType, driverInstanceId, "DataType",
                        tagName: t.Name),
                    Writable: t.Writable ?? true,
                    WriteIdempotent: t.WriteIdempotent ?? false))]
                : [],
            Probe = new AbLegacyProbeOptions
            {
                Enabled = dto.Probe?.Enabled ?? true,
                Interval = TimeSpan.FromMilliseconds(dto.Probe?.IntervalMs ?? 5_000),
                Timeout = TimeSpan.FromMilliseconds(dto.Probe?.TimeoutMs ?? 2_000),
                ProbeAddress = dto.Probe?.ProbeAddress ?? "S:0",
            },
            Timeout = TimeSpan.FromMilliseconds(dto.TimeoutMs ?? 2_000),
        };

        return new AbLegacyDriver(options, driverInstanceId);
    }

    private static T ParseEnum<T>(string? raw, string driverInstanceId, string field,
        string? tagName = null, T? fallback = null) where T : struct, Enum
    {
        if (string.IsNullOrWhiteSpace(raw))
        {
            if (fallback.HasValue) return fallback.Value;
            throw new InvalidOperationException(
                $"AB Legacy {(tagName is null ? "config" : $"tag '{tagName}'")} in '{driverInstanceId}' missing {field}");
        }
        return Enum.TryParse<T>(raw, ignoreCase: true, out var v)
            ? v
            : throw new InvalidOperationException(
                $"AB Legacy {(tagName is null ? "config" : $"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 AbLegacyDriverConfigDto
    {
        public int? TimeoutMs { get; init; }
        public List<AbLegacyDeviceDto>? Devices { get; init; }
        public List<AbLegacyTagDto>? Tags { get; init; }
        public AbLegacyProbeDto? Probe { get; init; }
    }

    internal sealed class AbLegacyDeviceDto
    {
        public string? HostAddress { get; init; }
        public string? PlcFamily { get; init; }
        public string? DeviceName { get; init; }
    }

    internal sealed class AbLegacyTagDto
    {
        public string? Name { get; init; }
        public string? DeviceHostAddress { get; init; }
        public string? Address { get; init; }
        public string? DataType { get; init; }
        public bool? Writable { get; init; }
        public bool? WriteIdempotent { get; init; }
    }

    internal sealed class AbLegacyProbeDto
    {
        public bool? Enabled { get; init; }
        public int? IntervalMs { get; init; }
        public int? TimeoutMs { get; init; }
        public string? ProbeAddress { get; init; }
    }
}
