Ok now review the following code and tell us what we did wrong and then list all the mistakes and rewrite it all again in full working code please in elixir

#!/usr/bin/env elixir

defmodule ChatbotFormatter do
  @moduledoc """
  A sophisticated formatter for chatbot outputs, designed for Mac and Linux command lines.
  Handles ANSI escape codes, syntax highlighting, and markdown formatting.
  """

  @default_config %{
    max_width: 100,
    indent: "  ",
    colors: %{
      reset: "\x1b[0m",
      bold: "\x1b[1m",
      dim: "\x1b[2m",
      italic: "\x1b[3m",
      underline: "\x1b[4m",
      black: "\x1b[30m",
      red: "\x1b[31m",
      green: "\x1b[32m",
      yellow: "\x1b[33m",
      blue: "\x1b[34m",
      magenta: "\x1b[35m",
      cyan: "\x1b[36m",
      white: "\x1b[37m",
      bg_magenta: "\x1b[45m",
      gray: "\x1b[90m"
    }
  }

  def run(config \\ @default_config) do
    width = get_terminal_width(config)
    state = %{prev_line: nil, mode: :normal, lang: nil, input_state: :user_input, in_code_block: false}
    display_welcome_message(config)
    stream_input(state, width, config)
  end

  defp stream_input(state, width, config) do
    case IO.gets("") do
      :eof -> :ok
      {:error, reason} -> IO.puts("Error: #{reason}")
      line ->
        {new_state, formatted} = process_line(line, state, width, config)
        stream_output(formatted)
        stream_input(new_state, width, config)
    end
  end

  defp stream_output(text) do
    text
    |> String.graphemes()
    |> Stream.chunk_every(5)
    |> Stream.each(fn chunk ->
      IO.write(Enum.join(chunk))
      Process.sleep(1)
    end)
    |> Stream.run()
  end

  defp process_line(line, state, width, config) do
    line = unescape_ansi(line)
    trimmed_line = String.trim(line)
    {new_state, formatted} = 
      cond do
        String.starts_with?(trimmed_line, "> ") ->
          {%{state | mode: :normal, lang: nil, input_state: :user_input, in_code_block: false}, format_user_input(line, config)}
        String.match?(trimmed_line, ~r/^```\w*$/) ->
          new_lang = String.trim(trimmed_line, "`")
          {%{state | in_code_block: !state.in_code_block, lang: new_lang, mode: :code, input_state: :ai_output}, format_code_block_delimiter(new_lang, config)}
        state.in_code_block ->
          {state, format_code(line, state.lang, width, config)}
        true ->
          formatted = format_ai_response(trimmed_line, state.prev_line, width, config)
          {%{state | mode: :normal, lang: nil, input_state: :ai_output}, formatted}
      end

    {%{new_state | prev_line: line}, formatted}
  end

  defp format_user_input(line, config) do
    "#{config.colors.yellow}👤 #{config.colors.green}#{String.trim(line)}#{config.colors.reset}\n"
  end

  defp format_ai_response(line, prev_line, width, config) do
    start_block = if should_start_new_block?(prev_line) do
      [
        "\n#{config.colors.cyan}🤖 #{config.colors.reset}",
        "#{config.colors.magenta}┌#{"─" |> String.duplicate(width - 2)}┐#{config.colors.reset}\n"
      ]
    else
      []
    end

    content = format_markdown(line, width, config)

    end_block = if String.trim(line) == "" do
      ["#{config.colors.magenta}└#{"─" |> String.duplicate(width - 2)}┘#{config.colors.reset}\n"]
    else
      []
    end

    Enum.join(start_block ++ [content] ++ end_block)
  end

  defp should_start_new_block?(prev_line) do
    prev_line == nil or String.starts_with?(String.trim(prev_line), "> ")
  end

  defp format_markdown(line, width, config) do
    line
    |> highlight_markdown(config)
    |> wrap_text(width - 4)
    |> Enum.map(fn l -> 
      "#{config.colors.magenta}│#{config.colors.reset} #{l}#{String.duplicate(" ", max(0, width - String.length(strip_ansi(l)) - 3))}#{config.colors.magenta}│#{config.colors.reset}\n"
    end)
    |> Enum.join()
  end

  defp format_code_block_delimiter(lang, config) do
    "#{config.colors.gray}```#{lang}#{config.colors.reset}\n"
  end

  defp format_code(line, lang, width, config) do
    line
    |> highlight_code(lang, config)
    |> wrap_text(width - 4)
    |> Enum.map(fn l -> "#{config.indent}#{l}\n" end)
    |> Enum.join()
  end

  defp highlight_markdown(line, config) do
    rules = [
      {~r/^(#+)\s+(.+)$/, fn _, hashes, title ->
        "#{config.colors.blue}#{config.colors.bold}#{hashes} #{title}#{config.colors.reset}"
      end},
      {~r/`([^`]+)`/, "#{config.colors.cyan}\\1#{config.colors.reset}"},
      {~r/\*\*([^*]+)\*\*/, "#{config.colors.bold}\\1#{config.colors.reset}"},
      {~r/\*([^*]+)\*/, "#{config.colors.italic}\\1#{config.colors.reset}"},
      {~r/\[([^\]]+)\]\(([^)]+)\)/, "#{config.colors.blue}\\1#{config.colors.reset}#{config.colors.green}(\\2)#{config.colors.reset}"},
      {~r/^> (.+)$/, "#{config.colors.gray}> \\1#{config.colors.reset}"},
      {~r/^([ \t]*)([-*+]) (.+)$/, "\\1#{config.colors.yellow}\\2#{config.colors.reset} \\3"},
      {~r/^([ \t]*)(\d+\.) (.+)$/, "\\1#{config.colors.yellow}\\2#{config.colors.reset} \\3"}
    ]
    apply_highlight_rules(line, rules, config)
  end

  defp highlight_code(line, lang, config) do
    rules = language_rules(lang)
    apply_highlight_rules(line, rules, config)
  end

  defp language_rules(lang) do
    case lang do
      "elixir" -> elixir_rules()
      "typescript" -> typescript_rules()
      "javascript" -> javascript_rules()
      "python" -> python_rules()
      _ -> default_rules()
    end
  end

  defp elixir_rules do
    [
      {~r/\b(def|defmodule|do|end|if|else|case|cond|fn|when|import|use|alias)\b/, :magenta},
      {~r/\b(nil|true|false)\b/, :yellow},
      {~r/"([^"]*)"/, :green},
      {~r/'([^']*)'/, :green},
      {~r/\b([A-Z]\w*)\b/, :cyan},
      {~r/\b\d+(\.\d+)?\b/, :blue},
      {~r/(@[a-z]\w*)/, :red},
      {~r/(#.*)$/, :gray}
    ]
  end

  defp typescript_rules do
    [
      {~r/\b(const|let|var|function|class|interface|type|enum|import|export|from|as)\b/, :blue},
      {~r/\b(if|else|for|while|do|switch|case|break|continue|return|throw|try|catch|finally|async|await)\b/, :magenta},
      {~r/\b(string|number|boolean|any|void|null|undefined)\b/, :cyan},
      {~r/(".*?"|'.*?'|`.*?`)/, :green},
      {~r/\b(\d+(\.\d+)?)\b/, :yellow},
      {~r/\/\/.*/, :gray},
      {~r/\/\*[\s\S]*?\*\//, :gray},
      {~r/\b([A-Z]\w*)\b/, :red}
    ]
  end

  defp javascript_rules do
    [
      {~r/\b(const|let|var|function|class|import|export|from)\b/, :blue},
      {~r/\b(if|else|for|while|do|switch|case|break|continue|return|throw|try|catch|finally|async|await)\b/, :magenta},
      {~r/\b(true|false|null|undefined)\b/, :cyan},
      {~r/(".*?"|'.*?'|`.*?`)/, :green},
      {~r/\b(\d+(\.\d+)?)\b/, :yellow},
      {~r/\/\/.*/, :gray},
      {~r/\/\*[\s\S]*?\*\//, :gray},
      {~r/\b([A-Z]\w*)\b/, :red}
    ]
  end

  defp python_rules do
    [
      {~r/\b(def|class|import|from|as|if|elif|else|for|while|try|except|finally|with|async|await)\b/, :blue},
      {~r/\b(return|yield|pass|break|continue|raise)\b/, :magenta},
      {~r/\b(int|float|str|bool|list|dict|tuple|set|None|True|False)\b/, :cyan},
      {~r/(".*?"|'.*?')/, :green},
      {~r/\b(\d+(\.\d+)?)\b/, :yellow},
      {~r/#.*/, :gray},
      {~r/\b([A-Z]\w*)\b/, :red}
    ]
  end

  defp default_rules do
    [
      {~r/\b([a-zA-Z_]\w*)\s*(?==)/, :cyan},
      {~r/"([^"]*)"/, :green},
      {~r/'([^']*)'/, :green},
      {~r/\b\d+(\.\d+)?\b/, :yellow},
      {~r/[{}()\[\]]/, :magenta},
      {~r/[+\-*\/%=<>!&|^]+/, :red}
    ]
  end

  defp apply_highlight_rules(text, rules, config) do
    Enum.reduce(rules, text, fn
      {regex, color}, acc when is_atom(color) ->
        Regex.replace(regex, acc, "#{Map.get(config.colors, color)}\\0#{config.colors.reset}")
      {regex, replacement}, acc when is_binary(replacement) ->
        Regex.replace(regex, acc, replacement)
      {regex, fun}, acc when is_function(fun) ->
        Regex.replace(regex, acc, fun)
    end)
  end

  defp wrap_text(text, width) do
    words = String.split(text, ~r/\s+/)
    do_wrap_text(words, width, [])
  end

  defp do_wrap_text([], _, acc), do: Enum.reverse(acc)
  defp do_wrap_text(words, width, acc) do
    {line, rest} = take_line(words, width, [])
    do_wrap_text(rest, width, [Enum.join(line, " ") | acc])
  end

  defp take_line([], _, acc), do: {Enum.reverse(acc), []}
  defp take_line([word | rest], width, acc) do
    new_line = [word | acc]
    new_length = new_line |> Enum.join(" ") |> strip_ansi() |> String.length()
    if new_length <= width do
      take_line(rest, width, new_line)
    else
      {Enum.reverse(acc), [word | rest]}
    end
  end

  defp strip_ansi(string) do
    Regex.replace(~r/\x1b\[[0-9;]*[mG]/, string, "")
  end

  defp unescape_ansi(text) do
    text
    |> String.replace("[0m", "\x1b[0m")
    |> String.replace("[30m", "\x1b[30m")
    |> String.replace("[31m", "\x1b[31m")
    |> String.replace("[32m", "\x1b[32m")
    |> String.replace("[33m", "\x1b[33m")
    |> String.replace("[34m", "\x1b[34m")
    |> String.replace("[35m", "\x1b[35m")
    |> String.replace("[36m", "\x1b[36m")
    |> String.replace("[37m", "\x1b[37m")
  end

  defp get_terminal_width(config) do
    case System.cmd("tput", ["cols"]) do
      {result, 0} -> 
        width = String.trim(result) |> String.to_integer()
        min(width, config.max_width)
      _ -> config.max_width
    end
  end

  defp display_welcome_message(config) do
    IO.puts """
    #{config.colors.green}Welcome to your friendly Terminal Chatbot! 🌟#{config.colors.reset}
    #{config.colors.magenta}Here to assist you with coding and more, with a touch of fun!#{config.colors.reset}
    #{config.colors.blue}Type your messages and press Enter to chat.#{config.colors.reset}
    #{config.colors.blue}Type 'exit' or 'quit' to end the conversation.#{config.colors.reset}
    #{config.colors.blue}Press Ctrl+C to exit at any time.#{config.colors.reset}
    #{config.colors.green}----------------------------------------------------#{config.colors.reset}
    """
  end
end

ChatbotFormatter.run()


Again, so I need the syntax highlighter to be a bit more universal, particularly oriented towards languages such as TypeScript, JavaScript, C++, and Elixir, and also Python. So I wanted to be able to do all of them in a somewhat real-time fashion while being able to handle buffering. And the most important part is that it has to be really performant, and it has to be able to grab any command that you give it. And for example, it could be an IRC chatbot. It could be a system logs viewer. It could be a code review editor. I just wanted to be able to take any interactive command line application and be able to, in real time, apply syntax highlighting too. So can you do that for me, please? So first, tell me step by step how the code does, and then rewrite it all in rust in a much better way and include instructions in emojis etc on how to run this on a mac, try to avoid any dependencies please