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

# Writes lib/getstream/vision_agents/generated/spec.rb from acceleration/api/openapi.yaml.
#
#   script/generate           regenerate
#   script/generate --check   fail if the committed file is not what the spec gives
#
# What is generated is a table, not a client: every operation's method, path, parameters and
# body schema, and every schema's property names. Client#get and friends look a path up in it,
# so a misspelt path, query parameter or body key is refused before a request is made.

require "fileutils"
require "psych"

ROOT = File.expand_path("..", __dir__)
SPEC = File.expand_path("../../acceleration/api/openapi.yaml", ROOT)
OUTPUT = File.join(ROOT, "lib/getstream/vision_agents/generated/spec.rb")
METHODS = %w[get post put patch delete].freeze

spec = Psych.safe_load(File.read(SPEC), aliases: false)
parameters = spec.dig("components", "parameters") || {}
schemas = spec.dig("components", "schemas") || {}

def ref_name(node)
  node.is_a?(Hash) && node["$ref"] ? node["$ref"].split("/").last : nil
end

operations = []
spec.fetch("paths").each do |path, item|
  shared = item["parameters"] || []
  METHODS.each do |method|
    operation = item[method] or next
    declared = (shared + (operation["parameters"] || [])).map do |parameter|
      name = ref_name(parameter)
      name ? parameters.fetch(name) : parameter
    end
    body = operation.dig("requestBody", "content", "application/json", "schema")
    operations << {
      id: operation.fetch("operationId"),
      method: method,
      path: path,
      path_params: declared.select { |p| p["in"] == "path" }.map { |p| p["name"] },
      query: declared.select { |p| p["in"] == "query" }.map { |p| p["name"] },
      body: body ? ref_name(body) || "" : nil,
      body_required: operation.dig("requestBody", "required") == true,
      socket: operation.fetch("responses", {}).key?("101"),
      client_accessible: operation["x-client-accessible"] == true
    }
  end
end

def words(list)
  list.empty? ? "[].freeze" : "%w[#{list.join(" ")}].freeze"
end

lines = []
lines << "# frozen_string_literal: true"
lines << ""
lines << "# Code generated by script/generate from acceleration/api/openapi.yaml. DO NOT EDIT."
lines << ""
lines << "module GetStream"
lines << "  module VisionAgents"
lines << "    module Generated"
lines << "      SPEC_VERSION = #{spec.dig("info", "version").to_s.inspect}"
lines << ""
lines << "      OPERATIONS = {"
operations.sort_by { |op| op[:id] }.each do |op|
  lines << "        #{op[:id].inspect} => {"
  lines << "          method: :#{op[:method]}, path: #{op[:path].inspect},"
  lines << "          path_params: #{words(op[:path_params])}, query: #{words(op[:query])},"
  lines << "          body: #{op[:body].inspect}, body_required: #{op[:body_required]},"
  lines << "          socket: #{op[:socket]}, client_accessible: #{op[:client_accessible]}"
  lines << "        }.freeze,"
end
lines << "      }.freeze"
lines << ""
lines << "      SCHEMAS = {"
schemas.keys.sort.each do |name|
  schema = schemas[name]
  next unless schema["type"] == "object" && schema["properties"]

  open = schema["additionalProperties"] ? true : false
  lines << "        #{name.inspect} => {"
  lines << "          properties: #{words(schema["properties"].keys)},"
  lines << "          required: #{words(schema["required"] || [])}, open: #{open}"
  lines << "        }.freeze,"
end
lines << "      }.freeze"
lines << "    end"
lines << "  end"
lines << "end"
generated = "#{lines.join("\n")}\n"

if ARGV.include?("--check")
  current = File.exist?(OUTPUT) ? File.read(OUTPUT) : ""
  if current != generated
    warn "#{OUTPUT} is out of date with the spec; run script/generate"
    exit 1
  end
  puts "generated spec is up to date (#{operations.size} operations)"
else
  FileUtils.mkdir_p(File.dirname(OUTPUT))
  File.write(OUTPUT, generated)
  puts "wrote #{operations.size} operations to #{OUTPUT}"
end
