File size: 35,368 Bytes
2f6c4ad
 
 
 
 
49a97fa
2f6c4ad
 
 
 
 
49a97fa
2f6c4ad
 
49a97fa
2f6c4ad
93512e0
 
 
949e416
02aa0ba
949e416
2f6c4ad
 
 
49a97fa
2f6c4ad
 
 
 
93512e0
 
 
 
 
49a97fa
323649f
2f6c4ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49a97fa
 
 
2f6c4ad
 
 
93512e0
 
 
 
 
 
49a97fa
93512e0
 
 
 
 
 
 
 
 
49a97fa
93512e0
 
 
 
 
 
49a97fa
93512e0
 
 
 
49a97fa
93512e0
 
 
49a97fa
93512e0
 
 
2f6c4ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93512e0
 
49a97fa
2f6c4ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93512e0
 
 
 
 
49a97fa
93512e0
 
 
 
 
 
 
2f6c4ad
93512e0
2f6c4ad
 
93512e0
49a97fa
93512e0
 
 
 
 
 
2f6c4ad
93512e0
 
2f6c4ad
 
93512e0
49a97fa
93512e0
 
 
 
 
 
2f6c4ad
 
 
 
 
 
93512e0
 
49a97fa
2f6c4ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49a97fa
 
2f6c4ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49a97fa
2f6c4ad
 
 
 
 
49a97fa
 
2f6c4ad
 
 
49a97fa
2f6c4ad
 
 
 
 
 
49a97fa
2f6c4ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49a97fa
 
 
2f6c4ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49a97fa
2f6c4ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49a97fa
93512e0
 
 
 
949e416
49a97fa
2f6c4ad
949e416
93512e0
49a97fa
2f6c4ad
 
 
 
 
 
 
 
49a97fa
93512e0
2f6c4ad
49a97fa
93512e0
 
2f6c4ad
 
 
49a97fa
93512e0
 
49a97fa
93512e0
 
 
49a97fa
2f6c4ad
 
93512e0
 
49a97fa
93512e0
49a97fa
 
2f6c4ad
 
49a97fa
2f6c4ad
 
 
 
 
 
 
49a97fa
2f6c4ad
 
 
 
49a97fa
 
2f6c4ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49a97fa
 
2f6c4ad
49a97fa
 
2f6c4ad
 
49a97fa
2f6c4ad
49a97fa
 
2f6c4ad
 
 
49a97fa
2f6c4ad
 
49a97fa
2f6c4ad
 
49a97fa
2f6c4ad
 
 
 
49a97fa
2f6c4ad
49a97fa
2f6c4ad
 
 
49a97fa
 
2f6c4ad
 
 
 
 
 
 
 
49a97fa
2f6c4ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49a97fa
 
 
 
 
2f6c4ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49a97fa
2f6c4ad
 
 
 
 
 
 
49a97fa
2f6c4ad
49a97fa
 
2f6c4ad
 
49a97fa
2f6c4ad
49a97fa
 
2f6c4ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49a97fa
2f6c4ad
 
49a97fa
2f6c4ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49a97fa
2f6c4ad
49a97fa
 
2f6c4ad
 
 
49a97fa
2f6c4ad
49a97fa
 
 
2f6c4ad
49a97fa
2f6c4ad
49a97fa
 
 
 
 
 
 
 
 
 
 
 
 
 
2f6c4ad
 
49a97fa
 
 
 
 
 
 
2f6c4ad
 
49a97fa
 
 
 
 
 
 
 
 
 
 
2f6c4ad
 
49a97fa
 
2f6c4ad
 
49a97fa
2f6c4ad
 
 
 
49a97fa
2f6c4ad
49a97fa
2f6c4ad
49a97fa
2f6c4ad
 
49a97fa
2f6c4ad
 
 
 
49a97fa
2f6c4ad
49a97fa
2f6c4ad
 
 
 
49a97fa
2f6c4ad
 
 
 
49a97fa
 
2f6c4ad
 
 
 
49a97fa
2f6c4ad
 
 
 
 
49a97fa
2f6c4ad
 
 
 
49a97fa
2f6c4ad
49a97fa
93512e0
2f6c4ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93512e0
2f6c4ad
 
 
 
 
 
 
 
 
49a97fa
93512e0
 
 
2f6c4ad
 
93512e0
49a97fa
 
 
2f6c4ad
 
49a97fa
 
2f6c4ad
49a97fa
2f6c4ad
 
 
 
49a97fa
2f6c4ad
 
 
 
49a97fa
2f6c4ad
49a97fa
2f6c4ad
 
 
 
 
 
 
49a97fa
2f6c4ad
 
 
 
 
 
 
49a97fa
2f6c4ad
49a97fa
2f6c4ad
49a97fa
2f6c4ad
 
49a97fa
2f6c4ad
 
49a97fa
2f6c4ad
 
 
49a97fa
2f6c4ad
49a97fa
2f6c4ad
 
 
 
 
49a97fa
2f6c4ad
 
 
 
49a97fa
2f6c4ad
 
 
 
49a97fa
2f6c4ad
 
49a97fa
 
2f6c4ad
 
 
 
 
 
 
 
 
 
 
 
 
49a97fa
2f6c4ad
49a97fa
 
2f6c4ad
 
 
 
49a97fa
 
2f6c4ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49a97fa
2f6c4ad
 
 
 
49a97fa
2f6c4ad
49a97fa
2f6c4ad
 
49a97fa
2f6c4ad
 
 
 
 
93512e0
2f6c4ad
49a97fa
2f6c4ad
 
 
 
49a97fa
2f6c4ad
49a97fa
2f6c4ad
 
 
 
 
 
 
 
 
 
49a97fa
2f6c4ad
 
49a97fa
2f6c4ad
 
 
 
 
 
 
 
 
 
 
 
49a97fa
 
2f6c4ad
49a97fa
2f6c4ad
 
49a97fa
2f6c4ad
 
 
 
 
49a97fa
2f6c4ad
49a97fa
2f6c4ad
 
 
 
49a97fa
2f6c4ad
 
49a97fa
2f6c4ad
 
 
 
 
49a97fa
2f6c4ad
 
 
49a97fa
2f6c4ad
 
 
49a97fa
 
2f6c4ad
 
49a97fa
2f6c4ad
 
 
 
 
 
 
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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230

import os
import re
import csv
import uuid
import html
import json
import fitz
from pathlib import Path
from datetime import datetime
from typing import TypedDict, Literal

import streamlit as st
import streamlit.components.v1 as components
from openai import OpenAI

from langchain_community.document_loaders import PyMuPDFLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain_community.vectorstores import FAISS
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.documents import Document

from langgraph.graph import StateGraph, END


# =========================================================
# 0. ๊ธฐ๋ณธ ์„ค์ •
# =========================================================
st.set_page_config(
    page_title="AIVLE ํ•™์Šต๋„์šฐ๋ฏธ",
    page_icon="๐Ÿค–",
    layout="wide"
)

