

translate_line <- function(n, context) {

  line_folder   <- context$line_folder
  dic           <- context$dic
  text          <- context$text
  mapping       <- context$mapping
  min_freq      <- context$min_freq
  sentence_prob <- context$sentence_prob

  line_file <- paste0(line_folder, "/Line_", n, ".txt")

  # 1. Gespeicherte Übersetzung laden falls vorhanden
  if (file.exists(line_file)) {
    x       <- sub("^Structure: ", "", readLines(line_file, n = 1))
    df_fill <- fill_substr_info(line_file)
  } else {
    x       <- n
    df_fill <- NULL
  }

  # 2. Primärwörterbuch aufbauen
  line_files <- list.files(line_folder, "^Line_[0-9]+\\.txt$", full.names = TRUE)
  line_files <- line_files[!str_ends(line_files, paste0("Line_", n, ".txt"))]

  if (is.character(dic) && length(dic) >= 1) {
    primary <- read_dictionary(dic[1])
  } else if (is.data.frame(dic)) {
    primary <- dic
  } else if (is.list(dic) && length(dic) >= 1 && is.data.frame(dic[[1]])) {
    primary <- dic[[1]]
  } else {
    primary <- read_dictionary()
  }

  if (length(line_files) > 0) {
    dic_from_text <- make_dictionary(line_files)
    dics <- list(primary, dic_from_text)
  }else{
    dics <- list(primary)
  }

  # 3. Wörterbuchliste (Primär + Nachschlagewerke)

  if (is.character(dic) && length(dic) >= 2) {
    for (i in 2:length(dic))
      dics[[length(dics) + 1]] <- read_dictionary(dic[i])
  } else if (is.list(dic) && length(dic) >= 2) {
    for (i in 2:length(dic))
      dics[[length(dics) + 1]] <- if (is.character(dic[[i]])) read_dictionary(dic[[i]]) else dic[[i]]
  }

  # 4. Übersetzen
  result <- translate(x, text = text, dic = dics, mapping = mapping,
                      fill = df_fill, min_freq = min_freq,
                      sentence_prob = sentence_prob)

  # 5. Ergebnis speichern
  if (is.null(result)) {
    cat("Note: The translation wasn't saved.\n")
  } else {
    print(result)
    writeLines(result, line_file)
    cat(paste0("\nNote: Result is saved to file '", line_file, "'.\n\n"))
  }
}
