defmodule Lux.Prisms.Telegram.Interactive.SendSticker do
  @moduledoc """
  A prism for sending stickers via the Telegram Bot API.

  This prism provides a simple interface to send stickers to Telegram chats.
  It uses the Telegram Bot API to send stickers either by file ID or URL.

  ## Implementation Details

  - Uses Telegram Bot API endpoint: POST /sendSticker
  - Supports required parameters (chat_id, sticker) and optional parameters
  - Returns the sent message data on success
  - Preserves original Telegram API errors for better error handling by LLMs

  ## Examples

      # Send a sticker by file ID
      iex> SendSticker.handler(%{
      ...>   chat_id: 123_456_789,
      ...>   sticker: "CAACAgIAAxkBAAEBpF5jX-qMJzJxcjTg_nJQdl"
      ...> }, %{name: "Agent"})
      {:ok, %{sent: true, message_id: 42, chat_id: 123_456_789, sticker: "CAACAgIAAxkBAAEBpF5jX-qMJzJxcjTg_nJQdl"}}

      # Send a sticker with optional parameters
      iex> SendSticker.handler(%{
      ...>   chat_id: 123_456_789,
      ...>   sticker: "CAACAgIAAxkBAAEBpF5jX-qMJzJxcjTg_nJQdl",
      ...>   disable_notification: true,
      ...>   protect_content: true
      ...> }, %{name: "Agent"})
      {:ok, %{sent: true, message_id: 42, chat_id: 123_456_789, sticker: "CAACAgIAAxkBAAEBpF5jX-qMJzJxcjTg_nJQdl"}}
  """

  use Lux.Prism,
    name: "Send Telegram Sticker",
    description: "Sends stickers via the Telegram Bot API",
    input_schema: %{
      type: :object,
      properties: %{
        chat_id: %{
          type: [:string, :integer],
          description: "Unique identifier for the target chat or username of the target channel"
        },
        sticker: %{
          type: :string,
          description: "Sticker to send. Pass a file_id as String to send a sticker that exists on the Telegram servers, or pass an HTTP URL as a String for Telegram to get a .WEBP, .TGS, or .WEBM file from the Internet"
        },
        emoji: %{
          type: :string,
          description: "Emoji associated with the sticker; only for just uploaded stickers"
        },
        disable_notification: %{
          type: :boolean,
          description: "Sends the message silently. Users will receive a notification with no sound"
        },
        protect_content: %{
          type: :boolean,
          description: "Protects the contents of the sent message from forwarding and saving"
        },
        reply_to_message_id: %{
          type: :integer,
          description: "If the message is a reply, ID of the original message"
        },
        allow_sending_without_reply: %{
          type: :boolean,
          description: "Pass True if the message should be sent even if the specified replied-to message is not found"
        },
        reply_markup: %{
          type: :object,
          description: "Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user"
        }
      },
      required: ["chat_id", "sticker"]
    },
    output_schema: %{
      type: :object,
      properties: %{
        sent: %{
          type: :boolean,
          description: "Whether the sticker was successfully sent"
        },
        message_id: %{
          type: :integer,
          description: "Identifier of the sent message"
        },
        chat_id: %{
          type: [:string, :integer],
          description: "Identifier of the target chat"
        },
        sticker: %{
          type: :string,
          description: "The sticker that was sent"
        }
      },
      required: ["sent", "message_id"]
    }

  alias Lux.Integrations.Telegram.Client
  require Logger

  @doc """
  Handles the request to send a sticker to a Telegram chat.

  This implementation:
  - Makes a direct request to Telegram Bot API using the Client module
  - Returns success/failure responses without additional error transformation
  - Logs the operation for monitoring purposes
  """
  def handler(params, agent) do
    with {:ok, chat_id} <- validate_param(params, :chat_id),
         {:ok, sticker} <- validate_param(params, :sticker) do

      agent_name = agent[:name] || "Unknown Agent"
      Logger.info("Agent #{agent_name} sending sticker to chat #{chat_id}")

      # Build the request body
      request_body = Map.take(params, [:chat_id, :sticker, :emoji, :disable_notification,
                              :protect_content, :reply_to_message_id,
                              :allow_sending_without_reply, :reply_markup])

      # Prepare request options
      request_opts = %{json: request_body}

      case Client.request(:post, "/sendSticker", request_opts) do
        {:ok, %{"result" => result}} when is_map(result) ->
          Logger.info("Successfully sent sticker to chat #{chat_id}")

          {:ok, %{
            sent: true,
            message_id: result["message_id"],
            chat_id: chat_id,
            sticker: sticker
          }}

        {:error, {status, %{"description" => description}}} ->
          {:error, "Failed to send sticker: #{description} (HTTP #{status})"}

        {:error, {status, description}} when is_binary(description) ->
          {:error, "Failed to send sticker: #{description} (HTTP #{status})"}

        {:error, error} ->
          {:error, "Failed to send sticker: #{inspect(error)}"}
      end
    end
  end

  defp validate_param(params, key, _type \\ :any) do
    case Map.fetch(params, key) do
      {:ok, value} when is_binary(value) and value != "" -> {:ok, value}
      {:ok, value} when is_integer(value) -> {:ok, value}
      _ -> {:error, "Missing or invalid #{key}"}
    end
  end
end