BASE_DIR = Path(__file__).resolve().parent
# ํ†ตํ•ฉ ๋ฐฑ์„œ PDF ํ•˜๋‚˜๋งŒ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.
# ํŒŒ์ผ๋ช…์ด ๋‹ค๋ฅผ ์ˆ˜ ์žˆ์–ด, ์•„๋ž˜ ํ›„๋ณด ์ˆœ์„œ๋Œ€๋กœ ๋จผ์ € ์กด์žฌํ•˜๋Š” PDF๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.
PDF_CANDIDATES = [
    BASE_DIR / "AIVLE_School_๋ฐฑ์„œ_ํ†ตํ•ฉ๋ณธ.pdf",
]

PDF_PATH = next((path for path in PDF_CANDIDATES if path.exists()), PDF_CANDIDATES[0])
UPLOAD_DIR = BASE_DIR / "uploads"
TEMP_DIR = BASE_DIR / "temp"
IMAGE_BANNER_PATH = BASE_DIR / "images" / "์ด๋ฏธ์ง€.png"
LOGO_PATH = BASE_DIR / "images" / "์—์ด๋ธ”ํ•™์Šต๋„์šฐ๋ฏธ ๋กœ๊ณ .png"

UPLOAD_DIR.mkdir(exist_ok=True)
TEMP_DIR.mkdir(exist_ok=True)

client = OpenAI()


# =========================================================
# 1. CSS: 1๋ฒˆ ์‚ฌ์ด๋“œ๋ฐ”/๋กœ๊ทธ์ธ UI + 2๋ฒˆ ์ฑ„ํŒ… UI ๊ฒฐํ•ฉ
# =========================================================
st.markdown("""
<style>
.main .block-container {
    padding-top: 2rem;
    max-width: 1100px;
}

.hero-box {
    background: #d9f3f2;
    border-radius: 22px;
    padding: 34px 38px;
    margin-bottom: 28px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.hero-title {
    font-size: 30px;
    font-weight: 800;
    color: #111827;
    margin-bottom: 10px;
}

.hero-sub {
    font-size: 15px;
    color: #6b7280;
}

.robot {
    font-size: 72px;
}

.section-title {
    font-size: 17px;
    font-weight: 800;
    margin: 20px 0 12px 0;
}

.login-lock-box {
    background: #f9fafb;
    border: 1px solid #e5e7eb;
    border-radius: 18px;
    padding: 36px;
    text-align: center;
    margin-top: 80px;
}

.login-lock-title {
    font-size: 26px;
    font-weight: 800;
    margin-bottom: 10px;
}

.login-lock-sub {
    color: #6b7280;
    font-size: 15px;
}

section[data-testid="stSidebar"] {
    background-color: #f8fafc;
}

.sidebar-title {
    font-size: 22px;
    font-weight: 900;
    color: #111827;
    margin-bottom: 4px;
}

.sidebar-subtitle {
    font-size: 13px;
    color: #6b7280;
    line-height: 1.5;
    margin-bottom: 18px;
}

.account-card {
    background: #ecfdf5;
    border: 1px solid #d1fae5;
    border-radius: 16px;
    padding: 14px 16px;
    margin-bottom: 12px;
}

.account-name {
    font-size: 15px;
    font-weight: 800;
    color: #065f46;
}

.account-status {
    font-size: 12px;
    color: #059669;
    margin-top: 4px;
}

.sidebar-section-title {
    font-size: 13px;
    font-weight: 800;
    color: #374151;
    margin-top: 22px;
    margin-bottom: 8px;
}

.history-caption {
    font-size: 11px;
    color: #9ca3af;
    margin-top: -6px;
    margin-bottom: 8px;
}

.sidebar-help {
    font-size: 12px;
    color: #9ca3af;
    line-height: 1.5;
}

.chat-wrap {
    border-top: 1px solid #e5e7eb;
    margin-top: 28px;
    padding-top: 26px;
}

.user-bubble {
    background: #d9f3f2;
    padding: 14px 18px;
    border-radius: 18px;
    width: fit-content;
    max-width: 70%;
    margin-left: auto;
    margin-bottom: 14px;
    font-weight: 500;
    line-height: 1.6;
    word-break: break-word;
}

.assistant-card {
    background: white;
    border: 1px solid #e5e7eb;
    border-radius: 18px;
    padding: 20px;
    margin-top: 8px;
    margin-bottom: 8px;
    max-width: 780px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.04);
    line-height: 1.7;
    word-break: break-word;
}

.assistant-name {
    font-size: 14px;
    color: #6b7280;
    font-weight: 700;
    margin-bottom: 8px;
}

.message-tools {
    display: flex;
    gap: 8px;
    margin-bottom: 18px;
}
</style>
""", unsafe_allow_html=True)


# =========================================================
# 2. ์„ธ์…˜ ์ƒํƒœ ์ดˆ๊ธฐํ™”
# =========================================================
def init_session_state():
    if "logged_in" not in st.session_state:
        st.session_state.logged_in = False

    if "user_id" not in st.session_state:
        st.session_state.user_id = ""

    if "user_name" not in st.session_state:
        st.session_state.user_name = ""

    if "page" not in st.session_state:
        st.session_state.page = "home"

    if "chats" not in st.session_state:
        st.session_state.chats = {}

    if "current_chat_id" not in st.session_state:
        st.session_state.current_chat_id = None

    if "recommended_questions" not in st.session_state:
        st.session_state.recommended_questions = [
            "์ถœ์„ ์ธ์ • ์š”์ฒญ์€ ์–ด๋–ป๊ฒŒ ํ•˜๋‚˜์š”?",
            "๊ฐ•์˜ ๋‹ค์‹œ๋ณด๊ธฐ๋ฅผ ํ•  ์ˆ˜ ์žˆ๋‚˜์š”?",
            "ํ›ˆ๋ จ์žฅ๋ ค๊ธˆ์€ ์–ธ์ œ ์ง€๊ธ‰๋˜๋‚˜์š”?",
            "๊ฐœ์ธ ํฌํŠธํด๋ฆฌ์˜ค๋กœ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ๋ฒ”์œ„๊ฐ€ ์–ด๋–ป๊ฒŒ ๋˜๋‚˜์š”?"
        ]

    if "rag_upload_signature" not in st.session_state:
        st.session_state.rag_upload_signature = None

    if "retriever" not in st.session_state:
        st.session_state.retriever = None

    if "rag_chain" not in st.session_state:
        st.session_state.rag_chain = None

    if "format_docs" not in st.session_state:
        st.session_state.format_docs = None


init_session_state()


# =========================================================
# 3. ๋Œ€ํ™” ์„ธ์…˜ ๊ด€๋ฆฌ ํ•จ์ˆ˜: 1๋ฒˆ ์ฝ”๋“œ ๊ธฐ๋ฐ˜
# =========================================================
def create_new_chat():
    chat_id = str(uuid.uuid4())

    st.session_state.chats[chat_id] = {
        "title": "์ƒˆ ๋Œ€ํ™”",
        "created_at": datetime.now().strftime("%Y-%m-%d %H:%M"),
        "messages": []
    }

    st.session_state.current_chat_id = chat_id
    st.session_state.page = "home"


