# frozen_string_literal: true

# Internal: Adds all assets generated by Vite to the static_files list, so
# that they are copied over to the built site.
class Jekyll::Vite::Generator < Jekyll::Generator
  safe true
  priority :highest

  class ViteAssetFile < Jekyll::StaticFile
    # Override (4.2): Copy to the configured public_output_dir
    if method_defined?(:cleaned_relative_path)
      def cleaned_relative_path
        replace_build_path(super)
      end
    end

    # Override: Copy to the configured public_output_dir
    def destination_rel_dir
      replace_build_path(super)
    end

  private

    def replace_build_path(src)
      src.sub(
        ViteRuby.config.build_output_dir.relative_path_from(@site.source).to_s,
        ViteRuby.config.public_output_dir,
      )
    end
  end

  # Internal: Set the mode based on which command was run.
  # Builds assets with Vite only if `jekyll build` was run.
  def generate(site)
    serving = site.config['serving']
    ENV['JEKYLL_ENV'] ||= serving ? 'development' : 'production'
    generate_vite_build(site) unless serving
  end

  # Internal: Build all assets with Vite and add them to the site's static files.
  def generate_vite_build(site)
    ViteRuby.commands.build_from_task
    add_static_files(site, ViteRuby.config.build_output_dir)
  end

  # Internal: Add generated assets to the site's static files.
  def add_static_files(site, assets_dir)
    relative_assets_dir = assets_dir.relative_path_from(site.source).to_s
    vite_static_files = Dir.chdir(assets_dir.to_s) {
      Dir.glob('**/*').select { |f| File.file?(f) }
    }.map { |file|
      ViteAssetFile.new(site, site.source, relative_assets_dir, file)
    }
    site.static_files.concat(vite_static_files)
  end
end
