using UnityEditor;
using UnityEditor.AddressableAssets;
using UnityEditor.AddressableAssets.Settings;
using UnityEngine;
using System.IO;
using System.Text.RegularExpressions;

/// <summary>
/// WORKAROUND for Unity 6 bug where m_EnableJsonCatalog is ignored
/// This script patches settings.json to force JSON catalog loading
/// </summary>
public class ForceJsonCatalogWorkaround
{
    [MenuItem("Addressables/Fix/Patch settings.json for JSON Catalogs")]
    public static void PatchSettingsForJsonCatalog()
    {
        Debug.Log("[ForceJsonCatalog] WORKAROUND: Patching settings.json to use .json catalogs instead of .bin");

        // Find all settings.json files
        string[] settingsFiles = Directory.GetFiles("Library/com.unity.addressables", "settings.json", SearchOption.AllDirectories);
        
        if (settingsFiles.Length == 0)
        {
            Debug.LogWarning("[ForceJsonCatalog] No settings.json found. Build Addressables content first!");
            return;
        }

        foreach (string settingsPath in settingsFiles)
        {
            PatchSettingsFile(settingsPath);
        }

        // Also patch ServerData if it exists
        string[] serverSettingsFiles = Directory.GetFiles("ServerData", "settings.json", SearchOption.AllDirectories);
        foreach (string settingsPath in serverSettingsFiles)
        {
            PatchSettingsFile(settingsPath);
        }

        // Rename .bin catalogs to .json
        RenameBinCatalogsToJson();

        Debug.Log("[ForceJsonCatalog] ✓ Patch complete! settings.json now references .json catalogs");
        Debug.Log("[ForceJsonCatalog] Next steps:");
        Debug.Log("  1. Rebuild your APK");
        Debug.Log("  2. Upload ServerData/Android/ contents to your server");
        Debug.Log("  3. Test on device");
    }

    private static void PatchSettingsFile(string settingsPath)
    {
        try
        {
            string content = File.ReadAllText(settingsPath);
            
            // Replace all references from .bin to .json in catalog URLs
            string patchedContent = content.Replace("catalog.bin", "catalog.json");
            patchedContent = patchedContent.Replace("catalog_2.0.0.bin", "catalog_2.0.0.json");
            
            // Also patch the m_IsLocalCatalogInBundle if needed
            patchedContent = Regex.Replace(patchedContent, 
                @"""m_IsLocalCatalogInBundle"":\s*true", 
                "\"m_IsLocalCatalogInBundle\":false");

            File.WriteAllText(settingsPath, patchedContent);
            Debug.Log($"[ForceJsonCatalog] ✓ Patched: {settingsPath}");
        }
        catch (System.Exception ex)
        {
            Debug.LogError($"[ForceJsonCatalog] Error patching {settingsPath}: {ex.Message}");
        }
    }

    private static void RenameBinCatalogsToJson()
    {
        // Rename catalog.bin files to catalog.json
        string[] paths = new string[] { "Library/com.unity.addressables", "ServerData" };

        foreach (string basePath in paths)
        {
            if (!Directory.Exists(basePath)) continue;

            string[] binFiles = Directory.GetFiles(basePath, "catalog*.bin", SearchOption.AllDirectories);
            
            foreach (string binFile in binFiles)
            {
                string jsonFile = binFile.Replace(".bin", ".json");
                
                try
                {
                    // Copy (don't delete .bin yet for safety)
                    File.Copy(binFile, jsonFile, true);
                    Debug.Log($"[ForceJsonCatalog] ✓ Created: {Path.GetFileName(jsonFile)}");
                }
                catch (System.Exception ex)
                {
                    Debug.LogError($"[ForceJsonCatalog] Error renaming {binFile}: {ex.Message}");
                }
            }
        }

        AssetDatabase.Refresh();
    }

    [MenuItem("Addressables/Fix/Build + Patch (Complete Fix)")]
    public static void BuildAndPatchForJsonCatalog()
    {
        Debug.Log("[ForceJsonCatalog] Starting complete build with JSON catalog fix...");

        // 1. Build Addressables normally
        Debug.Log("[ForceJsonCatalog] Step 1/3: Building Addressables content...");
        AddressableAssetSettings.BuildPlayerContent();

        // 2. Patch settings.json files
        Debug.Log("[ForceJsonCatalog] Step 2/3: Patching settings.json files...");
        PatchSettingsForJsonCatalog();

        // 3. Done
        Debug.Log("[ForceJsonCatalog] ============================================");
        Debug.Log("[ForceJsonCatalog] ✓ BUILD COMPLETE WITH JSON CATALOG FIX!");
        Debug.Log("[ForceJsonCatalog] ============================================");
        Debug.Log("[ForceJsonCatalog] Next steps:");
        Debug.Log("[ForceJsonCatalog]   1. Rebuild APK in Unity (File → Build Settings → Build)");
        Debug.Log("[ForceJsonCatalog]   2. Upload ServerData/Android/ to server");
        Debug.Log("[ForceJsonCatalog]   3. Install APK and test");
        Debug.Log("[ForceJsonCatalog] ============================================");
    }
}
