File size: 25,378 Bytes
6be0e6a
12b4400
867f974
6be0e6a
 
12b4400
 
 
867f974
12b4400
 
867f974
12b4400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
867f974
12b4400
 
867f974
12b4400
 
 
867f974
12b4400
 
867f974
12b4400
 
 
 
 
 
 
 
 
 
867f974
 
 
 
12b4400
 
 
 
 
867f974
 
12b4400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
867f974
 
12b4400
 
 
 
 
 
 
 
 
 
 
 
867f974
12b4400
 
 
867f974
12b4400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
867f974
 
 
12b4400
867f974
 
 
 
 
 
 
12b4400
867f974
12b4400
 
 
 
 
 
867f974
 
 
 
 
12b4400
 
 
867f974
12b4400
 
867f974
 
 
 
 
 
12b4400
 
 
 
 
 
 
 
6be0e6a
12b4400
 
867f974
 
12b4400
 
 
 
 
 
 
 
 
 
 
 
 
bf43f8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12b4400
 
867f974
 
bf43f8e
 
 
12b4400
 
 
867f974
12b4400
 
bf43f8e
 
 
 
 
 
 
 
 
12b4400
 
867f974
12b4400
867f974
12b4400
 
 
 
 
 
 
867f974
 
 
 
6be0e6a
12b4400
867f974
12b4400
 
 
 
 
 
 
867f974
 
 
 
12b4400
 
867f974
 
 
 
12b4400
 
 
867f974
12b4400
 
 
 
 
 
 
6be0e6a
12b4400
 
 
 
 
 
867f974
 
 
 
12b4400
867f974
12b4400
 
6be0e6a
12b4400
 
 
6be0e6a
 
12b4400
 
 
 
867f974
 
 
 
 
 
12b4400
 
 
6be0e6a
12b4400
 
6be0e6a
12b4400
 
 
 
 
 
 
867f974
12b4400
867f974
12b4400
 
867f974
12b4400
 
 
6be0e6a
bf43f8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12b4400
 
867f974
 
bf43f8e
 
 
12b4400
bf43f8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12b4400
 
 
867f974
12b4400
867f974
12b4400
 
 
 
 
 
 
 
867f974
12b4400
 
 
 
867f974
 
12b4400
 
 
 
 
 
 
 
 
 
 
867f974
 
12b4400
 
867f974
12b4400
 
867f974
12b4400
 
 
867f974
12b4400
 
 
867f974
12b4400
 
 
867f974
12b4400
 
 
 
 
 
 
 
 
 
 
867f974
12b4400
 
 
 
 
 
 
 
 
 
 
867f974
 
12b4400
 
 
 
 
 
 
867f974
 
 
 
12b4400
 
867f974
12b4400
 
 
 
 
867f974
12b4400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
867f974
12b4400
 
 
 
 
 
 
 
 
 
 
 
 
 
867f974
 
12b4400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
867f974
12b4400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
867f974
12b4400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
867f974
12b4400
 
 
 
 
 
 
 
 
 
 
 
 
867f974
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf43f8e
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
/**
 * RAG 검색 챗봇 UI JavaScript
 * 메인 파일 - μ½”μ–΄ 및 μž₯치 μ œμ–΄ λͺ¨λ“ˆκ³Ό 톡합
 */

// DOM μš”μ†Œ
const chatTab = document.getElementById('chatTab');
const docsTab = document.getElementById('docsTab');
const deviceTab = document.getElementById('deviceTab'); // μž₯치 μ œμ–΄ νƒ­ μΆ”κ°€
const chatSection = document.getElementById('chatSection');
const docsSection = document.getElementById('docsSection');
const deviceSection = document.getElementById('deviceSection'); // μž₯치 μ œμ–΄ μ„Ήμ…˜ μΆ”κ°€
const chatMessages = document.getElementById('chatMessages');
const userInput = document.getElementById('userInput');
const sendButton = document.getElementById('sendButton');
const micButton = document.getElementById('micButton');
const stopRecordingButton = document.getElementById('stopRecordingButton');
const recordingStatus = document.getElementById('recordingStatus');
const uploadForm = document.getElementById('uploadForm');
const documentFile = document.getElementById('documentFile');
const fileName = document.getElementById('fileName');
const uploadButton = document.getElementById('uploadButton');
const uploadStatus = document.getElementById('uploadStatus');
const refreshDocsButton = document.getElementById('refreshDocsButton');
const docsList = document.getElementById('docsList');
const docsLoading = document.getElementById('docsLoading');
const noDocsMessage = document.getElementById('noDocsMessage');
const llmSelect = document.getElementById('llmSelect');
const currentLLMInfo = document.getElementById('currentLLMInfo');

