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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f4d5d0
2903edf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568

// Global application state
let currentResults = [];
let currentMode = 'single';

// Initialization
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
});

function initializeApp() {
    setupTabHandlers();
    setupKeyboardHandlers();
    updateHeaderStats('Ready');
}

// Tab management
function setupTabHandlers() {
    document.querySelectorAll('.tab-button').forEach(button => {
        button.addEventListener('click', function() {
            const mode = this.dataset.mode;
            switchMode(mode);
        });
    });
}

function switchMode(mode) {
    currentMode = mode;
    
    // Update tabs
    document.querySelectorAll('.tab-button').forEach(btn => {
        btn.classList.remove('active');
    });
    document.querySelector(`[data-mode="${mode}"]`).classList.add('active');
    
    // Update forms
    document.querySelectorAll('.search-form').forEach(form => {
        form.classList.remove('active');
    });
    document.getElementById(`${mode}-form`).classList.add('active');
    
    // Reset results
    hideResults();
}

// Show version field only when the input looks like a spec (ETSI or 3GPP)
const ETSI_SPEC_RE = /^\d{3} \d{3}/;
const ETSI_TDOC_RE = /^(?:SET|SCP|SETTEC|SETREQ|SCPTEC|SCPREQ)\(\d+\)\d+/i;
const GPP_SPEC_RE  = /^\d{2}\.\d{3}/;

function toggleVersionField() {
    const docId = document.getElementById('doc-id').value.trim();
    const versionGroup = document.getElementById('single-version-group');
    const formatGroup  = document.getElementById('single-format-group');
    const isSpec     = ETSI_SPEC_RE.test(docId) || GPP_SPEC_RE.test(docId);
    const isEtsiSpec = ETSI_SPEC_RE.test(docId);
    versionGroup.style.display = isSpec     ? 'block' : 'none';
    formatGroup.style.display  = isEtsiSpec ? 'block' : 'none';
    if (!isSpec)     document.getElementById('doc-version').value = '';
    if (!isEtsiSpec) document.getElementById('doc-format').value  = 'pdf';
}

// Keyboard shortcuts management
function setupKeyboardHandlers() {
    document.getElementById('doc-id').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') searchSingle();
    });
    
    document.getElementById('keywords').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') searchKeyword();
    });
    
    document.getElementById('bm25-keywords').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') searchBM25();
    });
}

// Search functions
async function searchSingle() {
    const docId = document.getElementById('doc-id').value.trim();

    if (!docId) {
        showError('Please enter a document ID');
        return;
    }

    const format = document.getElementById('doc-format').value || 'pdf';
    const isDocx = ETSI_SPEC_RE.test(docId) && format === 'docx';

    if (isDocx) {
        downloadDocx(docId);
        return;
    }

    showLoading();
    updateHeaderStats('Searching...');

    try {
        const version = document.getElementById('doc-version').value.trim() || null;
        const body = { doc_id: docId };
        if (version) body.version = version;

        const response = await fetch(`/find/single`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(body)
        });

        const data = await response.json();

        if (response.ok) {
            displaySingleResult(data);
            updateHeaderStats(`Found in ${data.search_time.toFixed(3)}s`);
        } else {
            showError(data.detail);
            updateHeaderStats('Error');
        }
    } catch (error) {
        showError('Error connecting to server');
        updateHeaderStats('Error');
        console.error('Error:', error);
    } finally {
        hideLoading();
    }
}

async function downloadDocx(docId) {
    showLoading();
    updateHeaderStats('Downloading DOCX...');

    try {
        const version = document.getElementById('doc-version').value.trim() || null;
        const body = { doc_id: docId };
        if (version) body.version = version;

        const response = await fetch('/find/docx', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(body)
        });

        if (response.ok) {
            const blob = await response.blob();
            const disposition = response.headers.get('Content-Disposition') || '';
            const fnMatch = disposition.match(/filename="?([^";\n]+)"?/);
            const filename = fnMatch ? fnMatch[1] : `${docId.replace(/ /g, '_')}.docx`;
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            updateHeaderStats('DOCX downloaded');
        } else {
            const data = await response.json();
            showError(data.detail);
            updateHeaderStats('Error');
        }
    } catch (error) {
        showError('Error connecting to server');
        updateHeaderStats('Error');
        console.error('Error:', error);
    } finally {
        hideLoading();
    }
}

