using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;

public class TexturePlatformSync
{
    [MenuItem("LillithRosePup/Sync Texture Platforms (Android -> iOS)")]
    public static void SyncTexturePlatforms()
    {
        var proceed = EditorUtility.DisplayDialog(
            "Sync Texture Platforms",
            "This will find all textures in the project and copy Android import settings to iOS if they differ.\n\nThis may take a while for large projects. Continue?",
            "Continue",
            "Cancel"
        );

        if (!proceed)
        {
            return;
        }

        SyncAllTextures();
    }

    private static void SyncAllTextures()
    {
        // Find all texture assets in the project
        string[] textureGuids = AssetDatabase.FindAssets("t:Texture2D");
        
        int totalTextures = textureGuids.Length;
        int syncedCount = 0;
        int skippedCount = 0;
        int errorCount = 0;
        bool wasCancelled = false;

        Debug.Log($"Found {totalTextures} textures. Starting sync...");

        // Start batching asset imports to pause reimporting until complete
        AssetDatabase.StartAssetEditing();

        try
        {
            for (int i = 0; i < textureGuids.Length; i++)
            {
                string guid = textureGuids[i];
                string path = AssetDatabase.GUIDToAssetPath(guid);

                // Update progress bar
                if (EditorUtility.DisplayCancelableProgressBar(
                    "Syncing Texture Platforms",
                    $"Processing: {System.IO.Path.GetFileName(path)} ({i + 1}/{totalTextures})",
                    (float)i / totalTextures))
                {
                    wasCancelled = true;
                    Debug.LogWarning("Texture platform sync cancelled by user.");
                    break;
                }

                try
                {
                    TextureImporter importer = AssetImporter.GetAtPath(path) as TextureImporter;
                    if (importer == null)
                    {
                        skippedCount++;
                        continue;
                    }

                    // Get Android and iOS platform settings
                    TextureImporterPlatformSettings androidSettings = importer.GetPlatformTextureSettings("Android");
                    TextureImporterPlatformSettings iosSettings = importer.GetPlatformTextureSettings("iOS");

                    // Check if settings differ
                    if (SettingsDiffer(androidSettings, iosSettings))
                    {
                        // Copy Android settings to iOS
                        TextureImporterPlatformSettings newIosSettings = new TextureImporterPlatformSettings
                        {
                            name = "iOS",
                            overridden = androidSettings.overridden,
                            maxTextureSize = androidSettings.maxTextureSize,
                            textureCompression = androidSettings.textureCompression,
                            compressionQuality = androidSettings.compressionQuality,
                            allowsAlphaSplitting = androidSettings.allowsAlphaSplitting,
                            format = androidSettings.format,
                            crunchedCompression = androidSettings.crunchedCompression
                        };

                        importer.SetPlatformTextureSettings(newIosSettings);
                        // Import within the batch session - imports will be queued until StopAssetEditing
                        AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
                        syncedCount++;
                        Debug.Log($"Synced: {path}");
                    }
                    else
                    {
                        skippedCount++;
                    }
                }
                catch (System.Exception ex)
                {
                    errorCount++;
                    Debug.LogError($"Error processing {path}: {ex.Message}");
                }
            }
        }
        finally
        {
            // Stop batching - this will trigger all queued imports at once
            AssetDatabase.StopAssetEditing();
        }

        EditorUtility.ClearProgressBar();
        AssetDatabase.Refresh();

        // Show completion dialog with statistics (even if cancelled)
        string title = wasCancelled ? "Sync Cancelled" : "Sync Complete";
        string message = wasCancelled 
            ? $"Texture platform sync was cancelled.\n\n" +
              $"Total textures: {totalTextures}\n" +
              $"Processed: {syncedCount + skippedCount + errorCount}\n" +
              $"Synced: {syncedCount}\n" +
              $"Skipped (already matching): {skippedCount}\n" +
              $"Errors: {errorCount}"
            : $"Texture platform sync completed!\n\n" +
              $"Total textures: {totalTextures}\n" +
              $"Synced: {syncedCount}\n" +
              $"Skipped (already matching): {skippedCount}\n" +
              $"Errors: {errorCount}";

        EditorUtility.DisplayDialog(title, message, "OK");

        string logMessage = wasCancelled
            ? $"Texture platform sync cancelled. Processed: {syncedCount + skippedCount + errorCount}, Synced: {syncedCount}, Skipped: {skippedCount}, Errors: {errorCount}"
            : $"Texture platform sync complete. Synced: {syncedCount}, Skipped: {skippedCount}, Errors: {errorCount}";
        Debug.Log(logMessage);
    }

    private static bool SettingsDiffer(TextureImporterPlatformSettings android, TextureImporterPlatformSettings ios)
    {
        // If Android settings are not overridden, they match by default
        if (!android.overridden)
        {
            return false;
        }

        // Compare all relevant settings
        return android.maxTextureSize != ios.maxTextureSize ||
               android.textureCompression != ios.textureCompression ||
               android.compressionQuality != ios.compressionQuality ||
               android.allowsAlphaSplitting != ios.allowsAlphaSplitting ||
               android.format != ios.format ||
               android.crunchedCompression != ios.crunchedCompression ||
               android.overridden != ios.overridden;
    }
}