// LLM κ΄€λ ¨ λ³€μˆ˜
let currentLLM = 'openai';
let supportedLLMs = [];

// λ…ΉμŒ κ΄€λ ¨ λ³€μˆ˜
let mediaRecorder = null;
let audioChunks = [];
let isRecording = false;

// μ•± μ΄ˆκΈ°ν™” μƒνƒœ 확인 ν•¨μˆ˜
async function checkAppStatus() {
    try {
        console.log('μ•± μƒνƒœ 확인 μš”μ²­ 전솑');
        const response = await fetch('/api/status');
        if (!response.ok) {
            console.error(`μ•± μƒνƒœ 확인 μ‹€νŒ¨: ${response.status}`);
            return false;
        }
        const data = await response.json();
        console.log(`μ•± μƒνƒœ 확인 κ²°κ³Ό: ${data.ready ? '쀀비됨' : 'μ€€λΉ„ μ•ˆλ¨'}`);
        return data.ready;
    } catch (error) {
        console.error('μ•± μƒνƒœ 확인 쀑 였λ₯˜ λ°œμƒ:', error);
        return false;
    }
}

/**
 * LLM λͺ©λ‘ λ‘œλ“œ ν•¨μˆ˜
 */
async function loadLLMs() {
    try {
        // API μš”μ²­
        console.log('LLM λͺ©λ‘ μš”μ²­ 전솑');
        const response = await AppUtils.fetchWithTimeout('/api/llm', {
            method: 'GET'
        });
        
        const data = await response.json();
        supportedLLMs = data.supported_llms;
        currentLLM = data.current_llm.id;
        
        console.log(`LLM λͺ©λ‘ λ‘œλ“œ 성곡: ${supportedLLMs.length}개 λͺ¨λΈ`);
        
        // LLM 선택 λ“œλ‘­λ‹€μš΄ μ—…λ°μ΄νŠΈ
        llmSelect.innerHTML = '';
        supportedLLMs.forEach(llm => {
            const option = document.createElement('option');
            option.value = llm.id;
            option.textContent = llm.name;
            option.selected = llm.current;
            llmSelect.appendChild(option);
        });
        
        // ν˜„μž¬ LLM ν‘œμ‹œ
        updateCurrentLLMInfo(data.current_llm);
    } catch (error) {
        console.error('LLM λͺ©λ‘ λ‘œλ“œ μ‹€νŒ¨:', error);
    }
}

/**
 * LLM λ³€κ²½ ν•¨μˆ˜
 * @param {string} llmId - λ³€κ²½ν•  LLM ID
 */
async function changeLLM(llmId) {
    try {
        // API μš”μ²­
        console.log(`LLM λ³€κ²½ μš”μ²­: ${llmId}`);
        const response = await AppUtils.fetchWithTimeout('/api/llm', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ llm_id: llmId })
        });
        
        const data = await response.json();
        
        if (data.success) {
            currentLLM = llmId;
            updateCurrentLLMInfo(data.current_llm);
            console.log(`LLM λ³€κ²½ 성곡: ${data.current_llm.name}`);
            
            // μ‹œμŠ€ν…œ λ©”μ‹œμ§€ μΆ”κ°€
            const systemMessage = `LLM이 ${data.current_llm.name}(으)둜 λ³€κ²½λ˜μ—ˆμŠ΅λ‹ˆλ‹€. λͺ¨λΈ: ${data.current_llm.model}`;
            AppUtils.addSystemNotification(systemMessage);
        } else if (data.error) {
            console.error('LLM λ³€κ²½ 였λ₯˜:', data.error);
            alert(`LLM λ³€κ²½ 였λ₯˜: ${data.error}`);
        }
    } catch (error) {
        console.error('LLM λ³€κ²½ μ‹€νŒ¨:', error);
        alert('LLM λ³€κ²½ 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€.');
    }
}

/**
 * ν˜„μž¬ LLM 정보 ν‘œμ‹œ μ—…λ°μ΄νŠΈ
 * @param {Object} llmInfo - LLM 정보 객체
 */
function updateCurrentLLMInfo(llmInfo) {
    if (currentLLMInfo) {
        currentLLMInfo.textContent = `${llmInfo.name} (${llmInfo.model})`;
    }
}

