File size: 70,542 Bytes
a2cc18f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
import os, json, re, logging, requests, markdown, time, io
from datetime import datetime
import random
import base64
from io import BytesIO
from PIL import Image

import streamlit as st
from openai import OpenAI

from gradio_client import Client
import pandas as pd
import PyPDF2  # For handling PDF files
import kagglehub

# ──────────────────────────────── Environment Variables / Constants ─────────────────────────
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")  
BRAVE_KEY      = os.getenv("SERPHOUSE_API_KEY", "")  # Keep this name
BRAVE_ENDPOINT = "https://api.search.brave.com/res/v1/web/search"
BRAVE_VIDEO_ENDPOINT = "https://api.search.brave.com/res/v1/videos/search"
BRAVE_NEWS_ENDPOINT  = "https://api.search.brave.com/res/v1/news/search"
IMAGE_API_URL  = "http://211.233.58.201:7896"
MAX_TOKENS     = 7999
KAGGLE_API_KEY = os.getenv("KDATA_API", "")

# Set Kaggle API key
os.environ["KAGGLE_KEY"] = KAGGLE_API_KEY

# Analysis modes and style definitions
ANALYSIS_MODES = {
    "price_forecast": "농산물 가격 예츑과 μ‹œμž₯ 뢄석",
    "market_trend": "μ‹œμž₯ 동ν–₯ 및 μˆ˜μš” νŒ¨ν„΄ 뢄석",
    "production_analysis": "μƒμ‚°λŸ‰ 뢄석 및 μ‹λŸ‰ μ•ˆλ³΄ 전망",
    "agricultural_policy": "농업 μ •μ±… 및 규제 영ν–₯ 뢄석",
    "climate_impact": "κΈ°ν›„ λ³€ν™”κ°€ 농업에 λ―ΈμΉ˜λŠ” 영ν–₯ 뢄석"
}

RESPONSE_STYLES = {
    "professional": "전문적이고 ν•™μˆ μ μΈ 뢄석",
    "simple": "μ‰½κ²Œ 이해할 수 μžˆλŠ” κ°„κ²°ν•œ μ„€λͺ…",
    "detailed": "μƒμ„Έν•œ 톡계 기반 깊이 μžˆλŠ” 뢄석",
    "action_oriented": "μ‹€ν–‰ κ°€λŠ₯ν•œ μ‘°μ–Έκ³Ό μΆ”μ²œ 쀑심"
}

# Example search queries
EXAMPLE_QUERIES = {
    "example1": "μŒ€ 가격 μΆ”μ„Έ 및 ν–₯ν›„ 6κ°œμ›” 전망을 λΆ„μ„ν•΄μ£Όμ„Έμš”",
    "example2": "κΈ°ν›„ λ³€ν™”λ‘œ ν•œκ΅­ 과일 생산 μ „λž΅κ³Ό μˆ˜μš” 예츑 λ³΄κ³ μ„œλ₯Ό μž‘μ„±ν•˜λΌ.",
    "example3": "2025λ…„λΆ€ν„° 2030λ…„κΉŒμ§€ 좩뢁 μ¦ν‰κ΅°μ—μ„œ μž¬λ°°ν•˜λ©΄ μœ λ§ν•œ μž‘λ¬Όμ€? μˆ˜μ΅μ„±κ³Ό 관리성이 μ’‹μ•„μ•Όν•œλ‹€"
}

# ──────────────────────────────── Logging ────────────────────────────────
logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s - %(levelname)s - %(message)s")

# ──────────────────────────────── OpenAI Client ──────────────────────────

@st.cache_resource
def get_openai_client():
    """Create an OpenAI client with timeout and retry settings."""
    if not OPENAI_API_KEY:
        raise RuntimeError("⚠️ OPENAI_API_KEY ν™˜κ²½ λ³€μˆ˜κ°€ μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.")
    return OpenAI(
        api_key=OPENAI_API_KEY,
        timeout=60.0,
        max_retries=3
    )

# ────────────────────────────── Kaggle Dataset Access ──────────────────────
@st.cache_resource
def load_agriculture_dataset():
    """Download and load the UN agriculture dataset from Kaggle"""
    try:
        path = kagglehub.dataset_download("unitednations/global-food-agriculture-statistics")
        logging.info(f"Kaggle dataset downloaded to: {path}")
        
        # Load metadata about available files
        available_files = []
        for root, dirs, files in os.walk(path):
            for file in files:
                if file.endswith('.csv'):
                    file_path = os.path.join(root, file)
                    file_size = os.path.getsize(file_path) / (1024 * 1024)  # Size in MB
                    available_files.append({
                        'name': file,
                        'path': file_path,
                        'size_mb': round(file_size, 2)
                    })
        
        return {
            'base_path': path,
            'files': available_files
        }
    except Exception as e:
        logging.error(f"Error loading Kaggle dataset: {e}")
        return None

# New function to load Advanced Soybean Agricultural Dataset
@st.cache_resource
def load_soybean_dataset():
    """Download and load the Advanced Soybean Agricultural Dataset from Kaggle"""
    try:
        path = kagglehub.dataset_download("wisam1985/advanced-soybean-agricultural-dataset-2025")
        logging.info(f"Soybean dataset downloaded to: {path}")
        
        available_files = []
        for root, dirs, files in os.walk(path):
            for file in files:
                if file.endswith(('.csv', '.xlsx')):
                    file_path = os.path.join(root, file)
                    file_size = os.path.getsize(file_path) / (1024 * 1024)  # Size in MB
                    available_files.append({
                        'name': file,
                        'path': file_path,
                        'size_mb': round(file_size, 2)
                    })
        
        return {
            'base_path': path,
            'files': available_files
        }
    except Exception as e:
        logging.error(f"Error loading Soybean dataset: {e}")
        return None

# Function to load Crop Recommendation Dataset
@st.cache_resource
def load_crop_recommendation_dataset():
    """Download and load the Soil and Environmental Variables Crop Recommendation Dataset"""
    try:
        path = kagglehub.dataset_download("agriinnovate/agricultural-crop-dataset")
        logging.info(f"Crop recommendation dataset downloaded to: {path}")
        
        available_files = []
        for root, dirs, files in os.walk(path):
            for file in files:
                if file.endswith(('.csv', '.xlsx')):
                    file_path = os.path.join(root, file)
                    file_size = os.path.getsize(file_path) / (1024 * 1024)  # Size in MB
                    available_files.append({
                        'name': file,
                        'path': file_path,
                        'size_mb': round(file_size, 2)
                    })
        
        return {
            'base_path': path,
            'files': available_files
        }
    except Exception as e:
        logging.error(f"Error loading Crop recommendation dataset: {e}")
        return None

# Function to load Climate Change Impact Dataset
@st.cache_resource
def load_climate_impact_dataset():
    """Download and load the Climate Change Impact on Agriculture Dataset"""
    try:
        path = kagglehub.dataset_download("waqi786/climate-change-impact-on-agriculture")
        logging.info(f"Climate impact dataset downloaded to: {path}")
        
        available_files = []
        for root, dirs, files in os.walk(path):
            for file in files:
                if file.endswith(('.csv', '.xlsx')):
                    file_path = os.path.join(root, file)
                    file_size = os.path.getsize(file_path) / (1024 * 1024)  # Size in MB
                    available_files.append({
                        'name': file,
                        'path': file_path,
                        'size_mb': round(file_size, 2)
                    })
        
        return {
            'base_path': path,
            'files': available_files
        }
    except Exception as e:
        logging.error(f"Error loading Climate impact dataset: {e}")
        return None

def get_dataset_summary():
    """Generate a summary of the available agriculture datasets"""
    dataset_info = load_agriculture_dataset()
    if not dataset_info:
        return "Failed to load the UN global food and agriculture statistics dataset."
    
    summary = "# UN κΈ€λ‘œλ²Œ μ‹λŸ‰ 및 농업 톡계 데이터셋\n\n"
    summary += f"총 {len(dataset_info['files'])}개의 CSV 파일이 ν¬ν•¨λ˜μ–΄ μžˆμŠ΅λ‹ˆλ‹€.\n\n"
    
    # List files with sizes
    summary += "## μ‚¬μš© κ°€λŠ₯ν•œ 데이터 파일:\n\n"
    for i, file_info in enumerate(dataset_info['files'][:10], 1):  # Limit to first 10 files
        summary += f"{i}. **{file_info['name']}** ({file_info['size_mb']} MB)\n"
    
    if len(dataset_info['files']) > 10:
        summary += f"\n...μ™Έ {len(dataset_info['files']) - 10}개 파일\n"
    
    # Add example of data structure
    try:
        if dataset_info['files']:
            sample_file = dataset_info['files'][0]['path']
            df = pd.read_csv(sample_file, nrows=5)
            summary += "\n## 데이터 μƒ˜ν”Œ ꡬ쑰:\n\n"
            summary += df.head(5).to_markdown() + "\n\n"
            
            summary += "## 데이터셋 λ³€μˆ˜ μ„€λͺ…:\n\n"
            for col in df.columns:
                summary += f"- **{col}**: [λ³€μˆ˜ μ„€λͺ… ν•„μš”]\n"
    except Exception as e:
        logging.error(f"Error generating dataset sample: {e}")
        summary += "\n데이터 μƒ˜ν”Œμ„ μƒμ„±ν•˜λŠ” 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€.\n"
    
    return summary

