{% extends 'admin/base.html.twig' %}

{% block title %}Ingest Job{% endblock %}

{% block body %}

    {% set jobStatus = job.status|upper %}
    {% set isActiveJob = jobStatus in ['QUEUED', 'RUNNING'] %}

    <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2">
        <div>
            <h1 class="h3 mb-1">
                <i class="bi bi-terminal"></i> Ingest Job
            </h1>
            <div class="small text-muted">
                Detailansicht für einen einzelnen Indexierungs- oder Rebuild-Job.
            </div>
        </div>

        <a href="{{ path('admin_jobs') }}"
           class="btn btn-sm btn-outline-secondary">
            Zurück zur Übersicht
        </a>
    </div>

    <div class="card bg-dark border-secondary text-light mb-4 shadow-sm">
        <div class="card-body row g-4">
            <div class="col-lg-7">
                <h5 class="text-info mb-3">Einordnung</h5>
                <ul class="small mb-0">
                    <li><strong>DOCUMENT</strong> verarbeitet ein einzelnes Dokument neu.</li>
                    <li><strong>DOCUMENT_VERSION_ACTIVATE</strong> aktiviert eine Version und zieht sie deterministisch neu in den Index.</li>
                    <li><strong>DOCUMENT_DELETE</strong> entfernt Dokumentinhalt wieder sauber aus dem Wissensbestand.</li>
                    <li><strong>GLOBAL_REINDEX</strong> baut den Gesamtindex vollständig neu auf.</li>
                </ul>
            </div>

            <div class="col-lg-5">
                <h5 class="text-info mb-3">Aktueller Zustand</h5>
                <div class="d-flex flex-wrap gap-2">
                    {% if jobStatus == 'COMPLETED' %}
                        <span class="badge bg-success">COMPLETED</span>
                    {% elseif jobStatus == 'QUEUED' %}
                        <span class="badge bg-secondary">QUEUED</span>
                    {% elseif jobStatus == 'RUNNING' %}
                        <span class="badge bg-warning text-dark">RUNNING</span>
                    {% elseif jobStatus == 'FAILED' %}
                        <span class="badge bg-danger">FAILED</span>
                    {% elseif jobStatus == 'ABORTED' %}
                        <span class="badge bg-dark border border-danger text-danger">ABORTED</span>
                    {% else %}
                        <span class="badge bg-dark border border-secondary">{{ jobStatus }}</span>
                    {% endif %}

                    {% if isActiveJob %}
                        <span class="badge text-bg-info">Polling aktiv</span>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>

    <div class="card bg-black border-secondary text-light shadow-sm">
        <div class="card-body">

            <div class="row g-4">
                <div class="col-lg-6">
                    <div class="mb-3">
                        <div class="small text-muted mb-1">Job-ID</div>
                        <div class="fw-semibold small text-light">{{ job.id }}</div>
                    </div>

                    <div class="mb-3">
                        <div class="small text-muted mb-1">Typ</div>
                        <div>
                            <span class="badge bg-info text-dark">{{ job.type }}</span>
                        </div>
                    </div>

                    <div class="mb-3">
                        <div class="small text-muted mb-1">Status</div>
                        <div id="job-status-badge">
                            {% if jobStatus == 'COMPLETED' %}
                                <span class="badge bg-success">COMPLETED</span>
                            {% elseif jobStatus == 'QUEUED' %}
                                <span class="badge bg-secondary">QUEUED</span>
                            {% elseif jobStatus == 'RUNNING' %}
                                <span class="badge bg-warning text-dark">RUNNING</span>
                            {% elseif jobStatus == 'FAILED' %}
                                <span class="badge bg-danger">FAILED</span>
                            {% elseif jobStatus == 'ABORTED' %}
                                <span class="badge bg-dark border border-danger text-danger">ABORTED</span>
                            {% else %}
                                <span class="badge bg-dark border border-secondary">{{ jobStatus }}</span>
                            {% endif %}
                        </div>
                    </div>

                    <div class="mb-3">
                        <div class="small text-muted mb-1">Dokument</div>
                        <div>
                            {% if job.documentId %}
                                <a href="{{ path('admin_document_show', {id: job.documentId}) }}"
                                   class="text-light text-decoration-none">
                                    {{ job.documentId }}
                                </a>
                            {% else %}
                                -
                            {% endif %}
                        </div>
                    </div>

                    <div class="mb-0">
                        <div class="small text-muted mb-1">Dokumentversion</div>
                        <div>{{ job.documentVersionId ?? '-' }}</div>
                    </div>
                </div>

                <div class="col-lg-6">
                    <div class="mb-3">
                        <div class="small text-muted mb-1">Gestartet</div>
                        <div>
                            {{ job.startedAt ? job.startedAt|date('d.m.Y H:i:s') : '-' }}
                        </div>
                    </div>

                    <div class="mb-3">
                        <div class="small text-muted mb-1">Beendet</div>
                        <div id="job-finished-at">
                            {{ job.finishedAt ? job.finishedAt|date('d.m.Y H:i:s') : '-' }}
                        </div>
                    </div>

                    <div class="mb-3">
                        <div class="small text-muted mb-1">Gestartet von</div>
                        <div>{{ job.startedBy ? job.startedBy.email : '-' }}</div>
                    </div>

                    <div class="mb-0">
                        <div class="small text-muted mb-1">Polling</div>
                        <div class="small text-light">
                            {% if isActiveJob %}
                                Status wird automatisch aktualisiert.
                            {% else %}
                                Kein Live-Polling nötig.
                            {% endif %}
                        </div>
                    </div>
                </div>
            </div>

            <div id="job-loader"
                 class="mt-4 {% if not isActiveJob %}d-none{% endif %}">
                <div class="d-flex align-items-center gap-2">
                    <div class="spinner-border spinner-border-sm text-info" role="status"></div>
                    <div>
                        <strong>Prozess läuft…</strong><br>
                        <small class="text-secondary">
                            Der Status wird automatisch aktualisiert.
                        </small>
                    </div>
                </div>
            </div>

            <div id="job-error"
                 class="alert alert-danger mt-4 {% if not job.errorMessage %}d-none{% endif %}">
                {% if job.errorMessage %}
                    <strong>Fehler:</strong><br>
                    {{ job.errorMessage }}
                {% endif %}
            </div>

        </div>
    </div>

    <div class="mt-4 small text-secondary">
        Hinweis: Bei <strong>DOCUMENT_VERSION_ACTIVATE</strong>-Jobs wird ein vollständiger
        NDJSON-Rebuild und FAISS-Reindex durchgeführt. Bei <strong>GLOBAL_REINDEX</strong>
        wird der gesamte Wissensindex neu aufgebaut.
    </div>

    <script>
        (function () {
            const statusUrl = {{ path('admin_job_status', {id: job.id})|json_encode|raw }};
            const badgeWrap = document.getElementById('job-status-badge');
            const finishedAtEl = document.getElementById('job-finished-at');
            const loaderEl = document.getElementById('job-loader');
            const errorEl = document.getElementById('job-error');

            let timer = null;

            function escapeHtml(value) {
                return String(value)
                    .replaceAll('&', '&amp;')
                    .replaceAll('<', '&lt;')
                    .replaceAll('>', '&gt;')
                    .replaceAll('"', '&quot;')
                    .replaceAll("'", '&#039;');
            }

            function renderBadge(status) {
                const map = {
                    COMPLETED: 'bg-success',
                    QUEUED: 'bg-secondary',
                    RUNNING: 'bg-warning text-dark',
                    FAILED: 'bg-danger',
                    ABORTED: 'bg-dark border border-danger text-danger'
                };

                const css = map[status] || 'bg-dark border border-secondary';
                badgeWrap.innerHTML = `<span class="badge ${css}">${escapeHtml(status || 'UNKNOWN')}</span>`;
            }

            function stopPolling() {
                if (timer) {
                    clearInterval(timer);
                    timer = null;
                }
            }

            function renderError(message) {
                if (!message) {
                    errorEl.classList.add('d-none');
                    errorEl.innerHTML = '';
                    return;
                }

                errorEl.classList.remove('d-none');
                errorEl.innerHTML = `<strong>Fehler:</strong><br>${escapeHtml(message)}`;
            }

            async function poll() {
                try {
                    const res = await fetch(statusUrl, {
                        headers: {
                            'Accept': 'application/json'
                        },
                        cache: 'no-store'
                    });

                    if (!res.ok) {
                        stopPolling();
                        return;
                    }

                    const data = await res.json();
                    const status = String(data.status || '').toUpperCase();

                    renderBadge(status);

                    finishedAtEl.textContent = data.finishedAt
                        ? new Date(data.finishedAt).toLocaleString('de-DE')
                        : '-';

                    if (status === 'QUEUED' || status === 'RUNNING') {
                        loaderEl.classList.remove('d-none');
                    } else {
                        loaderEl.classList.add('d-none');
                        stopPolling();
                    }

                    if (status === 'FAILED' || status === 'ABORTED') {
                        renderError(data.errorMessage || '');
                    } else {
                        renderError('');
                    }
                } catch (e) {
                    stopPolling();
                }
            }

            renderBadge({{ jobStatus|json_encode|raw }});

            if ({{ isActiveJob ? 'true' : 'false' }}) {
                timer = setInterval(poll, 2000);
            }
        })();
    </script>

{% endblock %}