// νƒ­ μ „ν™˜ ν•¨μˆ˜
function switchTab(tabName) {
    console.log(`νƒ­ μ „ν™˜: ${tabName}`);
    
    // λͺ¨λ“  νƒ­κ³Ό μ„Ήμ…˜ λΉ„ν™œμ„±ν™”
    chatTab.classList.remove('active');
    docsTab.classList.remove('active');
    deviceTab.classList.remove('active');
    chatSection.classList.remove('active');
    docsSection.classList.remove('active');
    deviceSection.classList.remove('active');
    
    // μ„ νƒν•œ νƒ­κ³Ό μ„Ήμ…˜ ν™œμ„±ν™”
    if (tabName === 'chat') {
        chatTab.classList.add('active');
        chatSection.classList.add('active');
    } else if (tabName === 'docs') {
        docsTab.classList.add('active');
        docsSection.classList.add('active');
        // λ¬Έμ„œ λͺ©λ‘ λ‘œλ“œ
        loadDocuments();
    } else if (tabName === 'device') {
        deviceTab.classList.add('active');
        deviceSection.classList.add('active');
    }
}

// μ±„νŒ… λ©”μ‹œμ§€ 전솑 ν•¨μˆ˜
async function sendMessage() {
    const message = userInput.value.trim();
    if (!message) {
        console.log('λ©”μ‹œμ§€κ°€ λΉ„μ–΄μžˆμ–΄ μ „μ†‘ν•˜μ§€ μ•ŠμŒ');
        return;
    }
    
    console.log('λ©”μ‹œμ§€ 전솑 μ‹œμž‘');
    
    // UI μ—…λ°μ΄νŠΈ
    addMessage(message, 'user');
    userInput.value = '';
    adjustTextareaHeight();
    
    // λ‘œλ”© λ©”μ‹œμ§€ μΆ”κ°€
    const loadingMessageId = addLoadingMessage();
    
    try {
        // API μš”μ²­
        console.log(`/api/chat API 호좜: ${message.substring(0, 30)}${message.length > 30 ? '...' : ''}`);
        const response = await AppUtils.fetchWithTimeout('/api/chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ 
                query: message,
                llm_id: currentLLM  // ν˜„μž¬ μ„ νƒλœ LLM 전솑
            })
        });
        
        // λ‘œλ”© λ©”μ‹œμ§€ 제거
        removeLoadingMessage(loadingMessageId);
        
        // 응닡 ν˜•μ‹ 확인
        let data;
        try {
            data = await response.json();
            console.log('API 응닡 μˆ˜μ‹  μ™„λ£Œ');
            
            // 디버깅: 응닡 ꡬ쑰 및 λ‚΄μš© λ‘œκΉ…
            console.log('응닡 ꡬ쑰:', Object.keys(data));
            if (data.answer) {
                console.log('응닡 길이:', data.answer.length);
                console.log('응닡 λ‚΄μš© 일뢀:', data.answer.substring(0, 50) + '...');
            }
        } catch (jsonError) {
            console.error('응닡 JSON νŒŒμ‹± μ‹€νŒ¨:', jsonError);
            AppUtils.addErrorMessage('μ„œλ²„ 응닡을 μ²˜λ¦¬ν•  수 μ—†μŠ΅λ‹ˆλ‹€. λ‹€μ‹œ μ‹œλ„ν•΄ μ£Όμ„Έμš”.');
            return;
        }
        
        // 응닡 ν‘œμ‹œ
        if (data.error) {
            console.error(`API 였λ₯˜ 응닡: ${data.error}`);
            AppUtils.addErrorMessage(data.error);
        } else if (!data.answer || data.answer.trim() === '') {
            console.error('응닡 λ‚΄μš©μ΄ λΉ„μ–΄μžˆμŒ');
            AppUtils.addErrorMessage('μ„œλ²„μ—μ„œ 빈 응닡을 λ°›μ•˜μŠ΅λ‹ˆλ‹€. λ‹€μ‹œ μ‹œλ„ν•΄ μ£Όμ„Έμš”.');
        } else {
            // LLM 정보 μ—…λ°μ΄νŠΈ
            if (data.llm) {
                console.log(`LLM 정보 μ—…λ°μ΄νŠΈ: ${data.llm.name}`);
                updateCurrentLLMInfo(data.llm);
            }
            
            try {
                // λ©”μ‹œμ§€ μΆ”κ°€
                addMessage(data.answer, 'bot', null, data.sources);
                console.log('챗봇 응닡 ν‘œμ‹œ μ™„λ£Œ');
            } catch (displayError) {
                console.error('응닡 ν‘œμ‹œ 쀑 였λ₯˜:', displayError);
                AppUtils.addErrorMessage('응닡을 ν‘œμ‹œν•˜λŠ” 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€. λ‹€μ‹œ μ‹œλ„ν•΄ μ£Όμ„Έμš”.');
            }
        }
    } catch (error) {
        console.error('λ©”μ‹œμ§€ 전솑 쀑 였λ₯˜ λ°œμƒ:', error);
        removeLoadingMessage(loadingMessageId);
        AppUtils.addErrorMessage('였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€. λ‹€μ‹œ μ‹œλ„ν•΄ μ£Όμ„Έμš”.');
    }
}

