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

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

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

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

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

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

        if (string.IsNullOrWhiteSpace(dto.Host))
            throw new InvalidOperationException(
                $"Modbus driver config for '{driverInstanceId}' missing required Host");

        var options = new ModbusDriverOptions
        {
            Host = dto.Host!,
            Port = dto.Port ?? 502,
            UnitId = dto.UnitId ?? 1,
            Timeout = TimeSpan.FromMilliseconds(dto.TimeoutMs ?? 2_000),
            MaxRegistersPerRead = dto.MaxRegistersPerRead ?? 125,
            MaxRegistersPerWrite = dto.MaxRegistersPerWrite ?? 123,
            AutoReconnect = dto.AutoReconnect ?? true,
            Tags = dto.Tags is { Count: > 0 }
                ? [.. dto.Tags.Select(t => BuildTag(t, driverInstanceId))]
                : [],
            Probe = new ModbusProbeOptions
            {
                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 ?? 0,
            },
        };

        return new ModbusDriver(options, driverInstanceId);
    }

    private static ModbusTagDefinition BuildTag(ModbusTagDto t, string driverInstanceId) =>
        new(
            Name: t.Name ?? throw new InvalidOperationException(
                $"Modbus config for '{driverInstanceId}' has a tag missing Name"),
            Region: ParseEnum<ModbusRegion>(t.Region, t.Name, driverInstanceId, "Region"),
            Address: t.Address ?? throw new InvalidOperationException(
                $"Modbus tag '{t.Name}' in '{driverInstanceId}' missing Address"),
            DataType: ParseEnum<ModbusDataType>(t.DataType, t.Name, driverInstanceId, "DataType"),
            Writable: t.Writable ?? true,
            ByteOrder: t.ByteOrder is null
                ? ModbusByteOrder.BigEndian
                : ParseEnum<ModbusByteOrder>(t.ByteOrder, t.Name, driverInstanceId, "ByteOrder"),
            BitIndex: t.BitIndex ?? 0,
            StringLength: t.StringLength ?? 0,
            StringByteOrder: t.StringByteOrder is null
                ? ModbusStringByteOrder.HighByteFirst
                : ParseEnum<ModbusStringByteOrder>(t.StringByteOrder, t.Name, driverInstanceId, "StringByteOrder"),
            WriteIdempotent: t.WriteIdempotent ?? false);

    private static T ParseEnum<T>(string? raw, string? tagName, string driverInstanceId, string field) where T : struct, Enum
    {
        if (string.IsNullOrWhiteSpace(raw))
            throw new InvalidOperationException(
                $"Modbus tag '{tagName ?? "<unnamed>"}' in '{driverInstanceId}' missing {field}");
        return Enum.TryParse<T>(raw, ignoreCase: true, out var v)
            ? v
            : throw new InvalidOperationException(
                $"Modbus 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 ModbusDriverConfigDto
    {
        public string? Host { get; init; }
        public int? Port { get; init; }
        public byte? UnitId { get; init; }
        public int? TimeoutMs { get; init; }
        public ushort? MaxRegistersPerRead { get; init; }
        public ushort? MaxRegistersPerWrite { get; init; }
        public bool? AutoReconnect { get; init; }
        public List<ModbusTagDto>? Tags { get; init; }
        public ModbusProbeDto? Probe { get; init; }
    }

    internal sealed class ModbusTagDto
    {
        public string? Name { get; init; }
        public string? Region { get; init; }
        public ushort? Address { get; init; }
        public string? DataType { get; init; }
        public bool? Writable { get; init; }
        public string? ByteOrder { get; init; }
        public byte? BitIndex { get; init; }
        public ushort? StringLength { get; init; }
        public string? StringByteOrder { get; init; }
        public bool? WriteIdempotent { get; init; }
    }

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