{% extends "themis/base.html" %}

{% block title %}{{ library.name }} — {{ themis_app_name }}{% endblock %}

{% block content %}
<div class="mb-4">
    <a href="{% url 'library:library-list' %}" class="btn btn-ghost btn-sm">← Libraries</a>
</div>

<div class="flex justify-between items-start mb-6">
    <div>
        <h1 class="text-3xl font-bold">{{ library.name }}</h1>
        <div class="flex flex-wrap gap-2 mt-2">
            <div class="badge badge-primary">{{ library.library_type }}</div>
            {% if library.managed_by_display %}
            <div class="badge badge-warning gap-1"
                 {% if library.workspace_id %}title="Workspace {{ library.workspace_id }}"{% endif %}>
                Managed by {{ library.managed_by_display }}
            </div>
            {% endif %}
        </div>
        {% if library.description %}
        <p class="mt-3 opacity-80">{{ library.description }}</p>
        {% endif %}
    </div>
    <div class="flex gap-2">
        <a href="{% url 'library:library-edit' uid=library.uid %}" class="btn btn-sm btn-outline">Edit</a>
        <a href="{% url 'library:library-delete' uid=library.uid %}" class="btn btn-sm btn-error btn-outline">Delete</a>
    </div>
</div>

{% if library.managed_by_display %}
<div class="alert alert-warning mb-6">
    <div>
        <div class="font-semibold">Managed by {{ library.managed_by_display }}</div>
        <div class="text-sm opacity-80">
            {% if library.workspace_id %}
            This library was created for workspace
            <code class="font-mono">{{ library.workspace_id }}</code>.
            Normally you manage it from {{ library.managed_by_display }}.
            Deleting it here removes its embedded content from Mnemosyne, but
            the source files still live in {{ library.managed_by_display }} —
            it will be recreated and re-embedded on the next sync.
            Use Delete to clear an orphaned library that is blocking workspace
            re-registration.
            {% else %}
            Content in this library is pushed by
            {{ library.managed_by_display }}. Edits made here may be
            overwritten or re-created on its next sync.
            {% endif %}
        </div>
    </div>
</div>
{% endif %}

<!-- Content-Type Configuration -->
<div class="collapse collapse-arrow bg-base-200 mb-6">
    <input type="checkbox" />
    <div class="collapse-title font-medium">Content-Type Configuration</div>
    <div class="collapse-content">
        <div class="grid grid-cols-1 gap-4">
            {% if library.embedding_instruction %}
            <div>
                <h4 class="font-semibold text-sm opacity-60">Embedding Instruction</h4>
                <p class="text-sm mt-1">{{ library.embedding_instruction }}</p>
            </div>
            {% endif %}
            {% if library.reranker_instruction %}
            <div>
                <h4 class="font-semibold text-sm opacity-60">Reranker Instruction</h4>
                <p class="text-sm mt-1">{{ library.reranker_instruction }}</p>
            </div>
            {% endif %}
            {% if library.llm_context_prompt %}
            <div>
                <h4 class="font-semibold text-sm opacity-60">LLM Context Prompt</h4>
                <p class="text-sm mt-1">{{ library.llm_context_prompt }}</p>
            </div>
            {% endif %}
        </div>
    </div>
</div>

