using CliFx.Attributes;
using CliFx.Infrastructure;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Cli.Common;

namespace ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Cli.Commands;

/// <summary>
///     Watch a FOCAS address via polled subscription until Ctrl+C. FOCAS has no push
///     model; <c>PollGroupEngine</c> handles the tick loop.
/// </summary>
[Command("subscribe", Description = "Watch a FOCAS address via polled subscription until Ctrl+C.")]
public sealed class SubscribeCommand : FocasCommandBase
{
    [CommandOption("address", 'a', Description = "FOCAS address — same format as `read`.", IsRequired = true)]
    public string Address { get; init; } = default!;

    [CommandOption("type", 't', Description =
        "Bit / Byte / Int16 / Int32 / Float32 / Float64 / String (default Int16).")]
    public FocasDataType DataType { get; init; } = FocasDataType.Int16;

    [CommandOption("interval-ms", 'i', Description = "Publishing interval ms (default 1000).")]
    public int IntervalMs { get; init; } = 1000;

    public override async ValueTask ExecuteAsync(IConsole console)
    {
        ConfigureLogging();
        var ct = console.RegisterCancellationHandler();

        var tagName = ReadCommand.SynthesiseTagName(Address, DataType);
        var tag = new FocasTagDefinition(
            Name: tagName,
            DeviceHostAddress: HostAddress,
            Address: Address,
            DataType: DataType,
            Writable: false);
        var options = BuildOptions([tag]);

        await using var driver = new FocasDriver(options, DriverInstanceId);
        ISubscriptionHandle? handle = null;
        try
        {
            await driver.InitializeAsync("{}", ct);

            driver.OnDataChange += (_, e) =>
            {
                var line = $"[{DateTime.UtcNow:HH:mm:ss.fff}] " +
                    $"{e.FullReference} = {SnapshotFormatter.FormatValue(e.Snapshot.Value)} " +
                    $"({SnapshotFormatter.FormatStatus(e.Snapshot.StatusCode)})";
                console.Output.WriteLine(line);
            };

            handle = await driver.SubscribeAsync([tagName], TimeSpan.FromMilliseconds(IntervalMs), ct);

            await console.Output.WriteLineAsync(
                $"Subscribed to {Address} @ {IntervalMs}ms. Ctrl+C to stop.");
            try
            {
                await Task.Delay(System.Threading.Timeout.InfiniteTimeSpan, ct);
            }
            catch (OperationCanceledException)
            {
                // Expected on Ctrl+C.
            }
        }
        finally
        {
            if (handle is not null)
            {
                try { await driver.UnsubscribeAsync(handle, CancellationToken.None); }
                catch { /* teardown best-effort */ }
            }
            await driver.ShutdownAsync(CancellationToken.None);
        }
    }
}