def get_current_messages():
    if st.session_state.current_chat_id is None:
        create_new_chat()

    return st.session_state.chats[st.session_state.current_chat_id]["messages"]


def update_chat_title(question):
    chat_id = st.session_state.current_chat_id

    if chat_id is None:
        return

    current_title = st.session_state.chats[chat_id]["title"]

    if current_title == "์ƒˆ ๋Œ€ํ™”":
        title = question.strip()
        if len(title) > 24:
            title = title[:24] + "..."
        st.session_state.chats[chat_id]["title"] = title


def delete_chat(chat_id):
    if chat_id in st.session_state.chats:
        del st.session_state.chats[chat_id]

    if st.session_state.current_chat_id == chat_id:
        if st.session_state.chats:
            latest_chat_id = list(st.session_state.chats.keys())[-1]
            st.session_state.current_chat_id = latest_chat_id
        else:
            create_new_chat()

    st.session_state.page = "home"


# =========================================================
# 4. ๋ฌธ์„œ ๋กœ๋”ฉ ํ•จ์ˆ˜: 1๋ฒˆ ์ฝ”๋“œ ๊ธฐ๋ฐ˜ + UPLOAD_DIR ๋ณด์™„
# =========================================================
def safe_filename(filename):
    filename = re.sub(r"[^๊ฐ€-ํžฃa-zA-Z0-9_.-]", "_", filename)
    return filename


def load_txt_file(file_path):
    try:
        text = file_path.read_text(encoding="utf-8")
    except UnicodeDecodeError:
        text = file_path.read_text(encoding="cp949")

    return [
        Document(
            page_content=text,
            metadata={"source": str(file_path)}
        )
    ]


def load_csv_file(file_path):
    rows = []

    try:
        f = open(file_path, "r", encoding="utf-8")
    except UnicodeDecodeError:
        f = open(file_path, "r", encoding="cp949")

    with f:
        reader = csv.reader(f)
        for row in reader:
            rows.append(" | ".join(row))

    text = "\n".join(rows)

    return [
        Document(
            page_content=text,
            metadata={"source": str(file_path)}
        )
    ]


def load_pdf_file(file_path):
    loader = PyMuPDFLoader(str(file_path))
    return loader.load()


