using System;
using System.IO;
using UnityEngine;
using Newtonsoft.Json;
using System.Collections.Generic;
using IntelligentProjectAnalyzer.Helper;

// All using statements now refer to the new data-only class
using static IntelligentProjectAnalyzer.Editor.DependencyBuilderData;

namespace IntelligentProjectAnalyzer.Editor
{
    /// <summary>
    /// Manages all file system operations related to the dependency cache.
    /// </summary>
    public static class DependencyCacheManager
    {
        private const string CacheFolderName = "DependencyCache";

        /// <summary>
        /// Gets the full path to the dependency cache directory.
        /// </summary>
        /// <returns>The absolute path to the cache folder within the project's Library folder.</returns>
        public static string GetCachePath()
        {
            return Path.Combine("Library", CacheFolderName);
        }

        /// <summary>
        /// Deletes the existing cache directory and recreates it to ensure a clean state.
        /// </summary>
        public static void CleanAndPrepareCache()
        {
            var cachePath = GetCachePath();
            if (Directory.Exists(cachePath))
            {
                try
                {
                    Directory.Delete(cachePath, true);
                }
                catch (Exception e)
                {
                    Debug.LogError($"Could not clean cache folder at {cachePath}. Please remove it manually. Error: {e.Message}");
                    return;
                }
            }
            Directory.CreateDirectory(cachePath);
        }

        /// <summary>
        /// Writes the analysis results to individual JSON files using the wrapper object.
        /// </summary>
        /// <param name="results">The list of unified AssetMetadata to write to disk.</param>
        public static void WriteResults(List<AssetMetadata> results)
        {
            var cachePath = GetCachePath();
            foreach (var result in results)
            {
                var typeIndex = MetadataTypeHelper.GetIndexFromType(result.GetType());
                if (typeIndex == -1)
                {
                    Debug.LogWarning($"Could not find a registered type for {result.GetType()}. Skipping asset with GUID {result.Guid}.");
                    continue;
                }
                // Create the wrapper object.
                var wrapper = new MetadataWrapper
                {
                    // Store the fully qualified type name so we can deserialize correctly later.
                    AssetTypeIndex = typeIndex,
                    // Serialize the actual metadata object into a JSON string.
                    JsonData = JsonFileSystem.GetJson(result)
                };

                var outputPath = Path.Combine(cachePath, $"{result.Guid}.json");
                // Now, serialize the WRAPPER object to the file. This is safe because
                // MetadataWrapper is a concrete, non-abstract class.
                JsonFileSystem.Write(wrapper, outputPath);
            }
        }
    }
}