def analyze_dataset_for_query(query):
    """Find and analyze relevant data from the dataset based on the query"""
    dataset_info = load_agriculture_dataset()
    if not dataset_info:
        return "데이터셋을 뢈러올 수 μ—†μŠ΅λ‹ˆλ‹€. Kaggle API 연결을 ν™•μΈν•΄μ£Όμ„Έμš”."
    
    # Extract key terms from the query
    query_lower = query.lower()
    
    # Define keywords to look for in the dataset files
    keywords = {
        "μŒ€": ["rice", "grain"],
        "λ°€": ["wheat", "grain"],
        "μ˜₯수수": ["corn", "maize", "grain"],
        "μ±„μ†Œ": ["vegetable", "produce"],
        "과일": ["fruit", "produce"],
        "가격": ["price", "cost", "value"],
        "생산": ["production", "yield", "harvest"],
        "수좜": ["export", "trade"],
        "μˆ˜μž…": ["import", "trade"],
        "μ†ŒλΉ„": ["consumption", "demand"]
    }
    
    # Find relevant files based on the query
    relevant_files = []
    
    # First check for Korean keywords in the query
    found_keywords = []
    for k_term, e_terms in keywords.items():
        if k_term in query_lower:
            found_keywords.extend([k_term] + e_terms)
    
    # If no Korean keywords found, check for English terms in the filenames
    if not found_keywords:
        # Generic search through all files
        relevant_files = dataset_info['files'][:5]  # Take first 5 files as default
    else:
        # Search for files related to the found keywords
        for file_info in dataset_info['files']:
            file_name_lower = file_info['name'].lower()
            for keyword in found_keywords:
                if keyword.lower() in file_name_lower:
                    relevant_files.append(file_info)
                    break
        
        # If still no relevant files, take the first 5 files
        if not relevant_files:
            relevant_files = dataset_info['files'][:5]
    
    # Read and analyze the relevant files
    analysis_result = "# 농업 데이터 뢄석 κ²°κ³Ό\n\n"
    analysis_result += f"쿼리: '{query}'에 λŒ€ν•œ 뢄석을 μˆ˜ν–‰ν–ˆμŠ΅λ‹ˆλ‹€.\n\n"
    
    if found_keywords:
        analysis_result += f"## 뢄석 ν‚€μ›Œλ“œ: {', '.join(set(found_keywords))}\n\n"
    
    # Process each relevant file
    for file_info in relevant_files[:3]:  # Limit to 3 files for performance
        try:
            analysis_result += f"## 파일: {file_info['name']}\n\n"
            
            # Read the CSV file
            df = pd.read_csv(file_info['path'])
            
            # Basic file stats
            analysis_result += f"- ν–‰ 수: {len(df)}\n"
            analysis_result += f"- μ—΄ 수: {len(df.columns)}\n"
            analysis_result += f"- μ—΄ λͺ©λ‘: {', '.join(df.columns.tolist())}\n\n"
            
            # Sample data
            analysis_result += "### 데이터 μƒ˜ν”Œ:\n\n"
            analysis_result += df.head(5).to_markdown() + "\n\n"
            
            # Statistical summary of numeric columns
            numeric_cols = df.select_dtypes(include=['number']).columns
            if len(numeric_cols) > 0:
                analysis_result += "### κΈ°λ³Έ 톡계:\n\n"
                stats_df = df[numeric_cols].describe()
                analysis_result += stats_df.to_markdown() + "\n\n"
            
            # Time series analysis if possible
            time_cols = [col for col in df.columns if 'year' in col.lower() or 'date' in col.lower()]
            if time_cols:
                analysis_result += "### μ‹œκ³„μ—΄ νŒ¨ν„΄:\n\n"
                analysis_result += "데이터셋에 μ‹œκ°„ κ΄€λ ¨ 열이 μžˆμ–΄ μ‹œκ³„μ—΄ 뢄석이 κ°€λŠ₯ν•©λ‹ˆλ‹€.\n\n"
            
        except Exception as e:
            logging.error(f"Error analyzing file {file_info['name']}: {e}")
            analysis_result += f"이 파일 뢄석 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: {str(e)}\n\n"
    
    analysis_result += "## 농산물 가격 예츑 및 μˆ˜μš” 뢄석에 λŒ€ν•œ μΈμ‚¬μ΄νŠΈ\n\n"
    analysis_result += "λ°μ΄ν„°μ…‹μ—μ„œ μΆ”μΆœν•œ 정보λ₯Ό λ°”νƒ•μœΌλ‘œ λ‹€μŒ μΈμ‚¬μ΄νŠΈλ₯Ό μ œκ³΅ν•©λ‹ˆλ‹€:\n\n"
    analysis_result += "1. 데이터 기반 뢄석 (기본적인 μš”μ•½)\n"
    analysis_result += "2. μ£Όμš” 가격 및 μˆ˜μš” 동ν–₯\n"
    analysis_result += "3. μƒμ‚°λŸ‰ 및 무역 νŒ¨ν„΄\n\n"
    
    analysis_result += "이 뢄석은 UN κΈ€λ‘œλ²Œ μ‹λŸ‰ 및 농업 톡계 데이터셋을 기반으둜 ν•©λ‹ˆλ‹€.\n\n"
    
    return analysis_result

# Function to analyze crop recommendation dataset
def analyze_crop_recommendation_dataset(query):
    """Find and analyze crop recommendation data based on the query"""
    try:
        dataset_info = load_crop_recommendation_dataset()
        if not dataset_info or not dataset_info['files']:
            return "μž‘λ¬Ό μΆ”μ²œ 데이터셋을 뢈러올 수 μ—†μŠ΅λ‹ˆλ‹€."
        
        analysis_result = "# ν† μ–‘ 및 ν™˜κ²½ λ³€μˆ˜ 기반 μž‘λ¬Ό μΆ”μ²œ 데이터 뢄석\n\n"
        
        # Process main files
        for file_info in dataset_info['files'][:2]:  # Limit to the first 2 files
            try:
                analysis_result += f"## 파일: {file_info['name']}\n\n"
                
                if file_info['name'].endswith('.csv'):
                    df = pd.read_csv(file_info['path'])
                elif file_info['name'].endswith('.xlsx'):
                    df = pd.read_excel(file_info['path'])
                else:
                    continue
                
                # Basic dataset info
                analysis_result += f"- 데이터 크기: {len(df)} ν–‰ Γ— {len(df.columns)} μ—΄\n"
                analysis_result += f"- ν¬ν•¨λœ μž‘λ¬Ό μ’…λ₯˜: "
                
                # Check if crop column exists
                crop_cols = [col for col in df.columns if 'crop' in col.lower() or 'μž‘λ¬Ό' in col.lower()]
                if crop_cols:
                    main_crop_col = crop_cols[0]
                    unique_crops = df[main_crop_col].unique()
                    analysis_result += f"{len(unique_crops)}μ’… ({', '.join(str(c) for c in unique_crops[:10])})\n\n"
                else:
                    analysis_result += "μž‘λ¬Ό 정보 열을 찾을 수 μ—†μŒ\n\n"
                
                # Extract environmental factors
                env_factors = [col for col in df.columns if col.lower() not in ['crop', 'label', 'id', 'index']]
                if env_factors:
                    analysis_result += f"- 고렀된 ν™˜κ²½ μš”μ†Œ: {', '.join(env_factors)}\n\n"
                
                # Sample data
                analysis_result += "### 데이터 μƒ˜ν”Œ:\n\n"
                analysis_result += df.head(5).to_markdown() + "\n\n"
                
                # Summary statistics for environmental factors
                if env_factors:
                    numeric_factors = df[env_factors].select_dtypes(include=['number']).columns
                    if len(numeric_factors) > 0:
                        analysis_result += "### ν™˜κ²½ μš”μ†Œ 톡계:\n\n"
                        stats_df = df[numeric_factors].describe().round(2)
                        analysis_result += stats_df.to_markdown() + "\n\n"
                
                # Check for query-specific crops
                query_terms = query.lower().split()
                relevant_crops = []
                
                if crop_cols:
                    for crop in df[main_crop_col].unique():
                        crop_str = str(crop).lower()
                        if any(term in crop_str for term in query_terms):
                            relevant_crops.append(crop)
                
                if relevant_crops:
                    analysis_result += f"### 쿼리 κ΄€λ ¨ μž‘λ¬Ό 뢄석: {', '.join(str(c) for c in relevant_crops)}\n\n"
                    for crop in relevant_crops[:3]:  # Limit to 3 crops
                        crop_data = df[df[main_crop_col] == crop]
                        analysis_result += f"#### {crop} μž‘λ¬Ό μš”μ•½:\n\n"
                        analysis_result += f"- μƒ˜ν”Œ 수: {len(crop_data)}개\n"
                        
                        if len(numeric_factors) > 0:
                            crop_stats = crop_data[numeric_factors].describe().round(2)
                            analysis_result += f"- 평균 ν™˜κ²½ 쑰건:\n"
                            for factor in numeric_factors[:5]:  # Limit to 5 factors
                                analysis_result += f"  * {factor}: {crop_stats.loc['mean', factor]}\n"
                        analysis_result += "\n"
            
            except Exception as e:
                logging.error(f"Error analyzing crop recommendation file {file_info['name']}: {e}")
                analysis_result += f"뢄석 였λ₯˜: {str(e)}\n\n"
        
        analysis_result += "## μž‘λ¬Ό μΆ”μ²œ μΈμ‚¬μ΄νŠΈ\n\n"
        analysis_result += "ν† μ–‘ 및 ν™˜κ²½ λ³€μˆ˜ 데이터셋 뢄석 κ²°κ³Ό, λ‹€μŒκ³Ό 같은 μ£Όμš” μΈμ‚¬μ΄νŠΈλ₯Ό μ œκ³΅ν•©λ‹ˆλ‹€:\n\n"
        analysis_result += "1. μ§€μ—­ ν™˜κ²½μ— μ ν•©ν•œ μž‘λ¬Ό μΆ”μ²œ\n"
        analysis_result += "2. μž‘λ¬Ό 생산성에 영ν–₯을 λ―ΈμΉ˜λŠ” μ£Όμš” ν™˜κ²½ μš”μΈ\n"
        analysis_result += "3. 지속 κ°€λŠ₯ν•œ 농업을 μœ„ν•œ 졜적의 μž‘λ¬Ό 선택 κΈ°μ€€\n\n"
        
        return analysis_result
        
    except Exception as e:
        logging.error(f"Crop recommendation dataset analysis error: {e}")
        return "μž‘λ¬Ό μΆ”μ²œ 데이터셋 뢄석 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€."

