using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Threading.Tasks;
using FantasyNetTest;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
using NBC;

public class ScriptLoader
{
    public void LoadAndExecuteScriptsAsync(string folderPath)
    {
        // 1. 读取所有 .cs 文件
        var csFiles = Directory.GetFiles(folderPath, "*.cs", SearchOption.AllDirectories);

        if (!csFiles.Any())
        {
            Console.WriteLine("没有找到 .cs 文件");
            return;
        }

        // 2. 创建语法树
        var syntaxTrees = csFiles.Select(file =>
            CSharpSyntaxTree.ParseText(File.ReadAllText(file))
        );

        // 3. 引用程序集
        var references = AppDomain.CurrentDomain.GetAssemblies()
            .Where(a => !a.IsDynamic && !string.IsNullOrWhiteSpace(a.Location))
            .Select(a => MetadataReference.CreateFromFile(a.Location))
            .Cast<MetadataReference>();

        // 4. 编译成内存程序集
        var compilation = CSharpCompilation.Create(
            assemblyName: "DynamicScripts",
            syntaxTrees: syntaxTrees,
            references: references,
            options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
        );

        using var ms = new MemoryStream();
        var result = compilation.Emit(ms);

        if (!result.Success)
        {
            foreach (var diag in result.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error))
                Console.WriteLine(diag.ToString());
            return;
        }

        // 5. 加载程序集
        ms.Seek(0, SeekOrigin.Begin);
        
        var assembly = AssemblyLoadContext.Default.LoadFromStream(ms);

        // 6. 调用示例
        var type = assembly.GetType("MyNamespace.MyClass"); // 你的类名
        var method = type?.GetMethod("Run"); // 你的方法名
        method?.Invoke(null, null); // 假设是静态方法无参数
    }
}