using System.Diagnostics;
using System.Net.Sockets;
using System.Text.Json;
using System.Text.Json.Serialization;
using libplctag;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.AbCip.PlcFamilies;

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

/// <summary>
///     Two-phase Test-Connect probe for the <see cref="AbCipDriverOptions"/>-shaped driver config.
///     Phase 1: bare TCP connect to the first device's gateway host + EtherNet/IP port to
///     quickly reject unreachable targets. Phase 2: initialises a libplctag <see cref="Tag"/>
///     against the same device to open a real EIP session and perform a CIP Forward Open —
///     confirming the remote endpoint actually speaks EtherNet/IP CIP, not just accepts TCP.
///     A device that accepts the TCP connection but is not a CIP controller (wrong CIP path,
///     non-CIP server) returns <c>Ok = false</c> with a "handshake failed" message instead of
///     a false-positive green tick.
///     <para>
///     Status-code discrimination: libplctag statuses that indicate the controller answered
///     the CIP session but could not resolve the probe tag
///     (<see cref="Status.ErrorNotFound"/>, <see cref="Status.ErrorNoMatch"/>,
///     <see cref="Status.ErrorBadDevice"/>) are treated as "reachable — Ok = true" because
///     a non-existent tag name proves CIP connectivity. Statuses that indicate a transport or
///     session failure (<see cref="Status.ErrorTimeout"/>, <see cref="Status.ErrorBadConnection"/>,
///     <see cref="Status.ErrorBadGateway"/>, <see cref="Status.ErrorWinsock"/>,
///     <see cref="Status.ErrorOpen"/>, <see cref="Status.ErrorClose"/>,
///     <see cref="Status.ErrorRead"/>, <see cref="Status.ErrorWrite"/>,
///     <see cref="Status.ErrorBadReply"/>, <see cref="Status.ErrorRemoteErr"/>,
///     <see cref="Status.ErrorPartial"/>, <see cref="Status.ErrorAbort"/>) are treated as
///     "handshake failed — Ok = false". All other error statuses default to
///     "handshake failed" (conservative).
///     </para>
/// </summary>
public sealed class AbCipDriverProbe : IDriverProbe
{
    private static readonly JsonSerializerOptions _opts = new()
    {
        PropertyNameCaseInsensitive = true,
        UnmappedMemberHandling = JsonUnmappedMemberHandling.Skip,
        Converters = { new JsonStringEnumConverter() },
    };

    /// <inheritdoc />
    public string DriverType => "AbCip";