# Function to analyze climate impact dataset
def analyze_climate_impact_dataset(query):
    """Find and analyze climate impact on agriculture data based on the query"""
    try:
        dataset_info = load_climate_impact_dataset()
        if not dataset_info or not dataset_info['files']:
            return "κΈ°ν›„ λ³€ν™” 영ν–₯ 데이터셋을 뢈러올 수 μ—†μŠ΅λ‹ˆλ‹€."
        
        analysis_result = "# κΈ°ν›„ λ³€ν™”κ°€ 농업에 λ―ΈμΉ˜λŠ” 영ν–₯ 데이터 뢄석\n\n"
        
        # Process main files
        for file_info in dataset_info['files'][:2]:  # Limit to first 2 files
            try:
                analysis_result += f"## 파일: {file_info['name']}\n\n"
                
                if file_info['name'].endswith('.csv'):
                    df = pd.read_csv(file_info['path'])
                elif file_info['name'].endswith('.xlsx'):
                    df = pd.read_excel(file_info['path'])
                else:
                    continue
                
                # Basic dataset info
                analysis_result += f"- 데이터 크기: {len(df)} ν–‰ Γ— {len(df.columns)} μ—΄\n"
                
                # Check for region column
                region_cols = [col for col in df.columns if 'region' in col.lower() or 'country' in col.lower() or 'μ§€μ—­' in col.lower()]
                if region_cols:
                    main_region_col = region_cols[0]
                    regions = df[main_region_col].unique()
                    analysis_result += f"- ν¬ν•¨λœ μ§€μ—­: {len(regions)}개 ({', '.join(str(r) for r in regions[:5])})\n"
                
                # Identify climate and crop related columns
                climate_cols = [col for col in df.columns if any(term in col.lower() for term in 
                                ['temp', 'rainfall', 'precipitation', 'climate', 'weather', '기온', 'κ°•μˆ˜λŸ‰'])]
                crop_cols = [col for col in df.columns if any(term in col.lower() for term in 
                            ['yield', 'production', 'crop', 'harvest', 'μˆ˜ν™•λŸ‰', 'μƒμ‚°λŸ‰'])]
                
                if climate_cols:
                    analysis_result += f"- κΈ°ν›„ κ΄€λ ¨ λ³€μˆ˜: {', '.join(climate_cols)}\n"
                if crop_cols:
                    analysis_result += f"- μž‘λ¬Ό κ΄€λ ¨ λ³€μˆ˜: {', '.join(crop_cols)}\n\n"
                
                # Sample data
                analysis_result += "### 데이터 μƒ˜ν”Œ:\n\n"
                analysis_result += df.head(5).to_markdown() + "\n\n"
                
                # Time series pattern if available
                year_cols = [col for col in df.columns if 'year' in col.lower() or 'date' in col.lower() or '연도' in col.lower()]
                if year_cols:
                    analysis_result += "### μ‹œκ³„μ—΄ κΈ°ν›„ 영ν–₯ νŒ¨ν„΄:\n\n"
                    analysis_result += "이 데이터셋은 μ‹œκ°„μ— λ”°λ₯Έ κΈ°ν›„ 변화와 농업 생산성 κ°„μ˜ 관계λ₯Ό 뢄석할 수 μžˆμŠ΅λ‹ˆλ‹€.\n\n"
                
                # Statistical summary of key variables
                key_vars = climate_cols + crop_cols
                numeric_vars = df[key_vars].select_dtypes(include=['number']).columns
                if len(numeric_vars) > 0:
                    analysis_result += "### μ£Όμš” λ³€μˆ˜ 톡계:\n\n"
                    stats_df = df[numeric_vars].describe().round(2)
                    analysis_result += stats_df.to_markdown() + "\n\n"
                
                # Check for correlations between climate and crop variables
                if len(climate_cols) > 0 and len(crop_cols) > 0:
                    numeric_climate = df[climate_cols].select_dtypes(include=['number']).columns
                    numeric_crop = df[crop_cols].select_dtypes(include=['number']).columns
                    
                    if len(numeric_climate) > 0 and len(numeric_crop) > 0:
                        analysis_result += "### 기후와 μž‘λ¬Ό 생산 κ°„μ˜ 상관관계:\n\n"
                        try:
                            corr_vars = list(numeric_climate)[:2] + list(numeric_crop)[:2]  # Limit to 2 of each type
                            corr_df = df[corr_vars].corr().round(3)
                            analysis_result += corr_df.to_markdown() + "\n\n"
                            analysis_result += "μœ„ 상관관계 ν‘œλŠ” κΈ°ν›„ λ³€μˆ˜μ™€ μž‘λ¬Ό 생산성 κ°„μ˜ 관계 강도λ₯Ό λ³΄μ—¬μ€λ‹ˆλ‹€.\n\n"
                        except:
                            analysis_result += "상관관계 계산 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€.\n\n"
            
            except Exception as e:
                logging.error(f"Error analyzing climate impact file {file_info['name']}: {e}")
                analysis_result += f"뢄석 였λ₯˜: {str(e)}\n\n"
        
        analysis_result += "## κΈ°ν›„ λ³€ν™” 영ν–₯ μΈμ‚¬μ΄νŠΈ\n\n"
        analysis_result += "κΈ°ν›„ λ³€ν™”κ°€ 농업에 λ―ΈμΉ˜λŠ” 영ν–₯ 데이터 뢄석 κ²°κ³Ό, λ‹€μŒκ³Ό 같은 μΈμ‚¬μ΄νŠΈλ₯Ό μ œκ³΅ν•©λ‹ˆλ‹€:\n\n"
        analysis_result += "1. 기온 변화에 λ”°λ₯Έ μž‘λ¬Ό 생산성 변동 νŒ¨ν„΄\n"
        analysis_result += "2. κ°•μˆ˜λŸ‰ λ³€ν™”κ°€ 농업 μˆ˜ν™•λŸ‰μ— λ―ΈμΉ˜λŠ” 영ν–₯\n"
        analysis_result += "3. κΈ°ν›„ 변화에 λŒ€μ‘ν•˜κΈ° μœ„ν•œ 농업 μ „λž΅ μ œμ•ˆ\n"
        analysis_result += "4. 지역별 κΈ°ν›„ μ·¨μ•½μ„± 및 적응 λ°©μ•ˆ\n\n"
        
        return analysis_result
        
    except Exception as e:
        logging.error(f"Climate impact dataset analysis error: {e}")
        return "κΈ°ν›„ λ³€ν™” 영ν–₯ 데이터셋 뢄석 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€."

# Function to analyze soybean dataset if selected
def analyze_soybean_dataset(query):
    """Find and analyze soybean agriculture data based on the query"""
    try:
        dataset_info = load_soybean_dataset()
        if not dataset_info or not dataset_info['files']:
            return "λŒ€λ‘ 농업 데이터셋을 뢈러올 수 μ—†μŠ΅λ‹ˆλ‹€."
        
        analysis_result = "# κ³ κΈ‰ λŒ€λ‘ 농업 데이터 뢄석\n\n"
        
        # Process main files
        for file_info in dataset_info['files'][:2]:  # Limit to the first 2 files
            try:
                analysis_result += f"## 파일: {file_info['name']}\n\n"
                
                if file_info['name'].endswith('.csv'):
                    df = pd.read_csv(file_info['path'])
                elif file_info['name'].endswith('.xlsx'):
                    df = pd.read_excel(file_info['path'])
                else:
                    continue
                
                # Basic file stats
                analysis_result += f"- 데이터 크기: {len(df)} ν–‰ Γ— {len(df.columns)} μ—΄\n"
                
                # Check for region/location columns
                location_cols = [col for col in df.columns if any(term in col.lower() for term in 
                                ['region', 'location', 'area', 'country', 'μ§€μ—­'])]
                if location_cols:
                    main_loc_col = location_cols[0]
                    locations = df[main_loc_col].unique()
                    analysis_result += f"- ν¬ν•¨λœ μ§€μ—­: {len(locations)}개 ({', '.join(str(loc) for loc in locations[:5])})\n"
                
                # Identify yield and production columns
                yield_cols = [col for col in df.columns if any(term in col.lower() for term in 
                             ['yield', 'production', 'harvest', 'μˆ˜ν™•λŸ‰', 'μƒμ‚°λŸ‰'])]
                if yield_cols:
                    analysis_result += f"- 생산성 κ΄€λ ¨ λ³€μˆ˜: {', '.join(yield_cols)}\n"
                
                # Identify environmental factors
                env_cols = [col for col in df.columns if any(term in col.lower() for term in 
                           ['temp', 'rainfall', 'soil', 'fertilizer', 'nutrient', 'irrigation', 
                            '기온', 'κ°•μˆ˜λŸ‰', 'ν† μ–‘', 'λΉ„λ£Œ', 'κ΄€κ°œ'])]
                if env_cols:
                    analysis_result += f"- ν™˜κ²½ κ΄€λ ¨ λ³€μˆ˜: {', '.join(env_cols)}\n\n"
                
                # Sample data
                analysis_result += "### 데이터 μƒ˜ν”Œ:\n\n"
                analysis_result += df.head(5).to_markdown() + "\n\n"
                
                # Statistical summary of key variables
                key_vars = yield_cols + env_cols
                numeric_vars = df[key_vars].select_dtypes(include=['number']).columns
                if len(numeric_vars) > 0:
                    analysis_result += "### μ£Όμš” λ³€μˆ˜ 톡계:\n\n"
                    stats_df = df[numeric_vars].describe().round(2)
                    analysis_result += stats_df.to_markdown() + "\n\n"
                
                # Time series analysis if possible
                year_cols = [col for col in df.columns if 'year' in col.lower() or 'date' in col.lower() or '연도' in col.lower()]
                if year_cols:
                    analysis_result += "### μ‹œκ³„μ—΄ 생산성 νŒ¨ν„΄:\n\n"
                    analysis_result += "이 데이터셋은 μ‹œκ°„μ— λ”°λ₯Έ λŒ€λ‘ μƒμ‚°μ„±μ˜ λ³€ν™”λ₯Ό 좔적할 수 μžˆμŠ΅λ‹ˆλ‹€.\n\n"
                
                # Check for correlations between environmental factors and yield
                if len(env_cols) > 0 and len(yield_cols) > 0:
                    numeric_env = df[env_cols].select_dtypes(include=['number']).columns
                    numeric_yield = df[yield_cols].select_dtypes(include=['number']).columns
                    
                    if len(numeric_env) > 0 and len(numeric_yield) > 0:
                        analysis_result += "### ν™˜κ²½ μš”μ†Œμ™€ λŒ€λ‘ 생산성 κ°„μ˜ 상관관계:\n\n"
                        try:
                            corr_vars = list(numeric_env)[:3] + list(numeric_yield)[:2]  # Limit variables
                            corr_df = df[corr_vars].corr().round(3)
                            analysis_result += corr_df.to_markdown() + "\n\n"
                        except:
                            analysis_result += "상관관계 계산 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€.\n\n"
            
            except Exception as e:
                logging.error(f"Error analyzing soybean file {file_info['name']}: {e}")
                analysis_result += f"뢄석 였λ₯˜: {str(e)}\n\n"
        
        analysis_result += "## λŒ€λ‘ 농업 μΈμ‚¬μ΄νŠΈ\n\n"
        analysis_result += "κ³ κΈ‰ λŒ€λ‘ 농업 데이터셋 뢄석 κ²°κ³Ό, λ‹€μŒκ³Ό 같은 μΈμ‚¬μ΄νŠΈλ₯Ό μ œκ³΅ν•©λ‹ˆλ‹€:\n\n"
        analysis_result += "1. 졜적의 λŒ€λ‘ 생산을 μœ„ν•œ ν™˜κ²½ 쑰건\n"
        analysis_result += "2. 지역별 λŒ€λ‘ 생산성 λ³€ν™” νŒ¨ν„΄\n"
        analysis_result += "3. 생산성 ν–₯상을 μœ„ν•œ 농업 기술 및 접근법\n"
        analysis_result += "4. μ‹œμž₯ μˆ˜μš”μ— λ§žλŠ” λŒ€λ‘ ν’ˆμ’… 선택 κ°€μ΄λ“œ\n\n"
        
        return analysis_result
        
    except Exception as e:
        logging.error(f"Soybean dataset analysis error: {e}")
        return "λŒ€λ‘ 농업 데이터셋 뢄석 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€."

