require "sketchup.rb"
require "extensions.rb"

module GG_CabinetTools
  PLUGIN_ID = "gg_cabinet_tools".freeze
  PLUGIN_NAME = "GG Cabinet Tools".freeze
  PLUGIN_DIR = File.join(File.dirname(__FILE__), PLUGIN_ID)
  CORE_DIR = File.join(PLUGIN_DIR, "core")

  # Loads a core file AT MOST ONCE per SketchUp session, and is shared with
  # `main` (which runs after this file) so the foundation below is not parsed a
  # second time there. `load` — not `require` — is still what runs the file, so
  # RubyEncoder's .rbe go through their loader; the registry just makes a repeat
  # call a no-op. Nothing reloads core over the running plugin any more (the old
  # auto-updater's hot-reload is gone), so a second load would only re-parse the
  # file and re-run its top-level constants for nothing.
  def self.load_core_once(path)
    @loaded_core ||= {}
    key = File.expand_path(path)
    return false if @loaded_core.key?(key)
    return false unless File.file?(key)

    @loaded_core[key] = true
    load key
    true
  end

  # Shared foundation — config, i18n (GG_CabinetTools.t) and API/HTTP — loaded
  # HERE, before both the standalone update launcher AND `main`, so the launcher
  # can reuse them (i18n + API calling live in core/, not only inside `main`).
  # Wrapped so a hiccup can't stop the plugin from at least registering +
  # offering the recovery menu.
  begin
    load_foundation = lambda do |name|
      rbe = File.join(CORE_DIR, "#{name}.rbe")
      rb  = File.join(CORE_DIR, "#{name}.rb")
      load_core_once(File.file?(rbe) ? rbe : rb)
    end
    load_core_once(File.join(CORE_DIR, "rgloader", "loader.rb"))
    %w[util locale api].each { |name| load_foundation.call(name) }
  rescue StandardError => e
    warn "[GG] foundation load failed: #{e.class}: #{e.message}"
  end

  # Independent update/revert entry point — loaded BEFORE `main` (uses the shared
  # foundation above) and wrapped so a failure here (or a crashed `main`) still
  # leaves the Extensions-menu item AND its standalone toolbar available to
  # update or roll back a broken build. Lives in core/ (rbe/rb-aware, same as
  # the foundation above) so it gets RubyEncoder-protected like every other
  # core file — unlike this loader and main.rb, which never can be.
  begin
    load_foundation.call("update_launcher")
    UpdateLauncher.install_menu!(plugin_dir: PLUGIN_DIR)
    UpdateLauncher.install_toolbar!(plugin_dir: PLUGIN_DIR)
  rescue StandardError => e
    warn "[GG UpdateLauncher] #{e.class}: #{e.message}"
  end

  extension = SketchupExtension.new(PLUGIN_NAME, File.join(PLUGIN_DIR, "main"))
  extension.version = "1.0.0"
  extension.description = "GG Cabinet Tools plugin with auto-update from GG CMS"
  extension.creator = "GG CMS"

  Sketchup.register_extension(extension, true)
end
