{% load i18n %}{% load anyllm_tags %}
{% show_internal as show_internal %}

{% include "django_anyllm/_message.html" with message=user_message %}

<div class="anyllm-message-wrapper assistant" id="msg-{{ assistant_message.pk }}">
  <div class="anyllm-avatar assistant">{% trans "AI" %}</div>
  <div class="anyllm-message-body">
    <div class="anyllm-message-meta">
      <span class="anyllm-message-role">{% trans "Assistant" %}</span>
      <span class="anyllm-message-time">{{ assistant_message.created_at|date:"g:i A" }}</span>
    </div>
    <div class="anyllm-message assistant">
      <div class="content" id="msg-content-{{ assistant_message.pk }}"></div>
      <div class="anyllm-streaming" id="msg-streaming-{{ assistant_message.pk }}">
        <div class="anyllm-streaming-dot"></div>
        <div class="anyllm-streaming-dot"></div>
        <div class="anyllm-streaming-dot"></div>
      </div>
      <div id="msg-tools-{{ assistant_message.pk }}"></div>
    </div>
  </div>
</div>

<script>
(function () {
  const source = new EventSource(
    "{% url 'django_anyllm:chat_stream' chat.pk %}?message={{ assistant_message.pk }}"
  );
  const contentEl = document.getElementById("msg-content-{{ assistant_message.pk }}");
  const streamingEl = document.getElementById("msg-streaming-{{ assistant_message.pk }}");
  const toolsEl = document.getElementById("msg-tools-{{ assistant_message.pk }}");
  let streamedContent = "";
  let mdParser = null;

  function preprocessMarkdown(text) {
    // Fix single-line tables: if a table separator exists but isn't on its own line,
    // the LLM output rows on a single line. Insert newlines between row boundaries.
    if (!/\|:[-:]+:?\|/.test(text)) return text;
    if (/\n\s*\|:[-:]+:?\|/.test(text)) return text;
    // Match "| |" (pipe-space-pipe) which is the boundary between rows in a single-line table
    return text.replace(/\| \|/g, '|\n|');
  }

  function renderMarkdown() {
    if (mdParser && streamedContent) {
      contentEl.innerHTML = mdParser(preprocessMarkdown(streamedContent));
    }
  }

  if (typeof marked !== "undefined" && marked.parse) {
    mdParser = function (text) { return marked.parse(text); };
  } else {
    var mdScript = document.createElement("script");
    mdScript.src = "https://cdn.jsdelivr.net/npm/marked@13/marked.min.js";
    mdScript.onload = function () {
      if (typeof marked !== "undefined" && marked.parse) {
        mdParser = function (text) { return marked.parse(text); };
        renderMarkdown();
      }
    };
    document.head.appendChild(mdScript);
  }

  source.addEventListener("content", function (e) {
    streamedContent += e.data;
    if (mdParser) {
      contentEl.innerHTML = mdParser(preprocessMarkdown(streamedContent));
    } else {
      contentEl.textContent += e.data;
    }
  });

  {% if show_internal %}
  source.addEventListener("reasoning", function (e) {
    let reasoningEl = contentEl.previousElementSibling;
    if (!reasoningEl || !reasoningEl.classList.contains("anyllm-reasoning")) {
      reasoningEl = document.createElement("div");
      reasoningEl.className = "anyllm-reasoning";
      reasoningEl.innerHTML = '<div class="anyllm-reasoning-label">{% trans "Reasoning" %}</div><div class="anyllm-reasoning-content"></div>';
      contentEl.parentNode.insertBefore(reasoningEl, contentEl);
    }
    reasoningEl.querySelector(".anyllm-reasoning-content").textContent += e.data;
  });

  source.addEventListener("tool_call", function (e) {
    const toolEl = document.createElement("div");
    toolEl.className = "anyllm-tool-call";
    toolEl.innerHTML = '<span>🔧</span><span>{% trans "Calling" %} <strong>' + e.data + '</strong>...</span>';
    toolsEl.appendChild(toolEl);
  });

  source.addEventListener("tool_result", function (e) {
    const resultEl = document.createElement("div");
    resultEl.className = "anyllm-tool-result";
    resultEl.textContent = e.data;
    toolsEl.appendChild(resultEl);
  });
  {% endif %}

  source.addEventListener("error", function (e) {
    streamingEl.style.display = "none";
    const errorEl = document.createElement("div");
    errorEl.className = "anyllm-error";
    errorEl.textContent = "{% trans 'Error:' %} " + (e.data || "{% trans 'Something went wrong' %}");
    contentEl.parentNode.appendChild(errorEl);
    source.close();
  });

  source.addEventListener("done", function () {
    streamingEl.style.display = "none";
    source.close();
  });
})();
</script>
