using CliFx;
using CliFx.Attributes;
using CliFx.Infrastructure;
using Opc.Ua;
using Opc.Ua.Client;
namespace OpcUaCli.Commands;
[Command("read", Description = "Read a value from a node")]
public class ReadCommand : ICommand
{
///
/// Gets the OPC UA endpoint URL to connect to before reading.
///
[CommandOption("url", 'u', Description = "OPC UA server endpoint URL", IsRequired = true)]
public string Url { get; init; } = default!;
[CommandOption("username", 'U', Description = "Username for authentication")]
public string? Username { get; init; }
[CommandOption("password", 'P', Description = "Password for authentication")]
public string? Password { get; init; }
[CommandOption("security", 'S', Description = "Transport security: none, sign, encrypt (default: none)")]
public string Security { get; init; } = "none";
[CommandOption("failover-urls", 'F', Description = "Comma-separated failover endpoint URLs for redundancy")]
public string? FailoverUrls { get; init; }
///
/// Gets the node identifier whose value should be read.
///
[CommandOption("node", 'n', Description = "Node ID (e.g. ns=2;s=MyNode)", IsRequired = true)]
public string NodeId { get; init; } = default!;
///
/// Connects to the endpoint, reads the target node, and prints the returned value details.
///
/// The console used to report the read result.
public async ValueTask ExecuteAsync(IConsole console)
{
var urls = FailoverUrlParser.Parse(Url, FailoverUrls);
using var failover = new OpcUaFailoverHelper(urls, Username, Password, Security);
using var session = await failover.ConnectAsync();
var node = new NodeId(NodeId);
var value = await session.ReadValueAsync(node);
await console.Output.WriteLineAsync($"Node: {NodeId}");
await console.Output.WriteLineAsync($"Value: {value.Value}");
await console.Output.WriteLineAsync($"Status: {value.StatusCode}");
await console.Output.WriteLineAsync($"Source Time: {value.SourceTimestamp:O}");
await console.Output.WriteLineAsync($"Server Time: {value.ServerTimestamp:O}");
}
}