using CliFx.Attributes;
using CliFx.Exceptions;
using CliFx.Infrastructure;
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Client.CLI.Helpers;
using ZB.MOM.WW.OtOpcUa.Client.Shared;
using ZB.MOM.WW.OtOpcUa.Client.Shared.Helpers;

namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Commands;

[Command("write", Description = "Write a value to a node")]
public class WriteCommand : CommandBase
{
    /// <summary>
    /// Creates the write command used to update a node from the terminal.
    /// </summary>
    /// <param name="factory">The factory that creates the shared client service for the command run.</param>
    public WriteCommand(IOpcUaClientServiceFactory factory) : base(factory)
    {
    }

    /// <summary>
    /// Gets the node whose value should be updated.
    /// </summary>
    [CommandOption("node", 'n', Description = "Node ID (e.g. ns=2;s=MyNode)", IsRequired = true)]
    public string NodeId { get; init; } = default!;

    /// <summary>
    /// Gets the raw operator-entered value that will be converted to the node's runtime type before writing.
    /// </summary>
    [CommandOption("value", 'v', Description = "Value to write", IsRequired = true)]
    public string Value { get; init; } = default!;

    /// <inheritdoc />
    public override async ValueTask ExecuteAsync(IConsole console)
    {
        ConfigureLogging();

        NodeId nodeId;
        try
        {
            nodeId = NodeIdParser.ParseRequired(NodeId);
        }
        catch (Exception ex) when (ex is FormatException or ArgumentException)
        {
            throw new CommandException($"Invalid --node value: {ex.Message}");
        }

        IOpcUaClientService? service = null;
        try
        {
            var ct = console.RegisterCancellationHandler();
            (service, _) = await CreateServiceAndConnectAsync(ct);

            // Read current value to determine type for conversion
            var currentValue = await service.ReadValueAsync(nodeId, ct);
            var typedValue = ValueConverter.ConvertValue(Value, currentValue.Value);

            var statusCode = await service.WriteValueAsync(nodeId, typedValue, ct);

            if (StatusCode.IsGood(statusCode))
                await console.Output.WriteLineAsync($"Write successful: {NodeId} = {typedValue}");
            else
                await console.Output.WriteLineAsync($"Write failed: {statusCode}");
        }
        finally
        {
            if (service != null)
            {
                await service.DisconnectAsync();
                service.Dispose();
            }
        }
    }
}
