using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using System.Text.Json; using Microsoft.Extensions.Logging; using MarketAlly.AIPlugin; using MarketAlly.AIPlugin.Analysis.Plugins; namespace MarketAlly.AIPlugin.Analysis.ModularMapTest { class Program { private static readonly ILoggerFactory _loggerFactory = LoggerFactory.Create(builder => builder.AddConsole().SetMinimumLevel(LogLevel.Information)); private static readonly ILogger _logger = _loggerFactory.CreateLogger(); static async Task Main(string[] args) { Console.WriteLine("🗺️ MarketAlly ModularMap Plugin Test Console"); Console.WriteLine("============================================="); Console.WriteLine(); try { // Initialize plugin registry var registryLogger = _loggerFactory.CreateLogger(); var registry = new AIPluginRegistry(registryLogger); // Register ModularMapPlugin var modularMapLogger = _loggerFactory.CreateLogger(); var modularMapPlugin = new ModularMapPlugin(modularMapLogger); registry.RegisterPlugin(modularMapPlugin); Console.WriteLine("✅ ModularMapPlugin registered successfully"); Console.WriteLine(); // Get test project path var testProjectPath = GetTestProjectPath(args); if (string.IsNullOrEmpty(testProjectPath)) { Console.WriteLine("❌ No valid project path provided."); Console.WriteLine("Usage: ModularMapTestConsole.exe [project-path]"); Console.WriteLine("Example: ModularMapTestConsole.exe C:\\MyProject"); Console.WriteLine("Example: ModularMapTestConsole.exe C:\\MyProject\\MyProject.sln"); return; } Console.WriteLine($"📁 Target Project: {testProjectPath}"); Console.WriteLine(); // Create output directory var outputDir = Path.Combine(Directory.GetCurrentDirectory(), "ModularMapOutput"); Directory.CreateDirectory(outputDir); Console.WriteLine($"📂 Output Directory: {outputDir}"); Console.WriteLine(); // Run comprehensive tests await RunBasicAnalysisTest(registry, testProjectPath, outputDir); await RunMermaidGenerationTest(registry, testProjectPath, outputDir); await RunCytoscapeGenerationTest(registry, testProjectPath, outputDir); await RunGraphVizGenerationTest(registry, testProjectPath, outputDir); await RunComprehensiveAnalysisTest(registry, testProjectPath, outputDir); await RunFilteredAnalysisTest(registry, testProjectPath, outputDir); await RunPerformanceTest(registry, testProjectPath); await RunErrorHandlingTest(registry); await RunScaffoldingFeaturesTest(registry, testProjectPath, outputDir); Console.WriteLine(); Console.WriteLine("🎉 All tests completed successfully!"); Console.WriteLine($"📊 Check the '{outputDir}' directory for generated files."); // Display summary of generated files DisplayGeneratedFiles(outputDir); } catch (Exception ex) { Console.WriteLine($"❌ Test execution failed: {ex.Message}"); _logger.LogError(ex, "Test execution failed"); } finally { _loggerFactory?.Dispose(); } Console.WriteLine(); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } private static string GetTestProjectPath(string[] args) { // Check command line arguments if (args.Length > 0) { var path = args[0]; if (Directory.Exists(path) || (File.Exists(path) && IsProjectOrSolutionFile(path))) { return path; } Console.WriteLine($"⚠️ Provided path does not exist or is not valid: {path}"); } // Try current directory var currentDir = Directory.GetCurrentDirectory(); if (HasCSharpProject(currentDir)) { Console.WriteLine("📍 Using current directory (found C# project files)"); return currentDir; } // Try common project locations var testPaths = new[] { Path.Combine(currentDir, "TestProject"), Path.Combine(currentDir, "src"), Path.Combine(currentDir, "Source"), Path.Combine(currentDir, ".."), Path.Combine(currentDir, "..", "MarketAlly.AIPlugin"), Path.Combine(currentDir, "..", "..", "MarketAlly.AIPlugin") }; foreach (var testPath in testPaths) { if (Directory.Exists(testPath) && HasCSharpProject(testPath)) { Console.WriteLine($"📍 Auto-detected project at: {testPath}"); return testPath; } } // Interactive prompt Console.WriteLine("🔍 No C# project automatically detected."); Console.Write("Enter the path to a C# project directory or solution file: "); var userPath = Console.ReadLine()?.Trim(); if (!string.IsNullOrEmpty(userPath) && (Directory.Exists(userPath) || (File.Exists(userPath) && IsProjectOrSolutionFile(userPath)))) { return userPath; } return null; } private static bool HasCSharpProject(string directory) { try { return Directory.GetFiles(directory, "*.csproj", SearchOption.AllDirectories).Length > 0 || Directory.GetFiles(directory, "*.sln", SearchOption.TopDirectoryOnly).Length > 0; } catch { return false; } } private static bool IsProjectOrSolutionFile(string filePath) { var extension = Path.GetExtension(filePath).ToLower(); return extension == ".sln" || extension == ".csproj" || extension == ".vbproj" || extension == ".fsproj"; } private static async Task RunBasicAnalysisTest(AIPluginRegistry registry, string projectPath, string outputDir) { Console.WriteLine("🔍 Test 1: Basic Dependency Analysis"); Console.WriteLine("====================================="); try { var parameters = new Dictionary { ["projectPath"] = projectPath, ["outputFormat"] = "json" }; var result = await registry.CallFunctionAsync("ModularMap", parameters); if (result.Success) { Console.WriteLine("✅ Basic analysis completed successfully"); // Save and analyze results var outputPath = Path.Combine(outputDir, "basic-analysis.json"); await SaveAndAnalyzeResult(result.Data, outputPath, "Basic Analysis"); } else { Console.WriteLine($"❌ Basic analysis failed: {result.Message}"); if (result.Error != null) { Console.WriteLine($" Error: {result.Error.Message}"); } } } catch (Exception ex) { Console.WriteLine($"❌ Basic analysis test failed: {ex.Message}"); } Console.WriteLine(); } private static async Task RunMermaidGenerationTest(AIPluginRegistry registry, string projectPath, string outputDir) { Console.WriteLine("🌊 Test 2: Mermaid Diagram Generation"); Console.WriteLine("===================================="); try { var parameters = new Dictionary { ["projectPath"] = projectPath, ["outputFormat"] = "mermaid", ["analyzeCoupling"] = true, ["outputPath"] = Path.Combine(outputDir, "dependency-diagram.mmd") }; var result = await registry.CallFunctionAsync("ModularMap", parameters); if (result.Success) { Console.WriteLine("✅ Mermaid diagram generated successfully"); Console.WriteLine($" 📄 Mermaid file: {Path.Combine(outputDir, "dependency-diagram.mmd")}"); // Also save the full result var resultPath = Path.Combine(outputDir, "mermaid-result.json"); await SaveResultToFile(result.Data, resultPath); // Show mermaid preview ShowMermaidPreview(result.Data); } else { Console.WriteLine($"❌ Mermaid generation failed: {result.Message}"); } } catch (Exception ex) { Console.WriteLine($"❌ Mermaid generation test failed: {ex.Message}"); } Console.WriteLine(); } private static async Task RunCytoscapeGenerationTest(AIPluginRegistry registry, string projectPath, string outputDir) { Console.WriteLine("🕸️ Test 3: Cytoscape Visualization Generation"); Console.WriteLine("============================================="); try { var parameters = new Dictionary { ["projectPath"] = projectPath, ["outputFormat"] = "cytoscape", ["analyzeCoupling"] = true, ["detectPatterns"] = true, ["outputPath"] = Path.Combine(outputDir, "cytoscape-visualization.json") }; var result = await registry.CallFunctionAsync("ModularMap", parameters); if (result.Success) { Console.WriteLine("✅ Cytoscape visualization generated successfully"); Console.WriteLine($" 📄 Cytoscape file: {Path.Combine(outputDir, "cytoscape-visualization.json")}"); // Save the full result var resultPath = Path.Combine(outputDir, "cytoscape-result.json"); await SaveAndAnalyzeResult(result.Data, resultPath, "Cytoscape"); } else { Console.WriteLine($"❌ Cytoscape generation failed: {result.Message}"); } } catch (Exception ex) { Console.WriteLine($"❌ Cytoscape generation test failed: {ex.Message}"); } Console.WriteLine(); } private static async Task RunGraphVizGenerationTest(AIPluginRegistry registry, string projectPath, string outputDir) { Console.WriteLine("📊 Test 4: GraphViz DOT Generation"); Console.WriteLine("=================================="); try { var parameters = new Dictionary { ["projectPath"] = projectPath, ["outputFormat"] = "graphviz", ["analyzeCoupling"] = true, ["detectPatterns"] = true, ["outputPath"] = Path.Combine(outputDir, "dependency-graph.dot") }; var result = await registry.CallFunctionAsync("ModularMap", parameters); if (result.Success) { Console.WriteLine("✅ GraphViz DOT file generated successfully"); Console.WriteLine($" 📄 DOT file: {Path.Combine(outputDir, "dependency-graph.dot")}"); Console.WriteLine(" 💡 Tip: Use Graphviz tools to render this file (e.g., dot -Tpng dependency-graph.dot -o graph.png)"); // Save the full result var resultPath = Path.Combine(outputDir, "graphviz-result.json"); await SaveResultToFile(result.Data, resultPath); } else { Console.WriteLine($"❌ GraphViz generation failed: {result.Message}"); } } catch (Exception ex) { Console.WriteLine($"❌ GraphViz generation test failed: {ex.Message}"); } Console.WriteLine(); } private static async Task RunComprehensiveAnalysisTest(AIPluginRegistry registry, string projectPath, string outputDir) { Console.WriteLine("🔬 Test 5: Comprehensive Analysis (All Features + Scaffolding)"); Console.WriteLine("==========================================================="); try { var parameters = new Dictionary { // Core analysis parameters ["projectPath"] = projectPath, ["outputFormat"] = "json", ["analyzeCoupling"] = true, ["detectPatterns"] = true, ["generateInsights"] = true, ["includeExternalDependencies"] = true, ["includeMethodLevel"] = true, ["maxDepth"] = 5, // Enhanced modular mapping parameters ["enableModuleGrouping"] = true, ["moduleGroupingStrategy"] = "auto", ["detectPlatformModules"] = true, ["includeEntryPoints"] = true, // NEW: Generation-focused parameters ["generateScaffoldingMetadata"] = true, ["includeLlmDescriptions"] = true, ["analyzeModuleTags"] = true, ["includeModuleFlags"] = true, ["outputPath"] = Path.Combine(outputDir, "comprehensive-scaffolding-analysis.json") }; var result = await registry.CallFunctionAsync("ModularMap", parameters); if (result.Success) { Console.WriteLine("✅ Comprehensive scaffolding analysis completed successfully"); var resultPath = Path.Combine(outputDir, "comprehensive-scaffolding-result.json"); await SaveAndAnalyzeResult(result.Data, resultPath, "Comprehensive Scaffolding"); // Show detailed metrics including new scaffolding features ShowDetailedScaffoldingMetrics(result.Data); } else { Console.WriteLine($"❌ Comprehensive analysis failed: {result.Message}"); } } catch (Exception ex) { Console.WriteLine($"❌ Comprehensive analysis test failed: {ex.Message}"); } Console.WriteLine(); } // Add this new method to show scaffolding-specific metrics private static void ShowDetailedScaffoldingMetrics(object data) { try { var jsonElement = JsonSerializer.Deserialize(JsonSerializer.Serialize(data)); Console.WriteLine(" 📊 Comprehensive Scaffolding Analysis Results:"); // Show modular structure info if (jsonElement.TryGetProperty("ModularStructure", out var modularStructure)) { Console.WriteLine(" 🧩 Modular Structure:"); if (modularStructure.TryGetProperty("modules", out var modules)) { Console.WriteLine($" Logical Modules: {modules.GetArrayLength()}"); // Show module categories var moduleTypes = new Dictionary(); var platformModules = 0; var scaffoldableModules = 0; var optionalModules = 0; foreach (var module in modules.EnumerateArray()) { if (module.TryGetProperty("moduleType", out var moduleType)) { var type = moduleType.GetString(); moduleTypes[type] = moduleTypes.GetValueOrDefault(type, 0) + 1; } if (module.TryGetProperty("platformSpecific", out var isPlatform) && isPlatform.GetBoolean()) platformModules++; if (module.TryGetProperty("scaffoldable", out var isScaffoldable) && isScaffoldable.GetBoolean()) scaffoldableModules++; if (module.TryGetProperty("optional", out var isOptional) && isOptional.GetBoolean()) optionalModules++; } Console.WriteLine($" Platform-Specific: {platformModules}"); Console.WriteLine($" Scaffoldable: {scaffoldableModules}"); Console.WriteLine($" Optional: {optionalModules}"); Console.WriteLine($" Module Types: {string.Join(", ", moduleTypes.Select(kvp => $"{kvp.Key}({kvp.Value})"))}"); } } // Show scaffolding guide if (jsonElement.TryGetProperty("scaffoldingGuide", out var scaffoldingGuide)) { Console.WriteLine(" 🛠️ Scaffolding Guide:"); if (scaffoldingGuide.TryGetProperty("coreModules", out var coreModules)) Console.WriteLine($" Core Modules: {coreModules.GetArrayLength()}"); if (scaffoldingGuide.TryGetProperty("optionalModules", out var optionalModules)) Console.WriteLine($" Optional Modules: {optionalModules.GetArrayLength()}"); if (scaffoldingGuide.TryGetProperty("platformModules", out var platformModules)) { var platformCount = 0; foreach (var platform in platformModules.EnumerateObject()) { platformCount++; } Console.WriteLine($" Platform Groups: {platformCount}"); } } // Show LLM prompt data if (jsonElement.TryGetProperty("llmPromptData", out var llmData)) { Console.WriteLine(" 🤖 LLM Integration Data:"); if (llmData.TryGetProperty("modulesByCategory", out var categories)) { var categoryCount = 0; foreach (var category in categories.EnumerateObject()) { categoryCount++; } Console.WriteLine($" Module Categories: {categoryCount}"); } if (llmData.TryGetProperty("commonCombinations", out var combinations)) Console.WriteLine($" Common Combinations: {combinations.GetArrayLength()}"); if (llmData.TryGetProperty("quickStartModules", out var quickStart)) Console.WriteLine($" Quick Start Modules: {quickStart.GetArrayLength()}"); } // Show original coupling metrics if (jsonElement.TryGetProperty("CouplingMetrics", out var coupling)) { Console.WriteLine(" 🔗 Coupling Analysis:"); if (coupling.TryGetProperty("OverallCouplingScore", out var score)) Console.WriteLine($" Overall Coupling Score: {score.GetDouble():F2}"); if (coupling.TryGetProperty("HighlyCoupledModules", out var highCoupling)) Console.WriteLine($" Highly Coupled Modules: {highCoupling.GetArrayLength()}"); if (coupling.TryGetProperty("CircularDependencies", out var circular)) Console.WriteLine($" Circular Dependencies: {circular.GetArrayLength()}"); } // Show architectural insights if (jsonElement.TryGetProperty("Insights", out var insights)) { Console.WriteLine(" 💡 Architectural Insights:"); if (insights.TryGetProperty("OverallArchitectureScore", out var archScore)) Console.WriteLine($" Architecture Score: {archScore.GetDouble():F1}/10"); if (insights.TryGetProperty("RefactoringOpportunities", out var refactoring)) Console.WriteLine($" Refactoring Opportunities: {refactoring.GetArrayLength()}"); if (insights.TryGetProperty("DesignPatternSuggestions", out var suggestions)) Console.WriteLine($" Design Pattern Suggestions: {suggestions.GetArrayLength()}"); } // Show generation readiness Console.WriteLine(" 🚀 Generation Readiness:"); Console.WriteLine($" Scaffolding Compatible: ✅"); Console.WriteLine($" LLM Optimized: ✅"); Console.WriteLine($" Module Tags Available: ✅"); Console.WriteLine($" Platform Detection: ✅"); } catch (Exception ex) { Console.WriteLine($" ⚠️ Could not parse scaffolding metrics: {ex.Message}"); } } private static async Task RunScaffoldingFeaturesTest(AIPluginRegistry registry, string projectPath, string outputDir) { Console.WriteLine("🏗️ Test 6: Scaffolding & Generation Features"); Console.WriteLine("==========================================="); try { var parameters = new Dictionary { ["projectPath"] = projectPath, ["outputFormat"] = "json", ["enableModuleGrouping"] = true, ["moduleGroupingStrategy"] = "feature", // Test feature-based grouping ["generateScaffoldingMetadata"] = true, ["includeLlmDescriptions"] = true, ["analyzeModuleTags"] = true, ["includeModuleFlags"] = true, ["detectPlatformModules"] = true, ["includeEntryPoints"] = true, ["outputPath"] = Path.Combine(outputDir, "scaffolding-blueprint.json") }; var result = await registry.CallFunctionAsync("ModularMap", parameters); if (result.Success) { Console.WriteLine("✅ Scaffolding features test completed successfully"); var resultPath = Path.Combine(outputDir, "scaffolding-features-result.json"); await SaveAndAnalyzeResult(result.Data, resultPath, "Scaffolding Features"); // Show scaffolding-specific analysis ShowScaffoldingCapabilities(result.Data); } else { Console.WriteLine($"❌ Scaffolding features test failed: {result.Message}"); } } catch (Exception ex) { Console.WriteLine($"❌ Scaffolding features test failed: {ex.Message}"); } Console.WriteLine(); } private static void ShowScaffoldingCapabilities(object data) { try { var jsonElement = JsonSerializer.Deserialize(JsonSerializer.Serialize(data)); Console.WriteLine(" 🛠️ Scaffolding Capabilities Analysis:"); if (jsonElement.TryGetProperty("ModularStructure", out var modularStructure) && modularStructure.TryGetProperty("modules", out var modules)) { Console.WriteLine(" 📦 Module Analysis:"); var sampleModules = modules.EnumerateArray().Take(3); foreach (var module in sampleModules) { if (module.TryGetProperty("name", out var name)) { Console.WriteLine($" • {name.GetString()}:"); if (module.TryGetProperty("tags", out var tags)) { var tagList = tags.EnumerateArray().Select(t => t.GetString()).Take(3); Console.WriteLine($" Tags: {string.Join(", ", tagList)}"); } if (module.TryGetProperty("promptDescription", out var desc)) { var description = desc.GetString(); var shortDesc = description.Length > 60 ? description.Substring(0, 60) + "..." : description; Console.WriteLine($" Description: {shortDesc}"); } if (module.TryGetProperty("optional", out var optional)) Console.WriteLine($" Optional: {optional.GetBoolean()}"); if (module.TryGetProperty("scaffoldable", out var scaffoldable)) Console.WriteLine($" Scaffoldable: {scaffoldable.GetBoolean()}"); } } } Console.WriteLine(" 🎯 Generation Features:"); Console.WriteLine(" ✅ Module tagging system"); Console.WriteLine(" ✅ LLM-friendly descriptions"); Console.WriteLine(" ✅ Optional/required flags"); Console.WriteLine(" ✅ Platform-specific detection"); Console.WriteLine(" ✅ Scaffolding metadata"); Console.WriteLine(" ✅ Setup instructions"); Console.WriteLine(" ✅ Dependency tracking"); } catch (Exception ex) { Console.WriteLine($" ⚠️ Could not analyze scaffolding capabilities: {ex.Message}"); } } private static async Task RunFilteredAnalysisTest(AIPluginRegistry registry, string projectPath, string outputDir) { Console.WriteLine("🎯 Test 6: Filtered Analysis (Namespace Filter)"); Console.WriteLine("==============================================="); try { var parameters = new Dictionary { ["projectPath"] = projectPath, ["outputFormat"] = "json", ["analyzeCoupling"] = true, ["namespaceFilter"] = "*", // Will match all namespaces as a test ["maxDepth"] = 3, ["outputPath"] = Path.Combine(outputDir, "filtered-analysis.json") }; var result = await registry.CallFunctionAsync("ModularMap", parameters); if (result.Success) { Console.WriteLine("✅ Filtered analysis completed successfully"); var resultPath = Path.Combine(outputDir, "filtered-result.json"); await SaveAndAnalyzeResult(result.Data, resultPath, "Filtered"); } else { Console.WriteLine($"❌ Filtered analysis failed: {result.Message}"); } } catch (Exception ex) { Console.WriteLine($"❌ Filtered analysis test failed: {ex.Message}"); } Console.WriteLine(); } private static async Task RunPerformanceTest(AIPluginRegistry registry, string projectPath) { Console.WriteLine("⏱️ Test 7: Performance Test"); Console.WriteLine("==========================="); try { var parameters = new Dictionary { ["projectPath"] = projectPath, ["outputFormat"] = "json", ["analyzeCoupling"] = true, ["detectPatterns"] = true, ["generateInsights"] = true }; var startTime = DateTime.UtcNow; var result = await registry.CallFunctionAsync("ModularMap", parameters); var endTime = DateTime.UtcNow; var duration = endTime - startTime; if (result.Success) { Console.WriteLine($"✅ Performance test completed in {duration.TotalMilliseconds:F2}ms"); Console.WriteLine($" ⚡ Average processing time: {duration.TotalSeconds:F2} seconds"); if (duration.TotalSeconds < 10) { Console.WriteLine(" 🚀 Performance: Excellent (< 10 seconds)"); } else if (duration.TotalSeconds < 30) { Console.WriteLine(" 👍 Performance: Good (< 30 seconds)"); } else { Console.WriteLine(" ⏳ Performance: Needs optimization (> 30 seconds)"); } } else { Console.WriteLine($"❌ Performance test failed: {result.Message}"); } } catch (Exception ex) { Console.WriteLine($"❌ Performance test failed: {ex.Message}"); } Console.WriteLine(); } private static async Task RunErrorHandlingTest(AIPluginRegistry registry) { Console.WriteLine("🛡️ Test 8: Error Handling"); Console.WriteLine("========================="); try { // Test with invalid path var invalidParameters = new Dictionary { ["projectPath"] = "C:\\NonExistentPath\\InvalidProject", ["outputFormat"] = "json" }; var result = await registry.CallFunctionAsync("ModularMap", invalidParameters); if (!result.Success) { Console.WriteLine("✅ Error handling works correctly for invalid paths"); Console.WriteLine($" 📝 Expected error message: {result.Message}"); } else { Console.WriteLine("⚠️ Warning: Plugin should have failed with invalid path"); } // Test with invalid parameters var invalidParamTest = new Dictionary { ["projectPath"] = "ValidPath", // Even though path is set ["maxDepth"] = -1 // Invalid depth }; var result2 = await registry.CallFunctionAsync("ModularMap", invalidParamTest); Console.WriteLine($" 📋 Invalid parameter test result: {(result2.Success ? "Handled gracefully" : "Error caught")}"); } catch (Exception ex) { Console.WriteLine($"✅ Exception handling working: {ex.Message}"); } Console.WriteLine(); } private static async Task SaveAndAnalyzeResult(object data, string filePath, string testName) { await SaveResultToFile(data, filePath); try { var jsonElement = JsonSerializer.Deserialize(JsonSerializer.Serialize(data)); Console.WriteLine($" 📊 {testName} Results Summary:"); // Show statistics if available if (jsonElement.TryGetProperty("Statistics", out var stats)) { if (stats.TryGetProperty("TotalModules", out var modules)) Console.WriteLine($" 📦 Modules Found: {modules.GetInt32()}"); if (stats.TryGetProperty("TotalDependencies", out var deps)) Console.WriteLine($" 🔗 Dependencies: {deps.GetInt32()}"); if (stats.TryGetProperty("ExternalDependencies", out var external)) Console.WriteLine($" 📚 External Dependencies: {external.GetInt32()}"); } // Show coupling metrics if available if (jsonElement.TryGetProperty("CouplingMetrics", out var coupling)) { if (coupling.TryGetProperty("OverallCouplingScore", out var score)) Console.WriteLine($" 🎯 Coupling Score: {score.GetDouble():F2}"); } // Show architectural patterns if available if (jsonElement.TryGetProperty("ArchitecturalPatterns", out var patterns)) { if (patterns.TryGetProperty("DetectedPattern", out var pattern)) Console.WriteLine($" 🏗️ Detected Pattern: {pattern.GetString()}"); } Console.WriteLine($" 💾 Saved: {Path.GetFileName(filePath)}"); } catch (Exception ex) { Console.WriteLine($" ⚠️ Could not analyze result: {ex.Message}"); Console.WriteLine($" 💾 Raw data saved: {Path.GetFileName(filePath)}"); } } private static async Task SaveResultToFile(object data, string filePath) { var json = JsonSerializer.Serialize(data, new JsonSerializerOptions { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); await File.WriteAllTextAsync(filePath, json); } private static void ShowMermaidPreview(object data) { try { var jsonElement = JsonSerializer.Deserialize(JsonSerializer.Serialize(data)); if (jsonElement.TryGetProperty("DependencyMap", out var map)) { var mermaidContent = map.GetString(); if (!string.IsNullOrEmpty(mermaidContent)) { Console.WriteLine(" 📋 Mermaid Diagram Preview (first 10 lines):"); var lines = mermaidContent.Split('\n'); for (int i = 0; i < Math.Min(10, lines.Length); i++) { Console.WriteLine($" {lines[i]}"); } if (lines.Length > 10) { Console.WriteLine($" ... ({lines.Length - 10} more lines)"); } } } } catch (Exception ex) { Console.WriteLine($" ⚠️ Could not show Mermaid preview: {ex.Message}"); } } private static void ShowDetailedMetrics(object data) { try { var jsonElement = JsonSerializer.Deserialize(JsonSerializer.Serialize(data)); Console.WriteLine(" 📊 Detailed Analysis Metrics:"); // Coupling metrics if (jsonElement.TryGetProperty("CouplingMetrics", out var coupling)) { Console.WriteLine(" 🔗 Coupling Analysis:"); if (coupling.TryGetProperty("HighlyCoupledModules", out var highCoupling)) Console.WriteLine($" High Coupling: {highCoupling.GetArrayLength()} modules"); if (coupling.TryGetProperty("LooselyCoupledModules", out var lowCoupling)) Console.WriteLine($" Low Coupling: {lowCoupling.GetArrayLength()} modules"); if (coupling.TryGetProperty("CircularDependencies", out var circular)) Console.WriteLine($" Circular Dependencies: {circular.GetArrayLength()} found"); } // Architectural insights if (jsonElement.TryGetProperty("Insights", out var insights)) { Console.WriteLine(" 💡 Architectural Insights:"); if (insights.TryGetProperty("OverallArchitectureScore", out var archScore)) Console.WriteLine($" Architecture Score: {archScore.GetDouble():F1}/10"); if (insights.TryGetProperty("RefactoringOpportunities", out var refactoring)) Console.WriteLine($" Refactoring Opportunities: {refactoring.GetArrayLength()}"); if (insights.TryGetProperty("DesignPatternSuggestions", out var suggestions)) Console.WriteLine($" Design Pattern Suggestions: {suggestions.GetArrayLength()}"); } } catch (Exception ex) { Console.WriteLine($" ⚠️ Could not show detailed metrics: {ex.Message}"); } } private static void DisplayGeneratedFiles(string outputDir) { Console.WriteLine(); Console.WriteLine("📁 Generated Files Summary:"); Console.WriteLine("=========================="); try { var files = Directory.GetFiles(outputDir); if (files.Length == 0) { Console.WriteLine(" ⚠️ No files were generated"); return; } foreach (var file in files) { var fileInfo = new FileInfo(file); var sizeKB = fileInfo.Length / 1024.0; var fileName = Path.GetFileName(file); var icon = Path.GetExtension(file).ToLower() switch { ".json" => "📄", ".mmd" => "🌊", ".dot" => "📊", _ => "📁" }; Console.WriteLine($" {icon} {fileName} ({sizeKB:F1} KB)"); } Console.WriteLine(); Console.WriteLine("💡 Usage Tips:"); Console.WriteLine(" 📄 JSON files: Use for programmatic analysis or data processing"); Console.WriteLine(" 🌊 .mmd files: View in Mermaid Live Editor (https://mermaid.live)"); Console.WriteLine(" 📊 .dot files: Render with Graphviz (dot -Tpng file.dot -o image.png)"); Console.WriteLine(" 🕸️ Cytoscape JSON: Import into Cytoscape for interactive analysis"); } catch (Exception ex) { Console.WriteLine($" ❌ Error reading output directory: {ex.Message}"); } } } }