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

/// <summary>
///     Write one value to a PCCC file address. Writes to timer / counter / control
///     sub-elements go through at the wire level but land on the integer field of the
///     sub-element — the PLC's runtime semantics (edge-triggered EN/DN bits, preset reloads)
///     are PLC-managed, not CLI-manipulable; write these with caution.
/// </summary>
[Command("write", Description = "Write a single PCCC file address.")]
public sealed class WriteCommand : AbLegacyCommandBase
{
    /// <summary>Gets or sets the PCCC file address to write to.</summary>
    [CommandOption("address", 'a', Description =
        "PCCC file address — same format as `read`.", IsRequired = true)]
    public string Address { get; init; } = default!;

    /// <summary>Gets or sets the data type for the write operation.</summary>
    [CommandOption("type", 't', Description =
        "Bit / Int / Long / Float / AnalogInt / String / TimerElement / CounterElement / " +
        "ControlElement (default Int).")]
    public AbLegacyDataType DataType { get; init; } = AbLegacyDataType.Int;

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

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

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

        var parsed = ParseValue(Value, DataType);

        // Plain `var driver`: explicit ShutdownAsync(CancellationToken.None) in the
        // finally is the deliberate teardown path; combining it with `await using`
        // (which itself calls ShutdownAsync) would tear the driver down twice.
        var driver = new AbLegacyDriver(options, DriverInstanceId);
        try
        {
            await driver.InitializeAsync("{}", ct);
            var results = await driver.WriteAsync([new WriteRequest(tagName, parsed)], ct);
            await console.Output.WriteLineAsync(SnapshotFormatter.FormatWrite(Address, results[0]));
        }
        finally
        {
            await driver.ShutdownAsync(CancellationToken.None);
            FlushLogging();
        }
    }

    /// <summary>Parse <c>--value</c> per <see cref="AbLegacyDataType"/>, invariant culture.</summary>
    /// <param name="raw">The raw string value to parse.</param>
    /// <param name="type">The target data type for parsing.</param>
    /// <returns>The parsed value.</returns>
    /// <exception cref="CliFx.Exceptions.CommandException">
    ///     Thrown when <paramref name="raw"/> cannot be parsed as the requested type (malformed
    ///     input or out-of-range value) so CliFx renders a clean one-line error instead of a raw
    ///     stack trace.
    /// </exception>
    internal static object ParseValue(string raw, AbLegacyDataType type)
    {
        try
        {
            return type switch
            {
                AbLegacyDataType.Bit => ParseBool(raw),
                AbLegacyDataType.Int or AbLegacyDataType.AnalogInt => short.Parse(raw, CultureInfo.InvariantCulture),
                AbLegacyDataType.Long => int.Parse(raw, CultureInfo.InvariantCulture),
                AbLegacyDataType.Float => float.Parse(raw, CultureInfo.InvariantCulture),
                AbLegacyDataType.String => raw,
                AbLegacyDataType.TimerElement or AbLegacyDataType.CounterElement
                    or AbLegacyDataType.ControlElement => int.Parse(raw, CultureInfo.InvariantCulture),
                _ => throw new CliFx.Exceptions.CommandException($"Unsupported DataType '{type}' for write."),
            };
        }
        catch (FormatException ex)
        {
            throw new CliFx.Exceptions.CommandException(
                $"Value '{raw}' is not a valid {type}: {ex.Message}", innerException: ex);
        }
        catch (OverflowException ex)
        {
            throw new CliFx.Exceptions.CommandException(
                $"Value '{raw}' is out of range for {type}: {ex.Message}", 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."),
    };
}
