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.AbCip.Cli.Commands;

/// <summary>
///     Write one value to a Logix tag by symbolic path. Mirrors <see cref="ReadCommand"/>'s
///     flag shape + adds <c>--value</c>. Value parsing respects <c>--type</c> so you can
///     write <c>--value 3.14 --type Real</c> without hex-encoding. GuardLogix safety tags
///     are refused at the driver level (they're forced to ViewOnly by PR 12).
/// </summary>
[Command("write", Description = "Write a single Logix tag by symbolic path.")]
public sealed class WriteCommand : AbCipCommandBase
{
    /// <summary>Gets the Logix symbolic path of the tag to write.</summary>
    [CommandOption("tag", 't', Description =
        "Logix symbolic path — same format as `read`.", IsRequired = true)]
    public string TagPath { get; init; } = default!;

    /// <summary>Gets the data type to write.</summary>
    [CommandOption("type", Description =
        "Bool / SInt / Int / DInt / LInt / USInt / UInt / UDInt / ULInt / Real / LReal / " +
        "String / Dt (default DInt).")]
    public AbCipDataType DataType { get; init; } = AbCipDataType.DInt;

    /// <summary>Gets the value to write, as a string.</summary>
    [CommandOption("value", 'v', Description =
        "Value to write. Parsed per --type (booleans accept true/false/1/0).",
        IsRequired = true)]
    public string Value { get; init; } = default!;

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

        if (DataType == AbCipDataType.Structure)
            throw new CliFx.Exceptions.CommandException(
                "Structure (UDT) writes need an explicit member layout — drop to the driver's " +
                "config JSON for those. The CLI covers atomic types only.");

        var tagName = ReadCommand.SynthesiseTagName(TagPath, DataType);
        var tag = new AbCipTagDefinition(
            Name: tagName,
            DeviceHostAddress: Gateway,
            TagPath: TagPath,
            DataType: DataType,
            Writable: true);
        var options = BuildOptions([tag]);

        var parsed = ParseValue(Value, DataType);

        await using var driver = new AbCipDriver(options, DriverInstanceId);
        try
        {
            await driver.InitializeAsync("{}", ct);
            var results = await driver.WriteAsync([new WriteRequest(tagName, parsed)], ct);
            await console.Output.WriteLineAsync(SnapshotFormatter.FormatWrite(TagPath, results[0]));
        }
        finally
        {
            await driver.ShutdownAsync(CancellationToken.None);
            // Flush Serilog before process exit so buffered log
            // output emitted during driver shutdown is not lost.
            FlushLogging();
        }
    }

    /// <summary>
    ///     Parse the operator's <c>--value</c> string into the CLR type the driver expects
    ///     for the declared <see cref="AbCipDataType"/>. Invariant culture everywhere.
    ///     Bad input (non-numeric text, out-of-range value) is caught and rethrown as a
    ///     <see cref="CliFx.Exceptions.CommandException"/> so CliFx renders a clean one-line
    ///     error rather than a full .NET stack trace.
    /// </summary>
    /// <param name="raw">The raw string value to parse.</param>
    /// <param name="type">The AbCip data type to parse the value into.</param>
    /// <returns>The parsed value as an object.</returns>
    internal static object ParseValue(string raw, AbCipDataType type)
    {
        try
        {
            return type switch
            {
                AbCipDataType.Bool => ParseBool(raw),
                AbCipDataType.SInt => sbyte.Parse(raw, CultureInfo.InvariantCulture),
                AbCipDataType.Int => short.Parse(raw, CultureInfo.InvariantCulture),
                AbCipDataType.DInt or AbCipDataType.Dt => int.Parse(raw, CultureInfo.InvariantCulture),
                AbCipDataType.LInt => long.Parse(raw, CultureInfo.InvariantCulture),
                AbCipDataType.USInt => byte.Parse(raw, CultureInfo.InvariantCulture),
                AbCipDataType.UInt => ushort.Parse(raw, CultureInfo.InvariantCulture),
                AbCipDataType.UDInt => uint.Parse(raw, CultureInfo.InvariantCulture),
                AbCipDataType.ULInt => ulong.Parse(raw, CultureInfo.InvariantCulture),
                AbCipDataType.Real => float.Parse(raw, CultureInfo.InvariantCulture),
                AbCipDataType.LReal => double.Parse(raw, CultureInfo.InvariantCulture),
                AbCipDataType.String => raw,
                _ => throw new CliFx.Exceptions.CommandException($"Unsupported DataType '{type}' for write."),
            };
        }
        catch (Exception ex) when (ex is FormatException or OverflowException)
        {
            throw new CliFx.Exceptions.CommandException(
                $"Cannot parse '{raw}' as {type}. " +
                $"Check the value is within the valid range for {type} and uses invariant-culture " +
                $"decimal notation (e.g. '3.14', not '3,14').",
                innerException: ex);
        }
    }

    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."),
    };
}
