defmodule RefugeWeb.API.BuildController do
  use RefugeWeb, :controller
  require Logger

  @default_example_dir "/Users/osayame/trace/examples/go-tutorial/stage2"
  @bazel_path "/usr/local/bin/bazel"

  def create(conn, params) do
    # Get the build directory from params or use default
    example_dir = Map.get(params, "build_dir", @default_example_dir)
    
    # Validate directory exists
    if not File.dir?(example_dir) do
      conn
      |> put_status(:bad_request)
      |> json(%{error: "The specified directory does not exist: #{example_dir}"})
      |> halt()
    else
      # Run build process
      {build_output, build_status} = System.cmd(
        @bazel_path, 
        ["build", "//:print_fortune"], 
        cd: example_dir,
        stderr_to_stdout: true
      )

      # Get the binary path
      binary_path = Path.join([example_dir, "bazel-bin/print_fortune_/print_fortune"])
      
      # Run the binary if build was successful
      {run_output, _run_status} = if build_status == 0 and File.exists?(binary_path) do
        System.cmd(binary_path, [])
      else
        {"Failed to run binary", 1}
      end

      # Return results as JSON
      conn
      |> put_status(if(build_status == 0, do: :ok, else: :unprocessable_entity))
      |> json(%{
        success: build_status == 0,
        build_output: build_output,
        run_output: run_output
      })
    end
  end
end
