#!/usr/bin/env ruby

require "fileutils"
require "pathname"

ROOT = Pathname.new(__dir__).join("../..").expand_path
DEFAULT_SOURCE_DIR = ROOT.join("trap-examples")
DEFAULT_OUTPUT_DIR = ROOT.join("trap-examples/generated-sql")

def extract_sql_blocks(content)
  blocks = []
  current_block = nil

  content.each_line do |line|
    if current_block
      if line.strip == "```"
        blocks << current_block.rstrip
        current_block = nil
      else
        current_block << line
      end
    elsif line.match?(/^```sql\s*$/i)
      current_block = +""
    end
  end

  blocks
end

def output_name_for(pathname)
  if pathname.basename.to_s.end_with?(".sql.md")
    pathname.basename(".md").to_s
  else
    "#{pathname.basename(".md")}".downcase.gsub(/[^a-z0-9]+/, "_").gsub(/\A_+|_+\z/, "") + ".sql"
  end
end

source_dir = Pathname.new(ARGV[0] || DEFAULT_SOURCE_DIR).expand_path
output_dir = Pathname.new(ARGV[1] || DEFAULT_OUTPUT_DIR).expand_path

unless source_dir.directory?
  warn "Source directory not found: #{source_dir}"
  exit 1
end

FileUtils.mkdir_p(output_dir)

written = []

source_dir.glob("*.md").sort.each do |markdown_file|
  sql_blocks = extract_sql_blocks(markdown_file.read)
  next if sql_blocks.empty?

  output_file = output_dir.join(output_name_for(markdown_file))
  sql = sql_blocks.each_with_index.map do |block, index|
    ["-- Extracted from #{markdown_file.basename} block #{index + 1}", block].join("\n")
  end.join("\n\n")

  output_file.write("#{sql}\n")
  written << output_file
end

puts "Wrote #{written.length} SQL file(s) to #{output_dir}"
written.each do |file|
  puts " - #{file.relative_path_from(ROOT)}"
end
