using System;
using System.IO;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEditor;

public static class VictorNativeBundleBuild
{
    public static void BuildForGame()
    {
        try
        {
            string root=Path.GetFullPath(Path.Combine(Application.dataPath,"../.."));
            string output=Path.Combine(root,"Output");Directory.CreateDirectory(output);
            const string shaderPath="Assets/NativePort/NativeRope.shader";
            var shader=AssetDatabase.LoadAssetAtPath<Shader>(shaderPath);
            if(!shader)throw new InvalidOperationException("Native effect shader was not imported");
            foreach(var message in ShaderUtil.GetShaderMessages(shader))
                if(message.severity.ToString()=="Error")throw new InvalidOperationException("Effect shader compilation: "+message.message);
            PlayerSettings.SetUseDefaultGraphicsAPIs(BuildTarget.StandaloneWindows64,false);
            PlayerSettings.SetGraphicsAPIs(BuildTarget.StandaloneWindows64,new[]{GraphicsDeviceType.Direct3D11,GraphicsDeviceType.Vulkan});
            var build=new AssetBundleBuild
            {
                assetBundleName="victornativefx",
                assetNames=new[]{shaderPath,"Assets/Resources/VictorNative/bendibeam_mono.png"}
            };
            var manifest=BuildPipeline.BuildAssetBundles(output,new[]{build},BuildAssetBundleOptions.ChunkBasedCompression|BuildAssetBundleOptions.ForceRebuildAssetBundle,BuildTarget.StandaloneWindows64);
            if(!manifest||!File.Exists(Path.Combine(output,"victornativefx")))throw new InvalidOperationException("Unity did not produce the native effect bundle");
            foreach(var message in ShaderUtil.GetShaderMessages(shader))
                if(message.severity.ToString()=="Error")throw new InvalidOperationException("Effect shader compilation: "+message.message);
            var verify=AssetBundle.LoadFromFile(Path.Combine(output,"victornativefx"));
            if(!verify)throw new InvalidOperationException("Built bundle cannot be loaded");
            try
            {
                if(!verify.LoadAsset<Shader>("assets/nativeport/nativerope.shader")||!verify.LoadAsset<Texture2D>("assets/resources/victornative/bendibeam_mono.png"))
                    throw new InvalidOperationException("Built bundle is missing its shader/texture asset index");
            }
            finally { verify.Unload(true); }
            File.WriteAllText(Path.Combine(root,"BUILD-SUCCEEDED.txt"),"Native effect bundle built with Unity "+Application.unityVersion+"\n"+manifest.GetAssetBundleHash("victornativefx"));
            Debug.Log("VICTOR NATIVE EFFECT BUNDLE BUILT: "+Path.Combine(output,"victornativefx"));
        }
        catch(Exception error){Debug.LogException(error);EditorApplication.Exit(1);}
    }
}
