require "net/http"
require "json"
require "uri"

Jekyll::Hooks.register :site, :post_write do |site|

  sitemap_file = File.join(site.dest, "sitemap.xml")

  unless File.exist?(sitemap_file)
    puts "sitemap.xml not found"
    next
  end

  xml = File.read(sitemap_file)

  current = xml.scan(/<loc>(.*?)<\/loc>/).flatten

  file = ".indexnow.json"
  old = File.exist?(file) ? JSON.parse(File.read(file)) : []

  urls = current - old

  if urls.empty?
    puts "No new URLs"
    next
  end

  uri = URI("https://api.indexnow.org/indexnow")

  response = Net::HTTP.post(
    uri,
    {
      host: "plumpos.com",
      key: "b6af4616be2c413985f528b4fa300eac",
      keyLocation: "https://plumpos.com/b6af4616be2c413985f528b4fa300eac.txt",
      urlList: urls
    }.to_json,
    "Content-Type" => "application/json"
  )

  if response.is_a?(Net::HTTPSuccess)
    File.write(file, current.to_json)
    puts "#{urls.size} URLs submitted to IndexNow"
  else
    puts "IndexNow failed: #{response.code} #{response.body}"
  end

rescue => e
  puts "IndexNow error: #{e.class} - #{e.message}"
end