{% extends "base.html" %} {% from "partials/status_badge.html" import
status_badge %} {% block content %}
<div class="pynmon-container">
  <div class="row">
    <div class="col-12">
      <div class="card pynmon-card">
        <div
          class="card-header pynmon-card-header d-flex justify-content-between align-items-center"
        >
          <span class="compact-header">Invocation Details</span>
          <div>
            <a
              href="/invocations"
              class="btn btn-sm btn-outline-secondary me-2 pynmon-action-btn"
            >
              Back to Invocations
            </a>
            <a
              href="#"
              id="view-in-timeline-btn"
              class="btn btn-sm btn-outline-success me-2 pynmon-action-btn"
              title="Zoom to this invocation in the timeline"
            >
              <span
                class="material-icons"
                style="font-size: 16px; vertical-align: middle"
                >zoom_in</span
              >
              Zoom to Timeline
            </a>
            <a
              href="/calls?call_id={{ call.call_id|urlencode }}"
              class="btn btn-sm btn-outline-info me-2 pynmon-action-btn"
            >
              View Call
            </a>
            <a
              href="/tasks/{{ task.task_id }}"
              class="btn btn-sm btn-outline-primary pynmon-action-btn"
            >
              View Task
            </a>
            <button
              id="rerun-call-btn"
              class="btn btn-sm btn-outline-warning pynmon-action-btn ms-2"
              title="Register a new identical call (new independent invocation)"
            >
              <span
                class="material-icons"
                style="font-size: 16px; vertical-align: middle"
                >replay</span
              >
              Re-run Call
            </button>
          </div>
        </div>
        <div class="card-body pynmon-card-body">
          <div class="row pynmon-row-compact">
            <div class="col-md-6">
              <div class="card pynmon-card">
                <div class="card-header pynmon-card-header compact-header">
                  Invocation information
                </div>
                <div class="card-body pynmon-card-body">
                  <table class="table pynmon-table">
                    <tbody>
                      <tr>
                        <th>Invocation ID:</th>
                        <td>
                          <code style="font-size: 11px; word-break: break-all"
                            >{{ invocation.invocation_id }}</code
                          >
                        </td>
                      </tr>
                      <tr>
                        <th>Status:</th>
                        <td>{{ status_badge(invocation.status.name) }}</td>
                      </tr>
                      <tr>
                        <th>Retries:</th>
                        <td>{{ invocation.num_retries }}</td>
                      </tr>
                      <tr>
                        <th>Parent Invocation:</th>
                        <td>
                          {% if invocation.parent_invocation_id %}
                          <a
                            href="/invocations/{{ invocation.parent_invocation_id }}"
                            class="text-decoration-none"
                            style="color: #0d6efd"
                          >
                            <code
                              style="
                                font-size: 11px;
                                word-break: break-all;
                                color: inherit;
                              "
                              >{{ invocation.parent_invocation_id }}</code
                            >
                          </a>
                          {% else %}
                          <span class="text-muted">None</span>
                          {% endif %}
                        </td>
                      </tr>
                      <tr>
                        <th>Created At:</th>
                        <td>{{ created_at }}</td>
                      </tr>
                      {% if completed_at %}
                      <tr>
                        <th>Completed At:</th>
                        <td>{{ completed_at }}</td>
                      </tr>
                      {% endif %} {% if duration %}
                      <tr>
                        <th>Duration:</th>
                        <td>{{ duration }}</td>
                      </tr>
                      {% endif %}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>

            <div class="col-md-6">
              <div class="card pynmon-card">
                <div class="card-header pynmon-card-header compact-header">
                  Call & task information
                </div>
                <div class="card-body pynmon-card-body">
                  <table class="table pynmon-table">
                    <tbody>
                      <tr>
                        <th>Call ID:</th>
                        <td>
                          <a
                            href="/calls/?call_id_key={{ call.call_id.key|urlencode }}"
                          >
                            <code style="font-size: 11px; word-break: break-all"
                              >{{ call.call_id }}</code
                            >
                          </a>
                        </td>
                      </tr>
                      <tr>
                        <th>Task ID:</th>
                        <td>
                          <a href="/tasks/{{ task.task_id }}">
                            {{ task.task_id }}
                          </a>
                        </td>
                      </tr>
                      <tr>
                        <th>Task Module:</th>
                        <td>{{ task.task_id.module }}</td>
                      </tr>
                      <tr>
                        <th>Task Function:</th>
                        <td>{{ task.task_id.func_name }}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>

          {% if workflow %}
          <div class="row pynmon-row-compact">
            <div class="col-12">
              <div class="card pynmon-card">
                <div class="card-header pynmon-card-header compact-header">
                  Workflow information
                </div>
                <div class="card-body pynmon-card-body">
                  <table class="table pynmon-table">
                    <tbody>
                      <tr>
                        <th>Workflow Type:</th>
                        <td>
                          <a
                            href="/workflows/{{ workflow.workflow_type | urlencode }}"
                          >
                            {{ workflow.workflow_type }}
                          </a>
                        </td>
                      </tr>
                      <tr>
                        <th>Workflow ID:</th>
                        <td>
                          <a href="/invocations/{{ workflow.workflow_id }}">
                            <code style="font-size: 11px; word-break: break-all"
                              >{{ workflow.workflow_id }}</code
                            >
                          </a>
                        </td>
                      </tr>
                      {% if workflow.parent_workflow_id %}
                      <tr>
                        <th>Parent Workflow:</th>
                        <td>
                          <a
                            href="/invocations/{{ workflow.parent_workflow_id }}"
                          >
                            <code style="font-size: 11px; word-break: break-all"
                              >{{ workflow.parent_workflow_id }}</code
                            >
                          </a>
                        </td>
                      </tr>
                      {% endif %}
                      <tr>
                        <th>Sub-workflow:</th>
                        <td>
                          {{ 'Yes' if workflow.is_subworkflow else 'No' }}
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
          {% endif %}

          <div class="row pynmon-row-compact">
            <div class="col-md-6">
              <div class="card pynmon-card">
                <div class="card-header pynmon-card-header compact-header">
                  Arguments
                </div>
                <div class="card-body pynmon-card-body">
                  {% if arguments %} {% with args=arguments,
                  id_prefix='invocation-args' %} {% include
                  "partials/formatted_arguments.html" %} {% endwith%} {% else %}
                  <p class="text-muted data-text">No arguments provided</p>
                  {% endif %}
                </div>
              </div>
            </div>

            <div class="col-md-6">
              <div class="card pynmon-card">
                <div class="card-header pynmon-card-header compact-header">
                  Result / exception
                </div>
                <div class="card-body pynmon-card-body">
                  {% if result is not none %}
                  <h6 class="text-success">Result:</h6>
                  <div class="result-container">
                    <pre class="result-content"><code>{{ result }}</code></pre>
                  </div>
                  {% elif exception is not none %}
                  <h6 class="text-danger">Exception:</h6>
                  <div class="result-container">
                    <pre
                      class="result-content"
                    ><code>{{ exception }}</code></pre>
                  </div>
                  {% else %}
                  <p class="text-muted">No result or exception available.</p>
                  {% endif %}
                </div>
              </div>
            </div>
          </div>

          <!-- New section for history timeline -->
          <div class="row pynmon-row-compact">
            <div class="col-12">
              <div class="card pynmon-card">
                <div class="card-header pynmon-card-header compact-header">
                  Status timeline
                </div>
                <div class="card-body pynmon-card-body">
                  {% if history %}
                  <div class="timeline compact-timeline">
                    {% for entry in history %}
                    <div class="timeline-item compact-timeline-item">
                      <div
                        class="timeline-marker {% if entry.status == 'SUCCESS' %}bg-success{% elif entry.status == 'FAILED' %}bg-danger{% elif entry.status == 'RUNNING' %}bg-info{% elif entry.status == 'PENDING' %}bg-warning{% elif entry.status == 'PAUSED' %}bg-primary{% elif entry.status == 'RETRY' %}bg-secondary{% else %}bg-dark{% endif %}"
                      ></div>
                      <div class="timeline-content compact-timeline-content">
                        <div class="timeline-title compact-timeline-title">
                          {{ status_badge(entry.status) }}
                        </div>
                        <div class="timeline-date metadata-text">
                          {{ entry.timestamp }}
                        </div>
                        {% if entry.runner_context_summary %}
                        <div
                          class="timeline-runner-info"
                          data-runner-id="{{ entry.runner_id }}"
                          style="
                            font-size: 11px;
                            margin-top: 6px;
                            background: #f8f9fa;
                            padding: 8px;
                            border-radius: 4px;
                            border-left: 3px solid #6c757d;
                          "
                        >
                          <!-- Current Runner Context -->
                          <div style="margin-bottom: 4px">
                            <strong style="color: #495057">Runner:</strong>
                            <span
                              class="badge bg-primary"
                              style="font-size: 10px"
                              >{{ entry.runner_cls or 'Unknown' }}</span
                            >
                            <a
                              href="/runners/{{ entry.runner_id }}"
                              class="text-decoration-none"
                              title="View runner details"
                            >
                              <code
                                style="
                                  font-size: 10px;
                                  background: #e9ecef;
                                  padding: 1px 4px;
                                  border-radius: 2px;
                                  color: #0d6efd;
                                "
                                >{{ entry.runner_id }}</code
                              >
                            </a>
                          </div>
                          <div
                            style="
                              color: #6c757d;
                              font-size: 10px;
                              margin-left: 8px;
                            "
                          >
                            {% if entry.hostname %}<span
                              >host: <strong>{{ entry.hostname }}</strong></span
                            >{% endif %} {% if entry.pid %}<span
                              style="margin-left: 8px"
                              >pid: <strong>{{ entry.pid }}</strong></span
                            >{% endif %} {% if entry.thread_id %}<span
                              style="margin-left: 8px"
                              >thread:
                              <strong>{{ entry.thread_id }}</strong></span
                            >{% endif %}
                          </div>

                          <!-- Parent Runner Context (if available) -->
                          {% if entry.parent_runner_id %}
                          <div
                            style="
                              margin-top: 6px;
                              padding-top: 6px;
                              border-top: 1px dashed #dee2e6;
                            "
                          >
                            <strong style="color: #6c757d; font-size: 10px"
                              >↳ Parent:</strong
                            >
                            <span
                              class="badge bg-secondary"
                              style="font-size: 10px"
                              >{{ entry.parent_runner_cls or 'Unknown' }}</span
                            >
                            <a
                              href="/runners/{{ entry.parent_runner_id }}"
                              class="text-decoration-none"
                              title="View parent runner details"
                            >
                              <code
                                style="
                                  font-size: 10px;
                                  background: #e9ecef;
                                  padding: 1px 4px;
                                  border-radius: 2px;
                                  color: #0d6efd;
                                "
                                >{{ entry.parent_runner_id }}</code
                              >
                            </a>
                            <div
                              style="
                                color: #6c757d;
                                font-size: 10px;
                                margin-left: 16px;
                                margin-top: 2px;
                              "
                            >
                              {% if entry.parent_hostname %}<span
                                >host:
                                <strong
                                  >{{ entry.parent_hostname }}</strong
                                ></span
                              >{% endif %} {% if entry.parent_pid %}<span
                                style="margin-left: 8px"
                                >pid:
                                <strong>{{ entry.parent_pid }}</strong></span
                              >{% endif %} {% if entry.parent_thread_id %}<span
                                style="margin-left: 8px"
                                >thread:
                                <strong
                                  >{{ entry.parent_thread_id }}</strong
                                ></span
                              >{% endif %}
                            </div>
                          </div>
                          {% endif %}
                        </div>
                        {% endif %} {% if entry.execution_context %}
                        <div class="timeline-text data-text">
                          {{ entry.execution_context }}
                        </div>
                        {% endif %}
                      </div>
                    </div>
                    {% endfor %}
                  </div>
                  {% else %}
                  <p class="text-muted data-text">No history available.</p>
                  {% endif %}
                </div>
              </div>
            </div>
          </div>
          <div
            id="ft-tree-loader"
            data-focus-id="{{ invocation.invocation_id }}"
          ></div>
        </div>
      </div>
    </div>
  </div>

  {% include "partials/ft_float_panel.html" %}
  <script>
    document.getElementById("ft-float-panel").style.display = "flex";
    // Restore FT panel state if navigating between detail pages
    if (window._ftRestoreState) window._ftRestoreState();
    // Load the family tree (restored expandedIds are preserved by restoreFtState)
    if (window._ftLoadTree) {
      window._ftLoadTree("{{ invocation.invocation_id }}");
    }
  </script>

  {% endblock %} {% block extra_js %}
  <script>
    // View in timeline functionality
    document
      .getElementById("view-in-timeline-btn")
      ?.addEventListener("click", function (e) {
        e.preventDefault();

        // Fetch invocation history to get time range
        fetch("/invocations/{{ invocation.invocation_id }}/history")
          .then((response) => response.json())
          .then((historyData) => {
            if (!historyData || historyData.length === 0) {
              alert("No history data available for this invocation");
              return;
            }

            // Get first and last timestamp
            const startTime = new Date(historyData[0].timestamp);
            const endTime = new Date(
              historyData[historyData.length - 1].timestamp
            );

            // Add 10% padding on each side
            const durationMs = endTime - startTime;
            const paddingMs = Math.max(durationMs * 0.1, 1000); // At least 1 second padding

            const paddedStart = new Date(startTime.getTime() - paddingMs);
            const paddedEnd = new Date(endTime.getTime() + paddingMs);

            // Format for datetime-local input (YYYY-MM-DDTHH:MM:SS)
            const formatForInput = (date) => date.toISOString().slice(0, 19);

            // Build the timeline URL with custom range, preserving the selected invocation
            const params = new URLSearchParams();
            params.set("time_range", "custom");
            params.set("start_date", formatForInput(paddedStart));
            params.set("end_date", formatForInput(paddedEnd));
            params.set("selected", "{{ invocation.invocation_id }}");

            // Navigate to timeline
            window.location.href = "/invocations/timeline?" + params.toString();
          })
          .catch((error) => {
            console.error("Error fetching history:", error);
            alert("Failed to load invocation history");
          });
      });

    // Re-run call functionality
    document
      .getElementById("rerun-call-btn")
      ?.addEventListener("click", function () {
        if (
          !confirm(
            "This will register a brand-new invocation with the same call arguments. " +
              "The new invocation will be completely independent. Continue?"
          )
        )
          return;

        const btn = this;
        btn.disabled = true;
        btn.innerHTML =
          '<span class="spinner-border spinner-border-sm" role="status"></span> Re-running…';

        fetch("/invocations/{{ invocation.invocation_id }}/rerun", {
          method: "POST",
        })
          .then((r) => r.json())
          .then((data) => {
            if (data.success) {
              // Navigate to the new invocation
              window.location.href = "/invocations/" + data.new_invocation_id;
            } else {
              alert("Failed to re-run: " + data.message);
              btn.disabled = false;
              btn.innerHTML =
                '<span class="material-icons" style="font-size:16px;vertical-align:middle">replay</span> Re-run Call';
            }
          })
          .catch((err) => {
            alert("Error: " + err);
            btn.disabled = false;
            btn.innerHTML =
              '<span class="material-icons" style="font-size:16px;vertical-align:middle">replay</span> Re-run Call';
          });
      });
  </script>
  {% endblock %}
</div>