/**
 * μŒμ„± λ…ΉμŒ μ‹œμž‘ ν•¨μˆ˜
 */
async function startRecording() {
    if (isRecording) {
        console.log('이미 λ…ΉμŒ 쀑');
        return;
    }
    
    try {
        console.log('마이크 μ ‘κ·Ό κΆŒν•œ μš”μ²­');
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        isRecording = true;
        audioChunks = [];
        
        mediaRecorder = new MediaRecorder(stream);
        
        mediaRecorder.addEventListener('dataavailable', (event) => {
            if (event.data.size > 0) {
                console.log('μ˜€λ””μ˜€ 청크 데이터 μˆ˜μ‹ ');
                audioChunks.push(event.data);
            }
        });
        
        mediaRecorder.addEventListener('stop', () => {
            console.log('λ…ΉμŒ 쀑지 이벀트 - μ˜€λ””μ˜€ λ©”μ‹œμ§€ 전솑');
            sendAudioMessage();
        });
        
        // λ…ΉμŒ μ‹œμž‘
        mediaRecorder.start();
        console.log('λ…ΉμŒ μ‹œμž‘λ¨');
        
        // UI μ—…λ°μ΄νŠΈ
        micButton.style.display = 'none';
        recordingStatus.classList.remove('hidden');
    } catch (error) {
        console.error('μŒμ„± λ…ΉμŒ κΆŒν•œμ„ 얻을 수 μ—†μŠ΅λ‹ˆλ‹€:', error);
        alert('마이크 μ ‘κ·Ό κΆŒν•œμ΄ ν•„μš”ν•©λ‹ˆλ‹€.');
    }
}

/**
 * μŒμ„± λ…ΉμŒ 쀑지 ν•¨μˆ˜
 */
function stopRecording() {
    if (!isRecording || !mediaRecorder) {
        console.log('λ…ΉμŒ 쀑이 μ•„λ‹˜');
        return;
    }
    
    console.log('λ…ΉμŒ 쀑지 μš”μ²­');
    mediaRecorder.stop();
    isRecording = false;
    
    // UI μ—…λ°μ΄νŠΈ
    micButton.style.display = 'flex';
    recordingStatus.classList.add('hidden');
}

/**
 * λ…ΉμŒλœ μ˜€λ””μ˜€ λ©”μ‹œμ§€ 전솑 ν•¨μˆ˜
 */
