require "roo"

# Seed supported languages
SUPPORTED_LANGUAGES = [
  { code: "fi", name: "Finnish", native_name: "Suomi", sort_order: 1 },
  { code: "en", name: "English", native_name: "English", sort_order: 2 },
  { code: "sv", name: "Swedish", native_name: "Svenska", sort_order: 3 },
  { code: "no", name: "Norwegian", native_name: "Norsk", sort_order: 4 },
  { code: "de", name: "German", native_name: "Deutsch", sort_order: 5 },
  { code: "ru", name: "Russian", native_name: "Русский", sort_order: 6 }
].freeze

SUPPORTED_LANGUAGES.each do |lang|
  SupportedLanguage.find_or_create_by!(code: lang[:code]) do |record|
    record.assign_attributes(lang.except(:code))
  end
end

puts "Seeded #{SupportedLanguage.count} languages"

# Import entries from Excel
HEADER_TO_LANG = {
  "Finnish" => :fi,
  "English" => :en,
  "Swedish" => :sv,
  "Norwegian" => :no,
  "German" => :de,
  "Russian" => :ru
}.freeze

source_path = Rails.root.join("public", "Kristillisyyden sanasto ver 23.5.2013.xlsx")

unless source_path.exist?
  abort "Seed file not found: #{source_path}"
end

sheet = Roo::Excelx.new(source_path.to_s).sheet(0)
headers = sheet.row(1).map { |cell| cell.to_s.strip }

column_map = headers.each_with_index.filter_map do |header, index|
  lang = HEADER_TO_LANG[header]
  [ lang, index ] if lang
end.to_h

if column_map.empty?
  abort "No language columns found in headers: #{headers.inspect}"
end

puts "Found columns: #{column_map.keys.join(', ')}"
puts "Importing entries..."

imported = 0
skipped = 0

sheet.each_row_streaming(offset: 1) do |row|
  translations = column_map.transform_values do |index|
    row[index]&.value.to_s.strip.presence
  end

  if translations.values.none?
    skipped += 1
    next
  end

  Entry.find_or_create_by!(translations) do |entry|
    entry.category = :word
  end

  imported += 1
end

puts "Imported #{imported} entries, skipped #{skipped} empty rows"