# ──────────────────────────────── System Prompt ─────────────────────────
def get_system_prompt(mode="price_forecast", style="professional", include_search_results=True, include_uploaded_files=False) -> str:
    """
    Generate a system prompt for the 'Agricultural Price & Demand Forecast AI Assistant' interface based on:
    - The selected analysis mode and style
    - Guidelines for using agricultural datasets, web search results and uploaded files
    """
    base_prompt = """
당신은 농업 데이터 μ „λ¬Έκ°€λ‘œμ„œ 농산물 가격 예츑과 μˆ˜μš” 뢄석을 μˆ˜ν–‰ν•˜λŠ” AI μ–΄μ‹œμŠ€ν„΄νŠΈμž…λ‹ˆλ‹€.

μ£Όμš” μž„λ¬΄:
1. UN κΈ€λ‘œλ²Œ μ‹λŸ‰ 및 농업 톡계 데이터셋을 기반으둜 농산물 μ‹œμž₯ 뢄석
2. 농산물 가격 μΆ”μ„Έ 예츑 및 μˆ˜μš” νŒ¨ν„΄ 뢄석
3. 데이터λ₯Ό λ°”νƒ•μœΌλ‘œ λͺ…ν™•ν•˜κ³  κ·Όκ±° μžˆλŠ” 뢄석 제곡
4. κ΄€λ ¨ 정보와 μΈμ‚¬μ΄νŠΈλ₯Ό μ²΄κ³„μ μœΌλ‘œ κ΅¬μ„±ν•˜μ—¬ μ œμ‹œ
5. μ‹œκ°μ  이해λ₯Ό 돕기 μœ„ν•΄ 차트, κ·Έλž˜ν”„ 등을 적절히 ν™œμš©
6. ν† μ–‘ 및 ν™˜κ²½ λ³€μˆ˜ 기반 μž‘λ¬Ό μΆ”μ²œ λ°μ΄ν„°μ…‹μ—μ„œ μΆ”μΆœν•œ μΈμ‚¬μ΄νŠΈ 적용
7. κΈ°ν›„ λ³€ν™”κ°€ 농업에 λ―ΈμΉ˜λŠ” 영ν–₯ 데이터셋을 ν†΅ν•œ ν™˜κ²½ λ³€ν™” μ‹œλ‚˜λ¦¬μ˜€ 뢄석

μ€‘μš” κ°€μ΄λ“œλΌμΈ:
- 데이터에 κΈ°λ°˜ν•œ 객관적 뢄석을 μ œκ³΅ν•˜μ„Έμš”
- 뢄석 κ³Όμ •κ³Ό 방법둠을 λͺ…ν™•νžˆ μ„€λͺ…ν•˜μ„Έμš”
- 톡계적 μ‹ λ’°μ„±κ³Ό ν•œκ³„μ μ„ 투λͺ…ν•˜κ²Œ μ œμ‹œν•˜μ„Έμš”
- μ΄ν•΄ν•˜κΈ° μ‰¬μš΄ μ‹œκ°μ  μš”μ†Œλ‘œ 뢄석 κ²°κ³Όλ₯Ό λ³΄μ™„ν•˜μ„Έμš”
- λ§ˆν¬λ‹€μš΄μ„ ν™œμš©ν•΄ 응닡을 μ²΄κ³„μ μœΌλ‘œ κ΅¬μ„±ν•˜μ„Έμš”
"""

    mode_prompts = {
        "price_forecast": """
농산물 가격 예츑 및 μ‹œμž₯ 뢄석에 μ§‘μ€‘ν•©λ‹ˆλ‹€:
- κ³Όκ±° 가격 데이터 νŒ¨ν„΄μ— κΈ°λ°˜ν•œ 예츑 제곡
- 가격 변동성 μš”μΈ 뢄석(κ³„μ ˆμ„±, 날씨, μ •μ±… λ“±)
- 단기 및 쀑μž₯κΈ° 가격 전망 μ œμ‹œ
- 가격에 영ν–₯을 λ―ΈμΉ˜λŠ” κ΅­λ‚΄μ™Έ μš”μΈ 식별
- μ‹œμž₯ λΆˆν™•μ‹€μ„±κ³Ό 리슀크 μš”μ†Œ κ°•μ‘°
""",
        "market_trend": """
μ‹œμž₯ 동ν–₯ 및 μˆ˜μš” νŒ¨ν„΄ 뢄석에 μ§‘μ€‘ν•©λ‹ˆλ‹€:
- μ£Όμš” 농산물 μˆ˜μš” λ³€ν™” νŒ¨ν„΄ 식별
- μ†ŒλΉ„μž μ„ ν˜Έλ„ 및 ꡬ맀 행동 뢄석
- μ‹œμž₯ μ„Έκ·Έλ¨ΌνŠΈ 및 ν‹ˆμƒˆμ‹œμž₯ 기회 탐색
- μ‹œμž₯ ν™•λŒ€/μΆ•μ†Œ νŠΈλ Œλ“œ 평가
- μˆ˜μš” 탄λ ₯μ„± 및 가격 민감도 뢄석
""",
        "production_analysis": """
μƒμ‚°λŸ‰ 뢄석 및 μ‹λŸ‰ μ•ˆλ³΄ 전망에 μ§‘μ€‘ν•©λ‹ˆλ‹€:
- μž‘λ¬Ό μƒμ‚°λŸ‰ μΆ”μ„Έ 및 변동 μš”μΈ 뢄석
- μ‹λŸ‰ 생산과 인ꡬ μ„±μž₯ κ°„μ˜ 관계 평가
- κ΅­κ°€/지역별 생산 μ—­λŸ‰ 비ꡐ
- μ‹λŸ‰ μ•ˆλ³΄ μœ„ν˜‘ μš”μ†Œ 및 취약점 식별
- 생산성 ν–₯상 μ „λž΅ 및 기회 μ œμ•ˆ
""",
        "agricultural_policy": """
농업 μ •μ±… 및 규제 영ν–₯ 뢄석에 μ§‘μ€‘ν•©λ‹ˆλ‹€:
- μ •λΆ€ μ •μ±…κ³Ό, 보쑰금, 규제의 μ‹œμž₯ 영ν–₯ 뢄석
- ꡭ제 무역 μ •μ±…κ³Ό κ΄€μ„Έμ˜ 농산물 가격 영ν–₯ 평가
- 농업 지원 ν”„λ‘œκ·Έλž¨μ˜ νš¨κ³Όμ„± κ²€ν† 
- 규제 ν™˜κ²½ 변화에 λ”°λ₯Έ μ‹œμž₯ μ‘°μ • 예츑
- 정책적 κ°œμž…μ˜ μ˜λ„λœ/μ˜λ„μΉ˜ μ•Šμ€ κ²°κ³Ό 뢄석
""",
        "climate_impact": """
κΈ°ν›„ λ³€ν™”κ°€ 농업에 λ―ΈμΉ˜λŠ” 영ν–₯ 뢄석에 μ§‘μ€‘ν•©λ‹ˆλ‹€:
- κΈ°ν›„ 변화와 농산물 μƒμ‚°λŸ‰/ν’ˆμ§ˆ κ°„μ˜ 상관관계 뢄석
- 기상 이변이 가격 변동성에 λ―ΈμΉ˜λŠ” 영ν–₯ 평가
- μž₯기적 κΈ°ν›„ 좔세에 λ”°λ₯Έ 농업 νŒ¨ν„΄ λ³€ν™” 예츑
- κΈ°ν›„ 회볡λ ₯ μžˆλŠ” 농업 μ‹œμŠ€ν…œ μ „λž΅ μ œμ•ˆ
- 지역별 κΈ°ν›„ μœ„ν—˜ λ…ΈμΆœλ„ 및 μ·¨μ•½μ„± λ§€ν•‘
"""
    }

    style_guides = {
        "professional": "전문적이고 ν•™μˆ μ μΈ μ–΄μ‘°λ₯Ό μ‚¬μš©ν•˜μ„Έμš”. 기술적 μš©μ–΄λ₯Ό 적절히 μ‚¬μš©ν•˜κ³  체계적인 데이터 뢄석을 μ œκ³΅ν•˜μ„Έμš”.",
        "simple": "쉽고 κ°„κ²°ν•œ μ–Έμ–΄λ‘œ μ„€λͺ…ν•˜μ„Έμš”. μ „λ¬Έ μš©μ–΄λŠ” μ΅œμ†Œν™”ν•˜κ³  핡심 κ°œλ…μ„ 일상적인 ν‘œν˜„μœΌλ‘œ μ „λ‹¬ν•˜μ„Έμš”.",
        "detailed": "μƒμ„Έν•˜κ³  포괄적인 뢄석을 μ œκ³΅ν•˜μ„Έμš”. λ‹€μ–‘ν•œ 데이터 포인트, 톡계적 λ‰˜μ•™μŠ€, 그리고 μ—¬λŸ¬ μ‹œλ‚˜λ¦¬μ˜€λ₯Ό κ³ λ €ν•œ 심측 뢄석을 μ œμ‹œν•˜μ„Έμš”.",
        "action_oriented": "μ‹€ν–‰ κ°€λŠ₯ν•œ μΈμ‚¬μ΄νŠΈμ™€ ꡬ체적인 ꢌμž₯사항에 μ΄ˆμ μ„ λ§žμΆ”μ„Έμš”. 'λ‹€μŒ 단계' 및 'μ‹€μ§ˆμ  μ‘°μ–Έ' μ„Ήμ…˜μ„ ν¬ν•¨ν•˜μ„Έμš”."
    }

    dataset_guide = """
농업 데이터셋 ν™œμš© μ§€μΉ¨:
- UN κΈ€λ‘œλ²Œ μ‹λŸ‰ 및 농업 톡계 데이터셋을 κΈ°λ³Έ λΆ„μ„μ˜ 근거둜 μ‚¬μš©ν•˜μ„Έμš”
- ν† μ–‘ 및 ν™˜κ²½ λ³€μˆ˜ 기반 μž‘λ¬Ό μΆ”μ²œ λ°μ΄ν„°μ…‹μ˜ μΈμ‚¬μ΄νŠΈλ₯Ό μž‘λ¬Ό 선택 및 재배 쑰건 뢄석에 ν†΅ν•©ν•˜μ„Έμš”
- κΈ°ν›„ λ³€ν™”κ°€ 농업에 λ―ΈμΉ˜λŠ” 영ν–₯ λ°μ΄ν„°μ…‹μ˜ 정보λ₯Ό 지속 κ°€λŠ₯μ„± 및 미래 전망 뢄석에 ν™œμš©ν•˜μ„Έμš”
- λ°μ΄ν„°μ˜ μΆœμ²˜μ™€ 연도λ₯Ό λͺ…ν™•νžˆ μΈμš©ν•˜μ„Έμš”
- 데이터셋 λ‚΄ μ£Όμš” λ³€μˆ˜ κ°„μ˜ 관계λ₯Ό λΆ„μ„ν•˜μ—¬ μΈμ‚¬μ΄νŠΈλ₯Ό λ„μΆœν•˜μ„Έμš”
- λ°μ΄ν„°μ˜ ν•œκ³„μ™€ λΆˆν™•μ‹€μ„±μ„ 투λͺ…ν•˜κ²Œ μ–ΈκΈ‰ν•˜μ„Έμš”
- ν•„μš”μ‹œ 데이터 격차λ₯Ό μ‹λ³„ν•˜κ³  μΆ”κ°€ 연ꡬ가 ν•„μš”ν•œ μ˜μ—­μ„ μ œμ•ˆν•˜μ„Έμš”
"""

    soybean_guide = """
κ³ κΈ‰ λŒ€λ‘ 농업 데이터셋 ν™œμš© μ§€μΉ¨:
- λŒ€λ‘ 생산 쑰건 및 μˆ˜ν™•λŸ‰ νŒ¨ν„΄μ„ λ‹€λ₯Έ μž‘λ¬Όκ³Ό λΉ„κ΅ν•˜μ—¬ λΆ„μ„ν•˜μ„Έμš”
- λŒ€λ‘ λ†μ—…μ˜ 경제적 κ°€μΉ˜μ™€ μ‹œμž₯ κΈ°νšŒμ— λŒ€ν•œ μΈμ‚¬μ΄νŠΈλ₯Ό μ œκ³΅ν•˜μ„Έμš”
- λŒ€λ‘ 생산성에 영ν–₯을 λ―ΈμΉ˜λŠ” μ£Όμš” ν™˜κ²½ μš”μΈμ„ κ°•μ‘°ν•˜μ„Έμš”
- λŒ€λ‘ 재배 기술 ν˜μ‹ κ³Ό μˆ˜μ΅μ„± ν–₯상 λ°©μ•ˆμ„ μ œμ•ˆν•˜μ„Έμš”
- 지속 κ°€λŠ₯ν•œ λŒ€λ‘ 농업을 μœ„ν•œ μ‹€μ§ˆμ μΈ 접근법을 κ³΅μœ ν•˜μ„Έμš”
"""

    crop_recommendation_guide = """
ν† μ–‘ 및 ν™˜κ²½ λ³€μˆ˜ 기반 μž‘λ¬Ό μΆ”μ²œ ν™œμš© μ§€μΉ¨:
- μ§€μ—­ νŠΉμ„±μ— λ§žλŠ” 졜적의 μž‘λ¬Ό 선택 기쀀을 μ œμ‹œν•˜μ„Έμš”
- ν† μ–‘ 쑰건과 μž‘λ¬Ό 적합성 κ°„μ˜ 상관관계λ₯Ό λΆ„μ„ν•˜μ„Έμš”
- ν™˜κ²½ λ³€μˆ˜μ— λ”°λ₯Έ μž‘λ¬Ό 생산성 예츑 λͺ¨λΈμ„ ν™œμš©ν•˜μ„Έμš”
- 농업 생산성과 μˆ˜μ΅μ„± ν–₯상을 μœ„ν•œ μž‘λ¬Ό 선택 μ „λž΅μ„ μ œμ•ˆν•˜μ„Έμš”
- 지속 κ°€λŠ₯ν•œ 농업을 μœ„ν•œ μž‘λ¬Ό λ‹€μ–‘ν™” 접근법을 ꢌμž₯ν•˜μ„Έμš”
"""

    climate_impact_guide = """
κΈ°ν›„ λ³€ν™”κ°€ 농업에 λ―ΈμΉ˜λŠ” 영ν–₯ 데이터셋 ν™œμš© μ§€μΉ¨:
- κΈ°ν›„ λ³€ν™” μ‹œλ‚˜λ¦¬μ˜€μ— λ”°λ₯Έ μž‘λ¬Ό 생산성 λ³€ν™”λ₯Ό μ˜ˆμΈ‘ν•˜μ„Έμš”
- κΈ°ν›„ μ μ‘ν˜• 농업 기술 및 μ „λž΅μ„ μ œμ•ˆν•˜μ„Έμš”
- 지역별 κΈ°ν›„ μœ„ν—˜ μš”μ†Œμ™€ λŒ€μ‘ λ°©μ•ˆμ„ λΆ„μ„ν•˜μ„Έμš”
- κΈ°ν›„ 변화에 λŒ€μ‘ν•˜κΈ° μœ„ν•œ μž‘λ¬Ό 선택 및 재배 μ‹œκΈ° μ‘°μ • λ°©μ•ˆμ„ μ œμ‹œν•˜μ„Έμš”
- κΈ°ν›„ λ³€ν™”κ°€ 농산물 가격 및 μ‹œμž₯ 동ν–₯에 λ―ΈμΉ˜λŠ” 영ν–₯을 ν‰κ°€ν•˜μ„Έμš”
"""

    search_guide = """
μ›Ή 검색 κ²°κ³Ό ν™œμš© μ§€μΉ¨:
- 데이터셋 뢄석을 λ³΄μ™„ν•˜λŠ” μ΅œμ‹  μ‹œμž₯ μ •λ³΄λ‘œ 검색 κ²°κ³Όλ₯Ό ν™œμš©ν•˜μ„Έμš”
- 각 μ •λ³΄μ˜ 좜처λ₯Ό λ§ˆν¬λ‹€μš΄ 링크둜 ν¬ν•¨ν•˜μ„Έμš”: [좜처λͺ…](URL)
- μ£Όμš” μ£Όμž₯μ΄λ‚˜ 데이터 ν¬μΈνŠΈλ§ˆλ‹€ 좜처λ₯Ό ν‘œμ‹œν•˜μ„Έμš”
- μΆœμ²˜κ°€ 상좩할 경우, λ‹€μ–‘ν•œ 관점과 신뒰도λ₯Ό μ„€λͺ…ν•˜μ„Έμš”
- κ΄€λ ¨ λ™μ˜μƒ λ§ν¬λŠ” [λΉ„λ””μ˜€: 제λͺ©](video_url) ν˜•μ‹μœΌλ‘œ ν¬ν•¨ν•˜μ„Έμš”
- 검색 정보λ₯Ό μΌκ΄€λ˜κ³  체계적인 μ‘λ‹΅μœΌλ‘œ ν†΅ν•©ν•˜μ„Έμš”
- λͺ¨λ“  μ£Όμš” 좜처λ₯Ό λ‚˜μ—΄ν•œ "μ°Έκ³  자료" μ„Ήμ…˜μ„ λ§ˆμ§€λ§‰μ— ν¬ν•¨ν•˜μ„Έμš”
"""

    upload_guide = """
μ—…λ‘œλ“œλœ 파일 ν™œμš© μ§€μΉ¨:
- μ—…λ‘œλ“œλœ νŒŒμΌμ„ μ‘λ‹΅μ˜ μ£Όμš” μ •λ³΄μ›μœΌλ‘œ ν™œμš©ν•˜μ„Έμš”
- 쿼리와 직접 κ΄€λ ¨λœ 파일 정보λ₯Ό μΆ”μΆœν•˜κ³  κ°•μ‘°ν•˜μ„Έμš”
- κ΄€λ ¨ κ΅¬μ ˆμ„ μΈμš©ν•˜κ³  νŠΉμ • νŒŒμΌμ„ 좜처둜 μΈμš©ν•˜μ„Έμš”
- CSV 파일의 수치 λ°μ΄ν„°λŠ” μš”μ•½ λ¬Έμž₯으둜 λ³€ν™˜ν•˜μ„Έμš”
- PDF μ½˜ν…μΈ λŠ” νŠΉμ • μ„Ήμ…˜μ΄λ‚˜ νŽ˜μ΄μ§€λ₯Ό μ°Έμ‘°ν•˜μ„Έμš”
- 파일 정보λ₯Ό μ›Ή 검색 결과와 μ›ν™œν•˜κ²Œ ν†΅ν•©ν•˜μ„Έμš”
- 정보가 상좩할 경우, 일반적인 μ›Ή 결과보닀 파일 μ½˜ν…μΈ λ₯Ό μš°μ„ μ‹œν•˜μ„Έμš”
"""

    # Base prompt
    final_prompt = base_prompt

    # Add mode-specific guidance
    if mode in mode_prompts:
        final_prompt += "\n" + mode_prompts[mode]

    # Style
    if style in style_guides:
        final_prompt += f"\n\n뢄석 μŠ€νƒ€μΌ: {style_guides[style]}"

    # Always include dataset guides
    final_prompt += f"\n\n{dataset_guide}"
    final_prompt += f"\n\n{crop_recommendation_guide}"
    final_prompt += f"\n\n{climate_impact_guide}"
    
    # Conditionally add soybean dataset guide if selected in UI
    if st.session_state.get('use_soybean_dataset', False):
        final_prompt += f"\n\n{soybean_guide}"

    if include_search_results:
        final_prompt += f"\n\n{search_guide}"

    if include_uploaded_files:
        final_prompt += f"\n\n{upload_guide}"

    final_prompt += """
\n\n응닡 ν˜•μ‹ μš”κ΅¬μ‚¬ν•­:
- λ§ˆν¬λ‹€μš΄ 제λͺ©(## 및 ###)을 μ‚¬μš©ν•˜μ—¬ 응닡을 μ²΄κ³„μ μœΌλ‘œ κ΅¬μ„±ν•˜μ„Έμš”
- μ€‘μš”ν•œ 점은 ꡡ은 ν…μŠ€νŠΈ(**ν…μŠ€νŠΈ**)둜 κ°•μ‘°ν•˜μ„Έμš”
- 3-5개의 후속 μ§ˆλ¬Έμ„ ν¬ν•¨ν•œ "κ΄€λ ¨ 질문" μ„Ήμ…˜μ„ λ§ˆμ§€λ§‰μ— μΆ”κ°€ν•˜μ„Έμš”
- μ μ ˆν•œ 간격과 단락 κ΅¬λΆ„μœΌλ‘œ 응닡을 μ„œμ‹ν™”ν•˜μ„Έμš”
- λͺ¨λ“  λ§ν¬λŠ” λ§ˆν¬λ‹€μš΄ ν˜•μ‹μœΌλ‘œ 클릭 κ°€λŠ₯ν•˜κ²Œ λ§Œλ“œμ„Έμš”: [ν…μŠ€νŠΈ](url)
- κ°€λŠ₯ν•œ 경우 데이터λ₯Ό μ‹œκ°μ μœΌλ‘œ ν‘œν˜„(ν‘œ, κ·Έλž˜ν”„ λ“±μ˜ μ„€λͺ…)ν•˜μ„Έμš”
"""
    return final_prompt

