using Org.Eclipse.Tahu.Protobuf;
using ZB.MOM.WW.OtOpcUa.Driver.Mqtt.SparkplugSimulator;

// ---------------------------------------------------------------------------
// Standalone entry point for the `sparkplug-sim` fixture container.
//
// Runs one or more simulated edge nodes against the fixture broker, forever: NBIRTH + DBIRTH once,
// then N/DDATA on a cadence, honouring rebirth NCMDs throughout. It exists so an operator (and Task
// 26's AdminUI `/run` verification) has a live Sparkplug plant to browse, NOT so the live tests have
// one — those drive `SparkplugEdgeNode` in process, because the §3.6 matrix needs an edge node it
// can command mid-test.
//
// Every setting comes from the environment; nothing is defaulted to a credential.
// ---------------------------------------------------------------------------

var host = Env("MQTT_SIM_HOST", "mosquitto");
var port = int.TryParse(Env("MQTT_SIM_PORT", "8883"), out var p) ? p : 8883;
var useTls = !string.Equals(Env("MQTT_SIM_USE_TLS", "true"), "false", StringComparison.OrdinalIgnoreCase);
var group = Env("MQTT_SIM_GROUP", "OtOpcUaSim");
var nodes = Env("MQTT_SIM_NODES", "EdgeA,EdgeB").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
var interval = int.TryParse(Env("MQTT_SIM_INTERVAL_SECONDS", "2"), out var i) && i > 0 ? i : 2;

var username = Environment.GetEnvironmentVariable("MQTT_FIXTURE_USERNAME");
var password = Environment.GetEnvironmentVariable("MQTT_FIXTURE_PASSWORD");
var caPath = Environment.GetEnvironmentVariable("MQTT_SIM_CA_CERT");
var allowUntrusted = string.Equals(Env("MQTT_SIM_ALLOW_UNTRUSTED", "false"), "true", StringComparison.OrdinalIgnoreCase);

if (string.IsNullOrEmpty(password))
{
    // Same fail-loud posture as the compose file's `${VAR:?}` guards: the broker runs
    // allow_anonymous=false, so a blank password would produce an unexplained connect refusal.
    Console.Error.WriteLine(
        "sparkplug-sim: MQTT_FIXTURE_PASSWORD is not set. The fixture broker runs allow_anonymous=false; "
        + "supply the password gen-fixture-material.sh was run with.");
    return 2;
}

using var stopping = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) =>
{
    e.Cancel = true;
    stopping.Cancel();
};
AppDomain.CurrentDomain.ProcessExit += (_, _) => stopping.Cancel();

Console.WriteLine(
    $"sparkplug-sim: broker={host}:{port} tls={useTls} group={group} nodes=[{string.Join(", ", nodes)}] "
    + $"interval={interval}s");

var running = new List<Task>();
var edges = new List<SparkplugEdgeNode>();

foreach (var node in nodes)
{
    var edge = new SparkplugEdgeNode(
        new SparkplugEdgeNodeOptions
        {
            Host = host,
            Port = port,
            UseTls = useTls,
            CaCertificatePath = caPath,
            AllowUntrustedServerCertificate = allowUntrusted,
            Username = username,
            Password = password,
            GroupId = group,
            EdgeNodeId = node,
        },
        Console.WriteLine);

    // A small but genuinely heterogeneous catalog: a float, a double, a NEGATIVE int32 (the two's
    // complement case), a bool and a string — plus one device, so the picker's
    // Group → EdgeNode → Device → Metric tree has every level populated.
    edge.SetNodeMetrics(
        new SparkplugMetricSeed("Temperature", 1, DataType.Float, 21.5f),
        new SparkplugMetricSeed("Pressure", 2, DataType.Double, 101.325d),
        new SparkplugMetricSeed("Count", 3, DataType.Int32, -42),
        new SparkplugMetricSeed("Running", 4, DataType.Boolean, true),
        new SparkplugMetricSeed("Serial", 5, DataType.String, $"{node}-001"));

    edge.SetDeviceMetrics(
        "Filler1",
        new SparkplugMetricSeed("Temperature", 10, DataType.Float, 55.5f),
        new SparkplugMetricSeed("FillCount", 11, DataType.Int64, 1000L),
        new SparkplugMetricSeed("Jammed", 12, DataType.Boolean, false));

    edges.Add(edge);
}

try
{
    foreach (var edge in edges)
    {
        await edge.ConnectAsync(stopping.Token);
        running.Add(edge.RunAsync(TimeSpan.FromSeconds(interval), stopping.Token));
    }

    await Task.WhenAll(running);
}
catch (OperationCanceledException)
{
    Console.WriteLine("sparkplug-sim: stopping.");
}
finally
{
    foreach (var edge in edges)
    {
        await edge.DisposeAsync();
    }
}

return 0;

static string Env(string name, string fallback) =>
    Environment.GetEnvironmentVariable(name) is { Length: > 0 } value ? value : fallback;