async function searchBatch() {
    const batchText = document.getElementById('batch-ids').value.trim();
    
    if (!batchText) {
        showError('Please enter at least one document ID');
        return;
    }
    
    const docIds = batchText.split('\n')
        .map(id => id.trim())
        .filter(id => id !== '');
    
    if (docIds.length === 0) {
        showError('Please enter at least one valid document ID');
        return;
    }
    
    showLoading();
    updateHeaderStats('Searching...');
    
    try {
        const version = document.getElementById('batch-version').value.trim() || null;
        const body = { doc_ids: docIds };
        if (version) body.version = version;

        const response = await fetch(`/find/batch`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(body)
        });
        
        const data = await response.json();
        
        if (response.ok) {
            displayBatchResults(data);
            updateHeaderStats(`${Object.keys(data.results).length} found, ${data.missing.length} missing - ${data.search_time.toFixed(3)}s`);
        } else {
            showError(data.detail);
            updateHeaderStats('Error');
        }
    } catch (error) {
        showError('Error connecting to server');
        updateHeaderStats('Error');
        console.error('Error:', error);
    } finally {
        hideLoading();
    }
}

async function searchKeyword() {
    const keywords = document.getElementById('keywords').value.trim();
    const searchMode = document.getElementById('search-mode-filter').value;
    
    if (!keywords && searchMode === 'deep') {
        showError('Please enter at least one keyword in deep search mode');
        return;
    }
    
    showLoading();
    updateHeaderStats('Searching...');
    
    try {
        const body = {
            keywords: keywords,
            search_mode: searchMode,
            case_sensitive: document.getElementById('case-sensitive-filter').checked,
            source: document.getElementById('source-filter').value,
            mode: document.getElementById('mode-filter').value
        };
        
        const specType = document.getElementById('spec-type-filter').value;
        if (specType) {
            body.spec_type = specType;
        }
        
        const response = await fetch(`/search`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(body)
        });
        
        const data = await response.json();
        
        if (response.ok) {
            displaySearchResults(data);
            updateHeaderStats(`${data.results.length} result(s) - ${data.search_time.toFixed(3)}s`);
        } else {
            showError(data.detail);
            updateHeaderStats('Error');
        }
    } catch (error) {
        showError('Error connecting to server');
        updateHeaderStats('Error');
        console.error('Error:', error);
    } finally {
        hideLoading();
    }
}

async function searchBM25() {
    const keywords = document.getElementById('bm25-keywords').value.trim();
    
    if (!keywords) {
        showError('Please enter a search query');
        return;
    }
    
    showLoading();
    updateHeaderStats('Searching...');
    
    try {
        const body = {
            keywords: keywords,
            source: document.getElementById('bm25-source-filter').value,
            threshold: parseInt(document.getElementById('threshold').value) || 60
        };
        
        const specType = document.getElementById('bm25-spec-type-filter').value;
        if (specType) {
            body.spec_type = specType;
        }
        
        const response = await fetch(`/search/bm25`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(body)
        });
        
        const data = await response.json();
        
        if (response.ok) {
            displaySearchResults(data);
            updateHeaderStats(`${data.results.length} result(s) - ${data.search_time.toFixed(3)}s`);
        } else {
            showError(data.detail);
            updateHeaderStats('Error');
        }
    } catch (error) {
        showError('Error connecting to server');
        updateHeaderStats('Error');
        console.error('Error:', error);
    } finally {
        hideLoading();
    }
}

// Results display functions
function displaySingleResult(data) {
    const resultsContent = document.getElementById('results-content');
    const isEtsiTdoc = ETSI_TDOC_RE.test(data.doc_id);

    const urlBlock = isEtsiTdoc
        ? `<div class="result-detail">
               <strong>URL:</strong> <span class="result-url-text">${data.url}</span>
               <button class="btn btn-primary download-btn" onclick="downloadTdoc('${data.doc_id}')">Download</button>
           </div>`
        : `<div class="result-detail result-url">
               <strong>URL:</strong> <a href="${data.url}" target="_blank">${data.url}</a>
           </div>`;

    resultsContent.innerHTML = `
        <div class="result-item">
            <div class="result-header">
                <div class="result-id">${data.doc_id}</div>
                <div class="result-status status-found">Found</div>
            </div>
            <div class="result-details">
                ${data.version ? `<div class="result-detail"><strong>Version:</strong> ${data.version}</div>` : ''}
                ${data.scope ? `<div class="result-detail"><strong>Scope:</strong> ${data.scope}</div>` : ''}
                ${urlBlock}
            </div>
        </div>
    `;

    showResults();
}

async function downloadTdoc(docId) {
    showLoading();
    updateHeaderStats('Downloading...');
    try {
        const response = await fetch('/find/tdoc/download', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ doc_id: docId })
        });
        if (response.ok) {
            const blob = await response.blob();
            const disposition = response.headers.get('Content-Disposition') || '';
            const fnMatch = disposition.match(/filename="?([^";\n]+)"?/);
            const filename = fnMatch ? fnMatch[1] : `${docId}.docx`;
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            updateHeaderStats('Downloaded');
        } else {
            const data = await response.json();
            showError(data.detail);
            updateHeaderStats('Error');
        }
    } catch (error) {
        showError('Error connecting to server');
        updateHeaderStats('Error');
        console.error('Error:', error);
    } finally {
        hideLoading();
    }
}