def load_faq_from_pdf(pdf_path):
    """
    ์—…๋กœ๋“œ๋œ ํ†ตํ•ฉ ๋ฐฑ์„œ PDF ์•ˆ์˜ ์ œ4์žฅ FAQ ํ‘œ๋ฅผ ์ฝ์–ด์„œ
    category/question/answer ๊ตฌ์กฐ๋กœ ๋ณ€ํ™˜ํ•œ๋‹ค.

    ์ด ํ•จ์ˆ˜๋Š” ๋ณ„๋„ FAQ PDF๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š”๋‹ค.
    ํ˜„์žฌ ํŒŒ์ผ์ฒ˜๋Ÿผ FAQ๊ฐ€ 18~31์ชฝ์— ์—ฌ๋Ÿฌ ํ‘œ๋กœ ๋‚˜๋‰˜์–ด ์žˆ๊ณ ,
    ์ผ๋ถ€ ํŽ˜์ด์ง€์—๋Š” ํ‘œ ํ—ค๋”๊ฐ€ ๋ฐ˜๋ณต๋˜์ง€ ์•Š๊ฑฐ๋‚˜ ๋‹ต๋ณ€์ด ๋‹ค์Œ ํŽ˜์ด์ง€๋กœ ์ด์–ด์ง€๋Š” ๊ฒฝ์šฐ๊นŒ์ง€ ์ฒ˜๋ฆฌํ•œ๋‹ค.
    """
    if not pdf_path.exists():
        st.warning(f"ํ†ตํ•ฉ ๋ฐฑ์„œ PDF ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค: {pdf_path}")
        return []

    faq_data = []

    # ์ด PDF์—์„œ ์‹ค์ œ FAQ ํ‘œ์— ์“ฐ์ด๋Š” ์นดํ…Œ๊ณ ๋ฆฌ๋งŒ ํ—ˆ์šฉํ•œ๋‹ค.
    # ์ด๋ ‡๊ฒŒ ํ•ด์•ผ 1~8๊ธฐ ์šฐ์ˆ˜ ํ”„๋กœ์ ํŠธ ๋ชฉ๋ก ๊ฐ™์€ ๋‹ค๋ฅธ ํ‘œ๊ฐ€ FAQ๋กœ ์ž˜๋ชป ๋“ค์–ด๊ฐ€๋Š” ๊ฒƒ์„ ๋ง‰์„ ์ˆ˜ ์žˆ๋‹ค.
    valid_categories = {
        "๋ชจ์ง‘/์„ ๋ฐœ",
        "์ถœ์„",
        "๊ฐ•์˜",
        "KDT",
        "AIVLE-EDU",
        "๊ต์œก์žฅ",
        "๊ธฐํƒ€",
        "์ฝ”๋”ฉ ํ•™์Šต",
        "๋…ธํŠธ๋ถ",
        "๊ตญ๋ฏผ์ทจ์—…์ œ๋„",
        "์ทจ์—…์ง€์›/์ฑ„์šฉ์—ฐ๊ณ„",
        "ํ•™์Šต",
        "ํ”„๋กœ์ ํŠธ",
    }

    def clean_text(text):
        if text is None:
            return ""

        text = str(text).replace("\n", " ")
        text = re.sub(r"\s+", " ", text)
        return text.strip()

    def normalize_category(text):
        category = clean_text(text)

        # PDF ํ‘œ ์ถ”์ถœ ์‹œ ์ค„๋ฐ”๊ฟˆ ๋•Œ๋ฌธ์— ์นดํ…Œ๊ณ ๋ฆฌ๊ฐ€ ์ชผ๊ฐœ์ง€๋Š” ๊ฒฝ์šฐ ๋ณด์ •
        category = category.replace("๊ตญ๋ฏผ์ทจ์—…์ œ ๋„", "๊ตญ๋ฏผ์ทจ์—…์ œ๋„")
        category = category.replace("์ทจ์—…์ง€์›/ ์ฑ„์šฉ์—ฐ๊ณ„", "์ทจ์—…์ง€์›/์ฑ„์šฉ์—ฐ๊ณ„")

        return category

    try:
        doc = fitz.open(str(pdf_path))

        in_faq_section = False
        last_item = None

        for page in doc:
            page_text = page.get_text("text")

            # ๋ชฉ์ฐจ์—๋„ "์ œ4์žฅ" ๋ฌธ๊ตฌ๊ฐ€ ์žˆ๊ธฐ ๋•Œ๋ฌธ์—, FAQ ๋ณธ๋ฌธ ์•ˆ๋‚ด ๋ฌธ์žฅ ๋˜๋Š” ์‹ค์ œ ๋ณธ๋ฌธ ํŽ˜์ด์ง€ ์กฐ๊ฑด์œผ๋กœ ์‹œ์ž‘์ ์„ ์žก๋Š”๋‹ค.
            if (
                "FAQ ๋Š” ์ง€์› ์ „ ๊ถ๊ธˆ์ฆ" in page_text
                or (
                    re.search(r"์ œ\s*4\s*์žฅ\.?\s*์ž์ฃผ ๋ฌป๋Š” ์งˆ๋ฌธ", page_text)
                    and "๋ชฉ ์ฐจ" not in page_text
                    and page.number > 5
                )
            ):
                in_faq_section = True

            if not in_faq_section:
                continue

            tables = page.find_tables()

            for table in tables:
                rows = table.extract()

                for row in rows:
                    # PyMuPDF๊ฐ€ 9์—ด์งœ๋ฆฌ ํ‘œ์ฒ˜๋Ÿผ ์ฝ๋”๋ผ๋„ ๋นˆ ์นธ์„ ์ œ๊ฑฐํ•˜๋ฉด
                    # ์‹ค์ œ ๊ฐ’์€ ["๊ตฌ๋ถ„", "์งˆ๋ฌธ", "๋‹ต๋ณ€"] ๋˜๋Š” [์นดํ…Œ๊ณ ๋ฆฌ, ์งˆ๋ฌธ, ๋‹ต๋ณ€] ํ˜•ํƒœ๊ฐ€ ๋œ๋‹ค.
                    cells = [clean_text(cell) for cell in row if clean_text(cell)]

                    if not cells:
                        continue

                    # ํ‘œ ํ—ค๋” ์ œ๊ฑฐ
                    if cells == ["๊ตฌ๋ถ„", "์งˆ๋ฌธ", "๋‹ต๋ณ€"]:
                        continue

                    # ์ด์ „ ๋‹ต๋ณ€์ด ๋‹ค์Œ ํŽ˜์ด์ง€/๋‹ค์Œ ํ–‰์œผ๋กœ ์ด์–ด์ง„ ๊ฒฝ์šฐ
                    # ์˜ˆ: ์•ž ํŽ˜์ด์ง€ ๋งˆ์ง€๋ง‰ ๋‹ต๋ณ€์˜ ๋‚˜๋จธ์ง€ ๋ฌธ์žฅ์ด ๋‹ค์Œ ํŽ˜์ด์ง€ ์ฒซ ํ–‰์— ๋‹จ๋…์œผ๋กœ ์žกํžˆ๋Š” ๊ฒฝ์šฐ
                    if len(cells) == 1:
                        if last_item and not cells[0].startswith("KT AIVLE"):
                            last_item["answer"] = f"{last_item['answer']}\n{cells[0]}".strip()
                        continue

                    if len(cells) < 3:
                        continue

                    category = normalize_category(cells[0])
                    question = clean_text(cells[1])
                    answer = clean_text(cells[2])

                    if category not in valid_categories:
                        continue

                    if not question or not answer:
                        continue

                    if question == "์งˆ๋ฌธ" or answer == "๋‹ต๋ณ€":
                        continue

                    item = {
                        "category": category,
                        "question": question,
                        "answer": answer
                    }

                    faq_data.append(item)
                    last_item = item

            # ์ œ5์žฅ์ด ๋‚˜์˜ค๋ฉด FAQ๋Š” ๋๋‚œ๋‹ค.
            # ๊ฐ™์€ ํŽ˜์ด์ง€์— FAQ ํ‘œ๊ฐ€ ๋จผ์ € ์žˆ๊ณ  ์ œ5์žฅ์ด ์•„๋ž˜์— ๋ถ™์–ด ์žˆ์„ ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ
            # ํ˜„์žฌ ํŽ˜์ด์ง€ ์ฒ˜๋ฆฌ๋Š” ๋งˆ์นœ ๋’ค ์ข…๋ฃŒํ•œ๋‹ค.
            if re.search(r"์ œ\s*5\s*์žฅ\.?\s*์„ ๋ฐฐ", page_text):
                break

        doc.close()

    except Exception as e:
        st.warning(f"ํ†ตํ•ฉ ๋ฐฑ์„œ์—์„œ FAQ ํ‘œ ์ถ”์ถœ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {e}")
        return []

    # ์ค‘๋ณต ์ œ๊ฑฐ: ๊ฐ™์€ ์งˆ๋ฌธ์ด ์š”์•ฝ FAQ ํ‘œ์— ํ•œ ๋ฒˆ ๋” ๋‚˜์˜ฌ ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ ์งˆ๋ฌธ ๊ธฐ์ค€์œผ๋กœ ํ•œ ๋ฒˆ๋งŒ ํ‘œ์‹œ
    unique_faq_data = []
    seen_questions = set()

    for item in faq_data:
        normalized_question = re.sub(r"\s+", " ", item["question"]).strip()

        if normalized_question in seen_questions:
            continue

        seen_questions.add(normalized_question)
        unique_faq_data.append(item)

    return unique_faq_data


def save_uploaded_files(uploaded_files):
    saved_paths = []

    if not uploaded_files:
        return saved_paths

    for uploaded_file in uploaded_files:
        filename = safe_filename(uploaded_file.name)
        save_path = UPLOAD_DIR / filename

        with open(save_path, "wb") as f:
            f.write(uploaded_file.getbuffer())

        saved_paths.append(save_path)

    return saved_paths


def load_all_documents(uploaded_files):
    docs = []

    if PDF_PATH.exists():
        docs.extend(load_pdf_file(PDF_PATH))
    else:
        st.warning(f"๊ธฐ๋ณธ ๋ฐฑ์„œ PDF๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค: {PDF_PATH}")

    # FAQ๋Š” ๋ณ„๋„ PDF๊ฐ€ ์•„๋‹ˆ๋ผ ํ†ตํ•ฉ ๋ฐฑ์„œ PDF ์•ˆ์— ํฌํ•จ๋˜์–ด ์žˆ์œผ๋ฏ€๋กœ
    # ์—ฌ๊ธฐ์—์„œ ๋”ฐ๋กœ ์ถ”๊ฐ€ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. PDF_PATH ํ•˜๋‚˜๋งŒ ๋ฌธ์„œ๋กœ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.
    saved_paths = save_uploaded_files(uploaded_files)

    for path in saved_paths:
        suffix = path.suffix.lower()

        if suffix == ".pdf":
            docs.extend(load_pdf_file(path))
        elif suffix == ".txt":
            docs.extend(load_txt_file(path))
        elif suffix == ".csv":
            docs.extend(load_csv_file(path))

    return docs


def get_upload_signature(uploaded_files):
    if not uploaded_files:
        return "no_upload"

    return "|".join([f"{f.name}:{f.size}" for f in uploaded_files])


FAQ_DATA = load_faq_from_pdf(PDF_PATH)

if not FAQ_DATA:
    st.warning("ํ†ตํ•ฉ ๋ฐฑ์„œ์—์„œ FAQ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜ค์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค. FAQ ํ‘œ ๊ตฌ์กฐ๋ฅผ ํ™•์ธํ•˜์„ธ์š”.")


