using System.Threading.Channels;
using CliFx.Attributes;
using CliFx.Exceptions;
using CliFx.Infrastructure;
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Client.CLI.Helpers;
using ZB.MOM.WW.OtOpcUa.Client.Shared;
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;

namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Commands;

[Command("alarms", Description = "Subscribe to alarm events")]
public class AlarmsCommand : CommandBase
{
    /// <summary>
    /// Creates the alarm-monitoring command used to stream OPC UA condition events to the terminal.
    /// </summary>
    /// <param name="factory">The factory that creates the shared client service for the command run.</param>
    public AlarmsCommand(IOpcUaClientServiceFactory factory) : base(factory)
    {
    }

    /// <summary>
    /// Gets the optional source node whose alarm events should be monitored instead of the server root.
    /// </summary>
    [CommandOption("node", 'n', Description = "Node ID to monitor for events (default: Server node)")]
    public string? NodeId { get; init; }

    /// <summary>
    /// Gets the publishing interval, in milliseconds, for the alarm subscription.
    /// </summary>
    [CommandOption("interval", 'i', Description = "Publishing interval in milliseconds")]
    public int Interval { get; init; } = 1000;

    /// <summary>
    /// Gets a value indicating whether retained alarm conditions should be refreshed immediately after subscribing.
    /// </summary>
    [CommandOption("refresh", Description = "Request a ConditionRefresh after subscribing")]
    public bool Refresh { get; init; }

    /// <inheritdoc />
    public override async ValueTask ExecuteAsync(IConsole console)
    {
        ConfigureLogging();
        if (Interval <= 0)
            throw new CommandException($"--interval must be greater than 0 (was {Interval}).");

        NodeId? sourceNodeId;
        try
        {
            sourceNodeId = NodeIdParser.Parse(NodeId);
        }
        catch (Exception ex) when (ex is FormatException or ArgumentException)
        {
            throw new CommandException($"Invalid --node value: {ex.Message}");
        }

        IOpcUaClientService? service = null;
        try
        {
            var ct = console.RegisterCancellationHandler();
            (service, _) = await CreateServiceAndConnectAsync(ct);

            // Channel serialises SDK notification-thread writes to the main async loop so
            // that concurrent alarm callbacks never interleave on the shared TextWriter.
            var outputChannel = Channel.CreateUnbounded<string>(
                new UnboundedChannelOptions { SingleReader = true });

            void AlarmEventHandler(object? sender, AlarmEventArgs e)
            {
                try
                {
                    var activeStr = e.ActiveState ? "Active" : "Inactive";
                    var ackedStr = e.AckedState ? "Acknowledged" : "Unacknowledged";
                    outputChannel.Writer.TryWrite($"[{e.Time:O}] ALARM  {e.SourceName}");
                    outputChannel.Writer.TryWrite($"  Condition: {e.ConditionName}");
                    outputChannel.Writer.TryWrite($"  State:     {activeStr}, {ackedStr}");
                    outputChannel.Writer.TryWrite($"  Severity:  {e.Severity}");
                    if (!string.IsNullOrEmpty(e.Message))
                        outputChannel.Writer.TryWrite($"  Message:   {e.Message}");
                    outputChannel.Writer.TryWrite($"  Retain:    {e.Retain}");
                    outputChannel.Writer.TryWrite(string.Empty);
                }
                catch
                {
                    // Never let handler exceptions escape into the SDK callback.
                }
            }

            service.AlarmEvent += AlarmEventHandler;

            await service.SubscribeAlarmsAsync(sourceNodeId, Interval, ct);
            await console.Output.WriteLineAsync(
                $"Subscribed to alarm events (interval: {Interval}ms). Press Ctrl+C to stop.");

            if (Refresh)
                try
                {
                    await service.RequestConditionRefreshAsync(ct);
                    await console.Output.WriteLineAsync("Condition refresh requested.");
                }
                catch (Exception ex)
                {
                    await console.Output.WriteLineAsync($"Condition refresh not supported: {ex.Message}");
                }

            // Drain the output channel on the main thread until cancellation fires.
            using var drainCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
            var drainTask = Task.Run(async () =>
            {
                await foreach (var line in outputChannel.Reader.ReadAllAsync(drainCts.Token))
                    await console.Output.WriteLineAsync(line);
            }, CancellationToken.None);

            // Wait until cancellation
            try
            {
                await Task.Delay(Timeout.Infinite, ct);
            }
            catch (OperationCanceledException)
            {
                // Expected on Ctrl+C
            }

            // Stop accepting new notifications before writing final output.
            service.AlarmEvent -= AlarmEventHandler;
            outputChannel.Writer.Complete();
            await drainCts.CancelAsync();
            try { await drainTask; } catch (OperationCanceledException) { }

            await service.UnsubscribeAlarmsAsync();
            await console.Output.WriteLineAsync("Unsubscribed.");
        }
        finally
        {
            if (service != null)
            {
                await service.DisconnectAsync();
                service.Dispose();
            }
        }
    }
}
