using System.Collections.Frozen;

namespace ScadaLink.Commons.Messages.Management;

/// <summary>
/// Bidirectional name registry for management command records. The registry contains
/// exactly the non-abstract <c>*Command</c> types declared in the
/// <c>ScadaLink.Commons.Messages.Management</c> namespace; these are the commands that
/// travel over the HTTP / ClusterClient management boundary.
/// </summary>
/// <remarks>
/// <see cref="Resolve"/> and <see cref="GetCommandName"/> are symmetric:
/// <c>Resolve(GetCommandName(t))</c> returns <c>t</c> for every type
/// <see cref="GetCommandName"/> accepts. <see cref="GetCommandName"/> rejects any type
/// the registry does not contain rather than computing an unresolvable name.
/// </remarks>
public static class ManagementCommandRegistry
{
    private static readonly FrozenDictionary<string, Type> Commands = BuildRegistry();

    /// <summary>
    /// Names keyed by command type, for the reverse lookup. Keeps
    /// <see cref="GetCommandName"/> in lock-step with the forward registry.
    /// </summary>
    private static readonly FrozenDictionary<Type, string> NamesByType =
        Commands.ToFrozenDictionary(kv => kv.Value, kv => kv.Key);

    public static Type? Resolve(string commandName)
    {
        return Commands.GetValueOrDefault(commandName);
    }

    /// <summary>
    /// Returns the registered wire name for a management command type.
    /// </summary>
    /// <exception cref="ArgumentException">
    /// Thrown when <paramref name="commandType"/> is not a registered management
    /// command — i.e. not a non-abstract <c>*Command</c> type in the
    /// <c>ScadaLink.Commons.Messages.Management</c> namespace. This keeps the method
    /// symmetric with <see cref="Resolve"/>: it never yields a name that
    /// <see cref="Resolve"/> cannot turn back into the same type.
    /// </exception>
    public static string GetCommandName(Type commandType)
    {
        ArgumentNullException.ThrowIfNull(commandType);

        if (NamesByType.TryGetValue(commandType, out var name))
            return name;

        throw new ArgumentException(
            $"'{commandType.FullName}' is not a registered management command. " +
            $"Management commands must be non-abstract '*Command' records declared in " +
            $"the '{typeof(ManagementEnvelope).Namespace}' namespace.",
            nameof(commandType));
    }

    private static FrozenDictionary<string, Type> BuildRegistry()
    {
        var ns = typeof(ManagementEnvelope).Namespace!;
        var assembly = typeof(ManagementEnvelope).Assembly;

        return assembly.GetTypes()
            .Where(t => t.Namespace == ns
                && t.Name.EndsWith("Command", StringComparison.Ordinal)
                && !t.IsAbstract)
            .ToFrozenDictionary(
                t => t.Name[..^"Command".Length],
                t => t,
                StringComparer.OrdinalIgnoreCase);
    }
}