# ──────────────────────────────── Brave Search API ────────────────────────
@st.cache_data(ttl=3600)
def brave_search(query: str, count: int = 10):
    if not BRAVE_KEY:
        raise RuntimeError("⚠️ SERPHOUSE_API_KEY (Brave API Key) environment variable is empty.")

    headers = {"Accept": "application/json", "Accept-Encoding": "gzip", "X-Subscription-Token": BRAVE_KEY}
    params = {"q": query + " 농산물 가격 동ν–₯ 농업 데이터", "count": str(count)}

    for attempt in range(3):
        try:
            r = requests.get(BRAVE_ENDPOINT, headers=headers, params=params, timeout=15)
            r.raise_for_status()
            data = r.json()

            raw = data.get("web", {}).get("results") or data.get("results", [])
            if not raw:
                logging.warning(f"No Brave search results found. Response: {data}")
                raise ValueError("No search results found.")
            
            arts = []
            for i, res in enumerate(raw[:count], 1):
                url = res.get("url", res.get("link", ""))
                host = re.sub(r"https?://(www\.)?", "", url).split("/")[0]
                arts.append({
                    "index": i,
                    "title": res.get("title", "No title"),
                    "link": url,
                    "snippet": res.get("description", res.get("text", "No snippet")),
                    "displayed_link": host
                })

            return arts

        except Exception as e:
            logging.error(f"Brave search failure (attempt {attempt+1}/3): {e}")
            if attempt < 2:
                time.sleep(5)

    return []