# =========================================================
# 5. RAG ๊ตฌ์„ฑ ํ•จ์ˆ˜: 1๋ฒˆ ์ฝ”๋“œ ๊ธฐ๋ฐ˜
# =========================================================
def build_rag(uploaded_files):
    docs = load_all_documents(uploaded_files)

    if not docs:
        st.error("RAG์— ์‚ฌ์šฉํ•  ๋ฌธ์„œ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ๊ธฐ๋ณธ ๋ฐฑ์„œ PDF ๋˜๋Š” ์—…๋กœ๋“œ ํŒŒ์ผ์„ ํ™•์ธํ•˜์„ธ์š”.")
        st.stop()

    splitter = RecursiveCharacterTextSplitter(
        chunk_size=1200,
        chunk_overlap=200,
        separators=["\n\n", "\n", ".", " ", ""]
    )

    chunks = splitter.split_documents(docs)
    embedding = OpenAIEmbeddings(model="text-embedding-3-small")
    vectorstore = FAISS.from_documents(chunks, embedding)

    retriever = vectorstore.as_retriever(
        search_kwargs={"k": 8}
    )

    llm = ChatOpenAI(
        model="gpt-4o-mini",
        temperature=0
    )

    prompt = ChatPromptTemplate.from_template("""
๋‹น์‹ ์€ AIVLE School ๋ฐฑ์„œ, FAQ, ์‚ฌ์šฉ์ž๊ฐ€ ์—…๋กœ๋“œํ•œ ์ž๋ฃŒ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ๋‹ต๋ณ€ํ•˜๋Š” ํ•™์Šต๋„์šฐ๋ฏธ ์ฑ—๋ด‡์ž…๋‹ˆ๋‹ค.

๊ทœ์น™:
1. ๋ฐ˜๋“œ์‹œ [๋ฌธ์„œ ๋‚ด์šฉ]์— ๊ทผ๊ฑฐํ•ด์„œ ๋‹ต๋ณ€ํ•˜์„ธ์š”.
2. ๋ฌธ์„œ์—์„œ ํ™•์ธ๋˜์ง€ ์•Š๋Š” ๋‚ด์šฉ์€ "๋ฌธ์„œ์—์„œ ํ™•์ธ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค."๋ผ๊ณ  ๋‹ตํ•˜์„ธ์š”.
3. ํ•œ๊ตญ์–ด๋กœ ์นœ์ ˆํ•˜๊ณ  ๊ฐ„๊ฒฐํ•˜๊ฒŒ ๋‹ต๋ณ€ํ•˜์„ธ์š”.
4. ์งˆ๋ฌธ๊ณผ ์ง์ ‘ ๊ด€๋ จ๋œ ๋‚ด์šฉ๋งŒ ๋‹ต๋ณ€ํ•˜์„ธ์š”.

[๋ฌธ์„œ ๋‚ด์šฉ]
{context}

[์งˆ๋ฌธ]
{question}
""")

    chain = prompt | llm | StrOutputParser()

    def format_docs(docs):
        return "\n\n".join(doc.page_content for doc in docs)

    return retriever, chain, format_docs


def ensure_rag_ready(uploaded_files):
    current_signature = get_upload_signature(uploaded_files)

    if (
        st.session_state.retriever is None
        or st.session_state.rag_chain is None
        or st.session_state.rag_upload_signature != current_signature
    ):
        with st.spinner("๋ฌธ์„œ๋ฅผ ์ฝ๊ณ  AI ๊ฒ€์ƒ‰ ์ธ๋ฑ์Šค๋ฅผ ์ค€๋น„ํ•˜๋Š” ์ค‘์ž…๋‹ˆ๋‹ค..."):
            retriever, rag_chain, format_docs = build_rag(uploaded_files)

        st.session_state.retriever = retriever
        st.session_state.rag_chain = rag_chain
        st.session_state.format_docs = format_docs
        st.session_state.rag_upload_signature = current_signature


# =========================================================
# 6. FAQ ๊ธฐ๋ฐ˜ ์ถ”์ฒœ ์งˆ๋ฌธ: 1๋ฒˆ ์ฝ”๋“œ ๊ธฐ๋ฐ˜
# =========================================================
@st.cache_resource
def build_faq_retriever():
    faq_docs = []

    for item in FAQ_DATA:
        faq_docs.append(
            Document(
                page_content=item["question"],
                metadata={
                    "category": item["category"],
                    "answer": item["answer"]
                }
            )
        )

    if not faq_docs:
        return None

    embedding = OpenAIEmbeddings(model="text-embedding-3-small")
    faq_vectorstore = FAISS.from_documents(faq_docs, embedding)

    return faq_vectorstore.as_retriever(search_kwargs={"k": 4})


def recommend_questions(user_question):
    try:
        faq_retriever = build_faq_retriever()

        if faq_retriever is None:
            return []

        docs = faq_retriever.invoke(user_question)
        recommended = []

        for doc in docs:
            q = doc.page_content.strip()
            if q and q not in recommended:
                recommended.append(q)

        return recommended[:4]

    except Exception as e:
        st.warning(f"์ถ”์ฒœ์งˆ๋ฌธ ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {e}")
        return []


# =========================================================
# 7. LangGraph ์งˆ๋ฌธ ๋ถ„๊ธฐ ์ฒ˜๋ฆฌ: 1๋ฒˆ ์ฝ”๋“œ ๊ธฐ๋ฐ˜
# =========================================================
class ChatState(TypedDict):
    question: str
    route: str
    context: str
    answer: str


