using System;
using System.Collections.Generic;
using UnityEngine;

namespace CustomAssetBundleSystem
{
    /// <summary>
    /// Simple JSON catalog structure for remote AssetBundles
    /// No Unity Addressables bugs, full control, lightweight
    /// </summary>
    [Serializable]
    public class RemoteAssetCatalog
    {
        public string version = "1.0.0";
        public long timestamp;
        public string baseUrl = "https://addressable.uncaptured.co/AssetBundles/Android";
        public List<BundleEntry> bundles = new List<BundleEntry>();

        [Serializable]
        public class BundleEntry
        {
            public string bundleName;           // e.g., "gamescene"
            public string fileName;             // e.g., "gamescene.bundle"
            public string hash;                 // MD5/CRC for verification
            public long size;                   // File size in bytes
            public List<string> scenes;         // Scenes contained in this bundle
            public List<string> dependencies;   // Other bundles this depends on
            
            public string GetFullUrl(string baseUrl)
            {
                return $"{baseUrl}/{fileName}";
            }
        }

        /// <summary>
        /// Find bundle entry by scene name
        /// </summary>
        public BundleEntry FindBundleByScene(string sceneName)
        {
            foreach (var bundle in bundles)
            {
                if (bundle.scenes != null && bundle.scenes.Contains(sceneName))
                {
                    return bundle;
                }
            }
            return null;
        }

        /// <summary>
        /// Find bundle entry by bundle name
        /// </summary>
        public BundleEntry FindBundleByName(string bundleName)
        {
            return bundles.Find(b => b.bundleName == bundleName);
        }

        /// <summary>
        /// Get all dependencies recursively
        /// </summary>
        public List<BundleEntry> GetAllDependencies(BundleEntry bundle, HashSet<string> visited = null)
        {
            if (visited == null) visited = new HashSet<string>();
            var result = new List<BundleEntry>();

            if (bundle.dependencies == null || bundle.dependencies.Count == 0)
                return result;

            foreach (var depName in bundle.dependencies)
            {
                if (visited.Contains(depName)) continue;
                visited.Add(depName);

                var depBundle = FindBundleByName(depName);
                if (depBundle != null)
                {
                    result.Add(depBundle);
                    result.AddRange(GetAllDependencies(depBundle, visited));
                }
            }

            return result;
        }
    }
}
