class SvelteOnRails::RenderServerSide

def self.file_exist_case_sensitive?(containing_dir, filename)

def self.file_exist_case_sensitive?(containing_dir, filename)
  # Combine the directory path and filename
  full_path = File.join(containing_dir, filename)
  # Check if the file exists and the path matches case-sensitively
  File.exist?(full_path) && Dir[File.join(containing_dir, "**/*")].any? do |f|
    f == full_path
  end
end

def self.gem_app_dir

def self.gem_app_dir
  File.expand_path('../svelte_on_rails', __dir__) + '/'
end

def self.reset_and_compile_all

def self.reset_and_compile_all
  SvelteOnRails::RenderServerSide.reset_dist
  cnf = SvelteOnRails::Configuration.instance
  frontend_folder = cnf.frontend_folder_full
  sveltes = Dir.glob(cnf.frontend_folder_full.join('**/*.svelte'))
  sveltes.each_with_index do |file, ind|
    comp_name = file.to_s[(cnf.frontend_folder_full.to_s.length + 1)..-1]
    n = SvelteOnRails::RenderServerSide.new(comp_name, base_path: frontend_folder)
    n.compile
    puts "compiled #{ind + 1}/#{sveltes.length}: #{comp_name}"
  end
end

def self.reset_dist

assets:precompile
def self.reset_dist
  unless Dir.exist?(SvelteOnRails::Configuration.instance.dist_folder)
    FileUtils.mkdir_p(SvelteOnRails::Configuration.instance.dist_folder)
  end
  FileUtils.rm_rf Dir.glob("#{SvelteOnRails::Configuration.instance.dist_folder}/*")
  FileUtils.touch SvelteOnRails::Configuration.instance.dist_folder.join('reset_timestamp')
end

def compile

def compile
  start_time = Time.now
  cnf = SvelteOnRails::Configuration.instance
  subs = @svelte_filename.split('/')[0..-2].join('/')
  dist = cnf.dist_folder + cnf.components_folder + subs
  cmd = [
    'node',
    self.class.gem_app_dir + 'compile.js',
    @svelte_file,
    dist,
    self.class.gem_app_dir
  ].join(' ')
  stdout, stderr, status = Open3.capture3(cmd, chdir: SvelteOnRails::Configuration.instance.rails_root)
  unless status.to_s.match(/^pid [0-9]+ exit 0$/)
    raise "Compiling «#{@svelte_filename}» Server-side, script compile.js, executed within Rails.root:\n\n#{cmd}\n\n++++++\n\n#{stderr}\n\n++++++\n\n"
  end
  time = Time.now - start_time
  Rails.logger.info "  Compiled #{@svelte_filename}.js: #{time.round(3)}ms" rescue nil
end

def compile_if_changes

def compile_if_changes
  # letzte Änderung innerhalb des ordners ermitteln
  watch_changes = SvelteOnRails::Configuration.instance.watch_changes?
  ts_file = SvelteOnRails::Configuration.instance.dist_folder.join('reset_timestamp')
  have_changes = if watch_changes && File.exist?(ts_file)
                   # compare last modification timestamp
                   last_modification = 100.years.ago.to_time
                   Dir.glob("#{SvelteOnRails::Configuration.instance.components_folder}**/*").each do |path|
                     if File.file?(path)
                       mtime = File.mtime(path)
                       if mtime > last_modification
                         last_modification = mtime
                       end
                     end
                   end
                   File.mtime(ts_file) < last_modification
                 elsif watch_changes
                   true
                 elsif !File.exist?(ts_file)
                   true
                 else
                   false
                 end
  if have_changes || !File.exist?(compiled_js_file) || !File.exist?(compiled_css_file)
    if have_changes || (!File.exist?(ts_file) && watch_changes)
      self.class.reset_dist
    end
    compile
  end
end

def compiled_css_file

def compiled_css_file
  @compiled_file + '.css'
end

def compiled_js_file

def compiled_js_file
  @compiled_file + '.js'
end

def initialize(filename, base_path: SvelteOnRails::Configuration.instance.components_folder_full)

def initialize(filename, base_path: SvelteOnRails::Configuration.instance.components_folder_full)
  fn = (filename.match(/\.svelte$/) ? filename[0..-8] : filename)
  @svelte_file = base_path + filename
  @svelte_filename = filename
  cnf = SvelteOnRails::Configuration.instance
  cf = cnf.dist_folder + cnf.components_folder + fn
  @compiled_file = cf.to_s
end

def render_compiled_file(props = {})

def render_compiled_file(props = {})
  require 'base64'
  require 'json'
  props_enc = Base64.strict_encode64(props.to_json).strip
  cmd = [
    'node',
    '/Users/christian/projects-gmbh/gems/svelte-on-rails/svelte-on-rails-gem/lib/svelte_on_rails/render.js',
    compiled_js_file,
    props_enc,
    SvelteOnRails::Configuration.instance.rails_root
  ].join(' ')
  stdout, stderr, status = Open3.capture3(cmd, chdir: self.class.gem_app_dir)
  unless status.to_s.match(/^pid [0-9]+ exit 0$/)
    raise "Render Svelte Server-side =>\n#{cmd}\n\nError output from render.js (stderr) =>\n+++\n" + stderr + "+++\n\n"
  end
  begin
    res = JSON.parse(stdout)
    if File.exist?(compiled_css_file)
      res['css'] = File.read(compiled_css_file)
    end
    return res
  rescue JSON::ParserError => e
    raise "Render Svelte Server-side: Expected JSON, got: «#{stdout}»"
  end
end