using System.Linq;
using UnityEditor;
using UnityEditor.Compilation;

namespace IntelligentProjectAnalyzer.Editor
{
    /// <summary>
    /// Hooks into Unity's editor events to automatically trigger the dependency build process.
    /// </summary>
    [InitializeOnLoad]
    public static class DependencyBuilderTriggers
    {
        [MenuItem("Tools/Analyzer/Build Dependency Store")]
        public static void TriggerBuild() => DependencyStoreBuilder.BuildStore();
        
        // Unity calls static constructor when the editor loads.
        static DependencyBuilderTriggers()
        {
            // Trigger a build after scripts have finished compiling.
            CompilationPipeline.compilationFinished += OnCompilationFinished;
        }

        /// <summary>
        /// Callback for when script compilation is finished.
        /// </summary>
        private static void OnCompilationFinished(object context)
        {
            // We can add a delay here if needed, but for now, let's trigger it directly.
            // DependencyStoreBuilder.BuildStore(); // Temporarily disabled
        }
    }

    /// <summary>
    /// AssetPostprocessor to trigger the dependency build on any relevant asset changes.
    /// </summary>
    internal class DependencyBuilderAssetPostprocessor : AssetPostprocessor
    {
        /// <summary>
        /// Unity calls this method after any assets are imported, deleted, or moved.
        /// </summary>
        private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
        {
            // Check if any of the changed assets are scripts, as this is our primary concern.
            // This prevents running the full analysis for simple texture or material changes.
            var scriptsChanged = importedAssets.Any(path => path.EndsWith(".cs")) ||
                                 deletedAssets.Any(path => path.EndsWith(".cs")) ||
                                 movedAssets.Any(path => path.EndsWith(".cs"));

            if (scriptsChanged)
            {
                // A script has changed, so we trigger a rebuild of the dependency store.
                // DependencyStoreBuilder.BuildStore(); // Temporarily disabled
            }
        }
    }
}
