#!/usr/bin/env ruby
# frozen_string_literal: true

# Post to social media with the Ampost Ruby SDK.
#
# One call publishes (or schedules) a post on every network you name:
# Instagram, Facebook, Threads, X, YouTube, Pinterest, Bluesky, Telegram and
# Discord. Ruby 3.1+ and the `ampost` gem:
#
#   gem install ampost
#
#   export AMPOST_API_KEY=amp_live_...
#   ruby post_with_sdk.rb --text "Hello from Ruby" --platforms bluesky,threads
#   ruby post_with_sdk.rb --text "New post" --platforms threads --link https://example.com/post
#   ruby post_with_sdk.rb --text "Launch" --platforms instagram,threads --media launch.jpg
#   ruby post_with_sdk.rb --text "Tomorrow" --platforms bluesky --schedule 2027-01-14T15:00:00Z
#
# Guide: https://ampost.io/how-to/post-to-social-media-from-ruby
# SDK: https://ampost.io/docs/tools/ruby-sdk

require "optparse"
require "ampost"

def parse_options(argv)
  options = { media_type: "image" }
  parser = OptionParser.new do |opts|
    opts.banner = "Usage: ruby post_with_sdk.rb --text TEXT --platforms LIST [options]"
    opts.on("--text TEXT", "the post text") { |v| options[:text] = v }
    opts.on("--platforms LIST",
            "comma-separated: instagram, facebook, threads, twitter, youtube, pinterest, bluesky, telegram, discord") do |v|
      options[:platforms] = v
    end
    opts.on("--link URL", "a link to attach (linkUrl)") { |v| options[:link] = v }
    opts.on("--media FILE_OR_URL", "an image or video: a local file or a public https URL") { |v| options[:media] = v }
    opts.on("--media-type TYPE", %w[image video], "the type of a --media URL: image (default) or video") do |v|
      options[:media_type] = v
    end
    opts.on("--schedule TIME", "publish later, at this ISO 8601 time, e.g. 2027-01-14T15:00:00Z") { |v| options[:schedule] = v }
    opts.on("--idempotency-key KEY", "reuse a key to make re-runs safe (default: one per run)") do |v|
      options[:idempotency_key] = v
    end
  end
  parser.parse!(argv)
  abort(parser.help) unless options[:text] && options[:platforms]
  options
end

def build_body(client, options)
  platforms = options[:platforms].split(",").map(&:strip).reject(&:empty?)
  abort("--platforms needs at least one platform, for example bluesky,threads") if platforms.empty?

  body = { targets: [{ platforms: platforms }], text: options[:text] }
  body[:linkUrl] = options[:link] if options[:link]
  if options[:media]
    # A public https URL is fetched by Ampost; a local file is uploaded first.
    body[:media] = if options[:media].start_with?("https://")
                     [{ url: options[:media], type: options[:media_type] }]
                   else
                     [client.media.upload(options[:media])]
                   end
  end
  if options[:schedule]
    body[:scheduledFor] = options[:schedule]
  else
    body[:publishNow] = true
  end
  body
end

def main(argv)
  options = parse_options(argv)

  # The client reads AMPOST_API_KEY. It retries rate limits and server errors with the same
  # Idempotency-Key, so a retried request never posts twice.
  begin
    client = Ampost::Client.new
    post = client.posts.create(build_body(client, options), idempotency_key: options[:idempotency_key])
  rescue Ampost::Error => e
    # API errors read "400 VALIDATION_FAILED: ...": the status, Ampost's code and its message.
    # A missing AMPOST_API_KEY and a refused upload are Ampost::Error too.
    warn "Could not post: #{e.message}"
    return 1
  end

  puts "Post #{post["id"]} is #{post["status"]}"
  post["platformPosts"].each do |platform_post|
    puts "  #{platform_post["platform"]}: #{platform_post["status"]} #{platform_post["publishedUrl"]}".rstrip
  end
  0
end

exit(main(ARGV)) if $PROGRAM_NAME == __FILE__
