using System.Net.Sockets;

namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.IntegrationTests;

/// <summary>
///     Reachability probe for an <c>opc-plc</c> simulator (Microsoft Industrial IoT's
///     OPC UA PLC from <c>mcr.microsoft.com/iotedge/opc-plc</c>) or any real OPC UA
///     server the <c>OPCUA_SIM_ENDPOINT</c> env var points at. Parses
///     <c>OPCUA_SIM_ENDPOINT</c> (default <c>opc.tcp://10.100.0.35:50000</c> — the shared Docker host),
///     TCP-connects to the resolved host:port at collection init, and records a
///     <see cref="SkipReason"/> on failure. Tests call <c>Assert.Skip</c> on that, so
///     `dotnet test` stays green when Docker isn't running the simulator — mirrors the
///     <see cref="ModbusSimulatorFixture"/> / <c>Snap7ServerFixture</c> pattern.
/// </summary>
/// <remarks>
///     <para>
///         <b>Why opc-plc over loopback against our own server</b> — (1) independent
///         cert chain + user-token handling catches interop bugs loopback can't;
///         (2) built-in alarm ConditionType + history simulation gives
///         <see cref="Core.Abstractions.IAlarmSource"/> +
///         <see cref="Core.Abstractions.IHistoryProvider"/> coverage without a custom
///         driver fake; (3) pinned image tag fixes the test surface in a way our own
///         evolving server wouldn't. Follow-up: add <c>open62541/open62541</c> as a
///         second image once this lands, for fully-independent-stack interop.
///     </para>
///     <para>
///         Endpoint URL contract: parser strips the <c>opc.tcp://</c> scheme + resolves
///         host + port for the liveness probe only. The real test session always
///         dials the full endpoint URL via <see cref="OpcUaClientDriverOptions.EndpointUrl"/>
///         so cert negotiation + security-policy selection run end-to-end.
///     </para>
/// </remarks>
public sealed class OpcPlcFixture : IAsyncDisposable
{
    // 10.100.0.35 = the shared Docker host (see CLAUDE.md "Docker Workflow"). Migrated
    // off this VM's localhost on 2026-04-28 alongside the rest of the Docker-host move.
    // Override via OPCUA_SIM_ENDPOINT to point at a different host or a locally-running
    // opc-plc instance.
    private const string DefaultEndpoint = "opc.tcp://10.100.0.35:50000";
    private const string EndpointEnvVar = "OPCUA_SIM_ENDPOINT";

    /// <summary>Full <c>opc.tcp://host:port</c> URL the driver session should connect to.</summary>
    public string EndpointUrl { get; }
    /// <summary>Gets the host name of the OPC UA simulator.</summary>
    public string Host { get; }
    /// <summary>Gets the port number of the OPC UA simulator.</summary>
    public int Port { get; }
    /// <summary>Gets a skip reason if the simulator is unreachable; otherwise null.</summary>
    public string? SkipReason { get; }

    /// <summary>
    /// Initializes a new instance of the <see cref="OpcPlcFixture"/> class and probes the simulator.
    /// </summary>
    public OpcPlcFixture()
    {
        EndpointUrl = Environment.GetEnvironmentVariable(EndpointEnvVar) ?? DefaultEndpoint;

        (Host, Port) = ParseHostPort(EndpointUrl);

        try
        {
            using var client = new TcpClient(AddressFamily.InterNetwork);
            var task = client.ConnectAsync(
                System.Net.Dns.GetHostAddresses(Host)
                    .FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork)
                    ?? System.Net.IPAddress.Loopback,
                Port);
            if (!task.Wait(TimeSpan.FromSeconds(2)) || !client.Connected)
            {
                SkipReason = $"opc-plc simulator at {Host}:{Port} did not accept a TCP connection within 2s. " +
                             $"Start it (`docker compose -f Docker/docker-compose.yml up`) or override {EndpointEnvVar}.";
            }
        }
        catch (Exception ex)
        {
            SkipReason = $"opc-plc simulator at {Host}:{Port} unreachable: {ex.GetType().Name}: {ex.Message}. " +
                         $"Start it (`docker compose -f Docker/docker-compose.yml up`) or override {EndpointEnvVar}.";
        }
    }

    /// <summary>
    ///     Parse "opc.tcp://host:port[/path]" → (host, port). Defaults to port 4840
    ///     (OPC UA standard) when the URL omits the port, but opc-plc's default is
    ///     50000 so DefaultEndpoint carries it explicitly.
    /// </summary>
    private static (string Host, int Port) ParseHostPort(string endpointUrl)
    {
        const string scheme = "opc.tcp://";
        var body = endpointUrl.StartsWith(scheme, StringComparison.OrdinalIgnoreCase)
            ? endpointUrl[scheme.Length..]
            : endpointUrl;
        var slash = body.IndexOf('/');
        if (slash >= 0) body = body[..slash];
        var colon = body.IndexOf(':');
        if (colon < 0) return (body, 4840);
        var host = body[..colon];
        return int.TryParse(body[(colon + 1)..], out var p) ? (host, p) : (host, 4840);
    }

    /// <summary>
    /// Disposes the fixture resources (currently a no-op).
    /// </summary>
    public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}

[Xunit.CollectionDefinition(Name)]
public sealed class OpcPlcCollection : Xunit.ICollectionFixture<OpcPlcFixture>
{
    public const string Name = "OpcPlc";
}