    /// <inheritdoc />
    public async Task<DriverProbeResult> ProbeAsync(string configJson, TimeSpan timeout, CancellationToken ct)
    {
        AbCipDriverOptions? opts;
        try { opts = JsonSerializer.Deserialize<AbCipDriverOptions>(configJson, _opts); }
        catch (Exception ex) { return new(false, $"Config JSON is invalid: {ex.Message}", null); }
        if (opts is null) return new(false, "Config JSON deserialized to null.", null);

        var (parsed, firstDevice) = ExtractTarget(opts);
        if (parsed is null || string.IsNullOrWhiteSpace(parsed.Gateway) || parsed.Port <= 0)
            return new(false, "Config has no host/port to probe.", null);

        var host = parsed.Gateway;
        var port = parsed.Port;

        // Bound both phases by the caller timeout, independent of `ct`, so a device that accepts
        // TCP but stalls the CIP Forward Open cannot hang the probe.
        using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
        cts.CancelAfter(timeout);

        // Phase 1: bare TCP preflight — fast rejection for unreachable hosts.
        var sw = Stopwatch.StartNew();
        try
        {
            using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            await socket.ConnectAsync(host, port, cts.Token);
        }
        catch (SocketException ex)
        {
            return new(false, $"Connect failed: {ex.SocketErrorCode}", null);
        }
        catch (OperationCanceledException)
        {
            return new(false, $"Probe timed out after {timeout.TotalSeconds:F0}s.", null);
        }
        catch (Exception ex)
        {
            return new(false, ex.Message, null);
        }

        // Phase 2: CIP session via libplctag Tag.InitializeAsync. Open a real EIP session +
        // Forward Open to confirm the remote endpoint speaks CIP, not just TCP.
        var profile = AbCipPlcFamilyProfile.ForFamily(firstDevice?.PlcFamily ?? AbCipPlcFamily.ControlLogix);

        // Prefer the first authored tag path as the probe tag name (it must exist on the PLC). v3: the
        // tags arrive as RawTagEntry blobs — map each through the pure factory to recover its TagPath +
        // device routing key. Fall back to a benign system attribute present on all ControlLogix /
        // CompactLogix controllers (@raw_cpu_type); still returns ErrorNotFound on Micro800 / MicroLogix,
        // which is sufficient to confirm CIP reachability.
        var mappedTags = opts.RawTags
            .Select(e => AbCipTagDefinitionFactory.FromTagConfig(e.TagConfig, e.RawPath, out var d)
                ? (Ok: true, Device: e.DeviceName, d.TagPath)
                : (Ok: false, Device: e.DeviceName, TagPath: null!))
            .Where(x => x.Ok)
            .ToList();
        var tagName = mappedTags.FirstOrDefault(
                x => string.Equals(x.Device, firstDevice?.HostAddress, StringComparison.OrdinalIgnoreCase)
                    || (firstDevice?.DeviceName is { } dn && string.Equals(x.Device, dn, StringComparison.OrdinalIgnoreCase)))
                .TagPath
            ?? mappedTags.FirstOrDefault().TagPath
            ?? "@raw_cpu_type";

        var p = new AbCipTagCreateParams(
            Gateway: parsed.Gateway,
            Port: parsed.Port,
            CipPath: parsed.CipPath,
            LibplctagPlcAttribute: profile.LibplctagPlcAttribute,
            TagName: tagName,
            Timeout: timeout,
            AllowPacking: firstDevice?.AllowPacking ?? profile.SupportsRequestPacking,
            ConnectionSize: firstDevice?.ConnectionSize ?? profile.DefaultConnectionSize);

        var rt = new LibplctagTagRuntime(p);
        try
        {
            await rt.InitializeAsync(cts.Token);
            sw.Stop();

            // InitializeAsync completed without throwing — either the tag was found (Ok) or
            // libplctag returned a non-exception status. Check via GetStatus().
            var statusCode = (Status)rt.GetStatus();
            if (IsReachableStatus(statusCode))
            {
                var msg = statusCode == Status.Ok
                    ? "CIP session OK"
                    : "CIP session OK (controller reachable; probe tag not found)";
                return new(true, msg, sw.Elapsed);
            }

            // Non-Ok but non-exception: a session/transport error surfaced in the status word.
            return new(false, $"Reachable at {host}:{port} but CIP handshake failed: {statusCode}", null);
        }
        catch (OperationCanceledException)
        {
            return new(false, $"Probe timed out after {timeout.TotalSeconds:F0}s.", null);
        }
        catch (LibPlcTagException ex)
        {
            // LibPlcTagException carries the Status; classify as reachable vs transport failure.
            if (IsReachableException(ex))
            {
                sw.Stop();
                return new(true, "CIP session OK (controller reachable; probe tag not found)", sw.Elapsed);
            }

            return new(false, $"Reachable at {host}:{port} but CIP handshake failed: {ex.Message}", null);
        }
        catch (Exception ex)
        {
            return new(false, $"Reachable at {host}:{port} but CIP handshake failed: {ex.Message}", null);
        }
        finally
        {
            rt.Dispose();
        }
    }

    /// <summary>
    ///     Returns <c>true</c> for libplctag statuses that indicate the CIP controller answered
    ///     but the probe tag name was not found or did not match — sufficient to confirm CIP
    ///     reachability. Returns <c>true</c> for <see cref="Status.Ok"/> (tag was found).
    /// </summary>
    private static bool IsReachableStatus(Status s) => s is
        Status.Ok or
        Status.ErrorNotFound or
        Status.ErrorNoMatch or
        Status.ErrorBadDevice;

    /// <summary>
    ///     Inspects a <see cref="LibPlcTagException"/> message to decide whether the error is a
    ///     "controller answered CIP but tag not found" condition (reachable) versus a session /
    ///     transport failure (unreachable). Falls back to checking the exception message for
    ///     known tag-not-found phrases used by the libplctag native library.
    /// </summary>
    private static bool IsReachableException(LibPlcTagException ex)
    {
        // libplctag wraps the Status in the message as "STATUS_NOT_FOUND", "STATUS_NO_MATCH", etc.
        var msg = ex.Message ?? string.Empty;
        return msg.Contains("NOT_FOUND", StringComparison.OrdinalIgnoreCase)
            || msg.Contains("NO_MATCH", StringComparison.OrdinalIgnoreCase)
            || msg.Contains("BAD_DEVICE", StringComparison.OrdinalIgnoreCase);
    }

    private static (AbCipHostAddress? parsed, AbCipDeviceOptions? device) ExtractTarget(AbCipDriverOptions opts)
    {
        // Parse the first device's ab:// host address to extract the gateway IP + EIP port.
        var firstDevice = opts.Devices.FirstOrDefault();
        if (firstDevice is null) return (null, null);

        var parsed = AbCipHostAddress.TryParse(firstDevice.HostAddress);
        return (parsed, firstDevice);
    }
}
