using System.Reflection;
using ColaFlow.Modules.Mcp.Contracts.Resources;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace ColaFlow.Modules.Mcp.Application.Services;

/// <summary>
/// Implementation of Resource Discovery Service
/// Scans assemblies to find all IMcpResource implementations
/// </summary>
public class ResourceDiscoveryService(ILogger<ResourceDiscoveryService> logger) : IResourceDiscoveryService
{
    public IReadOnlyList<Type> DiscoverResourceTypes()
    {
        logger.LogInformation("Starting MCP Resource discovery via Assembly scanning...");

        var resourceTypes = new List<Type>();

        // Get all loaded assemblies
        var assemblies = AppDomain.CurrentDomain.GetAssemblies()
            .Where(a => !a.IsDynamic && a.FullName != null && a.FullName.StartsWith("ColaFlow"))
            .ToList();

        logger.LogDebug("Scanning {Count} assemblies for IMcpResource implementations", assemblies.Count);

        foreach (var assembly in assemblies)
        {
            try
            {
                var types = assembly.GetTypes()
                    .Where(t => typeof(IMcpResource).IsAssignableFrom(t)
                                && !t.IsInterface
                                && !t.IsAbstract
                                && t.IsClass)
                    .ToList();

                if (types.Any())
                {
                    logger.LogDebug("Found {Count} resources in assembly {Assembly}",
                        types.Count, assembly.GetName().Name);
                    resourceTypes.AddRange(types);
                }
            }
            catch (ReflectionTypeLoadException ex)
            {
                logger.LogWarning(ex, "Failed to load types from assembly {Assembly}", assembly.FullName);
            }
        }

        logger.LogInformation("Discovered {Count} MCP Resource types", resourceTypes.Count);

        return resourceTypes.AsReadOnly();
    }

    public IReadOnlyList<IMcpResource> DiscoverAndInstantiateResources(IServiceProvider serviceProvider)
    {
        var resourceTypes = DiscoverResourceTypes();
        var resources = new List<IMcpResource>();

        foreach (var resourceType in resourceTypes)
        {
            try
            {
                // Use DI to instantiate the resource (resolves dependencies automatically)
                var resource = ActivatorUtilities.CreateInstance(serviceProvider, resourceType) as IMcpResource;

                if (resource != null)
                {
                    resources.Add(resource);
                    logger.LogDebug("Instantiated resource: {ResourceType} -> {Uri}",
                        resourceType.Name, resource.Uri);
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Failed to instantiate resource type {ResourceType}", resourceType.FullName);
            }
        }

        logger.LogInformation("Instantiated {Count} MCP Resources", resources.Count);

        return resources.AsReadOnly();
    }
}
