# frozen_string_literal: true

require 'json'

module PluginConfig
  class SchemaError < StandardError
    attr_reader :check_result

    def initialize(check_result)
      @check_result = check_result
      super(check_result[:error])
    end

    def to_diagnostic_json
      {
        error: 'schema_mismatch',
        details: check_result
      }
    end
  end

  module Expectations
    SETTINGS = {
      description: 'Project settings file',
      required_keys: %w[enabledPlugins]
    }.freeze

    MARKETPLACE = {
      description: 'Marketplace registry',
      required_keys: %w[name plugins]
    }.freeze

    INSTALLED_PLUGINS = {
      description: 'Installed plugins registry',
      required_keys: %w[plugins]
    }.freeze

    def self.check(file_path, expected_keys)
      unless File.exist?(file_path)
        return { ok: false, error: "File not found: #{file_path}", missing_keys: expected_keys }
      end

      data = JSON.parse(File.read(file_path))
      missing = expected_keys.reject { |key| data.key?(key) }

      if missing.empty?
        { ok: true }
      else
        { ok: false, error: "Missing required keys in #{file_path}", missing_keys: missing }
      end
    rescue JSON::ParserError => e
      { ok: false, error: "Invalid JSON in #{file_path}: #{e.message}", missing_keys: expected_keys }
    end
  end
end