<!-- Search this library -->
<div class="card bg-base-200 shadow-sm mb-6">
    <div class="card-body">
        <h2 class="card-title">Search this library</h2>
        <p class="text-sm opacity-70 -mt-1">
            Runs the query twice — once without the re-ranker, once with — so you can see what the re-ranker changed.
        </p>

        <form method="post" action="{% url 'library:library-search' uid=library.uid %}"
              enctype="multipart/form-data" class="mt-2">
            {% csrf_token %}
            <div class="flex flex-col gap-3">
                <div class="join w-full">
                    <input type="text" name="query" value="{{ search_query }}"
                           placeholder="Text query…"
                           class="input input-bordered join-item w-full">
                    <button type="submit" class="btn btn-primary join-item">Compare with re-ranker</button>
                </div>

                {% if multimodal_available %}
                <div class="form-control">
                    <label class="label py-0">
                        <span class="label-text">Image query (optional)</span>
                        <span class="label-text-alt opacity-60">used for the vector embedding when present</span>
                    </label>
                    <input type="file" name="query_image" accept="image/*"
                           class="file-input file-input-bordered file-input-sm w-full max-w-md">
                </div>
                {% else %}
                <div class="text-sm opacity-60">
                    Multimodal embeddings not configured — image search disabled.
                </div>
                {% endif %}
            </div>
        </form>

        {% if search_error %}
        <div class="alert alert-error mt-4">
            <span>{{ search_error }}</span>
        </div>
        {% endif %}

        {% if results_baseline and results_reranked %}
        <div class="stats shadow mt-4 w-full">
            <div class="stat">
                <div class="stat-title">Query mode</div>
                <div class="stat-value text-base">
                    {% if search_used_image %}
                        <span class="badge badge-secondary">image + text</span>
                    {% else %}
                        <span class="badge badge-ghost">text</span>
                    {% endif %}
                </div>
            </div>
            <div class="stat">
                <div class="stat-title">Baseline time</div>
                <div class="stat-value text-base">{{ results_baseline.search_time_ms|floatformat:0 }}ms</div>
            </div>
            <div class="stat">
                <div class="stat-title">Re-ranked time</div>
                <div class="stat-value text-base">{{ results_reranked.search_time_ms|floatformat:0 }}ms</div>
            </div>
            <div class="stat">
                <div class="stat-title">Re-ranker</div>
                <div class="stat-value text-base">
                    {% if results_reranked.reranker_used %}
                        <span class="badge badge-success">{{ results_reranked.reranker_model|default:"on" }}</span>
                    {% else %}
                        {% comment %}
                        The A/B page always requests rerank=True, so a
                        negative here is always a skip with a reason —
                        surface the reason in a tooltip so the user
                        knows *why* the B side fell back to fusion order.
                        Django's ``{# #}`` comment is single-line only;
                        multi-line blocks must use ``{% comment %}``.
                        {% endcomment %}
                        <span class="badge badge-warning"
                              title="{{ results_reranked.reranker_skip_reason|default:'unknown' }}">
                            unavailable
                        </span>
                    {% endif %}
                </div>
                {% if not results_reranked.reranker_used and results_reranked.reranker_skip_reason %}
                <div class="stat-desc text-warning text-xs mt-1 max-w-xs truncate"
                     title="{{ results_reranked.reranker_skip_reason }}">
                    {{ results_reranked.reranker_skip_reason }}
                </div>
                {% endif %}
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-4 mt-4">
            <!-- Without reranker -->
            <div>
                <h3 class="font-semibold mb-2">Without re-ranker (fusion order)</h3>
                {% if results_baseline.candidates %}
                <div class="flex flex-col gap-2">
                    {% for candidate in results_baseline.candidates %}
                    <div class="card bg-base-100 shadow-sm">
                        <div class="card-body py-3">
                            <div class="flex justify-between items-start gap-3">
                                <div class="flex-1 min-w-0">
                                    <div class="text-xs opacity-60">#{{ forloop.counter }}</div>
                                    <a href="{% url 'library:item-detail' uid=candidate.item_uid %}"
                                       class="link link-primary font-medium">
                                        {{ candidate.item_title }}
                                    </a>
                                    <span class="badge badge-xs badge-outline ml-1">chunk #{{ candidate.chunk_index }}</span>
                                    <p class="text-sm opacity-80 mt-1 line-clamp-3">{{ candidate.text_preview }}</p>
                                </div>
                                <div class="flex flex-col items-end gap-1">
                                    <span class="badge badge-primary badge-sm">{{ candidate.score|floatformat:4 }}</span>
                                    <span class="badge badge-ghost badge-xs">{{ candidate.source }}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
                {% else %}
                <div class="opacity-60 text-sm">No results.</div>
                {% endif %}
            </div>

            <!-- With reranker -->
            <div>
                <h3 class="font-semibold mb-2">With re-ranker</h3>
                {% if results_reranked.candidates %}
                <div class="flex flex-col gap-2">
                    {% for candidate in results_reranked.candidates %}
                    <div class="card bg-base-100 shadow-sm">
                        <div class="card-body py-3">
                            <div class="flex justify-between items-start gap-3">
                                <div class="flex-1 min-w-0">
                                    <div class="text-xs opacity-60 flex items-center gap-2">
                                        <span>#{{ forloop.counter }}</span>
                                        {% if candidate.rank_delta_kind == "new" %}
                                            <span class="badge badge-success badge-xs">new</span>
                                        {% elif candidate.rank_delta_kind == "up" %}
                                            <span class="badge badge-success badge-xs">{{ candidate.rank_delta_label }}</span>
                                        {% elif candidate.rank_delta_kind == "down" %}
                                            <span class="badge badge-warning badge-xs">{{ candidate.rank_delta_label }}</span>
                                        {% else %}
                                            <span class="badge badge-ghost badge-xs">=</span>
                                        {% endif %}
                                    </div>
                                    <a href="{% url 'library:item-detail' uid=candidate.item_uid %}"
                                       class="link link-primary font-medium">
                                        {{ candidate.item_title }}
                                    </a>
                                    <span class="badge badge-xs badge-outline ml-1">chunk #{{ candidate.chunk_index }}</span>
                                    <p class="text-sm opacity-80 mt-1 line-clamp-3">{{ candidate.text_preview }}</p>
                                </div>
                                <div class="flex flex-col items-end gap-1">
                                    <span class="badge badge-primary badge-sm">{{ candidate.score|floatformat:4 }}</span>
                                    <span class="badge badge-ghost badge-xs">{{ candidate.source }}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
                {% else %}
                <div class="opacity-60 text-sm">No results.</div>
                {% endif %}
            </div>
        </div>

        {% if results_reranked.images %}
        <h3 class="font-semibold mt-6 mb-2">Image results</h3>
        <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
            {% for image in results_reranked.images %}
            <div class="card bg-base-100 shadow-sm">
                <div class="card-body p-3">
                    <div class="badge badge-sm badge-outline mb-1">{{ image.image_type }}</div>
                    <p class="text-xs opacity-80 line-clamp-2">{{ image.description }}</p>
                    <div class="flex justify-between items-center mt-1">
                        <a href="{% url 'library:item-detail' uid=image.item_uid %}"
                           class="text-xs link link-primary">{{ image.item_title|truncatechars:30 }}</a>
                        <span class="badge badge-primary badge-xs">{{ image.score|floatformat:3 }}</span>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>
        {% endif %}
        {% endif %}
    </div>
</div>

<!-- Collections -->
<div class="flex justify-between items-center mb-4">
    <h2 class="text-xl font-bold">Collections</h2>
    <a href="{% url 'library:collection-create' library_uid=library.uid %}" class="btn btn-sm btn-primary">
        + New Collection
    </a>
</div>

{% if collections %}
<div class="overflow-x-auto">
    <table class="table table-zebra w-full">
        <thead>
            <tr>
                <th>Name</th>
                <th>Description</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            {% for col in collections %}
            <tr>
                <td>
                    <a href="{% url 'library:collection-detail' uid=col.uid %}" class="link link-hover font-medium">
                        {{ col.name }}
                    </a>
                </td>
                <td class="opacity-70">{{ col.description|truncatewords:15 }}</td>
                <td>
                    <a href="{% url 'library:collection-detail' uid=col.uid %}" class="btn btn-xs btn-ghost">View</a>
                    <a href="{% url 'library:collection-edit' uid=col.uid %}" class="btn btn-xs btn-ghost">Edit</a>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</div>
{% else %}
<div class="text-center py-8 opacity-60">
    <p>No collections in this library yet.</p>
</div>
{% endif %}
{% endblock %}
