module SvelteOnRails::Installer::Vite

def self.configure_for_svelte(force: false)

def self.configure_for_svelte(force: false)
  # add import statement
  js_i = SvelteOnRails::Installer::Javascript
  pkg = '@sveltejs/vite-plugin-svelte'
  npm_i = SvelteOnRails::Installer::Npm
  npm_i.install_or_update_package(pkg)
  # add plugin
  file_path = 'vite.config.ts'
  if File.read(file_path).match?(/svelte/)
    puts "Svelte seams already configured in vite.config.ts, skipping here."
  else
    js_i.append_import_statement('vite.config.ts', pkg, "import {svelte} from '#{pkg}'")
    # Regex to match the plugins array and locate RubyPlugin()
    plugins_regex = /(plugins:\s*\[\s*)(\s*)RubyPlugin\(\),\s*([^\]]*?\])/m
    # Check if plugins array with RubyPlugin exists
    file_content = File.read(file_path)
    unless file_content.match?(plugins_regex)
      puts "Error: No plugins array with RubyPlugin() found in the input."
      return file_content
    end
    # Insert svelte({}), after RubyPlugin() with proper indentation
    modified_content = file_content.gsub(plugins_regex) do |match|
      prefix = $1 # Start of plugins array (e.g., "plugins: [")
      indent = '    ' # Indentation before RubyPlugin()
      rest = $3 # Remaining plugins and closing bracket
      "#{prefix}#{indent}RubyPlugin(),\n#{indent}svelte({}),\n#{indent}#{rest}"
    end
    File.write(file_path, modified_content)
    puts "Updated vite.config.ts with svelte() plugin."
  end
end