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

/// <summary>
///     Write one value to an S7 address. Mirrors <see cref="ReadCommand"/>'s flag shape.
///     Writes to M (merker) bits or Q (output) coils that drive edge-triggered routines
///     are real — be careful what you hit on a running PLC.
/// </summary>
[Command("write", Description = "Write a single S7 address.")]
public sealed class WriteCommand : S7CommandBase
{
    /// <summary>Gets or sets the S7 address to write to.</summary>
    [CommandOption("address", 'a', Description =
        "S7 address — same format as `read`.", IsRequired = true)]
    public string Address { get; init; } = default!;

    /// <summary>Gets or sets the data type of the value to write.</summary>
    // Help text reflects the types the driver currently implements.
    [CommandOption("type", 't', Description =
        "Bool / Byte / Int16 / UInt16 / Int32 / UInt32 / Float32 / Int64 / UInt64 / Float64 / String / DateTime (default Int16). " +
        "Wide types (Int64, UInt64, Float64/LReal, String, DateTime) are byte-anchored: address must use the B suffix " +
        "(e.g. DB1.DBB8, MB4) pointing at the first byte; width comes from the DataType. " +
        "Timer (T{n}) and Counter (C{n}) are read-only — writes to them return BadNotWritable.")]
    public S7DataType DataType { get; init; } = S7DataType.Int16;

    /// <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).",
        IsRequired = true)]
    public string Value { get; init; } = default!;

    /// <summary>Gets or sets the maximum length for string values.</summary>
    [CommandOption("string-length", Description =
        "For type=String: S7-string max length (default 254).")]
    public int StringLength { get; init; } = 254;

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

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

        var parsed = ParseValue(Value, DataType);

        // `await using` is the sole disposal mechanism — S7Driver.DisposeAsync
        // already invokes ShutdownAsync, so a redundant explicit ShutdownAsync(CancellationToken.None)
        // in a finally block ran shutdown twice. The await-using on the next line is enough.
        await using var driver = new S7Driver(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]));
        }
        catch (OperationCanceledException) when (ct.IsCancellationRequested)
        {
            // Ctrl+C during driver connect/write — exit quietly so
            // CliFx does not render a full stack trace for a user-initiated cancellation.
            await console.Output.WriteLineAsync("Cancelled.");
        }
    }

    /// <summary>Parse <c>--value</c> per <see cref="S7DataType"/>, invariant culture throughout.</summary>
    /// <remarks>
    ///     Numeric and <see cref="DateTime"/> parses are wrapped so that
    ///     malformed input (<see cref="FormatException"/> / <see cref="OverflowException"/>)
    ///     surfaces as a clean <see cref="CliFx.Exceptions.CommandException"/> rather than a
    ///     raw .NET stack trace — matching the friendly message the Bool path already produces.
    /// </remarks>
    /// <param name="raw">The raw string value to parse.</param>
    /// <param name="type">The target data type for parsing.</param>
    /// <returns>The parsed value as an object.</returns>
    internal static object ParseValue(string raw, S7DataType type)
    {
        if (type == S7DataType.Bool) return ParseBool(raw);
        if (type == S7DataType.String) return raw;
        try
        {
            return type switch
            {
                S7DataType.Byte     => (object)byte.Parse(raw, CultureInfo.InvariantCulture),
                S7DataType.Int16    => (object)short.Parse(raw, CultureInfo.InvariantCulture),
                S7DataType.UInt16   => (object)ushort.Parse(raw, CultureInfo.InvariantCulture),
                S7DataType.Int32    => (object)int.Parse(raw, CultureInfo.InvariantCulture),
                S7DataType.UInt32   => (object)uint.Parse(raw, CultureInfo.InvariantCulture),
                S7DataType.Int64    => (object)long.Parse(raw, CultureInfo.InvariantCulture),
                S7DataType.UInt64   => (object)ulong.Parse(raw, CultureInfo.InvariantCulture),
                S7DataType.Float32  => (object)float.Parse(raw, CultureInfo.InvariantCulture),
                S7DataType.Float64  => (object)double.Parse(raw, CultureInfo.InvariantCulture),
                S7DataType.DateTime => (object)DateTime.Parse(raw, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind),
                _ => 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}");
        }
        catch (OverflowException ex)
        {
            throw new CliFx.Exceptions.CommandException(
                $"Value '{raw}' is out of range for {type}: {ex.Message}");
        }
    }

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