@st.cache_data(ttl=3600)
def brave_video_search(query: str, count: int = 3):
    if not BRAVE_KEY:
        raise RuntimeError("⚠️ SERPHOUSE_API_KEY (Brave API Key) environment variable is empty.")

    headers = {"Accept": "application/json","Accept-Encoding": "gzip","X-Subscription-Token": BRAVE_KEY}
    params = {"q": query + " 농산물 가격 농업 μ‹œμž₯", "count": str(count)}

    for attempt in range(3):
        try:
            r = requests.get(BRAVE_VIDEO_ENDPOINT, headers=headers, params=params, timeout=15)
            r.raise_for_status()
            data = r.json()

            results = []
            for i, vid in enumerate(data.get("results", [])[:count], 1):
                results.append({
                    "index": i,
                    "title": vid.get("title", "Video"),
                    "video_url": vid.get("url", ""),
                    "thumbnail_url": vid.get("thumbnail", {}).get("src", ""),
                    "source": vid.get("provider", {}).get("name", "Unknown source")
                })

            return results

        except Exception as e:
            logging.error(f"Brave video search failure (attempt {attempt+1}/3): {e}")
            if attempt < 2:
                time.sleep(5)

    return []

@st.cache_data(ttl=3600)
def brave_news_search(query: str, count: int = 3):
    if not BRAVE_KEY:
        raise RuntimeError("⚠️ SERPHOUSE_API_KEY (Brave API Key) environment variable is empty.")

    headers = {"Accept": "application/json","Accept-Encoding": "gzip","X-Subscription-Token": BRAVE_KEY}
    params = {"q": query + " 농산물 가격 동ν–₯ 농업", "count": str(count)}

    for attempt in range(3):
        try:
            r = requests.get(BRAVE_NEWS_ENDPOINT, headers=headers, params=params, timeout=15)
            r.raise_for_status()
            data = r.json()

            results = []
            for i, news in enumerate(data.get("results", [])[:count], 1):
                results.append({
                    "index": i,
                    "title": news.get("title", "News article"),
                    "url": news.get("url", ""),
                    "description": news.get("description", ""),
                    "source": news.get("source", "Unknown source"),
                    "date": news.get("age", "Unknown date")
                })

            return results

        except Exception as e:
            logging.error(f"Brave news search failure (attempt {attempt+1}/3): {e}")
            if attempt < 2:
                time.sleep(5)

    return []

def mock_results(query: str) -> str:
    ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    return (f"# λŒ€μ²΄ 검색 μ½˜ν…μΈ  (생성 μ‹œκ°„: {ts})\n\n"
            f"'{query}'에 λŒ€ν•œ 검색 API μš”μ²­μ΄ μ‹€νŒ¨ν–ˆκ±°λ‚˜ κ²°κ³Όκ°€ μ—†μŠ΅λ‹ˆλ‹€. "
            f"κΈ°μ‘΄ 지식을 기반으둜 응닡을 μƒμ„±ν•΄μ£Όμ„Έμš”.\n\n"
            f"λ‹€μŒ 사항을 κ³ λ €ν•˜μ„Έμš”:\n\n"
            f"- {query}에 κ΄€ν•œ κΈ°λ³Έ κ°œλ…κ³Ό μ€‘μš”μ„±\n"
            f"- 일반적으둜 μ•Œλ €μ§„ κ΄€λ ¨ ν†΅κ³„λ‚˜ μΆ”μ„Έ\n"
            f"- 이 μ£Όμ œμ— λŒ€ν•œ μ „λ¬Έκ°€ 의견\n"
            f"- λ…μžκ°€ κ°€μ§ˆ 수 μžˆλŠ” 질문\n\n"
            f"μ°Έκ³ : μ΄λŠ” μ‹€μ‹œκ°„ 데이터가 μ•„λ‹Œ λŒ€μ²΄ μ§€μΉ¨μž…λ‹ˆλ‹€.\n\n")

def do_web_search(query: str) -> str:
    try:
        arts = brave_search(query, 10)
        if not arts:
            logging.warning("No search results, using fallback content")
            return mock_results(query)

        videos = brave_video_search(query, 2)
        news   = brave_news_search(query, 3)
        
        result = "# μ›Ή 검색 κ²°κ³Ό\nλ‹€μŒ κ²°κ³Όλ₯Ό ν™œμš©ν•˜μ—¬ 데이터셋 뢄석을 λ³΄μ™„ν•˜λŠ” 포괄적인 닡변을 μ œκ³΅ν•˜μ„Έμš”.\n\n"
        
        result += "## μ›Ή κ²°κ³Ό\n\n"
        for a in arts[:5]:
            result += f"### κ²°κ³Ό {a['index']}: {a['title']}\n\n{a['snippet']}\n\n"
            result += f"**좜처**: [{a['displayed_link']}]({a['link']})\n\n---\n"
        
        if news:
            result += "## λ‰΄μŠ€ κ²°κ³Ό\n\n"
            for n in news:
                result += f"### {n['title']}\n\n{n['description']}\n\n"
                result += f"**좜처**: [{n['source']}]({n['url']}) - {n['date']}\n\n---\n"
                
        if videos:
            result += "## λΉ„λ””μ˜€ κ²°κ³Ό\n\n"
            for vid in videos:
                result += f"### {vid['title']}\n\n"
                if vid.get('thumbnail_url'):
                    result += f"![썸넀일]({vid['thumbnail_url']})\n\n"
                result += f"**μ‹œμ²­**: [{vid['source']}]({vid['video_url']})\n\n"
        
        return result
        
    except Exception as e:
        logging.error(f"Web search process failed: {str(e)}")
        return mock_results(query)

# ──────────────────────────────── File Upload Handling ─────────────────────
def process_text_file(file):
    try:
        content = file.read()
        file.seek(0)

        text = content.decode('utf-8', errors='ignore')
        if len(text) > 10000:
            text = text[:9700] + "...(truncated)..."

        result = f"## ν…μŠ€νŠΈ 파일: {file.name}\n\n" + text
        return result
    except Exception as e:
        logging.error(f"Error processing text file: {str(e)}")
        return f"ν…μŠ€νŠΈ 파일 처리 였λ₯˜: {str(e)}"

def process_csv_file(file):
    try:
        content = file.read()
        file.seek(0)

        df = pd.read_csv(io.BytesIO(content))
        result = f"## CSV 파일: {file.name}\n\n"
        result += f"- ν–‰: {len(df)}\n"
        result += f"- μ—΄: {len(df.columns)}\n"
        result += f"- μ—΄ 이름: {', '.join(df.columns.tolist())}\n\n"

        result += "### 데이터 미리보기\n\n"
        preview_df = df.head(10)
        try:
            markdown_table = preview_df.to_markdown(index=False)
            if markdown_table:
                result += markdown_table + "\n\n"
            else:
                result += "CSV 데이터λ₯Ό ν‘œμ‹œν•  수 μ—†μŠ΅λ‹ˆλ‹€.\n\n"
        except Exception as e:
            logging.error(f"Markdown table conversion error: {e}")
            result += "ν…μŠ€νŠΈλ‘œ 데이터 ν‘œμ‹œ:\n\n" + str(preview_df) + "\n\n"

        num_cols = df.select_dtypes(include=['number']).columns
        if len(num_cols) > 0:
            result += "### κΈ°λ³Έ 톡계 정보\n\n"
            try:
                stats_df = df[num_cols].describe().round(2)
                stats_markdown = stats_df.to_markdown()
                if stats_markdown:
                    result += stats_markdown + "\n\n"
                else:
                    result += "톡계 정보λ₯Ό ν‘œμ‹œν•  수 μ—†μŠ΅λ‹ˆλ‹€.\n\n"
            except Exception as e:
                logging.error(f"Statistical info conversion error: {e}")
                result += "톡계 정보λ₯Ό 생성할 수 μ—†μŠ΅λ‹ˆλ‹€.\n\n"

        return result
    except Exception as e:
        logging.error(f"CSV file processing error: {str(e)}")
        return f"CSV 파일 처리 였λ₯˜: {str(e)}"

def process_pdf_file(file):
    try:
        file_bytes = file.read()
        file.seek(0)

        pdf_file = io.BytesIO(file_bytes)
        reader = PyPDF2.PdfReader(pdf_file, strict=False)

        result = f"## PDF 파일: {file.name}\n\n- 총 νŽ˜μ΄μ§€: {len(reader.pages)}\n\n"

        max_pages = min(5, len(reader.pages))
        all_text = ""

        for i in range(max_pages):
            try:
                page = reader.pages[i]
                page_text = page.extract_text()
                current_page_text = f"### νŽ˜μ΄μ§€ {i+1}\n\n"
                if page_text and len(page_text.strip()) > 0:
                    if len(page_text) > 1500:
                        current_page_text += page_text[:1500] + "...(좕약됨)...\n\n"
                    else:
                        current_page_text += page_text + "\n\n"
                else:
                    current_page_text += "(ν…μŠ€νŠΈλ₯Ό μΆ”μΆœν•  수 μ—†μŒ)\n\n"

                all_text += current_page_text

                if len(all_text) > 8000:
                    all_text += "...(λ‚˜λ¨Έμ§€ νŽ˜μ΄μ§€ 좕약됨)...\n\n"
                    break

            except Exception as page_err:
                logging.error(f"Error processing PDF page {i+1}: {str(page_err)}")
                all_text += f"### νŽ˜μ΄μ§€ {i+1}\n\n(λ‚΄μš© μΆ”μΆœ 였λ₯˜: {str(page_err)})\n\n"

        if len(reader.pages) > max_pages:
            all_text += f"\nμ°Έκ³ : 처음 {max_pages} νŽ˜μ΄μ§€λ§Œ ν‘œμ‹œλ©λ‹ˆλ‹€.\n\n"

        result += "### PDF λ‚΄μš©\n\n" + all_text
        return result

    except Exception as e:
        logging.error(f"PDF file processing error: {str(e)}")
        return f"## PDF 파일: {file.name}\n\n였λ₯˜: {str(e)}\n\nμ²˜λ¦¬ν•  수 μ—†μŠ΅λ‹ˆλ‹€."

