using System.Text.Json;
using System.Text.Json.Serialization;
using ZB.MOM.WW.OtOpcUa.Core.Hosting;
using S7NetCpuType = global::S7.Net.CpuType;

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

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

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

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

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

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

        var options = new S7DriverOptions
        {
            Host = dto.Host!,
            Port = dto.Port ?? 102,
            CpuType = ParseEnum<S7NetCpuType>(dto.CpuType, driverInstanceId, "CpuType",
                fallback: S7NetCpuType.S71500),
            Rack = dto.Rack ?? 0,
            Slot = dto.Slot ?? 0,
            Timeout = TimeSpan.FromMilliseconds(dto.TimeoutMs ?? 5_000),
            Tags = dto.Tags is { Count: > 0 }
                ? [.. dto.Tags.Select(t => BuildTag(t, driverInstanceId))]
                : [],
            Probe = new S7ProbeOptions
            {
                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 ?? "MW0",
            },
        };

        return new S7Driver(options, driverInstanceId);
    }

    private static S7TagDefinition BuildTag(S7TagDto t, string driverInstanceId) =>
        new(
            Name: t.Name ?? throw new InvalidOperationException(
                $"S7 config for '{driverInstanceId}' has a tag missing Name"),
            Address: t.Address ?? throw new InvalidOperationException(
                $"S7 tag '{t.Name}' in '{driverInstanceId}' missing Address"),
            DataType: ParseEnum<S7DataType>(t.DataType, driverInstanceId, "DataType",
                tagName: t.Name),
            Writable: t.Writable ?? true,
            StringLength: t.StringLength ?? 254,
            WriteIdempotent: t.WriteIdempotent ?? false);

    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(
                $"S7 tag '{tagName ?? "<unnamed>"}' in '{driverInstanceId}' missing {field}");
        }
        return Enum.TryParse<T>(raw, ignoreCase: true, out var v)
            ? v
            : throw new InvalidOperationException(
                $"S7 {(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 S7DriverConfigDto
    {
        public string? Host { get; init; }
        public int? Port { get; init; }
        public string? CpuType { get; init; }
        public short? Rack { get; init; }
        public short? Slot { get; init; }
        public int? TimeoutMs { get; init; }
        public List<S7TagDto>? Tags { get; init; }
        public S7ProbeDto? Probe { get; init; }
    }

    internal sealed class S7TagDto
    {
        public string? Name { get; init; }
        public string? Address { get; init; }
        public string? DataType { get; init; }
        public bool? Writable { get; init; }
        public int? StringLength { get; init; }
        public bool? WriteIdempotent { get; init; }
    }

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