def classify_question_node(state: ChatState) -> ChatState:
    question = state["question"]

    llm = ChatOpenAI(
        model="gpt-4o-mini",
        temperature=0
    )

    prompt = ChatPromptTemplate.from_template("""
๋‹น์‹ ์€ ์‚ฌ์šฉ์ž ์งˆ๋ฌธ์„ ๋ถ„๋ฅ˜ํ•˜๋Š” ๋ผ์šฐํ„ฐ์ž…๋‹ˆ๋‹ค.

์•„๋ž˜ ๊ธฐ์ค€์— ๋”ฐ๋ผ ์งˆ๋ฌธ์„ ๋ฐ˜๋“œ์‹œ ๋‘˜ ์ค‘ ํ•˜๋‚˜๋กœ๋งŒ ๋ถ„๋ฅ˜ํ•˜์„ธ์š”.

[AIVLE]
- KT AIVLE School, ์—์ด๋ธ”์Šค์ฟจ, ์—์ด๋ธ”๋Ÿฌ ๊ด€๋ จ ์งˆ๋ฌธ
- ์ถœ์„, ๊ฒฐ์„, ์ง€๊ฐ, ์กฐํ‡ด, ์™ธ์ถœ, ์ถœ์„ ์ธ์ • ๊ด€๋ จ ์งˆ๋ฌธ
- ๊ฐ•์˜, ๋‹ค์‹œ๋ณด๊ธฐ, ๊ต์œก ์ผ์ •, ์ฒดํฌ์ธ/์ฒดํฌ์•„์›ƒ ๊ด€๋ จ ์งˆ๋ฌธ
- KDT, ํ›ˆ๋ จ์žฅ๋ ค๊ธˆ, ๋‚ด์ผ๋ฐฐ์›€์นด๋“œ, ๊ตญ๋ฏผ์ทจ์—…์ง€์›์ œ๋„ ๊ด€๋ จ ์งˆ๋ฌธ
- ๊ต์œก์žฅ, ๋…ธํŠธ๋ถ, ์ฝ”๋”ฉ๋งˆ์Šคํ„ฐ์Šค, ์ฝ”๋”ฉ ํ•™์Šต ํ”Œ๋žซํผ ๊ด€๋ จ ์งˆ๋ฌธ
- ์ฑ„์šฉ์—ฐ๊ณ„, ํฌํŠธํด๋ฆฌ์˜ค, AX ์ฑŒ๋ฆฐ์ง€ ๋“ฑ ์—์ด๋ธ”์Šค์ฟจ ์ œ๋„ ๊ด€๋ จ ์งˆ๋ฌธ
- ์‚ฌ์šฉ์ž๊ฐ€ ์—…๋กœ๋“œํ•œ ๋ฐฑ์„œ/FAQ/๋ฌธ์„œ์—์„œ ๋‹ตํ•ด์•ผ ํ•  ์งˆ๋ฌธ

[GENERAL]
- ์œ„์™€ ๋ฌด๊ด€ํ•œ ์ผ๋ฐ˜ ์ง€์‹, ์ฝ”๋”ฉ, ์ƒํ™œ, ์Œ์‹, ๊ฑด๊ฐ•, ๋ฌธ์„œ ์ž‘์„ฑ, ๋ฒˆ์—ญ, ์ƒ๋‹ด ์งˆ๋ฌธ
- AIVLE ๋ฌธ์„œ ๊ทผ๊ฑฐ๊ฐ€ ํ•„์š” ์—†๋Š” ์ผ๋ฐ˜ ์งˆ๋ฌธ

์ถœ๋ ฅ ๊ทœ์น™:
- AIVLE ๊ด€๋ จ์ด๋ฉด AIVLE
- ์ผ๋ฐ˜ ์งˆ๋ฌธ์ด๋ฉด GENERAL
- ๋‹ค๋ฅธ ์„ค๋ช… ์—†์ด ๋‹จ์–ด ํ•˜๋‚˜๋งŒ ์ถœ๋ ฅ

[์‚ฌ์šฉ์ž ์งˆ๋ฌธ]
{question}
""")

    chain = prompt | llm | StrOutputParser()

    route = chain.invoke({
        "question": question
    }).strip().upper()

    if "AIVLE" in route:
        state["route"] = "aivle"
    else:
        state["route"] = "general"

    return state


def route_condition(state: ChatState) -> Literal["aivle", "general"]:
    return state["route"]


def aivle_rag_node(state: ChatState) -> ChatState:
    question = state["question"]

    docs = st.session_state.retriever.invoke(question)
    context = st.session_state.format_docs(docs)

    answer = st.session_state.rag_chain.invoke({
        "context": context,
        "question": question
    })

    state["context"] = context
    state["answer"] = answer

    return state


def general_llm_node(state: ChatState) -> ChatState:
    question = state["question"]

    llm = ChatOpenAI(
        model="gpt-4o-mini",
        temperature=0.3
    )

    prompt = ChatPromptTemplate.from_template("""
๋‹น์‹ ์€ ์นœ์ ˆํ•œ AI ํ•™์Šต ๋„์šฐ๋ฏธ์ž…๋‹ˆ๋‹ค.
์‚ฌ์šฉ์ž์˜ ์งˆ๋ฌธ์— ๋Œ€ํ•ด ํ•œ๊ตญ์–ด๋กœ ์ž์—ฐ์Šค๋Ÿฝ๊ณ  ์ดํ•ดํ•˜๊ธฐ ์‰ฝ๊ฒŒ ๋‹ต๋ณ€ํ•˜์„ธ์š”.

[์‚ฌ์šฉ์ž ์งˆ๋ฌธ]
{question}
""")

    chain = prompt | llm | StrOutputParser()

    answer = chain.invoke({
        "question": question
    })

    state["context"] = ""
    state["answer"] = answer

    return state


def build_question_graph():
    graph = StateGraph(ChatState)

    graph.add_node("classify", classify_question_node)
    graph.add_node("aivle_rag", aivle_rag_node)
    graph.add_node("general_llm", general_llm_node)

    graph.set_entry_point("classify")

    graph.add_conditional_edges(
        "classify",
        route_condition,
        {
            "aivle": "aivle_rag",
            "general": "general_llm"
        }
    )

    graph.add_edge("aivle_rag", END)
    graph.add_edge("general_llm", END)

    return graph.compile()


def run_langgraph_answer(question):
    app = build_question_graph()

    result = app.invoke({
        "question": question,
        "route": "",
        "context": "",
        "answer": ""
    })

    return result


# =========================================================
# 8. ์ฑ„ํŒ… ๋ถ€๊ฐ€ ๊ธฐ๋Šฅ: 2๋ฒˆ ์ฝ”๋“œ ๊ธฐ๋ฐ˜
# =========================================================
def copy_button(text, key):
    text_json = json.dumps(text, ensure_ascii=False)

    components.html(
        f"""
        <button onclick='navigator.clipboard.writeText({text_json})'
            style="
                margin-top:4px;
                padding:6px 12px;
                border-radius:8px;
                border:1px solid #d1d5db;
                background:white;
                cursor:pointer;
                font-size:13px;
            ">
            ๐Ÿ“‹ ๋ณต์‚ฌ
        </button>
        """,
        height=40
    )


def generate_tts(text, filename):
    speech_file = TEMP_DIR / f"{filename}.mp3"

    response = client.audio.speech.create(
        model="gpt-4o-mini-tts",
        voice="nova",
        input=text
    )

    response.stream_to_file(str(speech_file))
    return str(speech_file)


def transcribe_audio(audio_file):
    transcript = client.audio.transcriptions.create(
        model="whisper-1",
        file=audio_file
    )

    return transcript.text


def render_text_for_html(text):
    return html.escape(text).replace("\n", "<br>")


def answer_question(question):
    messages = get_current_messages()

    messages.append({
        "role": "user",
        "content": question
    })

    update_chat_title(question)

    result = run_langgraph_answer(question)

    answer = result["answer"]
    route = result["route"]

    if route == "aivle":
        route_label = "๐Ÿ“š FAQ/๋ฐฑ์„œ ๊ธฐ๋ฐ˜ ๋‹ต๋ณ€"
    else:
        route_label = "๐Ÿ’ฌ ์ผ๋ฐ˜ AI ๋‹ต๋ณ€"

    final_answer = f"{route_label}\n\n{answer}"

    messages.append({
        "role": "assistant",
        "content": final_answer
    })

    if route == "aivle":
        st.session_state.recommended_questions = recommend_questions(question)
    else:
        st.session_state.recommended_questions = []


