defmodule Refuge.BazelTest do
  use ExUnit.Case, async: true

  @example_dir "/Users/osayame/trace/examples/go-tutorial/stage1"
  
  @tag :external
  test "builds and runs bazel hello world example" do
    # Use the existing Bazel hello world example
    File.cd!(@example_dir, fn ->
        # Log start of build
        IO.puts("Starting Bazel build...")
        
        # Use absolute path to bazel binary
        bazel_path = "/usr/local/bin/bazel"
        
        # Try to build the target
        {build_output, build_status} = System.cmd(bazel_path, ["build", "//:hello"], stderr_to_stdout: true)
        IO.puts("Build output:\n#{build_output}")
        
        # Assert the build was successful
        assert build_status == 0, "Expected build to succeed, got status #{build_status}"
        
        # Run the built binary
        IO.puts("\nRunning the built hello world app...")
        
        # Get the absolute path to the built binary
        # First get the absolute path of the current directory
        current_dir = File.cwd!()
        
        # The binary is in the bazel-bin directory in the example_dir
        binary_relative_path = "bazel-bin/hello_/hello"
        binary_absolute_path = Path.join(@example_dir, binary_relative_path)
        
        IO.puts("Using binary at: #{binary_absolute_path}")
        
        # Check that the binary exists
        assert File.exists?(binary_absolute_path), "Binary does not exist at #{binary_absolute_path}"
        
        # Run the binary with absolute path
        {run_output, run_status} = System.cmd(binary_absolute_path, [])
        IO.puts("Run output:\n#{run_output}")
        
        # Assert the run was successful and produced expected output
        assert run_status == 0, "Expected run to succeed, got status #{run_status}"
        assert run_output =~ "Hello, Bazel!", "Expected output to contain 'Hello, Bazel!'"
      end)
  end
end
