defmodule Refuge.NativeLink.GoAppGRPCTest do
  use ExUnit.Case, async: false
  alias Refuge.Nativelink.BuildRequest
  alias Refuge.Nativelink.BuildResponse
  alias Refuge.NativeLink.GRPCServer

  @go_app_dir "/Users/osayame/trace/examples/go-tutorial/stage3"
  @go_app_target "//..."

  # Skip dependency on GRPC.Client by directly testing the module
  describe "ExecuteBuild with Go app" do
    test "successfully builds and returns correct output" do
      # Create a BuildRequest for the Go app example
      req = %BuildRequest{
        build_dir: @go_app_dir,
        target: @go_app_target
      }

      # Call the ExecuteBuild function directly (bypassing gRPC client)
      result = GRPCServer.execute_build(req, nil)

      # Assert the response is successful
      assert %BuildResponse{} = result
      # status 0 means success
      assert result.status == 0

      # Print the key build output for verification
      IO.puts("\n--------- BUILD TEST OUTPUT----------")

      # Extract and print the build output using regex
      build_info_regex =
        ~r/INFO: Analyzed target \/\/:hello.*?INFO: Build completed successfully/s

      case Regex.run(build_info_regex, result.build_output) do
        [full_match | _] ->
          IO.puts(full_match)

        _ ->
          IO.puts("Could not extract build info from output, printing full output:")
          IO.puts(result.build_output)
      end

      IO.puts("-------------------------------------------\n")

      # If run output exists, print that too
      if result.run_output && result.run_output != "" do
        IO.puts("\n----------GO APP RUN OUTPUT----------")
        IO.puts(result.run_output)
        IO.puts("-------------------------------------\n")
      end
    end

    test "returns error for non-existent directory" do
      # Test with a non-existent directory to verify error handling
      req = %BuildRequest{
        build_dir: "/non/existent/directory",
        target: @go_app_target
      }

      result = GRPCServer.execute_build(req, nil)

      # Assert error is returned
      assert %BuildResponse{} = result
      # non-zero status means error
      assert result.status != 0
      assert String.contains?(result.build_output, "directory does not exist")
    end

    test "handles build failure gracefully" do
      # Test with an invalid target to verify error handling
      req = %BuildRequest{
        build_dir: @go_app_dir,
        target: "//invalid:target"
      }

      result = GRPCServer.execute_build(req, nil)

      # Assert failed build is reported correctly
      assert %BuildResponse{} = result
      # non-zero status means error
      assert result.status != 0
    end
  end
end