function displayBatchResults(data) {
    const resultsContent = document.getElementById('results-content');
    let html = '';
    
    // Found results
    Object.entries(data.results).forEach(([docId, url]) => {
        html += `
            <div class="result-item">
                <div class="result-header">
                    <div class="result-id">${docId}</div>
                    <div class="result-status status-found">Found</div>
                </div>
                <div class="result-details">
                    <div class="result-detail result-url">
                        <strong>URL:</strong> <a href="${url}" target="_blank">${url}</a>
                    </div>
                </div>
            </div>
        `;
    });
    
    // Missing documents
    data.missing.forEach(docId => {
        html += `
            <div class="result-item">
                <div class="result-header">
                    <div class="result-id">${docId}</div>
                    <div class="result-status status-missing">Not Found</div>
                </div>
                <div class="result-details">
                    <div class="result-detail">Document not found or not indexed</div>
                </div>
            </div>
        `;
    });
    
    resultsContent.innerHTML = html;
    showResults();
}

function displaySearchResults(data) {
    const resultsContent = document.getElementById('results-content');
    currentResults = data.results;
    
    let html = '';
    
    data.results.forEach((spec, index) => {
        const hasContent = spec.contains && Object.keys(spec.contains).length > 0;
        
        html += `
            <div class="result-item">
                <div class="result-header">
                    <div class="result-id">${spec.id}</div>
                    <div class="result-status status-found">${spec.type || 'Specification'}</div>
                </div>
                <div class="result-details">
                    <div class="result-detail"><strong>Title:</strong> ${spec.title}</div>
                    ${spec.version ? `<div class="result-detail"><strong>Version:</strong> ${spec.version}</div>` : ''}
                    ${spec.working_group ? `<div class="result-detail"><strong>Working Group:</strong> ${spec.working_group}</div>` : ''}
                    ${spec.type ? `<div class="result-detail"><strong>Type:</strong> ${spec.type}</div>` : ''}
                    ${spec.scope ? `<div class="result-detail"><strong>Scope:</strong> ${spec.scope}</div>` : ''}
                    ${spec.url ? `<div class="result-detail result-url"><strong>URL:</strong> <a href="${spec.url}" target="_blank">${spec.url}</a></div>` : ''}
                    ${hasContent ? `<button class="view-content-btn" onclick="viewContent(${index})">View Content</button>` : ''}
                </div>
            </div>
        `;
    });
    
    resultsContent.innerHTML = html;
    showResults();
}

// Content display functions
function viewContent(index) {
    const spec = currentResults[index];
    
    if (!spec.contains) return;
    
    document.getElementById('content-title').textContent = `${spec.id} - ${spec.title}`;
    
    const contentSections = document.getElementById('content-sections');
    let html = '';
    
    Object.entries(spec.contains).forEach(([sectionTitle, content]) => {
        html += `
            <div class="content-section">
                <h3>${sectionTitle}</h3>
                <p>${content}</p>
                <button class="copy-section-btn" onclick="copyText('${content.replace(/'/g, "\\'")}')">
                    Copy this section
                </button>
            </div>
        `;
    });
    
    contentSections.innerHTML = html;
    showContentPage();
}

function closeContentPage() {
    hideContentPage();
}

function copyAllContent() {
    const sections = document.querySelectorAll('.content-section p');
    const allText = Array.from(sections).map(p => p.textContent).join('\n\n');
    copyText(allText);
}

function copyText(text) {
    navigator.clipboard.writeText(text).then(() => {
        showSuccess('Text copied to clipboard');
    }).catch(() => {
        showError('Error copying text');
    });
}

// Interface utilities
function showLoading() {
    document.getElementById('loading-container').style.display = 'flex';
    hideResults();
    hideError();
}

function hideLoading() {
    document.getElementById('loading-container').style.display = 'none';
}

function showResults() {
    document.getElementById('results-container').style.display = 'block';
    hideError();
}

function hideResults() {
    document.getElementById('results-container').style.display = 'none';
}

function showContentPage() {
    document.getElementById('content-page').classList.add('active');
}

function hideContentPage() {
    document.getElementById('content-page').classList.remove('active');
}

function showError(message) {
    hideError();
    const errorDiv = document.createElement('div');
    errorDiv.className = 'error-message';
    errorDiv.textContent = message;
    document.querySelector('.search-container').appendChild(errorDiv);
    
    setTimeout(() => {
        hideError();
    }, 5000);
}

function showSuccess(message) {
    hideError();
    const successDiv = document.createElement('div');
    successDiv.className = 'success-message';
    successDiv.textContent = message;
    document.querySelector('.search-container').appendChild(successDiv);
    
    setTimeout(() => {
        hideError();
    }, 3000);
}

function hideError() {
    const existingMessages = document.querySelectorAll('.error-message, .success-message');
    existingMessages.forEach(msg => msg.remove());
}

function updateHeaderStats(text) {
    document.getElementById('header-stats').innerHTML = `<span class="stat-item">${text}</span>`;
}