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

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

/// <summary>
///     Read one Modbus register / coil. Operator specifies the address via
///     <c>--region</c> + <c>--address</c> + <c>--type</c>; the CLI synthesises a single
///     <see cref="ModbusTagDefinition"/>, spins up the driver, reads once, prints the snapshot,
///     and shuts down. Multi-register types (Int32 / Float32 / String / BCD32) respect
///     <c>--byte-order</c> the same way real driver configs do.
/// </summary>
[Command("read", Description = "Read a single Modbus register or coil.")]
public sealed class ReadCommand : ModbusCommandBase
{
    /// <summary>Gets the Modbus region to read from.</summary>
    [CommandOption("region", 'r', Description =
        "Coils / DiscreteInputs / InputRegisters / HoldingRegisters", IsRequired = true)]
    public ModbusRegion Region { get; init; }

    /// <summary>Gets the zero-based address within the region.</summary>
    [CommandOption("address", 'a', Description =
        "Zero-based address within the region.", IsRequired = true)]
    public ushort Address { get; init; }

    /// <summary>Gets the data type to read.</summary>
    [CommandOption("type", 't', Description =
        "Bool / Int16 / UInt16 / Int32 / UInt32 / Int64 / UInt64 / Float32 / Float64 / " +
        "BitInRegister / String / Bcd16 / Bcd32", IsRequired = true)]
    public ModbusDataType DataType { get; init; }

    /// <summary>Gets the byte order for multi-register types.</summary>
    [CommandOption("byte-order", Description =
        "BigEndian (default, spec ABCD) or WordSwap (CDAB). Ignored for single-register types.")]
    public ModbusByteOrder ByteOrder { get; init; } = ModbusByteOrder.BigEndian;

    /// <summary>Gets the bit index for BitInRegister type.</summary>
    [CommandOption("bit-index", Description =
        "For type=BitInRegister: bit 0-15 LSB-first.")]
    public byte BitIndex { get; init; }

    /// <summary>Gets the string length for String type.</summary>
    [CommandOption("string-length", Description =
        "For type=String: character count (2 per register, rounded up).")]
    public ushort StringLength { get; init; }

    /// <summary>Gets the byte order for string values.</summary>
    [CommandOption("string-byte-order", Description =
        "For type=String: HighByteFirst (standard) or LowByteFirst (DirectLOGIC et al).")]
    public ModbusStringByteOrder StringByteOrder { get; init; } = ModbusStringByteOrder.HighByteFirst;

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

        var tagName = SynthesiseTagName(Region, Address, DataType);
        var tag = new ModbusTagDefinition(
            Name: tagName,
            Region: Region,
            Address: Address,
            DataType: DataType,
            Writable: false,
            ByteOrder: ByteOrder,
            BitIndex: BitIndex,
            StringLength: StringLength,
            StringByteOrder: StringByteOrder);
        var options = BuildOptions([tag]);

        await using var driver = new ModbusDriver(options, DriverInstanceId);
        try
        {
            await driver.InitializeAsync("{}", ct);
            var snapshot = await driver.ReadAsync([tagName], ct);
            await console.Output.WriteLineAsync(SnapshotFormatter.Format(tagName, 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.");
        }
        finally
        {
            await driver.ShutdownAsync(CancellationToken.None);
            // Flush Serilog before process exit so buffered log lines emitted during driver
            // shutdown are not lost. Matches Driver.AbCip.Cli pattern.
            FlushLogging();
        }
    }

    /// <summary>
    ///     Builds a human-readable tag name matching the operator's conceptual model
    ///     (<c>HR[100]</c>, <c>Coil[5]</c>, <c>IR[42]</c>) — the driver treats the name
    ///     purely as a lookup key, so any stable string works.
    /// </summary>
    /// <param name="region">The Modbus region (Coils, DiscreteInputs, InputRegisters, or HoldingRegisters).</param>
    /// <param name="address">The zero-based address within the region.</param>
    /// <param name="type">The Modbus data type being read.</param>
    /// <returns>A human-readable tag name.</returns>
    internal static string SynthesiseTagName(
        ModbusRegion region, ushort address, ModbusDataType type)
    {
        var prefix = region switch
        {
            ModbusRegion.Coils => "Coil",
            ModbusRegion.DiscreteInputs => "DI",
            ModbusRegion.InputRegisters => "IR",
            ModbusRegion.HoldingRegisters => "HR",
            _ => "Reg",
        };
        return $"{prefix}[{address}]:{type}";
    }
}