async function sendAudioMessage() {
    if (audioChunks.length === 0) {
        console.log('μ˜€λ””μ˜€ 청크가 μ—†μŒ');
        return;
    }
    
    console.log(`μ˜€λ””μ˜€ λ©”μ‹œμ§€ 전솑 μ‹œμž‘: ${audioChunks.length}개 청크`);
    
    // μ˜€λ””μ˜€ Blob 생성
    const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
    
    // λ‘œλ”© λ©”μ‹œμ§€ μΆ”κ°€
    const loadingMessageId = addLoadingMessage();
    
    try {
        // FormData에 μ˜€λ””μ˜€ μΆ”κ°€
        const formData = new FormData();
        formData.append('audio', audioBlob, 'recording.wav');
        // ν˜„μž¬ μ„ νƒλœ LLM μΆ”κ°€
        formData.append('llm_id', currentLLM);
        
        console.log('/api/voice API 호좜');
        // API μš”μ²­
        const response = await AppUtils.fetchWithTimeout('/api/voice', {
            method: 'POST',
            body: formData
        }, 30000); // μŒμ„± μ²˜λ¦¬λŠ” 더 κΈ΄ νƒ€μž„μ•„μ›ƒ
        
        // λ‘œλ”© λ©”μ‹œμ§€ 제거
        removeLoadingMessage(loadingMessageId);
        
        // 응닡 ν˜•μ‹ 확인
        let data;
        try {
            data = await response.json();
            console.log('μŒμ„± API 응닡 μˆ˜μ‹  μ™„λ£Œ');
            
            // 디버깅: 응닡 ꡬ쑰 및 λ‚΄μš© λ‘œκΉ…
            console.log('μŒμ„± 응닡 ꡬ쑰:', Object.keys(data));
            if (data.answer) {
                console.log('μŒμ„± 응닡 길이:', data.answer.length);
                console.log('μŒμ„± 응닡 λ‚΄μš© 일뢀:', data.answer.substring(0, 50) + '...');
            }
            if (data.transcription) {
                console.log('μŒμ„± 인식 길이:', data.transcription.length);
            }
        } catch (jsonError) {
            console.error('μŒμ„± 응닡 JSON νŒŒμ‹± μ‹€νŒ¨:', jsonError);
            AppUtils.addErrorMessage('μ„œλ²„ 응닡을 μ²˜λ¦¬ν•  수 μ—†μŠ΅λ‹ˆλ‹€. λ‹€μ‹œ μ‹œλ„ν•΄ μ£Όμ„Έμš”.');
            return;
        }
        
        // 응닡 ν‘œμ‹œ
        if (data.error) {
            console.error(`μŒμ„± API 였λ₯˜ 응닡: ${data.error}`);
            AppUtils.addErrorMessage(data.error);
        } else if (!data.answer || data.answer.trim() === '') {
            console.error('μŒμ„± 응닡 λ‚΄μš©μ΄ λΉ„μ–΄μžˆμŒ');
            AppUtils.addErrorMessage('μ„œλ²„μ—μ„œ 빈 응닡을 λ°›μ•˜μŠ΅λ‹ˆλ‹€. λ‹€μ‹œ μ‹œλ„ν•΄ μ£Όμ„Έμš”.');
        } else {
            try {
                // LLM 정보 μ—…λ°μ΄νŠΈ
                if (data.llm) {
                    console.log(`LLM 정보 μ—…λ°μ΄νŠΈ: ${data.llm.name}`);
                    updateCurrentLLMInfo(data.llm);
                }
                
                // μ‚¬μš©μž λ©”μ‹œμ§€(μŒμ„± ν…μŠ€νŠΈ) μΆ”κ°€
                if (data.transcription) {
                    console.log(`μŒμ„± 인식 κ²°κ³Ό: ${data.transcription.substring(0, 30)}${data.transcription.length > 30 ? '...' : ''}`);
                    addMessage(data.transcription, 'user');
                }
                
                // 봇 응닡 μΆ”κ°€
                addMessage(data.answer, 'bot', data.transcription, data.sources);
                console.log('μŒμ„± μ±„νŒ… 응닡 ν‘œμ‹œ μ™„λ£Œ');
            } catch (displayError) {
                console.error('μŒμ„± 응닡 ν‘œμ‹œ 쀑 였λ₯˜:', displayError);
                AppUtils.addErrorMessage('응닡을 ν‘œμ‹œν•˜λŠ” 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€. λ‹€μ‹œ μ‹œλ„ν•΄ μ£Όμ„Έμš”.');
            }
        }
    } catch (error) {
        console.error('μŒμ„± λ©”μ‹œμ§€ 전솑 쀑 였λ₯˜ λ°œμƒ:', error);
        removeLoadingMessage(loadingMessageId);
        AppUtils.addErrorMessage('μ˜€λ””μ˜€ 처리 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€. λ‹€μ‹œ μ‹œλ„ν•΄ μ£Όμ„Έμš”.');
    }
}

/**
 * λ¬Έμ„œ μ—…λ‘œλ“œ ν•¨μˆ˜
 */
