using System.Globalization;

namespace ZB.MOM.WW.MxGateway.Client.Cli;

/// <summary>Parses command-line arguments into flags and named values.</summary>
internal sealed class CliArguments
{
    private readonly Dictionary<string, string> _values = new(StringComparer.OrdinalIgnoreCase);
    private readonly HashSet<string> _flags = new(StringComparer.OrdinalIgnoreCase);

    /// <summary>Initializes a new instance by parsing the given command-line arguments.</summary>
    /// <param name="args">Unparsed command-line arguments; flags prefixed with '--' and values follow their flag.</param>
    public CliArguments(IEnumerable<string> args)
    {
        string? pendingName = null;

        foreach (string arg in args)
        {
            if (arg.StartsWith("--", StringComparison.Ordinal))
            {
                if (pendingName is not null)
                {
                    _flags.Add(pendingName);
                }

                pendingName = arg[2..];
                continue;
            }

            if (pendingName is null)
            {
                throw new ArgumentException($"Unexpected argument '{arg}'.");
            }

            _values[pendingName] = arg;
            pendingName = null;
        }

        if (pendingName is not null)
        {
            _flags.Add(pendingName);
        }
    }

    /// <summary>Returns whether the named flag was present in the arguments.</summary>
    /// <param name="name">The flag name (without '--' prefix).</param>
    /// <returns><c>true</c> if the flag was present; otherwise, <c>false</c>.</returns>
    public bool HasFlag(string name)
    {
        return _flags.Contains(name);
    }

    /// <summary>Returns the value for a named argument, or <c>null</c> if absent.</summary>
    /// <param name="name">The argument name (without '--' prefix).</param>
    /// <returns>The argument value, or <c>null</c> if the argument is absent.</returns>
    public string? GetOptional(string name)
    {
        return _values.TryGetValue(name, out string? value)
            ? value
            : null;
    }

    /// <summary>Returns the value for a required named argument, or throws if absent.</summary>
    /// <param name="name">The argument name (without '--' prefix).</param>
    /// <returns>The argument value.</returns>
    public string GetRequired(string name)
    {
        string? value = GetOptional(name);
        if (string.IsNullOrWhiteSpace(value))
        {
            throw new ArgumentException($"Missing required option --{name}.");
        }

        return value;
    }

    /// <summary>Parses and returns an int32 argument, or the default value if absent.</summary>
    /// <param name="name">The argument name (without '--' prefix).</param>
    /// <param name="defaultValue">The default value if the argument is absent; if <c>null</c>, the argument is required.</param>
    /// <returns>The parsed int32 value.</returns>
    public int GetInt32(string name, int? defaultValue = null)
    {
        string? value = GetOptional(name);
        if (string.IsNullOrWhiteSpace(value))
        {
            if (defaultValue.HasValue)
            {
                return defaultValue.Value;
            }

            throw new ArgumentException($"Missing required option --{name}.");
        }

        return int.Parse(value, CultureInfo.InvariantCulture);
    }

    /// <summary>Parses and returns a uint32 argument, or the default value if absent.</summary>
    /// <param name="name">The argument name (without '--' prefix).</param>
    /// <param name="defaultValue">The default value if the argument is absent.</param>
    /// <returns>The parsed uint32 value.</returns>
    public uint GetUInt32(string name, uint defaultValue)
    {
        string? value = GetOptional(name);
        return string.IsNullOrWhiteSpace(value)
            ? defaultValue
            : uint.Parse(value, CultureInfo.InvariantCulture);
    }

    /// <summary>Parses and returns a uint64 argument, or the default value if absent.</summary>
    /// <param name="name">The argument name (without '--' prefix).</param>
    /// <param name="defaultValue">The default value if the argument is absent.</param>
    /// <returns>The parsed uint64 value.</returns>
    public ulong GetUInt64(string name, ulong defaultValue)
    {
        string? value = GetOptional(name);
        return string.IsNullOrWhiteSpace(value)
            ? defaultValue
            : ulong.Parse(value, CultureInfo.InvariantCulture);
    }

    /// <summary>Parses and returns a TimeSpan argument, or the default value if absent. Supports "ms", "s", and standard TimeSpan format.</summary>
    /// <param name="name">The argument name (without '--' prefix).</param>
    /// <param name="defaultValue">The default value if the argument is absent.</param>
    /// <returns>The parsed duration.</returns>
    public TimeSpan GetDuration(string name, TimeSpan defaultValue)
    {
        string? value = GetOptional(name);
        if (string.IsNullOrWhiteSpace(value))
        {
            return defaultValue;
        }

        if (value.EndsWith("ms", StringComparison.OrdinalIgnoreCase))
        {
            return TimeSpan.FromMilliseconds(double.Parse(value[..^2], CultureInfo.InvariantCulture));
        }

        if (value.EndsWith('s'))
        {
            return TimeSpan.FromSeconds(double.Parse(value[..^1], CultureInfo.InvariantCulture));
        }

        return TimeSpan.Parse(value, CultureInfo.InvariantCulture);
    }
}
