using System.Linq;
using UnityEditor;
using System.Collections.Generic;
using IntelligentProjectAnalyzer.Editor.Graphing;
using IntelligentProjectAnalyzer.Editor.DependencyViewer;
using Object = UnityEngine.Object;

namespace LLM.Editor.Analysis
{
    /// <summary>
    /// Provides dependency information for a given asset by querying the cached DependencyGraph.
    /// </summary>
    public class DependencyGraphProvider : IContextProvider
    {
        public object GetContext(Object target, string qualifier)
        {
            if (!target)
            {
                return "Error: A valid target asset is required to get dependencies.";
            }

            var path = AssetDatabase.GetAssetPath(target);
            var guid = AssetDatabase.AssetPathToGUID(path);

            if (string.IsNullOrEmpty(guid))
            {
                return $"Error: Could not get GUID for asset '{target.name}'.";
            }

            var dependencyGraph = new DependencyGraph();
            if (!dependencyGraph.AssetExists(guid))
            {
                return $"Error: Asset '{target.name}' not found in the dependency graph. The cache might be out of date.";
            }

            // The qualifier determines if we get all recursive dependencies or only direct ones.
            var recursive = qualifier?.ToLower() == "recursive";
            
            var dependencyGuids = new HashSet<string>();
            if (recursive)
            {
                GetAllDependencies(guid, dependencyGraph, dependencyGuids);
            }
            else
            {
                dependencyGuids = new HashSet<string>(dependencyGraph.GetDependencies(guid));
            }

            // Convert the final list of GUIDs into structured, readable nodes.
            return dependencyGuids.Select(AssetNodeResolver.CreateNodeFromGuid).ToList();
        }

        /// <summary>
        /// Recursively traverses the dependency graph to collect all unique dependencies.
        /// </summary>
        private static void GetAllDependencies(string currentGuid, DependencyGraph graph, HashSet<string> collectedGuids)
        {
            var directDependencies = graph.GetDependencies(currentGuid);

            foreach (var depGuid in directDependencies.Where(collectedGuids.Add))
            {
                GetAllDependencies(depGuid, graph, collectedGuids);
            }
        }
    }
}