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

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

/// <summary>
///     Read one FOCAS address (PMC R/G/F file, parameter, macro, axis register).
/// </summary>
[Command("read", Description = "Read a single FOCAS address.")]
public sealed class ReadCommand : FocasCommandBase
{
    /// <summary>Gets the FOCAS address to read.</summary>
    [CommandOption("address", 'a', Description =
        "FOCAS address. Examples: R100 (PMC R-file word); X0.0 (PMC X-bit); " +
        "PARAM:1815/0 (parameter 1815, axis 0); MACRO:500 (macro variable 500).",
        IsRequired = true)]
    public string Address { get; init; } = default!;

    /// <summary>Gets the data type to interpret the address as.</summary>
    [CommandOption("type", 't', Description =
        "Bit / Byte / Int16 / Int32 / Float32 / Float64 / String (default Int16).")]
    public FocasDataType DataType { get; init; } = FocasDataType.Int16;

    /// <inheritdoc />
    public override async ValueTask ExecuteAsync(IConsole console)
    {
        ConfigureLogging();
        // Validate numeric option ranges before any driver work.
        ValidateOptions();
        var ct = console.RegisterCancellationHandler();

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

        // `await using` is the sole disposal mechanism — FocasDriver.DisposeAsync
        // already invokes ShutdownAsync, so a redundant explicit ShutdownAsync(CancellationToken.None)
        // in a finally block ran shutdown twice. The await-using on the next line is enough.
        await using var driver = new FocasDriver(options, DriverInstanceId);
        try
        {
            await driver.InitializeAsync("{}", ct);
            var snapshot = await driver.ReadAsync([tagName], ct);
            await console.Output.WriteLineAsync(SnapshotFormatter.Format(Address, snapshot[0]));
        }
        finally
        {
            // Flush Serilog before process exit so buffered log output
            // emitted during driver shutdown is not silently dropped (matching DriverCommandBase
            // docs and every sibling CLI — Modbus / AbCip / AbLegacy / TwinCAT).
            FlushLogging();
        }
    }

    /// <summary>Constructs a tag name from address and data type.</summary>
    /// <param name="address">The FOCAS address.</param>
    /// <param name="type">The data type.</param>
    /// <returns>The synthesised tag name in <c>address:type</c> form.</returns>
    internal static string SynthesiseTagName(string address, FocasDataType type)
        => $"{address}:{type}";
}
