defmodule Refuge.RemoteCache.Capabilities do
  @moduledoc """
  Implementation of the Capabilities service for Bazel Remote Execution API.

  This service informs clients what features this server supports.
  """

  use GRPC.Server, service: Build.Bazel.Remote.Execution.V2.Capabilities.Service

  require Logger
  alias Build.Bazel.Remote.Execution.V2.{
    GetCapabilitiesRequest,
    ServerCapabilities,
    CacheCapabilities,
    ExecutionCapabilities,
    SymlinkAbsolutePathStrategy,
    DigestFunction,
    PriorityCapabilities
  }

  @doc """
  Returns the server capabilities - what features are supported.
  """
  @spec get_capabilities(GetCapabilitiesRequest.t(), GRPC.Server.Stream.t()) :: ServerCapabilities.t()
  def get_capabilities(_request, _stream) do
    Logger.debug("GetCapabilities request received")

    # Define cache capabilities
    cache_capabilities = %CacheCapabilities{
      digest_functions: [:SHA256],  # SHA256 is supported
      action_cache_update_capabilities: %Build.Bazel.Remote.Execution.V2.ActionCacheUpdateCapabilities{
        update_enabled: true  # Allow updating the action cache
      },
      cache_priority_capabilities: %PriorityCapabilities{
        priorities: []  # No priorities supported
      },
      max_batch_total_size_bytes: 4 * 1024 * 1024,  # 4MB max batch size
      symlink_absolute_path_strategy: :DISALLOWED
    }

    # Define execution capabilities (we don't support remote execution, only caching)
    execution_capabilities = %ExecutionCapabilities{
      digest_function: :SHA256,
      exec_enabled: false,  # We don't support remote execution
      execution_priority_capabilities: nil
    }

    # Create the server capabilities response
    %ServerCapabilities{
      cache_capabilities: cache_capabilities,
      execution_capabilities: execution_capabilities,
      deprecated_api_version: %Build.Bazel.Semver.SemVer{
        major: 2,
        minor: 0,
        patch: 0
      },
      low_api_version: %Build.Bazel.Semver.SemVer{
        major: 2,
        minor: 0,
        patch: 0
      },
      high_api_version: %Build.Bazel.Semver.SemVer{
        major: 2,
        minor: 0,
        patch: 0
      }
    }
  end
end