# =========================================================
# 9. ์‚ฌ์ด๋“œ๋ฐ”: 1๋ฒˆ ์ฝ”๋“œ ๊ธฐ๋ฐ˜
# =========================================================
uploaded_files = None

with st.sidebar:
    if LOGO_PATH.exists():
        st.image(str(LOGO_PATH), width=240)
    else:
        st.markdown('<div class="sidebar-title">AIVLE ํ•™์Šต๋„์šฐ๋ฏธ</div>', unsafe_allow_html=True)

    st.markdown(
        '<div class="sidebar-subtitle">๋ฐฑ์„œ์™€ ์—…๋กœ๋“œ ์ž๋ฃŒ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ<br>ํ•™์Šต ์งˆ๋ฌธ์— ๋‹ต๋ณ€ํ•˜๋Š” AI ์ฑ—๋ด‡์ž…๋‹ˆ๋‹ค.</div>',
        unsafe_allow_html=True
    )

    st.markdown('<div class="sidebar-section-title">๐Ÿ‘ค ๊ณ„์ •</div>', unsafe_allow_html=True)

    if not st.session_state.logged_in:
        with st.form("login_form", clear_on_submit=False):
            login_name = st.text_input("์ด๋ฆ„", placeholder="์ด๋ฆ„์„ ์ž…๋ ฅํ•˜์„ธ์š”")
            login_id = st.text_input("์•„์ด๋””", placeholder="์•„์ด๋””๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”")
            login_pw = st.text_input("๋น„๋ฐ€๋ฒˆํ˜ธ", type="password", placeholder="๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”")

            login_btn = st.form_submit_button("๋กœ๊ทธ์ธ", use_container_width=True)

        if login_btn:
            if login_name.strip() and login_id.strip() and login_pw.strip():
                st.session_state.logged_in = True
                st.session_state.user_name = login_name.strip()
                st.session_state.user_id = login_id.strip()

                if st.session_state.current_chat_id is None:
                    create_new_chat()

                st.rerun()
            else:
                st.warning("์ด๋ฆ„, ์•„์ด๋””, ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ๋ชจ๋‘ ์ž…๋ ฅํ•˜์„ธ์š”.")

    else:
        st.markdown(
            f"""
            <div class="account-card">
                <div class="account-name">{html.escape(st.session_state.user_name)}๋‹˜</div>
                <div class="account-status">๋กœ๊ทธ์ธ ์ค‘</div>
            </div>
            """,
            unsafe_allow_html=True
        )

        if st.button("๋กœ๊ทธ์•„์›ƒ", use_container_width=True):
            st.session_state.logged_in = False
            st.session_state.user_name = ""
            st.session_state.user_id = ""
            st.session_state.page = "home"
            st.rerun()

    st.divider()

    if st.button("๏ผ‹ ์ƒˆ ๋Œ€ํ™” ์‹œ์ž‘", use_container_width=True, disabled=not st.session_state.logged_in):
        create_new_chat()
        st.rerun()

    col_home, col_faq = st.columns(2)

    with col_home:
        if st.button("๐Ÿ  ํ™ˆ", use_container_width=True, disabled=not st.session_state.logged_in):
            st.session_state.page = "home"
            st.rerun()

    with col_faq:
        if st.button("โ” FAQ", use_container_width=True, disabled=not st.session_state.logged_in):
            st.session_state.page = "faq"
            st.rerun()

    st.markdown('<div class="sidebar-section-title">๐Ÿ“Ž ์ž๋ฃŒ ์ถ”๊ฐ€</div>', unsafe_allow_html=True)

    with st.expander("ํŒŒ์ผ ์—…๋กœ๋“œ", expanded=False):
        uploaded_files = st.file_uploader(
            "PDF, TXT, CSV ํŒŒ์ผ์„ ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.",
            type=["pdf", "txt", "csv"],
            accept_multiple_files=True,
            disabled=not st.session_state.logged_in
        )

        if uploaded_files:
            st.success(f"{len(uploaded_files)}๊ฐœ ํŒŒ์ผ์ด ์ถ”๊ฐ€๋˜์—ˆ์Šต๋‹ˆ๋‹ค.")
        else:
            st.markdown(
                '<div class="sidebar-help">์—…๋กœ๋“œํ•œ ํŒŒ์ผ์€ ๊ธฐ์กด ๋ฐฑ์„œ์™€ ํ•จ๊ป˜ AI ๋‹ต๋ณ€์— ํ™œ์šฉ๋ฉ๋‹ˆ๋‹ค.</div>',
                unsafe_allow_html=True
            )

    st.divider()

    st.markdown('<div class="sidebar-section-title">๐Ÿ’ฌ ๋Œ€ํ™” ๊ธฐ๋ก</div>', unsafe_allow_html=True)

    if not st.session_state.logged_in:
        st.caption("๋กœ๊ทธ์ธ ํ›„ ๋Œ€ํ™” ๊ธฐ๋ก์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.")

    elif st.session_state.chats:
        chat_items = list(st.session_state.chats.items())[::-1]

        for chat_id, chat_info in chat_items:
            title = chat_info["title"]
            created_at = chat_info["created_at"]

            col_chat, col_delete = st.columns([5, 1])

            with col_chat:
                if st.button(f"๐Ÿ’ฌ {title}", key=f"chat_{chat_id}", use_container_width=True):
                    st.session_state.current_chat_id = chat_id
                    st.session_state.page = "home"
                    st.rerun()

            with col_delete:
                if st.button("๐Ÿ—‘", key=f"delete_{chat_id}", use_container_width=True):
                    delete_chat(chat_id)
                    st.rerun()

            st.markdown(
                f"<div class='history-caption'>{created_at}</div>",
                unsafe_allow_html=True
            )

    else:
        st.caption("์•„์ง ๋Œ€ํ™” ๊ธฐ๋ก์ด ์—†์Šต๋‹ˆ๋‹ค.")


# =========================================================
# 10. ๋กœ๊ทธ์ธ ์ „ ๊ธฐ๋Šฅ ์ฐจ๋‹จ: 1๋ฒˆ ์ฝ”๋“œ ๊ธฐ๋ฐ˜
# =========================================================
if not st.session_state.logged_in:
    st.markdown("""
    <div class="login-lock-box">
        <div class="login-lock-title">๐Ÿ”’ ๋กœ๊ทธ์ธ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค</div>
        <div class="login-lock-sub">
            ์‚ฌ์ด๋“œ๋ฐ”์—์„œ ์ด๋ฆ„, ์•„์ด๋””, ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด์•ผ<br>
            ์ฑ—๋ด‡, FAQ, ํŒŒ์ผ ์—…๋กœ๋“œ ๊ธฐ๋Šฅ์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
        </div>
    </div>
    """, unsafe_allow_html=True)

    st.stop()


# =========================================================
# 11. ๋กœ๊ทธ์ธ ํ›„ RAG ์ค€๋น„
# =========================================================
ensure_rag_ready(uploaded_files)


