using LibGit2Sharp; using MarketAlly.AIPlugin; using MarketAlly.AIPlugin.Analysis; using MarketAlly.AIPlugin.Analysis.Plugins; using MarketAlly.AIPlugin.Learning; using MarketAlly.AIPlugin.Learning.Configuration; using MarketAlly.AIPlugin.Learning.Exceptions; using MarketAlly.AIPlugin.Learning.Services; using MarketAlly.AIPlugin.Refactoring.Plugins; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using RefactorIQ.Services; using RefactorIQ.Core; using RefactorIQ.Persistence.Services; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography.Xml; using System.Text.Json; using System.Text.RegularExpressions; using System.Threading.Tasks; using Signature = LibGit2Sharp.Signature; using LogLevel = Microsoft.Extensions.Logging.LogLevel; namespace MarketAlly.AIPlugin.Learning { [AIPlugin("ComprehensiveLearningRefactor", "Complete self-learning refactoring system with ModularMap, RefactorIQ, Git safety, and warnings analysis")] public class ComprehensiveLearningRefactorPlugin : IAIPlugin, IDisposable { [AIParameter("Solution path to analyze and improve", required: true)] public string SolutionPath { get; set; } [AIParameter("Reports output directory", required: false)] public string ReportsDirectory { get; set; } = "Reports"; [AIParameter("Maximum learning iterations per session", required: false)] public int MaxIterations { get; set; } = 20; [AIParameter("Maximum attempts per file before giving up", required: false)] public int MaxAttemptsPerFile { get; set; } = 3; [AIParameter("Session timeout in minutes", required: false)] public int SessionTimeoutMinutes { get; set; } = 60; [AIParameter("Verbose reporting (detailed vs summary)", required: false)] public bool VerboseReporting { get; set; } = false; [AIParameter("Learning mode: conservative, moderate, aggressive", required: false)] public string LearningMode { get; set; } = "conservative"; [AIParameter("Skip warnings analysis", required: false)] public bool SkipWarningsAnalysis { get; set; } = false; [AIParameter("Configuration file path for RefactorIQ", required: false)] public string ConfigPath { get; set; } [AIParameter("Enable AI embeddings generation", required: false)] public bool EnableAIEmbeddings { get; set; } = false; [AIParameter("Enable semantic code search", required: false)] public bool EnableSemanticSearch { get; set; } = false; [AIParameter("OpenAI API key for embeddings", required: false)] public string OpenAIApiKey { get; set; } public IReadOnlyDictionary SupportedParameters => new Dictionary { ["solutionPath"] = typeof(string), ["reportsDirectory"] = typeof(string), ["maxIterations"] = typeof(int), ["maxAttemptsPerFile"] = typeof(int), ["sessionTimeoutMinutes"] = typeof(int), ["verboseReporting"] = typeof(bool), ["learningMode"] = typeof(string), ["skipWarningsAnalysis"] = typeof(bool), ["configPath"] = typeof(string), ["enableAIEmbeddings"] = typeof(bool), ["enableSemanticSearch"] = typeof(bool), ["openAIApiKey"] = typeof(string) }; private IServiceProvider? _serviceProvider; private bool _disposed = false; public async Task ExecuteAsync(IReadOnlyDictionary parameters) { try { // Build service provider with proper configuration _serviceProvider = BuildServiceProvider(parameters); var session = new ComprehensiveLearningSession { SessionId = Guid.NewGuid(), SolutionPath = parameters["solutionPath"].ToString(), ReportsDirectory = parameters.GetValueOrDefault("reportsDirectory", "Reports").ToString(), MaxIterations = Convert.ToInt32(parameters.GetValueOrDefault("maxIterations", 20)), MaxAttemptsPerFile = Convert.ToInt32(parameters.GetValueOrDefault("maxAttemptsPerFile", 3)), SessionTimeoutMinutes = Convert.ToInt32(parameters.GetValueOrDefault("sessionTimeoutMinutes", 60)), VerboseReporting = Convert.ToBoolean(parameters.GetValueOrDefault("verboseReporting", false)), LearningMode = parameters.GetValueOrDefault("learningMode", "conservative").ToString(), SkipWarningsAnalysis = Convert.ToBoolean(parameters.GetValueOrDefault("skipWarningsAnalysis", false)), ConfigPath = parameters.GetValueOrDefault("configPath", null)?.ToString(), EnableAIEmbeddings = Convert.ToBoolean(parameters.GetValueOrDefault("enableAIEmbeddings", false)), EnableSemanticSearch = Convert.ToBoolean(parameters.GetValueOrDefault("enableSemanticSearch", false)), OpenAIApiKey = parameters.GetValueOrDefault("openAIApiKey", null)?.ToString(), StartTime = DateTime.UtcNow }; // Use the new orchestrator service using var orchestrator = _serviceProvider.GetRequiredService(); var result = await orchestrator.ExecuteCompleteLearningSessionAsync(session); return new AIPluginResult(result, "Comprehensive learning session completed"); } catch (LearningException ex) { return new AIPluginResult(ex, $"Learning operation failed: {ex.Message}"); } catch (Exception ex) { return new AIPluginResult(ex, $"Comprehensive learning session failed: {ex.Message}"); } } private IServiceProvider BuildServiceProvider(IReadOnlyDictionary parameters) { var services = new ServiceCollection(); // Configuration var configuration = new ConfigurationBuilder() .AddInMemoryCollection(new Dictionary { ["Learning:Git:BranchPrefix"] = "ai-refactoring", ["Learning:Git:CommitterName"] = "AI Learning System", ["Learning:Git:CommitterEmail"] = "ai@learning.system", ["Learning:LearningModes:Conservative:MaxIterations"] = "10", ["Learning:LearningModes:Moderate:MaxIterations"] = "20", ["Learning:LearningModes:Aggressive:MaxIterations"] = "50", ["Learning:AI:EnableSemanticSearch"] = parameters.GetValueOrDefault("enableSemanticSearch", false).ToString(), ["Learning:AI:MaxSearchResults"] = "10", ["Learning:AI:MinSimilarityScore"] = "0.7" }) .Build(); services.AddSingleton(configuration); services.Configure(configuration.GetSection(LearningConfiguration.SectionName)); // Logging services.AddLogging(builder => builder.AddConsole().SetMinimumLevel(LogLevel.Information)); // Core services services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddTransient(); // Legacy services (temporarily until fully migrated) services.AddTransient(provider => new GitManager(parameters["solutionPath"].ToString())); services.AddTransient(); services.AddTransient(provider => new ReportsManager(parameters.GetValueOrDefault("reportsDirectory", "Reports").ToString())); services.AddTransient(provider => new RefactorIQIntegration(parameters.GetValueOrDefault("configPath", null)?.ToString())); // RefactorIQ services (would need proper implementation) // services.AddSingleton(); return services.BuildServiceProvider(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!_disposed && disposing) { if (_serviceProvider is IDisposable disposableProvider) { disposableProvider.Dispose(); } } _disposed = true; } } }