async function uploadDocument() {
    if (documentFile.files.length === 0) {
        console.log('μ„ νƒλœ 파일 μ—†μŒ');
        alert('νŒŒμΌμ„ 선택해 μ£Όμ„Έμš”.');
        return;
    }
    
    console.log(`λ¬Έμ„œ μ—…λ‘œλ“œ μ‹œμž‘: ${documentFile.files[0].name}`);
    
    // UI μ—…λ°μ΄νŠΈ
    uploadStatus.classList.remove('hidden');
    uploadStatus.className = 'upload-status';
    uploadStatus.innerHTML = '<div class="spinner"></div><p>μ—…λ‘œλ“œ 쀑...</p>';
    uploadButton.disabled = true;
    
    try {
        const formData = new FormData();
        formData.append('document', documentFile.files[0]);
        
        // API μš”μ²­
        console.log('/api/upload API 호좜');
        const response = await AppUtils.fetchWithTimeout('/api/upload', {
            method: 'POST',
            body: formData
        }, 20000); // μ—…λ‘œλ“œλŠ” 더 κΈ΄ νƒ€μž„μ•„μ›ƒ
        
        const data = await response.json();
        console.log('μ—…λ‘œλ“œ API 응닡 μˆ˜μ‹  μ™„λ£Œ');
        
        // 응닡 처리
        if (data.error) {
            console.error(`μ—…λ‘œλ“œ 였λ₯˜: ${data.error}`);
            uploadStatus.className = 'upload-status error';
            uploadStatus.textContent = `였λ₯˜: ${data.error}`;
        } else if (data.warning) {
            console.warn(`μ—…λ‘œλ“œ κ²½κ³ : ${data.message}`);
            uploadStatus.className = 'upload-status warning';
            uploadStatus.textContent = data.message;
        } else {
            console.log(`μ—…λ‘œλ“œ 성곡: ${data.message}`);
            uploadStatus.className = 'upload-status success';
            uploadStatus.textContent = data.message;
            
            // λ¬Έμ„œ λͺ©λ‘ μƒˆλ‘œκ³ μΉ¨
            loadDocuments();
            
            // μž…λ ₯ ν•„λ“œ μ΄ˆκΈ°ν™”
            documentFile.value = '';
            fileName.textContent = 'μ„ νƒλœ 파일 μ—†μŒ';
        }
    } catch (error) {
        console.error('λ¬Έμ„œ μ—…λ‘œλ“œ 쀑 였λ₯˜ λ°œμƒ:', error);
        uploadStatus.className = 'upload-status error';
        uploadStatus.textContent = 'μ—…λ‘œλ“œ 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€. λ‹€μ‹œ μ‹œλ„ν•΄ μ£Όμ„Έμš”.';
    } finally {
        uploadButton.disabled = false;
    }
}

/**
 * λ¬Έμ„œ λͺ©λ‘ λ‘œλ“œ ν•¨μˆ˜
 */
async function loadDocuments() {
    console.log('λ¬Έμ„œ λͺ©λ‘ λ‘œλ“œ μ‹œμž‘');
    
    // UI μ—…λ°μ΄νŠΈ
    docsList.querySelector('tbody').innerHTML = '';
    docsLoading.classList.remove('hidden');
    noDocsMessage.classList.add('hidden');
    
    try {
        // API μš”μ²­
        console.log('/api/documents API 호좜');
        const response = await AppUtils.fetchWithTimeout('/api/documents', {
            method: 'GET'
        });
        
        const data = await response.json();
        console.log(`λ¬Έμ„œ λͺ©λ‘ λ‘œλ“œ 성곡: ${data.documents ? data.documents.length : 0}개 λ¬Έμ„œ`);
        
        // 응닡 처리
        docsLoading.classList.add('hidden');
        
        if (!data.documents || data.documents.length === 0) {
            console.log('λ¬Έμ„œ μ—†μŒ');
            noDocsMessage.classList.remove('hidden');
            return;
        }
        
        // λ¬Έμ„œ λͺ©λ‘ μ—…λ°μ΄νŠΈ
        const tbody = docsList.querySelector('tbody');
        data.documents.forEach(doc => {
            const row = document.createElement('tr');
            
            const fileNameCell = document.createElement('td');
            fileNameCell.textContent = doc.filename || doc.source;
            row.appendChild(fileNameCell);
            
            const chunksCell = document.createElement('td');
            chunksCell.textContent = doc.chunks;
            row.appendChild(chunksCell);
            
            const typeCell = document.createElement('td');
            typeCell.textContent = doc.filetype || '-';
            row.appendChild(typeCell);
            
            tbody.appendChild(row);
        });
    } catch (error) {
        console.error('λ¬Έμ„œ λͺ©λ‘ λ‘œλ“œ 쀑 였λ₯˜ λ°œμƒ:', error);
        docsLoading.classList.add('hidden');
        noDocsMessage.classList.remove('hidden');
        noDocsMessage.querySelector('p').textContent = 'λ¬Έμ„œ λͺ©λ‘μ„ λΆˆλŸ¬μ˜€λŠ” 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€.';
    }
}

