using System.Linq;
using UnityEditor;
using UnityEngine;

namespace LLM.Editor.Analysis
{
    public class GetContextualMapProvider : IContextProvider
    {
        public object GetContext(Object target, string qualifier)
        {
            if (string.IsNullOrEmpty(qualifier))
            {
                return "Error: A search term (qualifier) is required for GetContextualMap.";
            }

            var prefabs = AssetDatabase.FindAssets($"t:Prefab {qualifier}")
                .Select(AssetDatabase.GUIDToAssetPath)
                .Select(path => new { name = System.IO.Path.GetFileName(path), path, guid = AssetDatabase.AssetPathToGUID(path) })
                .ToList();

            var scripts = AssetDatabase.FindAssets($"t:MonoScript {qualifier}")
                .Select(AssetDatabase.GUIDToAssetPath)
                .Where(path => path.StartsWith("Assets/"))
                .Select(path => new { name = System.IO.Path.GetFileName(path), path, guid = AssetDatabase.AssetPathToGUID(path) })
                .ToList();

            var sceneObjects = Object.FindObjectsOfType<GameObject>()
                .Where(go => go.name.ToLower().Contains(qualifier.ToLower()))
                .Select(go => new { go.name, id = go.GetInstanceID().ToString() })
                .ToList();
            
            var sceneObjectsByComponent = Object.FindObjectsOfType<Component>()
                .Where(c => c.GetType().Name.ToLower().Contains(qualifier.ToLower()))
                .Select(c => new { name = c.gameObject.name + $" Component: ({c.GetType().Name})", id = c.gameObject.GetInstanceID().ToString() })
                .ToList();

            return new
            {
                prefabs,
                scripts,
                sceneObjects,
                sceneObjectsByComponent
            };
        }
    }
}