require 'yaml'
require 'pathname'
require 'active_support/all'

def convert(f)
  filename = Pathname.new(f)
  yaml = YAML.load_file(filename)
  name = filename.basename('.yml').to_s

  File.write(filename, {
    name.camelize => {
      'type' => yaml['type'],
      'properties' => yaml['definitions'].except('identity')
    }
  }.to_yaml)

  api_file = 'schemata/api.yml'
  api_yaml = YAML.load_file(api_file)

  yaml['links'].each do |link|
    api_yaml['paths'] << {
      link['href'] => {
        link['method'].downcase => {
          'description' => link['description'],
          'parameters'  => link.dig('schema', 'properties') || nil,
          'responses'   => {
            200 =>  {
              'description' => name,
              'schema' => {'$ref' => './x.yml#/definitions/X'}
            }
          }
        }
      }
    }
  end

  File.write(
    api_file,
    api_yaml.to_yaml
  )
end

Dir['schemata/**/*.yml'].each do |f|
  next if f == 'schemata/api.yml'
  convert(f)
end