def process_uploaded_files(files):
    if not files:
        return None

    result = "# μ—…λ‘œλ“œλœ 파일 λ‚΄μš©\n\nμ‚¬μš©μžκ°€ μ œκ³΅ν•œ 파일의 λ‚΄μš©μž…λ‹ˆλ‹€.\n\n"
    for file in files:
        try:
            ext = file.name.split('.')[-1].lower()
            if ext == 'txt':
                result += process_text_file(file) + "\n\n---\n\n"
            elif ext == 'csv':
                result += process_csv_file(file) + "\n\n---\n\n"
            elif ext == 'pdf':
                result += process_pdf_file(file) + "\n\n---\n\n"
            else:
                result += f"### μ§€μ›λ˜μ§€ μ•ŠλŠ” 파일: {file.name}\n\n---\n\n"
        except Exception as e:
            logging.error(f"File processing error {file.name}: {e}")
            result += f"### 파일 처리 였λ₯˜: {file.name}\n\n였λ₯˜: {e}\n\n---\n\n"

    return result

# ──────────────────────────────── Image & Utility ─────────────────────────

def generate_image(prompt, w=768, h=768, g=3.5, steps=30, seed=3):
    if not prompt:
        return None, "Insufficient prompt"
    try:
        res = Client(IMAGE_API_URL).predict(
            prompt=prompt, width=w, height=h, guidance=g,
            inference_steps=steps, seed=seed,
            do_img2img=False, init_image=None,
            image2image_strength=0.8, resize_img=True,
            api_name="/generate_image"
        )
        return res[0], f"Seed: {res[1]}"
    except Exception as e:
        logging.error(e)
        return None, str(e)

def extract_image_prompt(response_text: str, topic: str):
    client = get_openai_client()
    try:
        response = client.chat.completions.create(
            model="gpt-4.1-mini",
            messages=[
                {"role": "system", "content": "농업 및 농산물에 κ΄€ν•œ 이미지 ν”„λ‘¬ν”„νŠΈλ₯Ό μƒμ„±ν•©λ‹ˆλ‹€. ν•œ μ€„μ˜ μ˜μ–΄λ‘œ 된 ν”„λ‘¬ν”„νŠΈλ§Œ λ°˜ν™˜ν•˜μ„Έμš”, λ‹€λ₯Έ ν…μŠ€νŠΈλŠ” ν¬ν•¨ν•˜μ§€ λ§ˆμ„Έμš”."},
                {"role": "user", "content": f"주제: {topic}\n\n---\n{response_text}\n\n---"}
            ],
            temperature=1,
            max_tokens=80,
            top_p=1
        )
        return response.choices[0].message.content.strip()
    except Exception as e:
        logging.error(f"OpenAI image prompt generation error: {e}")
        return f"A professional photograph of agricultural produce and farm fields, data visualization of crop prices and trends, high quality"

def md_to_html(md: str, title="농산물 μˆ˜μš” 예츑 뢄석 κ²°κ³Ό"):
    return f"<!DOCTYPE html><html><head><title>{title}</title><meta charset='utf-8'></head><body>{markdown.markdown(md)}</body></html>"

def keywords(text: str, top=5):
    cleaned = re.sub(r"[^κ°€-힣a-zA-Z0-9\s]", "", text)
    return " ".join(cleaned.split()[:top])

# ──────────────────────────────── Streamlit UI ────────────────────────────
def agricultural_price_forecast_app():
    st.title("농산물 μˆ˜μš” 및 가격 예츑 AI μ–΄μ‹œμŠ€ν„΄νŠΈ")
    st.markdown("UN κΈ€λ‘œλ²Œ μ‹λŸ‰ 및 농업 톡계 데이터셋 뢄석 기반의 농산물 μ‹œμž₯ 예츑")

    if "ai_model" not in st.session_state:
        st.session_state.ai_model = "gpt-4.1-mini"
    if "messages" not in st.session_state:
        st.session_state.messages = []
    if "auto_save" not in st.session_state:
        st.session_state.auto_save = True
    if "generate_image" not in st.session_state:
        st.session_state.generate_image = False
    if "web_search_enabled" not in st.session_state:
        st.session_state.web_search_enabled = True
    if "analysis_mode" not in st.session_state:
        st.session_state.analysis_mode = "price_forecast"
    if "response_style" not in st.session_state:
        st.session_state.response_style = "professional"
    if "use_soybean_dataset" not in st.session_state:
        st.session_state.use_soybean_dataset = False

    sb = st.sidebar
    sb.title("뢄석 μ„€μ •")
    
    # Kaggle dataset info display
    if sb.checkbox("데이터셋 정보 ν‘œμ‹œ", value=False):
        st.info("UN κΈ€λ‘œλ²Œ μ‹λŸ‰ 및 농업 톡계 데이터셋을 λΆˆλŸ¬μ˜€λŠ” 쀑...")
        dataset_info = load_agriculture_dataset()
        if dataset_info:
            st.success(f"데이터셋 λ‘œλ“œ μ™„λ£Œ: {len(dataset_info['files'])}개 파일")
            
            with st.expander("데이터셋 미리보기", expanded=False):
                for file_info in dataset_info['files'][:5]:
                    st.write(f"**{file_info['name']}** ({file_info['size_mb']} MB)")
        else:
            st.error("데이터셋을 λΆˆλŸ¬μ˜€λŠ”λ° μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€. Kaggle API 섀정을 ν™•μΈν•˜μ„Έμš”.")
    
    sb.subheader("뢄석 ꡬ성")
    sb.selectbox(
        "뢄석 λͺ¨λ“œ", 
        options=list(ANALYSIS_MODES.keys()), 
        format_func=lambda x: ANALYSIS_MODES[x],
        key="analysis_mode"
    )
    
    sb.selectbox(
        "응닡 μŠ€νƒ€μΌ",
        options=list(RESPONSE_STYLES.keys()),
        format_func=lambda x: RESPONSE_STYLES[x],
        key="response_style"
    )
    
    # Dataset selection
    sb.subheader("데이터셋 선택")
    sb.checkbox(
        "κ³ κΈ‰ λŒ€λ‘ 농업 데이터셋 μ‚¬μš©",
        key="use_soybean_dataset",
        help="λŒ€λ‘(콩) κ΄€λ ¨ μ§ˆλ¬Έμ— 더 μ •ν™•ν•œ 정보λ₯Ό μ œκ³΅ν•©λ‹ˆλ‹€."
    )
    
    # Always enabled datasets info
    sb.info("κΈ°λ³Έ ν™œμ„±ν™”λœ 데이터셋:\n- UN κΈ€λ‘œλ²Œ μ‹λŸ‰ 및 농업 톡계\n- ν† μ–‘ 및 ν™˜κ²½ λ³€μˆ˜ 기반 μž‘λ¬Ό μΆ”μ²œ\n- κΈ°ν›„ λ³€ν™”κ°€ 농업에 λ―ΈμΉ˜λŠ” 영ν–₯")
    
    # Example queries
    sb.subheader("μ˜ˆμ‹œ 질문")
    c1, c2, c3 = sb.columns(3)
    if c1.button("μŒ€ 가격 전망", key="ex1"):
        process_example(EXAMPLE_QUERIES["example1"])
    if c2.button("κΈ°ν›„ 영ν–₯", key="ex2"):
        process_example(EXAMPLE_QUERIES["example2"])
    if c3.button("증평ꡰ μž‘λ¬Ό", key="ex3"):
        process_example(EXAMPLE_QUERIES["example3"])
    
    sb.subheader("기타 μ„€μ •")
    sb.toggle("μžλ™ μ €μž₯", key="auto_save")
    sb.toggle("이미지 μžλ™ 생성", key="generate_image")
    
    web_search_enabled = sb.toggle("μ›Ή 검색 μ‚¬μš©", value=st.session_state.web_search_enabled)
    st.session_state.web_search_enabled = web_search_enabled
    
    if web_search_enabled:
        st.sidebar.info("βœ… μ›Ή 검색 κ²°κ³Όκ°€ 응닡에 ν†΅ν•©λ©λ‹ˆλ‹€.")

    # Download the latest response
    latest_response = next(
        (m["content"] for m in reversed(st.session_state.messages) 
         if m["role"] == "assistant" and m["content"].strip()), 
        None
    )
    if latest_response:
        title_match = re.search(r"# (.*?)(\n|$)", latest_response)
        if title_match:
            title = title_match.group(1).strip()
        else:
            first_line = latest_response.split('\n', 1)[0].strip()
            title = first_line[:40] + "..." if len(first_line) > 40 else first_line
        
        sb.subheader("μ΅œμ‹  응닡 λ‹€μš΄λ‘œλ“œ")
        d1, d2 = sb.columns(2)
        d1.download_button("λ§ˆν¬λ‹€μš΄μœΌλ‘œ λ‹€μš΄λ‘œλ“œ", latest_response, 
                           file_name=f"{title}.md", mime="text/markdown")
        d2.download_button("HTML둜 λ‹€μš΄λ‘œλ“œ", md_to_html(latest_response, title),
                           file_name=f"{title}.html", mime="text/html")

    # JSON conversation record upload
    up = sb.file_uploader("λŒ€ν™” 기둝 뢈러였기 (.json)", type=["json"], key="json_uploader")
    if up:
        try:
            st.session_state.messages = json.load(up)
            sb.success("λŒ€ν™” 기둝을 μ„±κ³΅μ μœΌλ‘œ λΆˆλŸ¬μ™”μŠ΅λ‹ˆλ‹€")
        except Exception as e:
            sb.error(f"뢈러였기 μ‹€νŒ¨: {e}")

    # JSON conversation record download
    if sb.button("λŒ€ν™” 기둝을 JSON으둜 λ‹€μš΄λ‘œλ“œ"):
        sb.download_button(
            "μ €μž₯",
            data=json.dumps(st.session_state.messages, ensure_ascii=False, indent=2),
            file_name="conversation_history.json",
            mime="application/json"
        )

    # File Upload
    st.subheader("파일 μ—…λ‘œλ“œ")
    uploaded_files = st.file_uploader(
        "μ°Έκ³  자료둜 μ‚¬μš©ν•  파일 μ—…λ‘œλ“œ (txt, csv, pdf)",
        type=["txt", "csv", "pdf"],
        accept_multiple_files=True,
        key="file_uploader"
    )
    
    if uploaded_files:
        file_count = len(uploaded_files)
        st.success(f"{file_count}개 파일이 μ—…λ‘œλ“œλ˜μ—ˆμŠ΅λ‹ˆλ‹€. μ§ˆμ˜μ— λŒ€ν•œ μ†ŒμŠ€λ‘œ μ‚¬μš©λ©λ‹ˆλ‹€.")
        
        with st.expander("μ—…λ‘œλ“œλœ 파일 미리보기", expanded=False):
            for idx, file in enumerate(uploaded_files):
                st.write(f"**파일λͺ…:** {file.name}")
                ext = file.name.split('.')[-1].lower()
                
                if ext == 'txt':
                    preview = file.read(1000).decode('utf-8', errors='ignore')
                    file.seek(0)
                    st.text_area(
                        f"{file.name} 미리보기",
                        preview + ("..." if len(preview) >= 1000 else ""),
                        height=150
                    )
                elif ext == 'csv':
                    try:
                        df = pd.read_csv(file)
                        file.seek(0)
                        st.write("CSV 미리보기 (μ΅œλŒ€ 5ν–‰)")
                        st.dataframe(df.head(5))
                    except Exception as e:
                        st.error(f"CSV 미리보기 μ‹€νŒ¨: {e}")
                elif ext == 'pdf':
                    try:
                        file_bytes = file.read()
                        file.seek(0)
                        
                        pdf_file = io.BytesIO(file_bytes)
                        reader = PyPDF2.PdfReader(pdf_file, strict=False)
                        
                        pc = len(reader.pages)
                        st.write(f"PDF 파일: {pc}νŽ˜μ΄μ§€")
                        
                        if pc > 0:
                            try:
                                page_text = reader.pages[0].extract_text()
                                preview = page_text[:500] if page_text else "(ν…μŠ€νŠΈ μΆ”μΆœ λΆˆκ°€)"
                                st.text_area("첫 νŽ˜μ΄μ§€ 미리보기", preview + "...", height=150)
                            except:
                                st.warning("첫 νŽ˜μ΄μ§€ ν…μŠ€νŠΈ μΆ”μΆœ μ‹€νŒ¨")
                    except Exception as e:
                        st.error(f"PDF 미리보기 μ‹€νŒ¨: {e}")

                if idx < file_count - 1:
                    st.divider()

    # Display existing messages
    for m in st.session_state.messages:
        with st.chat_message(m["role"]):
            st.markdown(m["content"], unsafe_allow_html=True)
            
            # Videos
            if "videos" in m and m["videos"]:
                st.subheader("κ΄€λ ¨ λΉ„λ””μ˜€")
                for video in m["videos"]:
                    video_title = video.get('title', 'κ΄€λ ¨ λΉ„λ””μ˜€')
                    video_url   = video.get('url', '')
                    thumbnail   = video.get('thumbnail', '')
                    
                    if thumbnail:
                        col1, col2 = st.columns([1, 3])
                        with col1:
                            st.write("🎬")
                        with col2:
                            st.markdown(f"**[{video_title}]({video_url})**")
                            st.write(f"좜처: {video.get('source', 'μ•Œ 수 μ—†μŒ')}")
                    else:
                        st.markdown(f"🎬 **[{video_title}]({video_url})**")
                        st.write(f"좜처: {video.get('source', 'μ•Œ 수 μ—†μŒ')}")

    # User input
    query = st.chat_input("농산물 가격, μˆ˜μš” λ˜λŠ” μ‹œμž₯ 동ν–₯ κ΄€λ ¨ μ§ˆλ¬Έμ„ μž…λ ₯ν•˜μ„Έμš”.")
    if query:
        process_input(query, uploaded_files)

    sb.markdown("---")
    sb.markdown("Created by Vidraft | [Community](https://discord.gg/openfreeai)")

