using System.Globalization;
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.Modbus.Cli.Commands;

/// <summary>
///     Write one value to a Modbus coil or holding register. Mirrors <see cref="ReadCommand"/>'s
///     region / address / type flags + adds <c>--value</c>. Input parsing respects the
///     declared <c>--type</c> so you can write <c>--value=3.14 --type=Float32</c> without
///     hex-encoding floats. The write is non-idempotent by default (driver's
///     <c>WriteIdempotent=false</c>) — replay is the operator's choice, not the driver's.
/// </summary>
[Command("write", Description = "Write a single Modbus coil or holding register.")]
public sealed class WriteCommand : ModbusCommandBase
{
    /// <summary>Gets the Modbus region to write to.</summary>
    [CommandOption("region", 'r', Description =
        "Coils or HoldingRegisters (the only writable regions per the protocol spec).",
        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 of the value to write.</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 value string to write and parse.</summary>
    [CommandOption("value", 'v', Description =
        "Value to write. Parsed per --type (booleans accept true/false/0/1).",
        IsRequired = true)]
    public string Value { get; init; } = default!;

    /// <summary>Gets the byte order for multi-register values.</summary>
    [CommandOption("byte-order", Description =
        "BigEndian (default, 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: which bit of the holding register (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 characters.</summary>
    [CommandOption("string-byte-order", Description =
        "For type=String: HighByteFirst (standard) or LowByteFirst (DirectLOGIC).")]
    public ModbusStringByteOrder StringByteOrder { get; init; } = ModbusStringByteOrder.HighByteFirst;

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

        if (Region is not (ModbusRegion.Coils or ModbusRegion.HoldingRegisters))
            throw new CliFx.Exceptions.CommandException(
                $"Region '{Region}' is read-only in the Modbus spec; writes require Coils or HoldingRegisters.");

        if (Region == ModbusRegion.Coils && DataType != ModbusDataType.Bool)
            throw new CliFx.Exceptions.CommandException(
                $"Region 'Coils' only supports boolean values (--type Bool). " +
                $"Type '{DataType}' cannot represent a single-bit coil write.");

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

        var parsed = ParseValue(Value, DataType);

        await using var driver = new ModbusDriver(options, DriverInstanceId);
        try
        {
            await driver.InitializeAsync("{}", ct);
            var results = await driver.WriteAsync([new WriteRequest(tagName, parsed)], ct);
            await console.Output.WriteLineAsync(SnapshotFormatter.FormatWrite(tagName, results[0]));
        }
        catch (OperationCanceledException) when (ct.IsCancellationRequested)
        {
            await console.Output.WriteLineAsync("Cancelled.");
        }
        finally
        {
            await driver.ShutdownAsync(CancellationToken.None);
            FlushLogging();
        }
    }

    /// <summary>
    ///     Parses the operator's <c>--value</c> string into the CLR type the driver expects
    ///     for the declared data type. Uses invariant culture everywhere
    ///     so <c>3.14</c> and <c>3,14</c> don't swap meaning between runs.
    /// </summary>
    /// <param name="raw">The raw value string from the command line.</param>
    /// <param name="type">The data type to parse into.</param>
    /// <returns>The parsed value in the appropriate CLR type.</returns>
    internal static object ParseValue(string raw, ModbusDataType type) => type switch
    {
        ModbusDataType.Bool or ModbusDataType.BitInRegister => ParseBool(raw),
        ModbusDataType.Int16 => short.Parse(raw, CultureInfo.InvariantCulture),
        ModbusDataType.UInt16 or ModbusDataType.Bcd16 => ushort.Parse(raw, CultureInfo.InvariantCulture),
        ModbusDataType.Int32 => int.Parse(raw, CultureInfo.InvariantCulture),
        ModbusDataType.UInt32 or ModbusDataType.Bcd32 => uint.Parse(raw, CultureInfo.InvariantCulture),
        ModbusDataType.Int64 => long.Parse(raw, CultureInfo.InvariantCulture),
        ModbusDataType.UInt64 => ulong.Parse(raw, CultureInfo.InvariantCulture),
        ModbusDataType.Float32 => float.Parse(raw, CultureInfo.InvariantCulture),
        ModbusDataType.Float64 => double.Parse(raw, CultureInfo.InvariantCulture),
        ModbusDataType.String => raw,
        _ => throw new CliFx.Exceptions.CommandException($"Unsupported DataType '{type}' for write."),
    };

    private static bool ParseBool(string raw) => raw.Trim().ToLowerInvariant() switch
    {
        "1" or "true" or "on" or "yes" => true,
        "0" or "false" or "off" or "no" => false,
        _ => throw new CliFx.Exceptions.CommandException(
            $"Boolean value '{raw}' is not recognised. Use true/false, 1/0, on/off, or yes/no."),
    };
}
