{% extends "base.html" %}

{% block content %}
<!-- Header -->
<section class="mb-2">
    <div class="grid">
        <div>
            <h1>🧠 Brain Search (Vector Admin)</h1>
            <p class="text-muted">Inspect the knowledge base by searching vectors directly.</p>
        </div>
        <div style="text-align: right;">
            <a href="/admin" role="button" class="secondary outline">← Back to Dashboard</a>
        </div>
    </div>
</section>

<!-- Search Controls -->
<section class="card">
    <div class="grid">
        <!-- Collection Select -->
        <label for="collection">
            Collection
            <select id="collection-select" onchange="performSearch()">
                <option value="" disabled selected>Loading...</option>
            </select>
        </label>

        <!-- Search Input -->
        <label for="query">
            Search Query
            <input type="search" id="query-input" placeholder="e.g. 'Wer ist die Eule?'"
                onkeydown="if(event.key==='Enter') performSearch()">
        </label>

        <!-- Action -->
        <label>
            &nbsp; <!-- Spacer -->
            <button onclick="performSearch()">Search Brain 🔍</button>
        </label>
    </div>
</section>

<!-- Results -->
<section style="margin-top: 2rem;">
    <h3 id="results-header">Results</h3>
    <div id="results-container">
        <!-- Results injected here -->
        <article class="card">
            <p class="text-muted text-center">Enter a query to search the vector database.</p>
        </article>
    </div>
</section>

<!-- Content Modal -->
<dialog id="contentModal">
    <article style="min-width: 70vw; min-height: 50vh;">
        <header>
            <button aria-label="Close" rel="prev" onclick="closeModal()"></button>
            <p>
                <strong>📄 Source Content</strong>
                <span id="modalTitle" style="margin-left: 1rem; opacity: 0.7;"></span>
            </p>
        </header>
        <div id="modalBody" style="white-space: pre-wrap; font-family: monospace; max-height: 60vh; overflow-y: auto;">
            Loading...
        </div>
    </article>
</dialog>

<script>
    async function loadCollections() {
        try {
            const res = await fetch('/admin/vectors/collections');
            const data = await res.json();
            const select = document.getElementById('collection-select');

            // Clear loading option
            select.innerHTML = '';

            if (data.collections.length === 0) {
                const opt = document.createElement('option');
                opt.text = "No collections found";
                select.add(opt);
                return;
            }

            let selectedOne = false;
            // Handle both string array and object array if format changes
            data.collections.forEach((c, index) => {
                const name = typeof c === 'string' ? c : c.name;
                const opt = document.createElement('option');
                opt.value = name;
                opt.text = name;

                // Auto-select something that looks like main content
                if (!selectedOne && (name.includes('post') || name.includes('crumbforest') || index === 0)) {
                    opt.selected = true;
                    selectedOne = true;
                }
                select.add(opt);
            });

        } catch (e) {
            console.error("Error loading collections:", e);
        }
    }

    async function performSearch() { // Renamed from searchVectors to match onchange/onclick
        const query = document.getElementById('query-input').value;
        const collection = document.getElementById('collection-select').value;
        const resultsDiv = document.getElementById('results-container');

        if (!query) return;

        resultsDiv.innerHTML = '<article aria-busy="true">Searching...</article>';

        try {
            const res = await fetch('/admin/vectors/search', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ query, collection, limit: 10 })
            });

            if (!res.ok) throw new Error(await res.text());

            const data = await res.json();

            if (data.error) throw new Error(data.error);

            const results = data.results || [];

            if (results.length === 0) {
                resultsDiv.innerHTML = '<article>No results found.</article>';
                return;
            }

            const html = results.map(r => {
                const payload = r.payload || {};
                const source = payload.title || payload.slug || 'Unknown Source';
                // Highlight matches? Maybe later.
                const content = payload.content ? payload.content.substring(0, 150).replace(/</g, "&lt;") + "..." : "No content preview";
                const scoreColor = r.score > 0.8 ? 'green' : (r.score > 0.7 ? 'orange' : 'red');
                const postId = payload.post_id || payload.id; // Try both

                const giteaBase = 'https://194-164-194-191.sslip.io/git/kruemel/Crumb-Core-v.1/src/branch/main/';
                const giteaLink = payload.file_path ? (giteaBase + payload.file_path) : null;

                return `
                <article class="card" style="margin-bottom: 1rem;">
                    <header>
                        <strong style="color: ${scoreColor}">${(r.score * 100).toFixed(1)}% Match</strong> &nbsp; 
                        <span class="badge secondary">${source}</span>
                        ${postId ? `<button class="outline contrast" style="float: right; padding: 2px 10px; font-size: 0.8em;" onclick="viewContent(${postId}, '${source}')">👀 View Full</button>` : ''}
                        ${giteaLink ? `<button class="outline secondary" style="float: right; padding: 2px 10px; font-size: 0.8em; margin-right: 0.5rem;" onclick="window.open('${giteaLink}', '_blank')">🐙 Gitea</button>` : ''}
                    </header>
                    <blockquote>${content}</blockquote>
                    <details>
                        <summary><small>View Full Payload (JSON)</small></summary>
                        <pre><code>${JSON.stringify(payload, null, 2)}</code></pre>
                    </details>
                </article>
                `;
            }).join('');

            resultsDiv.innerHTML = html;

        } catch (e) {
            resultsDiv.innerHTML = `<article class="headings"><p style="color:var(--pico-del-color)">Error: ${e.message}</p></article>`;
        }
    }

    async function viewContent(postId, title) {
        if (!postId) {
            alert("No Post ID available.");
            return;
        }

        const modal = document.getElementById('contentModal');
        const modalTitle = document.getElementById('modalTitle');
        const modalBody = document.getElementById('modalBody');

        modalTitle.innerText = title;
        modalBody.innerText = "Loading...";
        modal.showModal();

        try {
            const res = await fetch(`/admin/vectors/content/${postId}`);
            if (!res.ok) throw new Error("Content not found (might be deleted or orphaned)");

            const data = await res.json();
            modalBody.innerText = data.content || "No content text.";

        } catch (e) {
            modalBody.innerHTML = `<span style="color: red;">Error: ${e.message}</span>
            <br><small>This confirms the vector is 'Orphaned' (exists in brain, but body is gone).</small>`;
        }
    }

    function closeModal() {
        document.getElementById('contentModal').close();
    }

    // Auto-load collections
    loadCollections();
</script>

<style>
    .text-center {
        text-align: center;
    }

    blockquote {
        border-left: 4px solid var(--primary);
        padding-left: 1rem;
        background: rgba(0, 0, 0, 0.05);
        padding: 0.5rem;
    }
</style>
{% endblock %}