using CliFx.Attributes;
using CliFx.Exceptions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Cli.Common;

namespace ZB.MOM.WW.OtOpcUa.Driver.S7.Cli;

/// <summary>
///     Base for every S7 CLI command. Carries the ISO-on-TCP endpoint options
///     (host / port / CPU type / rack / slot) that S7.Net needs for its handshake +
///     exposes <see cref="BuildOptions"/> so each command can synthesise an
///     <see cref="S7DriverOptions"/> on demand.
/// </summary>
public abstract class S7CommandBase : DriverCommandBase
{
    /// <summary>Gets the PLC IP address or hostname.</summary>
    [CommandOption("host", 'h', Description = "PLC IP address or hostname.", IsRequired = true)]
    public string Host { get; init; } = default!;

    /// <summary>Gets the ISO-on-TCP port.</summary>
    [CommandOption("port", 'p', Description = "ISO-on-TCP port (default 102).")]
    public int Port { get; init; } = 102;

    /// <summary>Gets the S7 CPU family type.</summary>
    [CommandOption("cpu", 'c', Description =
        "S7 CPU family: S7200 / S7200Smart / S7300 / S7400 / S71200 / S71500 " +
        "(default S71500). Determines the ISO-TSAP slot byte.")]
    public S7CpuType CpuType { get; init; } = S7CpuType.S71500;

    /// <summary>Gets the rack number.</summary>
    [CommandOption("rack", Description = "Rack number (default 0 — single-rack).")]
    public short Rack { get; init; } = 0;

    /// <summary>Gets the CPU slot number.</summary>
    [CommandOption("slot", Description =
        "CPU slot. S7-300 = 2, S7-400 = 2 or 3, S7-1200 / S7-1500 = 0 (default 0).")]
    public short Slot { get; init; } = 0;

    /// <summary>Gets the per-operation timeout in milliseconds.</summary>
    [CommandOption("timeout-ms", Description = "Per-operation timeout in ms (default 5000).")]
    public int TimeoutMs { get; init; } = 5000;

    /// <inheritdoc />
    public override TimeSpan Timeout
    {
        get => TimeSpan.FromMilliseconds(TimeoutMs);
        init { /* driven by TimeoutMs */ }
    }

    /// <summary>
    ///     Build an <see cref="S7DriverOptions"/> with the endpoint fields this base
    ///     collected + whatever <paramref name="tags"/> the subclass declares. Each typed
    ///     definition is serialised to its <c>TagConfig</c> blob via
    ///     <see cref="S7TagDefinitionFactory.ToTagConfig"/> and packaged as a
    ///     <see cref="RawTagEntry"/> (RawPath = the def's <c>Name</c>) — the v3 delivery shape the
    ///     driver rebuilds definitions from. Probe disabled — CLI runs are one-shot.
    /// </summary>
    /// <param name="tags">The tag definitions to include in the options.</param>
    /// <returns>The constructed <see cref="S7DriverOptions"/>.</returns>
    protected S7DriverOptions BuildOptions(IReadOnlyList<S7TagDefinition> tags) => new()
    {
        Host = Host,
        Port = Port,
        CpuType = CpuType,
        Rack = Rack,
        Slot = Slot,
        Timeout = Timeout,
        RawTags = [.. tags.Select(t => new RawTagEntry(t.Name, S7TagDefinitionFactory.ToTagConfig(t), t.WriteIdempotent))],
        Probe = new S7ProbeOptions { Enabled = false },
    };

    /// <summary>Gets the driver instance ID for this CLI session.</summary>
    protected string DriverInstanceId => $"s7-cli-{Host}:{Port}";

    /// <summary>
    ///     Validate the endpoint flags at parse time so the operator
    ///     gets a clear <see cref="CommandException"/> instead of an opaque socket or
    ///     argument exception thrown deep inside the S7.Net stack.
    ///     <list type="bullet">
    ///       <item><c>--port</c>: 1..65535 (IANA TCP port space).</item>
    ///       <item><c>--timeout-ms</c>: strictly positive — a non-positive value would
    ///         propagate as an immediate-timeout into S7.Net and surface as a confusing
    ///         <see cref="TimeoutException"/>.</item>
    ///     </list>
    /// </summary>
    protected void ValidateEndpoint()
    {
        if (Port < 1 || Port > 65535)
            throw new CommandException(
                $"--port must be in 1..65535 (got {Port}).");
        if (TimeoutMs <= 0)
            throw new CommandException(
                $"--timeout-ms must be strictly positive (got {TimeoutMs}).");
    }
}
