using System.Diagnostics;

namespace Editor
{
    public static class ExcelTool
    {
        //[UnityEditor.MenuItem("Tool/ExcelTool/GenerateData")]
        public static void GenerateData()
        {
            string projectRoot = System.IO.Path.GetFullPath(System.IO.Path.Combine(UnityEngine.Application.dataPath, ".."));
            string toolDir = System.IO.Path.Combine(projectRoot, "Tool/ExcelTool");

#if UNITY_EDITOR_WIN
            string scriptPath = System.IO.Path.Combine(toolDir, "buildata.bat");
            ProcessStartInfo psi = new()
            {
                FileName = "cmd.exe",
                Arguments = $"/c \"{scriptPath}\"",
                WorkingDirectory = toolDir,
                UseShellExecute = false,
            };
#else
            string scriptPath = System.IO.Path.Combine(toolDir, "buildata.sh");
            ProcessStartInfo psi = new()
            {
                FileName = "/bin/bash",
                Arguments = scriptPath,
                WorkingDirectory = toolDir,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
            };
#endif

            Process process = Process.Start(psi);

            string stdout = process.StandardOutput.ReadToEnd();
            string stderr = process.StandardError.ReadToEnd();

            process.WaitForExit();

            UnityEngine.Debug.Log(stdout);

            if (!string.IsNullOrEmpty(stderr))
            {
                UnityEngine.Debug.LogError(stderr);
            }

            if (process.ExitCode == 0)
            {
                UnityEngine.Debug.Log("ExcelTool: GenerateData completed successfully.");
            }
            else
            {
                UnityEditor.EditorUtility.DisplayDialog(
                    "GenerateData Failed",
                    $"ExcelTool script exited with code {process.ExitCode}.",
                    "OK"
                );
            }
        }
    }
}
