using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEngine;
using System.IO;
using System.Linq;

/// <summary>
/// Pre-build check to ensure Addressables bundles are built and up-to-date
/// before creating an Android build. Prevents "Invalid serialized file version" errors.
/// </summary>
public class AddressablePreBuildCheck : IPreprocessBuildWithReport
{
    public int callbackOrder => -100; // Run early in the build process

    public void OnPreprocessBuild(BuildReport report)
    {
        if (report.summary.platform != BuildTarget.Android)
            return;

        CheckAddressablesBundles();
    }

    private void CheckAddressablesBundles()
    {
        string bundlePath = "ServerData/Android";
        string fullBundlePath = Path.Combine(Application.dataPath, "..", bundlePath);

        // Check if bundles directory exists and has content
        if (!Directory.Exists(fullBundlePath))
        {
            LogWarningAndPromptBuild("Addressables bundle directory not found!");
            return;
        }

        var bundles = Directory.GetFiles(fullBundlePath, "*.bundle");
        
        if (bundles.Length == 0)
        {
            LogWarningAndPromptBuild("No Addressables bundles found!");
            return;
        }

        // Check bundle age - warn if older than 1 day
        var oldestBundle = bundles
            .Select(f => new FileInfo(f))
            .OrderBy(f => f.LastWriteTime)
            .FirstOrDefault();

        if (oldestBundle != null)
        {
            var age = System.DateTime.Now - oldestBundle.LastWriteTime;
            
            if (age.TotalHours > 24)
            {
                Debug.LogWarning($"⚠️ [Addressables Check] Bundles are {age.TotalHours:F1} hours old.");
                Debug.LogWarning($"   Oldest bundle: {Path.GetFileName(oldestBundle.FullName)}");
                Debug.LogWarning($"   Last modified: {oldestBundle.LastWriteTime}");
                Debug.LogWarning("   Consider rebuilding Addressables to ensure version compatibility.");
                Debug.LogWarning("   Go to: Window > Asset Management > Addressables > Groups > Build > New Build");
            }
            else
            {
                Debug.Log($"✓ [Addressables Check] Bundles are recent ({age.TotalMinutes:F0} minutes old)");
            }
        }

        // Check catalog files
        var catalogs = Directory.GetFiles(fullBundlePath, "catalog_*.bin");
        if (catalogs.Length == 0)
        {
            Debug.LogWarning("⚠️ [Addressables Check] No catalog files found! Addressables may not load properly.");
        }
    }

    private void LogWarningAndPromptBuild(string message)
    {
        Debug.LogWarning($"⚠️ [Addressables Check] {message}");
        Debug.LogWarning("   Addressables content must be built before building the Android app.");
        Debug.LogWarning("   Go to: Window > Asset Management > Addressables > Groups > Build > New Build");
        Debug.LogWarning("   Or the app will fail to initialize with 'Invalid serialized file version' error!");
        
        // Optionally stop the build - uncomment if you want to enforce this
        // throw new BuildFailedException("Addressables bundles not found. Please build Addressables first.");
    }
}