/**
 * λ©”μ‹œμ§€ μΆ”κ°€ ν•¨μˆ˜
 * @param {string} text - λ©”μ‹œμ§€ λ‚΄μš©
 * @param {string} sender - λ©”μ‹œμ§€ λ°œμ‹ μž ('user' λ˜λŠ” 'bot' λ˜λŠ” 'system')
 * @param {string|null} transcription - μŒμ„± 인식 ν…μŠ€νŠΈ (선택 사항)
 * @param {Array|null} sources - μ†ŒμŠ€ 정보 λ°°μ—΄ (선택 사항)
 */
function addMessage(text, sender, transcription = null, sources = null) {
    console.log(`λ©”μ‹œμ§€ μΆ”κ°€: sender=${sender}, length=${text ? text.length : 0}`);
    
    const messageDiv = document.createElement('div');
    messageDiv.classList.add('message', sender);
    
    const contentDiv = document.createElement('div');
    contentDiv.classList.add('message-content');
    
    // μŒμ„± 인식 ν…μŠ€νŠΈ μΆ”κ°€ (μžˆλŠ” 경우)
    if (transcription && sender === 'bot') {
        const transcriptionP = document.createElement('p');
        transcriptionP.classList.add('transcription');
        transcriptionP.textContent = `"${transcription}"`;
        contentDiv.appendChild(transcriptionP);
    }
    
    // λ©”μ‹œμ§€ ν…μŠ€νŠΈ μΆ”κ°€
    const textP = document.createElement('p');
    textP.textContent = text;
    contentDiv.appendChild(textP);
    
    // μ†ŒμŠ€ 정보 μΆ”κ°€ (μžˆλŠ” 경우)
    if (sources && sources.length > 0 && sender === 'bot') {
        console.log(`μ†ŒμŠ€ 정보 μΆ”κ°€: ${sources.length}개 μ†ŒμŠ€`);
        const sourcesDiv = document.createElement('div');
        sourcesDiv.classList.add('sources');
        
        const sourcesTitle = document.createElement('strong');
        sourcesTitle.textContent = '좜처: ';
        sourcesDiv.appendChild(sourcesTitle);
        
        sources.forEach((source, index) => {
            if (index < 3) { // μ΅œλŒ€ 3κ°œκΉŒμ§€λ§Œ ν‘œμ‹œ
                const sourceSpan = document.createElement('span');
                sourceSpan.classList.add('source-item');
                sourceSpan.textContent = source.source;
                sourcesDiv.appendChild(sourceSpan);
            }
        });
        
        contentDiv.appendChild(sourcesDiv);
    }
    
    messageDiv.appendChild(contentDiv);
    chatMessages.appendChild(messageDiv);
    
    // μŠ€ν¬λ‘€μ„ κ°€μž₯ μ•„λž˜λ‘œ 이동
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

/**
 * λ‘œλ”© λ©”μ‹œμ§€ μΆ”κ°€ ν•¨μˆ˜
 * @returns {string} λ‘œλ”© λ©”μ‹œμ§€ ID
 */
function addLoadingMessage() {
    console.log('λ‘œλ”© λ©”μ‹œμ§€ μΆ”κ°€');
    const id = 'loading-' + Date.now();
    const messageDiv = document.createElement('div');
    messageDiv.classList.add('message', 'bot');
    messageDiv.id = id;
    
    const contentDiv = document.createElement('div');
    contentDiv.classList.add('message-content');
    
    const loadingP = document.createElement('p');
    loadingP.innerHTML = '<div class="spinner" style="width: 20px; height: 20px; display: inline-block; margin-right: 10px;"></div> 생각 쀑...';
    contentDiv.appendChild(loadingP);
    
    messageDiv.appendChild(contentDiv);
    chatMessages.appendChild(messageDiv);
    
    // μŠ€ν¬λ‘€μ„ κ°€μž₯ μ•„λž˜λ‘œ 이동
    chatMessages.scrollTop = chatMessages.scrollHeight;
    
    return id;
}

/**
 * λ‘œλ”© λ©”μ‹œμ§€ 제거 ν•¨μˆ˜
 * @param {string} id - λ‘œλ”© λ©”μ‹œμ§€ ID
 */
function removeLoadingMessage(id) {
    console.log(`λ‘œλ”© λ©”μ‹œμ§€ 제거: ${id}`);
    const loadingMessage = document.getElementById(id);
    if (loadingMessage) {
        loadingMessage.remove();
    }
}

/**
 * textarea 높이 μžλ™ μ‘°μ • ν•¨μˆ˜
 */
function adjustTextareaHeight() {
    userInput.style.height = 'auto';
    userInput.style.height = Math.min(userInput.scrollHeight, 100) + 'px';
}

// νŽ˜μ΄μ§€ λ‘œλ“œ μ‹œ μ΄ˆκΈ°ν™”
document.addEventListener('DOMContentLoaded', () => {
    console.log('메인 UI μ΄ˆκΈ°ν™” 쀑...');
    
    // μ•± μƒνƒœ 확인 (λ‘œλ”© νŽ˜μ΄μ§€κ°€ μ•„λ‹Œ κ²½μš°μ—λ§Œ)
    if (window.location.pathname === '/' && !document.getElementById('app-loading-indicator')) {
        // μ•± μƒνƒœ 주기적으둜 확인
        const statusInterval = setInterval(async () => {
            const isReady = await checkAppStatus();
            if (isReady) {
                clearInterval(statusInterval);
                console.log('앱이 μ€€λΉ„λ˜μ—ˆμŠ΅λ‹ˆλ‹€.');
                
                // 앱이 μ€€λΉ„λ˜λ©΄ LLM λͺ©λ‘ λ‘œλ“œ
                loadLLMs();
            }
        }, 5000);
    }

    // νƒ­ μ „ν™˜ 이벀트 λ¦¬μŠ€λ„ˆ
    chatTab.addEventListener('click', () => {
        console.log('μ±„νŒ… νƒ­ 클릭');
        switchTab('chat');
    });
    
    docsTab.addEventListener('click', () => {
        console.log('λ¬Έμ„œ 관리 νƒ­ 클릭');
        switchTab('docs');
    });
    
    // μž₯치 μ œμ–΄ 탭은 DeviceControl λͺ¨λ“ˆμ—μ„œ 이벀트 λ¦¬μŠ€λ„ˆ 등둝함
    
    // LLM 선택 이벀트 λ¦¬μŠ€λ„ˆ
    llmSelect.addEventListener('change', (event) => {
        console.log(`LLM λ³€κ²½: ${event.target.value}`);
        changeLLM(event.target.value);
    });
    
    // λ©”μ‹œμ§€ 전솑 이벀트 λ¦¬μŠ€λ„ˆ
    sendButton.addEventListener('click', () => {
        console.log('λ©”μ‹œμ§€ 전솑 λ²„νŠΌ 클릭');
        sendMessage();
    });
    
    userInput.addEventListener('keydown', (event) => {
        if (event.key === 'Enter' && !event.shiftKey) {
            console.log('ν…μŠ€νŠΈ μž…λ ₯μ—μ„œ μ—”ν„° ν‚€ 감지');
            event.preventDefault();
            sendMessage();
        }
    });
    
    // μŒμ„± 인식 이벀트 λ¦¬μŠ€λ„ˆ
    micButton.addEventListener('click', () => {
        console.log('마이크 λ²„νŠΌ 클릭');
        startRecording();
    });
    
    stopRecordingButton.addEventListener('click', () => {
        console.log('λ…ΉμŒ 쀑지 λ²„νŠΌ 클릭');
        stopRecording();
    });
    
    // λ¬Έμ„œ μ—…λ‘œλ“œ 이벀트 λ¦¬μŠ€λ„ˆ
    documentFile.addEventListener('change', (event) => {
        console.log('파일 선택 λ³€κ²½');
        if (event.target.files.length > 0) {
            fileName.textContent = event.target.files[0].name;
        } else {
            fileName.textContent = 'μ„ νƒλœ 파일 μ—†μŒ';
        }
    });
    
    uploadForm.addEventListener('submit', (event) => {
        console.log('λ¬Έμ„œ μ—…λ‘œλ“œ 폼 제좜');
        event.preventDefault();
        uploadDocument();
    });
    
    // λ¬Έμ„œ λͺ©λ‘ μƒˆλ‘œκ³ μΉ¨ 이벀트 λ¦¬μŠ€λ„ˆ
    refreshDocsButton.addEventListener('click', () => {
        console.log('λ¬Έμ„œ λͺ©λ‘ μƒˆλ‘œκ³ μΉ¨ λ²„νŠΌ 클릭');
        loadDocuments();
    });
    
    // μžλ™ μž…λ ₯ ν•„λ“œ 크기 μ‘°μ •
    userInput.addEventListener('input', adjustTextareaHeight);
    
    // 초기 λ¬Έμ„œ λͺ©λ‘ λ‘œλ“œ
    if (docsSection.classList.contains('active')) {
        loadDocuments();
    }
    
    console.log('메인 UI μ΄ˆκΈ°ν™” μ™„λ£Œ');
});