{% extends "base.html" %}

{% block content %}
{% if trace %}
<div class="trace-summary card">
    <div class="trace-meta">
        <span class="badge badge-{{ trace.status }}">{{ trace.status }}</span>
        <span>Duration: {{ trace.total_duration_ms | default('-') }}ms</span>
        <span>Cost: ${{ "%.6f" | format(trace.total_cost | default(0) | float) }}</span>
        <span>Tokens: {{ "{:,}".format(trace.total_input_tokens | default(0) | int) }}in / {{ "{:,}".format(trace.total_output_tokens | default(0) | int) }}out ({{ "{:,}".format(trace.total_tokens | default(0) | int) }} total)</span>
        <span>Spans: {{ trace.span_count | default(0) }}</span>
    </div>
    <div class="trace-id">Trace: {{ trace.trace_id }}</div>
    <div class="trace-time">Created: {{ trace.created_at }}</div>
</div>

{% if trace.entry_input %}
<section class="card">
    <h3>Input</h3>
    <pre class="code-block">{{ trace.entry_input }}</pre>
</section>
{% endif %}

{% if trace.final_output %}
<section class="card">
    <h3>Output</h3>
    <pre class="code-block">{{ trace.final_output }}</pre>
</section>
{% endif %}

{# ══════════════════════════════════════════════════════════════
   RECURSIVE SPAN MACRO — renders a span and all its children
   ══════════════════════════════════════════════════════════════ #}
{% macro render_span(span, tool_calls, is_last) %}
<div class="tree-node {{ 'tree-node--last' if is_last else '' }}">
    {# ── Connector line ── #}
    <div class="tree-connector">
        <div class="tree-line-v"></div>
        <div class="tree-dot tree-dot--{{ span.span_type }}"></div>
    </div>

    {# ── Span content ── #}
    <div class="tree-body">
        {# ── Header row ── #}
        <div class="span-header" data-span-toggle>
            <span class="toggle-arrow">&#9654;</span>

            {% if span.span_type == 'agent' %}
            <span class="span-type-badge span-type-badge--agent">AGENT</span>
            {% elif span.span_type == 'llm' %}
            <span class="span-type-badge span-type-badge--llm">LLM</span>
            {% else %}
            <span class="span-type-badge span-type-badge--tool">TOOL</span>
            {% endif %}

            <span class="span-name">{{ span.component_class }} <span class="span-label">"{{ span.component_name }}"</span></span>
            <span class="span-duration">({{ span.duration_ms | default('?') }}ms)</span>
            <span class="badge badge-{{ span.status }}">{{ span.status }}</span>

            {% if span.input_tokens %}
            <span class="token-summary">{{ span.input_tokens }}in / {{ span.output_tokens | default(0) }}out{% if span.cached_tokens %} ({{ span.cached_tokens }} cached){% endif %}</span>
            {% endif %}
            {% if span.total_cost %}
            <span class="cost-summary">${{ "%.6f" | format(span.total_cost | float) }}</span>
            {% endif %}
        </div>

        {# ── Waterfall timeline bar ── #}
        {% if span.waterfall_left_pct is defined and span.waterfall_width_pct is defined %}
        <div class="waterfall-bar-container">
            <div class="waterfall-bar waterfall-bar--{{ span.span_type }}"
                 style="left: {{ span.waterfall_left_pct }}%; width: {{ span.waterfall_width_pct }}%;"
                 title="{{ span.duration_ms | default('?') }}ms"></div>
        </div>
        {% endif %}

        {# ── Expandable details ── #}
        <div class="span-details" style="display:none;">
            {# ── Summary row ── #}
            {% if span.model %}
            <div class="detail-row"><strong>Model:</strong> {{ span.model }}</div>
            {% endif %}
            {% if span.error_message %}
            <div class="detail-row error"><strong>Error:</strong> {{ span.error_message }}</div>
            {% endif %}

            {# ══════════ LLM SPAN DETAILS ══════════ #}
            {% if span.span_type == 'llm' %}

            {# -- Tokens & Cost -- #}
            {% if span.input_tokens is not none %}
            <div class="detail-section">
                <div class="detail-section-header" onclick="toggleSection(this)">
                    <span class="section-arrow">&#9654;</span> Tokens & Cost
                </div>
                <div class="detail-section-body" style="display:none;">
                    <table class="detail-kv-table">
                        <tr><td>Input Tokens</td><td>{{ "{:,}".format(span.input_tokens | default(0) | int) }}{% if span.input_cost is not none %} <span class="cost-inline">(${{ "%.6f" | format(span.input_cost | float) }})</span>{% endif %}</td></tr>
                        {% if span.cached_tokens %}<tr><td>  Cached Input Tokens</td><td>{{ "{:,}".format(span.cached_tokens | int) }}{% if span.cached_cost is not none %} <span class="cost-inline">(${{ "%.6f" | format(span.cached_cost | float) }})</span>{% endif %}</td></tr>{% endif %}
                        <tr><td>Output Tokens</td><td>{{ "{:,}".format(span.output_tokens | default(0) | int) }}{% if span.output_cost is not none %} <span class="cost-inline">(${{ "%.6f" | format(span.output_cost | float) }})</span>{% endif %}</td></tr>
                        {% if span.reasoning_tokens %}<tr><td>Reasoning Tokens</td><td>{{ "{:,}".format(span.reasoning_tokens | int) }}{% if span.reasoning_cost is not none %} <span class="cost-inline">(${{ "%.6f" | format(span.reasoning_cost | float) }})</span>{% endif %}</td></tr>{% endif %}
                        <tr><td>Total Tokens</td><td>{{ "{:,}".format(span.total_tokens | default(0) | int) }}</td></tr>
                        {% if span.total_cost is not none %}<tr><td><strong>Total Cost</strong></td><td><strong>${{ "%.6f" | format(span.total_cost | float) }}</strong></td></tr>{% endif %}
                    </table>
                </div>
            </div>
            {% endif %}

            {# -- Configuration -- #}
            <div class="detail-section">
                <div class="detail-section-header" onclick="toggleSection(this)">
                    <span class="section-arrow">&#9654;</span> Configuration
                </div>
                <div class="detail-section-body" style="display:none;">
                    <table class="detail-kv-table">
                        {% if span.llm_model %}<tr><td>Model</td><td>{{ span.llm_model }}</td></tr>{% endif %}
                        {% if span.llm_provider %}<tr><td>Provider</td><td>{{ span.llm_provider }}</td></tr>{% endif %}
                        {% if span.llm_api_type %}<tr><td>API Type</td><td>{{ span.llm_api_type }}</td></tr>{% endif %}
                        {% if span.llm_temperature is not none %}<tr><td>Temperature</td><td>{{ span.llm_temperature }}</td></tr>{% endif %}
                        {% if span.llm_max_output_tokens is not none %}<tr><td>Max Output Tokens</td><td>{{ span.llm_max_output_tokens }}</td></tr>{% endif %}
                        {% if span.llm_top_p is not none %}<tr><td>Top P</td><td>{{ span.llm_top_p }}</td></tr>{% endif %}
                        {% if span.llm_reasoning_enabled is not none %}<tr><td>Reasoning Enabled</td><td>{{ span.llm_reasoning_enabled }}</td></tr>{% endif %}
                        {% if span.llm_reasoning_effort %}<tr><td>Reasoning Effort</td><td>{{ span.llm_reasoning_effort }}</td></tr>{% endif %}
                        {% if span.llm_streaming is not none %}<tr><td>Streaming</td><td>{{ span.llm_streaming }}</td></tr>{% endif %}
                        {% if span.stop_reason %}<tr><td>Stop Reason</td><td>{{ span.stop_reason }}</td></tr>{% endif %}
                        {% if span.llm_response_id %}<tr><td>Response ID</td><td class="mono">{{ span.llm_response_id }}</td></tr>{% endif %}
                    </table>
                </div>
            </div>

            {# -- Tools -- #}
            {% if span.llm_tool_names %}
            <div class="detail-section">
                <div class="detail-section-header" onclick="toggleSection(this)">
                    <span class="section-arrow">&#9654;</span> Tools ({{ span.llm_tool_names | length }})
                </div>
                <div class="detail-section-body" style="display:none;">
                    {% for tool in span.llm_tool_names %}
                    {% if tool is mapping %}
                    <div class="tool-detail-card">
                        <div class="tool-detail-header" onclick="toggleSection(this)">
                            <span class="section-arrow">&#9654;</span>
                            <span class="tool-detail-name">{{ tool.name }}</span>
                            {% if tool.description %}
                            <span class="tool-description-preview">{{ tool.description[:80] }}{% if tool.description | length > 80 %}...{% endif %}</span>
                            {% endif %}
                        </div>
                        <div class="detail-section-body" style="display:none;">
                            {% if tool.description %}
                            <div class="tool-subsection">
                                <div class="tool-subsection-label">Description:</div>
                                <div class="tool-description-full">{{ tool.description }}</div>
                            </div>
                            {% endif %}
                            {% if tool.parameters %}
                            <div class="tool-subsection">
                                <div class="tool-subsection-label">Parameters:</div>
                                <pre class="code-block code-block-sm">{{ tool.parameters | pretty_json }}</pre>
                            </div>
                            {% endif %}
                        </div>
                    </div>
                    {% else %}
                    <span class="tool-name-chip">{{ tool }}</span>
                    {% endif %}
                    {% endfor %}
                </div>
            </div>
            {% endif %}

            {# -- System Prompt -- #}
            {% if span.llm_system_prompt %}
            <div class="detail-section">
                <div class="detail-section-header" onclick="toggleSection(this)">
                    <span class="section-arrow">&#9654;</span> System Prompt
                </div>
                <div class="detail-section-body" style="display:none;">
                    <pre class="code-block">{{ span.llm_system_prompt }}</pre>
                </div>
            </div>
            {% endif %}

            {# -- Input Messages -- #}
            {% if span.llm_input_messages %}
            <div class="detail-section">
                <div class="detail-section-header" onclick="toggleSection(this)">
                    <span class="section-arrow">&#9654;</span> Input Messages ({{ span.llm_input_message_count | default('?') }})
                </div>
                <div class="detail-section-body" style="display:none;">
                    <pre class="code-block">{{ span.llm_input_messages | pretty_json }}</pre>
                </div>
            </div>
            {% endif %}

            {# -- Output -- #}
            {% if span.llm_output_text %}
            <div class="detail-section">
                <div class="detail-section-header" onclick="toggleSection(this)">
                    <span class="section-arrow">&#9654;</span> Output Text
                </div>
                <div class="detail-section-body" style="display:none;">
                    <pre class="code-block">{{ span.llm_output_text }}</pre>
                </div>
            </div>
            {% endif %}

            {# -- Output Content (structured) -- #}
            {% if span.llm_output_content %}
            <div class="detail-section">
                <div class="detail-section-header" onclick="toggleSection(this)">
                    <span class="section-arrow">&#9654;</span> Output Content (structured)
                </div>
                <div class="detail-section-body" style="display:none;">
                    <pre class="code-block">{{ span.llm_output_content | pretty_json }}</pre>
                </div>
            </div>
            {% endif %}

            {# -- Reasoning -- #}
            {% if span.llm_reasoning_text %}
            <div class="detail-section">
                <div class="detail-section-header" onclick="toggleSection(this)">
                    <span class="section-arrow">&#9654;</span> Reasoning
                </div>
                <div class="detail-section-body" style="display:none;">
                    <pre class="code-block">{{ span.llm_reasoning_text }}</pre>
                </div>
            </div>
            {% endif %}

            {# -- Full Config Snapshot -- #}
            {% if span.llm_config_snapshot %}
            <div class="detail-section">
                <div class="detail-section-header" onclick="toggleSection(this)">
                    <span class="section-arrow">&#9654;</span> Full Config Snapshot
                </div>
                <div class="detail-section-body" style="display:none;">
                    <pre class="code-block">{{ span.llm_config_snapshot | pretty_json }}</pre>
                </div>
            </div>
            {% endif %}

            {% endif %}{# end LLM #}

            {# ══════════ AGENT SPAN DETAILS ══════════ #}
            {% if span.span_type == 'agent' %}

            {# -- Agent Summary -- #}
            <div class="detail-section">
                <div class="detail-section-header" onclick="toggleSection(this)">
                    <span class="section-arrow">&#9654;</span> Agent Summary
                </div>
                <div class="detail-section-body" style="display:none;">
                    <table class="detail-kv-table">
                        {% if span.agent_detail_name %}<tr><td>Agent Name</td><td>{{ span.agent_detail_name }}</td></tr>{% endif %}
                        {% if span.agent_detail_class %}<tr><td>Agent Class</td><td>{{ span.agent_detail_class }}</td></tr>{% endif %}
                        {% if span.iteration_count is not none %}<tr><td>Iterations</td><td>{{ span.iteration_count }}</td></tr>{% endif %}
                        {% if span.agent_total_llm_calls is not none %}<tr><td>Total LLM Calls</td><td>{{ span.agent_total_llm_calls }}</td></tr>{% endif %}
                        {% if span.agent_tool_count is not none %}<tr><td>Tools Available</td><td>{{ span.agent_tool_count }}</td></tr>{% endif %}
                        {% if span.agent_sub_agent_count is not none %}<tr><td>Sub-Agents</td><td>{{ span.agent_sub_agent_count }}</td></tr>{% endif %}
                        {% if span.agent_input_message_count is not none %}<tr><td>Input Messages</td><td>{{ span.agent_input_message_count }}</td></tr>{% endif %}
                    </table>
                </div>
            </div>

            {# -- Tools -- #}
            {% if span.agent_tool_names %}
            <div class="detail-section">
                <div class="detail-section-header" onclick="toggleSection(this)">
                    <span class="section-arrow">&#9654;</span> Tools ({{ span.agent_tool_names | length }})
                </div>
                <div class="detail-section-body" style="display:none;">
                    {% for tool in span.agent_tool_names %}
                    {% if tool is mapping %}
                    <div class="tool-detail-card">
                        <div class="tool-detail-header" onclick="toggleSection(this)">
                            <span class="section-arrow">&#9654;</span>
                            <span class="tool-detail-name">{{ tool.name }}</span>
                            {% if tool.description %}
                            <span class="tool-description-preview">{{ tool.description[:80] }}{% if tool.description | length > 80 %}...{% endif %}</span>
                            {% endif %}
                        </div>
                        <div class="detail-section-body" style="display:none;">
                            {% if tool.description %}
                            <div class="tool-subsection">
                                <div class="tool-subsection-label">Description:</div>
                                <div class="tool-description-full">{{ tool.description }}</div>
                            </div>
                            {% endif %}
                            {% if tool.parameters %}
                            <div class="tool-subsection">
                                <div class="tool-subsection-label">Parameters:</div>
                                <pre class="code-block code-block-sm">{{ tool.parameters | pretty_json }}</pre>
                            </div>
                            {% endif %}
                        </div>
                    </div>
                    {% else %}
                    <span class="tool-name-chip">{{ tool }}</span>
                    {% endif %}
                    {% endfor %}
                </div>
            </div>
            {% endif %}

            {# -- Tool Interactions -- #}
            {% if span.agent_tool_interactions %}
            <div class="detail-section">
                <div class="detail-section-header" onclick="toggleSection(this)">
                    <span class="section-arrow">&#9654;</span> Tool Interactions ({{ span.agent_tool_interactions | length }})
                </div>
                <div class="detail-section-body" style="display:none;">
                    {% for ti in span.agent_tool_interactions %}
                    <div class="tool-call-card {% if ti.is_error %}tool-call-error{% endif %}">
                        <div class="tool-call-header" onclick="toggleSection(this)">
                            <span class="section-arrow">&#9654;</span>
                            <strong>{{ ti.tool_name | default('unknown') }}</strong>
                            <span class="badge badge-{{ 'failed' if ti.is_error else 'completed' }}">{{ 'error' if ti.is_error else 'ok' }}</span>
                            {% if ti.iteration is defined %}
                            <span class="tool-meta">iter={{ ti.iteration }}</span>
                            {% endif %}
                        </div>
                        <div class="detail-section-body" style="display:none;">
                            {% if ti.arguments %}
                            <div class="tool-subsection">
                                <div class="tool-subsection-label">Arguments:</div>
                                <pre class="code-block code-block-sm">{{ ti.arguments | pretty_json if ti.arguments is mapping else ti.arguments }}</pre>
                            </div>
                            {% endif %}
                            {% if ti.result %}
                            <div class="tool-subsection">
                                <div class="tool-subsection-label">Result:</div>
                                <pre class="code-block code-block-sm">{{ ti.result | pretty_json if ti.result is mapping else ti.result }}</pre>
                            </div>
                            {% endif %}
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
            {% endif %}

            {# -- System Prompt -- #}
            {% if span.agent_system_prompt %}
            <div class="detail-section">
                <div class="detail-section-header" onclick="toggleSection(this)">
                    <span class="section-arrow">&#9654;</span> System Prompt
                </div>
                <div class="detail-section-body" style="display:none;">
                    <pre class="code-block">{{ span.agent_system_prompt }}</pre>
                </div>
            </div>
            {% endif %}

            {# -- User Prompt Template -- #}
            {% if span.agent_user_prompt_template %}
            <div class="detail-section">
                <div class="detail-section-header" onclick="toggleSection(this)">
                    <span class="section-arrow">&#9654;</span> User Prompt Template
                </div>
                <div class="detail-section-body" style="display:none;">
                    <pre class="code-block">{{ span.agent_user_prompt_template }}</pre>
                </div>
            </div>
            {% endif %}

            {# -- Input Messages -- #}
            {% if span.agent_input_messages %}
            <div class="detail-section">
                <div class="detail-section-header" onclick="toggleSection(this)">
                    <span class="section-arrow">&#9654;</span> Input Messages ({{ span.agent_input_message_count | default('?') }})
                </div>
                <div class="detail-section-body" style="display:none;">
                    <pre class="code-block">{{ span.agent_input_messages | pretty_json }}</pre>
                </div>
            </div>
            {% endif %}

            {# -- Output -- #}
            {% if span.agent_output_text %}
            <div class="detail-section">
                <div class="detail-section-header" onclick="toggleSection(this)">
                    <span class="section-arrow">&#9654;</span> Output Text
                </div>
                <div class="detail-section-body" style="display:none;">
                    <pre class="code-block">{{ span.agent_output_text }}</pre>
                </div>
            </div>
            {% endif %}

            {# -- Output Content (structured) -- #}
            {% if span.agent_output_content %}
            <div class="detail-section">
                <div class="detail-section-header" onclick="toggleSection(this)">
                    <span class="section-arrow">&#9654;</span> Output Content (structured)
                </div>
                <div class="detail-section-body" style="display:none;">
                    <pre class="code-block">{{ span.agent_output_content | pretty_json }}</pre>
                </div>
            </div>
            {% endif %}

            {# -- Context -- #}
            {% if span.agent_context %}
            <div class="detail-section">
                <div class="detail-section-header" onclick="toggleSection(this)">
                    <span class="section-arrow">&#9654;</span> Context
                </div>
                <div class="detail-section-body" style="display:none;">
                    <pre class="code-block">{{ span.agent_context | pretty_json }}</pre>
                </div>
            </div>
            {% endif %}

            {# -- Full Config Snapshot -- #}
            {% if span.agent_config_snapshot %}
            <div class="detail-section">
                <div class="detail-section-header" onclick="toggleSection(this)">
                    <span class="section-arrow">&#9654;</span> Full Config Snapshot
                </div>
                <div class="detail-section-body" style="display:none;">
                    <pre class="code-block">{{ span.agent_config_snapshot | pretty_json }}</pre>
                </div>
            </div>
            {% endif %}

            {% endif %}{# end Agent #}

            {# ══════════ TOOL CALLS ══════════ #}
            {% set span_tools = tool_calls.get(span.span_id, []) if tool_calls else [] %}
            {% if span_tools %}
            <div class="detail-section">
                <div class="detail-section-header" onclick="toggleSection(this)">
                    <span class="section-arrow">&#9654;</span> Tool Calls ({{ span_tools | length }})
                </div>
                <div class="detail-section-body" style="display:none;">
                    {% for tc in span_tools %}
                    <div class="tool-call-card {% if tc.is_error %}tool-call-error{% endif %}">
                        <div class="tool-call-header" onclick="toggleSection(this)">
                            <span class="section-arrow">&#9654;</span>
                            <strong>{{ tc.tool_name }}</strong>
                            <span class="badge badge-{{ 'failed' if tc.is_error else 'completed' }}">{{ 'error' if tc.is_error else 'ok' }}</span>
                            <span class="duration">({{ tc.duration_ms | default('?') }}ms)</span>
                            <span class="tool-meta">iter={{ tc.iteration_number }} seq={{ tc.sequence_in_batch }}</span>
                        </div>
                        <div class="detail-section-body" style="display:none;">
                            {% if tc.arguments %}
                            <div class="tool-subsection">
                                <div class="tool-subsection-label">Arguments:</div>
                                <pre class="code-block code-block-sm">{{ tc.arguments | pretty_json }}</pre>
                            </div>
                            {% endif %}
                            {% if tc.result_content %}
                            <div class="tool-subsection">
                                <div class="tool-subsection-label">Result:</div>
                                <pre class="code-block code-block-sm">{{ tc.result_content }}</pre>
                            </div>
                            {% endif %}
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
            {% endif %}

        </div>{# end span-details #}

        {# ── Children (recursive) ── #}
        {% if span.children %}
        <div class="tree-children">
            {% for child in span.children %}
                {{ render_span(child, tool_calls, loop.last) }}
            {% endfor %}
        </div>
        {% endif %}

    </div>{# end tree-body #}
</div>{# end tree-node #}
{% endmacro %}

{# ══════════════════════════════════════════════════════════════ #}

<section class="card">
    <h3>Chain View</h3>
    <div class="chain-controls">
        <button class="btn btn-secondary btn-sm" onclick="expandAllNodes()">Expand All</button>
        <button class="btn btn-secondary btn-sm" onclick="collapseAllNodes()">Collapse All</button>
    </div>
    <div class="span-tree">
        {% for span in root_spans %}
            {{ render_span(span, tool_calls, loop.last) }}
        {% endfor %}
    </div>
</section>
{% else %}
<div class="card">
    <p>Trace not found.</p>
</div>
{% endif %}
{% endblock %}
