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.S7.Cli.Commands;

/// <summary>
///     Watch an S7 address via polled subscription until Ctrl+C. S7comm has no native push
///     model so this goes through <c>PollGroupEngine</c> same as Modbus / AB.
/// </summary>
[Command("subscribe", Description = "Watch an S7 address via polled subscription until Ctrl+C.")]
public sealed class SubscribeCommand : S7CommandBase
{
    /// <summary>Gets the S7 address to subscribe to.</summary>
    [CommandOption("address", 'a', Description = "S7 address — same format as `read`.", IsRequired = true)]
    public string Address { get; init; } = default!;

    /// <summary>Gets the data type of the address.</summary>
    // Driver.S7.Cli-002: help text trimmed to the types the driver actually implements.
    [CommandOption("type", 't', Description =
        "Bool / Byte / Int16 / UInt16 / Int32 / UInt32 / Float32 (default Int16). " +
        "Int64, UInt64, Float64, String, and DateTime are not yet implemented and will return BadNotSupported.")]
    public S7DataType DataType { get; init; } = S7DataType.Int16;

    /// <summary>Gets the polling interval in milliseconds.</summary>
    [CommandOption("interval-ms", 'i', Description = "Publishing interval ms (default 1000).")]
    public int IntervalMs { get; init; } = 1000;

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

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

        // Driver.S7.Cli-004: `await using` is the sole driver-disposal mechanism — S7Driver.DisposeAsync
        // already invokes ShutdownAsync, so a redundant ShutdownAsync(CancellationToken.None) in finally
        // ran shutdown twice. Only UnsubscribeAsync stays in the finally block — that's a subscription
        // lifecycle concern that is not part of driver disposal.
        await using var driver = new S7Driver(options, DriverInstanceId);
        ISubscriptionHandle? handle = null;
        try
        {
            await driver.InitializeAsync("{}", ct);

            // Driver.S7.Cli-007: route every data-change event to the CliFx console (not
            // System.Console — the analyzer flags it + IConsole is the testable abstraction).
            // The handler is synchronous because OnDataChange is raised from a driver
            // background thread; the IConsole.Output writer is thread-safe for line writes.
            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 */ }
            }
        }
    }
}
