using System.Diagnostics;
using System.IO;
using UnityEditor;
using UnityEngine;
using Debug = UnityEngine.Debug;

/// <summary>
/// Helper for building protocol buffer files from within the Unity Editor.
/// </summary>
public static class ProtoBuildHelper {
    private const string ScriptPath = "scripts/build_protos.sh";

    /// <summary>
    /// Rebuilds the protocol buffer files.
    /// Menu: Eagle0 > Build Protos
    /// </summary>
    [MenuItem("Eagle0/Build Protos %#p")]
    public static void BuildProtos() {
        // Find the repository root (where scripts/build_protos.sh lives)
        var repoRoot = FindRepoRoot();
        if (repoRoot == null) {
            Debug.LogError("[ProtoBuildHelper] Could not find repository root");
            return;
        }

        var scriptFullPath = Path.Combine(repoRoot, ScriptPath);
        if (!File.Exists(scriptFullPath)) {
            Debug.LogError($"[ProtoBuildHelper] Script not found: {scriptFullPath}");
            return;
        }

        Debug.Log("[ProtoBuildHelper] Building protos...");

        var startInfo = new ProcessStartInfo {
            FileName = "/bin/bash",
            Arguments = $"-c \"cd '{repoRoot}' && ./{ScriptPath}\"",
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            CreateNoWindow = true
        };

        using (var process = Process.Start(startInfo)) {
            var output = process.StandardOutput.ReadToEnd();
            var error = process.StandardError.ReadToEnd();
            process.WaitForExit();

            if (process.ExitCode == 0) {
                Debug.Log("[ProtoBuildHelper] Protos built successfully");
                if (!string.IsNullOrEmpty(output)) { Debug.Log(output); }
                AssetDatabase.Refresh();
            } else {
                Debug.LogError(
                        $"[ProtoBuildHelper] Proto build failed with exit code {process.ExitCode}");
                if (!string.IsNullOrEmpty(output)) { Debug.Log(output); }
                if (!string.IsNullOrEmpty(error)) { Debug.LogError(error); }
            }
        }
    }

    private static string FindRepoRoot() {
        // Start from the Unity project directory and walk up to find the repo root
        var current = Application.dataPath;  // Assets folder
        while (!string.IsNullOrEmpty(current)) {
            var scriptPath = Path.Combine(current, ScriptPath);
            if (File.Exists(scriptPath)) { return current; }

            var parent = Directory.GetParent(current);
            if (parent == null) break;
            current = parent.FullName;
        }
        return null;
    }
}