def process_example(topic):
    process_input(topic, [])

def process_input(query: str, uploaded_files):
    if not any(m["role"] == "user" and m["content"] == query for m in st.session_state.messages):
        st.session_state.messages.append({"role": "user", "content": query})

    with st.chat_message("user"):
        st.markdown(query)
    
    with st.chat_message("assistant"):
        placeholder = st.empty()
        message_placeholder = st.empty()
        full_response = ""

        use_web_search = st.session_state.web_search_enabled
        has_uploaded_files = bool(uploaded_files) and len(uploaded_files) > 0
        
        try:
            status = st.status("μ§ˆλ¬Έμ— λ‹΅λ³€ μ€€λΉ„ 쀑...")
            status.update(label="ν΄λΌμ΄μ–ΈνŠΈ μ΄ˆκΈ°ν™” 쀑...")
            
            client = get_openai_client()
            
            search_content = None
            video_results = []
            news_results = []
            
            # 농업 데이터셋 뢄석 κ²°κ³Ό κ°€μ Έμ˜€κΈ°
            status.update(label="농업 데이터셋 뢄석 쀑...")
            with st.spinner("데이터셋 뢄석 쀑..."):
                dataset_analysis = analyze_dataset_for_query(query)
                
                # 항상 ν¬ν•¨λ˜λŠ” μΆ”κ°€ 데이터셋 뢄석
                crop_recommendation_analysis = analyze_crop_recommendation_dataset(query)
                climate_impact_analysis = analyze_climate_impact_dataset(query)
                
                #


# 쑰건뢀 데이터셋 뢄석
                soybean_analysis = None
                if st.session_state.use_soybean_dataset:
                    status.update(label="λŒ€λ‘ 농업 데이터셋 뢄석 쀑...")
                    with st.spinner("λŒ€λ‘ 데이터셋 뢄석 쀑..."):
                        soybean_analysis = analyze_soybean_dataset(query)
            
            if use_web_search:
                # μ›Ή 검색 과정은 λ…ΈμΆœν•˜μ§€ μ•Šκ³  쑰용히 μ§„ν–‰
                with st.spinner("정보 μˆ˜μ§‘ 쀑..."):
                    search_content = do_web_search(keywords(query, top=5))
                    video_results = brave_video_search(query, 2)
                    news_results = brave_news_search(query, 3)
            
            file_content = None
            if has_uploaded_files:
                status.update(label="μ—…λ‘œλ“œλœ 파일 처리 쀑...")
                with st.spinner("파일 뢄석 쀑..."):
                    file_content = process_uploaded_files(uploaded_files)
            
            valid_videos = []
            for vid in video_results:
                url = vid.get('video_url')
                if url and url.startswith('http'):
                    valid_videos.append({
                        'url': url,
                        'title': vid.get('title', 'λΉ„λ””μ˜€'),
                        'thumbnail': vid.get('thumbnail_url', ''),
                        'source': vid.get('source', 'λΉ„λ””μ˜€ 좜처')
                    })
            
            status.update(label="μ’…ν•© 뢄석 μ€€λΉ„ 쀑...")
            sys_prompt = get_system_prompt(
                mode=st.session_state.analysis_mode,
                style=st.session_state.response_style,
                include_search_results=use_web_search,
                include_uploaded_files=has_uploaded_files
            )

            api_messages = [
                {"role": "system", "content": sys_prompt}
            ]
            
            user_content = query
            # 항상 κΈ°λ³Έ 데이터셋 뢄석 κ²°κ³Ό 포함
            user_content += "\n\n" + dataset_analysis
            user_content += "\n\n" + crop_recommendation_analysis
            user_content += "\n\n" + climate_impact_analysis
            
            # 쑰건뢀 데이터셋 κ²°κ³Ό 포함
            if soybean_analysis:
                user_content += "\n\n" + soybean_analysis
            
            if search_content:
                user_content += "\n\n" + search_content
            if file_content:
                user_content += "\n\n" + file_content
            
            if valid_videos:
                user_content += "\n\n# κ΄€λ ¨ λ™μ˜μƒ\n"
                for i, vid in enumerate(valid_videos):
                    user_content += f"\n{i+1}. **{vid['title']}** - [{vid['source']}]({vid['url']})\n"
            
            api_messages.append({"role": "user", "content": user_content})
            
            try:
                stream = client.chat.completions.create(
                    model="gpt-4.1-mini",
                    messages=api_messages,
                    temperature=1,
                    max_tokens=MAX_TOKENS,
                    top_p=1,
                    stream=True
                )
                
                for chunk in stream:
                    if chunk.choices and len(chunk.choices) > 0 and chunk.choices[0].delta.content is not None:
                        content_delta = chunk.choices[0].delta.content
                        full_response += content_delta
                        message_placeholder.markdown(full_response + "β–Œ", unsafe_allow_html=True)
                
                message_placeholder.markdown(full_response, unsafe_allow_html=True)
                
                if valid_videos:
                    st.subheader("κ΄€λ ¨ λΉ„λ””μ˜€")
                    for video in valid_videos:
                        video_title = video.get('title', 'κ΄€λ ¨ λΉ„λ””μ˜€')
                        video_url   = video.get('url', '')
                        
                        st.markdown(f"🎬 **[{video_title}]({video_url})**")
                        st.write(f"좜처: {video.get('source', 'μ•Œ 수 μ—†μŒ')}")

                status.update(label="응닡 μ™„λ£Œ!", state="complete")
                
                st.session_state.messages.append({
                    "role": "assistant", 
                    "content": full_response,
                    "videos": valid_videos
                })
                
            except Exception as api_error:
                error_message = str(api_error)
                logging.error(f"API 였λ₯˜: {error_message}")
                status.update(label=f"였λ₯˜: {error_message}", state="error")
                raise Exception(f"응닡 생성 였λ₯˜: {error_message}")
            
            if st.session_state.generate_image and full_response:
                with st.spinner("λ§žμΆ€ν˜• 이미지 생성 쀑..."):
                    try:
                        ip = extract_image_prompt(full_response, query)
                        img, cap = generate_image(ip)
                        if img:
                            st.subheader("AI 생성 이미지")
                            st.image(img, caption=cap, use_container_width=True)
                    except Exception as img_error:
                        logging.error(f"이미지 생성 였λ₯˜: {str(img_error)}")
                        st.warning("λ§žμΆ€ν˜• 이미지 생성에 μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€.")

            if full_response:
                st.subheader("이 응닡 λ‹€μš΄λ‘œλ“œ")
                c1, c2 = st.columns(2)
                c1.download_button(
                    "λ§ˆν¬λ‹€μš΄", 
                    data=full_response, 
                    file_name=f"{query[:30]}.md",
                    mime="text/markdown"
                )
                c2.download_button(
                    "HTML",
                    data=md_to_html(full_response, query[:30]),
                    file_name=f"{query[:30]}.html",
                    mime="text/html"
                )

            if st.session_state.auto_save and st.session_state.messages:
                try:
                    fn = f"conversation_history_auto_{datetime.now():%Y%m%d_%H%M%S}.json"
                    with open(fn, "w", encoding="utf-8") as fp:
                        json.dump(st.session_state.messages, fp, ensure_ascii=False, indent=2)
                except Exception as e:
                    logging.error(f"μžλ™ μ €μž₯ μ‹€νŒ¨: {e}")

        except Exception as e:
            error_message = str(e)
            placeholder.error(f"였λ₯˜ λ°œμƒ: {error_message}")
            logging.error(f"μž…λ ₯ 처리 였λ₯˜: {error_message}")
            ans = f"μš”μ²­ 처리 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: {error_message}"
            st.session_state.messages.append({"role": "assistant", "content": ans})

# ──────────────────────────────── main ────────────────────────────────────
def main():
    st.write("==== μ• ν”Œλ¦¬μΌ€μ΄μ…˜ μ‹œμž‘ μ‹œκ°„:", datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "=====")
    agricultural_price_forecast_app()

if __name__ == "__main__":
    main()