#nullable enable

using System;
using System.Linq;
using System.Reflection;

namespace MyCodeEditor.HDEUtils
{
    /// <summary>
    /// Redirects Microsoft.CodeAnalysis.* assembly loading to version 4.11.0.0 (already loaded by Gamma).
    /// This must be initialized before any RoslynPad types are accessed.
    /// </summary>
    internal static class RoslynAssemblyRedirect
    {
        private static bool _initialized;

        /// <summary>
        /// Force initialization of the assembly redirect handler.
        /// Call this early, before creating RoslynPadEditorView.
        /// </summary>
        public static void EnsureInitialized()
        {
            if (_initialized)
                return;

            _initialized = true;
            AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve;
        }

        private static Assembly? OnAssemblyResolve(object? sender, ResolveEventArgs args)
        {
            var requestedName = new AssemblyName(args.Name);
            
            // Redirect ALL Microsoft.CodeAnalysis.* assemblies to version 4.11.0.0 (loaded by Gamma)
            if (requestedName.Name != null && 
                requestedName.Name.StartsWith("Microsoft.CodeAnalysis", StringComparison.OrdinalIgnoreCase))
            {
                // Try to find the 4.11.0.0 version already loaded by Gamma
                var loaded = AppDomain.CurrentDomain.GetAssemblies()
                    .FirstOrDefault(a =>
                    {
                        try
                        {
                            var name = a.GetName();
                            return name.Name == requestedName.Name &&
                                   name.Version != null &&
                                   name.Version.Major == 4 && 
                                   (name.Version.Minor == 11 || name.Version.Minor == 12); // Accept both 4.11 and 4.12
                        }
                        catch
                        {
                            return false;
                        }
                    });
                
                if (loaded != null)
                {
                    return loaded;
                }
            }
            
            return null;
        }
    }
}

