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

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

/// <summary>
///     Read one S7 address (DB / M / I / Q area). Addresses use S7.Net grammar — the driver
///     parses them via <c>S7AddressParser</c> so whatever the server accepts the CLI accepts
///     too.
/// </summary>
[Command("read", Description = "Read a single S7 address.")]
public sealed class ReadCommand : S7CommandBase
{
    /// <summary>Gets the S7 address to read.</summary>
    [CommandOption("address", 'a', Description =
        "S7 address. Examples: DB1.DBW0 (DB1, word 0); M0.0 (merker bit); IW4 (input word 4); " +
        "QD8 (output dword 8); DB2.DBD20 (DB2, dword 20); DB5.DBX4.3 (DB5, byte 4, bit 3); " +
        "DB10.STRING[0] (DB10 string). Bit addresses use dot notation.",
        IsRequired = true)]
    public string Address { get; init; } = default!;

    /// <summary>Gets the data type to interpret the address as.</summary>
    [CommandOption("type", 't', Description =
        "Bool / Byte / Int16 / UInt16 / Int32 / UInt32 / Float32 / Int64 / UInt64 / Float64 / String / DateTime (default Int16). " +
        "Wide types (Int64, UInt64, Float64/LReal, String, DateTime) are byte-anchored: address must use the B suffix " +
        "(e.g. DB1.DBB8, MB4) pointing at the first byte; width comes from the DataType. " +
        "Timer (T{n}) reads elapsed seconds as Float64 (read-only). Counter (C{n}) reads the count as Int32 (read-only).")]
    public S7DataType DataType { get; init; } = S7DataType.Int16;

    /// <summary>Gets the maximum string length for string-type reads.</summary>
    [CommandOption("string-length", Description =
        "For type=String: S7-string max length (default 254, S7 max).")]
    public int StringLength { get; init; } = 254;

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

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

        // `await using` is the sole disposal mechanism — S7Driver.DisposeAsync already invokes
        // ShutdownAsync, so a redundant explicit ShutdownAsync(CancellationToken.None) in a
        // finally block would run shutdown twice.
        await using var driver = new S7Driver(options, DriverInstanceId);
        try
        {
            await driver.InitializeAsync("{}", ct);
            var snapshot = await driver.ReadAsync([tagName], ct);
            await console.Output.WriteLineAsync(SnapshotFormatter.Format(Address, snapshot[0]));
        }
        catch (OperationCanceledException) when (ct.IsCancellationRequested)
        {
            // Ctrl+C during driver connect/read — exit quietly so CliFx does not render a
            // full stack trace for a user-initiated cancellation.
            await console.Output.WriteLineAsync("Cancelled.");
        }
    }

    /// <summary>Tag-name key used internally. Address + type is already unique.</summary>
    /// <param name="address">The S7 address to encode in the tag name.</param>
    /// <param name="type">The data type to encode in the tag name.</param>
    /// <returns>A synthetic tag name combining the address and data type.</returns>
    internal static string SynthesiseTagName(string address, S7DataType type)
        => $"{address}:{type}";
}