# =========================================================
# 12. FAQ ํ™”๋ฉด: 1๋ฒˆ ์ฝ”๋“œ ๊ธฐ๋ฐ˜
# =========================================================
def render_faq_page():
    st.markdown("## โ” FAQ")
    st.caption("์ž์ฃผ ๋ฌป๋Š” ์งˆ๋ฌธ์„ ์นดํ…Œ๊ณ ๋ฆฌ๋ณ„๋กœ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.")

    if not FAQ_DATA:
        st.warning("ํ†ตํ•ฉ ๋ฐฑ์„œ์—์„œ FAQ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜ค์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค. FAQ ํ‘œ ๊ตฌ์กฐ๋ฅผ ํ™•์ธํ•˜์„ธ์š”.")
        return

    categories = ["์ „์ฒด"] + sorted(list(set(item["category"] for item in FAQ_DATA)))
    selected_tabs = st.tabs(categories)

    for idx, tab in enumerate(selected_tabs):
        category = categories[idx]

        with tab:
            if category == "์ „์ฒด":
                items = FAQ_DATA
            else:
                items = [
                    item for item in FAQ_DATA
                    if item["category"] == category
                ]

            if not items:
                st.info("ํ•ด๋‹น ์นดํ…Œ๊ณ ๋ฆฌ์˜ FAQ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.")
                continue

            for item in items:
                with st.expander(f"[{item['category']}] {item['question']}"):
                    st.write(item["answer"])


# =========================================================
# 13. ํ™ˆ / ์ฑ„ํŒ… ํ™”๋ฉด: 2๋ฒˆ ์ฝ”๋“œ ์ฑ„ํŒ… UI ๊ธฐ๋ฐ˜ + 1๋ฒˆ ์ถ”์ฒœ ์งˆ๋ฌธ ์œ ์ง€
# =========================================================
def render_home_page():
    if IMAGE_BANNER_PATH.exists():
        st.image(str(IMAGE_BANNER_PATH), use_container_width=True)
    else:
        st.markdown(f"""
        <div class="hero-box">
            <div>
                <div class="hero-title">์•ˆ๋…•ํ•˜์„ธ์š”, {html.escape(st.session_state.user_name)}๋‹˜! ๐Ÿ˜Š<br>๋ฌด์—‡์„ ๋„์™€๋“œ๋ฆด๊นŒ์š”?</div>
                <div class="hero-sub">AIVLE ๋ฐฑ์„œ์™€ ์—…๋กœ๋“œํ•œ ์ž๋ฃŒ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ๋‹ต๋ณ€๋“œ๋ฆด๊ฒŒ์š”.</div>
            </div>
            <div class="robot">๐Ÿค–</div>
        </div>
        """, unsafe_allow_html=True)

    # -------------------------
    # FAQ ๊ธฐ๋ฐ˜ ์ถ”์ฒœ ์งˆ๋ฌธ
    # -------------------------
    st.markdown('<div class="section-title">์ถ”์ฒœ ์งˆ๋ฌธ</div>', unsafe_allow_html=True)

    rec_questions = st.session_state.recommended_questions

    if rec_questions:
        cols = st.columns(2)

        for i, q in enumerate(rec_questions):
            with cols[i % 2]:
                if st.button(q, key=f"rec_{i}_{q}", use_container_width=True):
                    answer_question(q)
                    st.rerun()
    else:
        st.caption("AIVLE ๊ด€๋ จ ์งˆ๋ฌธ์„ ์ž…๋ ฅํ•˜๋ฉด FAQ ๊ธฐ๋ฐ˜ ์ถ”์ฒœ ์งˆ๋ฌธ์ด ํ‘œ์‹œ๋ฉ๋‹ˆ๋‹ค.")

    # -------------------------
    # ์นด๋“œํ˜• ์ฑ„ํŒ… ๋ฉ”์‹œ์ง€ ์ถœ๋ ฅ
    # -------------------------
    messages = get_current_messages()

    st.markdown('<div class="chat-wrap">', unsafe_allow_html=True)

    if not messages:
        st.markdown("""
        <div style="min-height: 420px;">
            <div class="assistant-name">๐Ÿค– AIVLE ๋„์šฐ๋ฏธ</div>
            <div class="assistant-card">
                ์•ˆ๋…•ํ•˜์„ธ์š”! AIVLE ๋ฐฑ์„œ์™€ FAQ, ์—…๋กœ๋“œํ•œ ๋ฌธ์„œ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ์งˆ๋ฌธ์— ๋‹ต๋ณ€๋“œ๋ฆด๊ฒŒ์š”.<br>
                ์ผ๋ฐ˜ ์งˆ๋ฌธ์€ ๋ฌธ์„œ ๊ฒ€์ƒ‰ ์—†์ด ์ผ๋ฐ˜ AI ๋‹ต๋ณ€์œผ๋กœ ์•ˆ๋‚ดํ•ฉ๋‹ˆ๋‹ค.
            </div>
        </div>
        """, unsafe_allow_html=True)

    for idx, msg in enumerate(messages):
        content_html = render_text_for_html(msg["content"])

        if msg["role"] == "user":
            st.markdown(
                f'<div class="user-bubble">{content_html}</div>',
                unsafe_allow_html=True
            )
        else:
            st.markdown(
                f"""
                <div class="assistant-name">๐Ÿค– AIVLE ๋„์šฐ๋ฏธ</div>
                <div class="assistant-card">{content_html}</div>
                """,
                unsafe_allow_html=True
            )

            col_copy, col_tts = st.columns([1, 5])

            with col_copy:
                copy_button(msg["content"], key=f"copy_{idx}")

            with col_tts:
                if st.button("๐Ÿ”Š ์Œ์„ฑ์œผ๋กœ ๋“ฃ๊ธฐ", key=f"tts_{idx}"):
                    with st.spinner("์Œ์„ฑ์„ ์ƒ์„ฑํ•˜๋Š” ์ค‘์ž…๋‹ˆ๋‹ค..."):
                        audio_path = generate_tts(msg["content"], f"audio_{idx}_{st.session_state.current_chat_id}")
                    st.audio(audio_path)

    st.markdown('</div>', unsafe_allow_html=True)

    # -------------------------
    # ํ…์ŠคํŠธ + ์Œ์„ฑ ์ž…๋ ฅ
    # -------------------------
    col_text, col_audio = st.columns([5, 1])

    with col_text:
        user_input = st.chat_input("๋ฉ”์‹œ์ง€๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”...")

    with col_audio:
        audio_file = st.audio_input(
            "๐ŸŽค ์Œ์„ฑ ์งˆ๋ฌธ",
            label_visibility="collapsed"
        )

    if user_input:
        answer_question(user_input)
        st.rerun()

    if audio_file is not None:
        with st.spinner("์Œ์„ฑ์„ ๋ถ„์„ํ•˜๋Š” ์ค‘์ž…๋‹ˆ๋‹ค..."):
            question = transcribe_audio(audio_file)

        answer_question(question)
        st.rerun()


# =========================================================
# 14. ํ™”๋ฉด ๋ผ์šฐํŒ…
# =========================================================
if st.session_state.page == "faq":
    render_faq_page()
else:
    render_home_page()