File size: 126,069 Bytes
0f10845
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95c306a
0f10845
 
95c306a
0f10845
 
 
 
 
 
 
 
 
 
 
95c306a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f10845
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95c306a
0f10845
 
 
 
 
 
 
95c306a
0f10845
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e5f56b
0f10845
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e5f56b
0f10845
 
 
 
 
 
9e5f56b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f10845
 
 
 
 
 
 
 
 
9e5f56b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f10845
 
95c306a
0f10845
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e5f56b
0f10845
9e5f56b
 
 
 
 
0f10845
 
9e5f56b
0f10845
9e5f56b
 
 
 
 
0f10845
 
9e5f56b
0f10845
9e5f56b
 
 
 
 
0f10845
 
9e5f56b
0f10845
9e5f56b
 
 
 
 
0f10845
 
9e5f56b
0f10845
9e5f56b
 
 
 
 
 
 
0f10845
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e5f56b
0f10845
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e5f56b
 
0f10845
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95c306a
0f10845
 
 
 
95c306a
 
 
 
 
0f10845
 
95c306a
0f10845
 
 
95c306a
0f10845
 
95c306a
0f10845
95c306a
0f10845
95c306a
0f10845
95c306a
 
0f10845
95c306a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f10845
 
95c306a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f10845
95c306a
 
0f10845
 
 
95c306a
 
0f10845
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95c306a
 
0f10845
 
 
 
95c306a
0f10845
95c306a
0f10845
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95c306a
 
0f10845
95c306a
0f10845
 
 
 
 
 
 
 
 
 
 
95c306a
0f10845
 
 
 
 
 
 
 
 
95c306a
0f10845
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95c306a
0f10845
95c306a
0f10845
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95c306a
0f10845
 
 
 
 
 
 
 
 
 
 
 
 
 
95c306a
0f10845
95c306a
 
 
 
 
0f10845
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95c306a
0f10845
 
 
95c306a
 
 
0f10845
95c306a
 
 
0f10845
95c306a
 
 
0f10845
 
 
 
 
 
 
95c306a
0f10845
 
 
 
 
95c306a
 
 
 
0f10845
95c306a
 
 
 
 
 
 
 
 
0f10845
 
95c306a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f10845
 
95c306a
0f10845
 
 
 
 
 
 
 
 
 
 
 
95c306a
0f10845
 
 
 
 
 
 
95c306a
0f10845
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95c306a
0f10845
 
 
 
 
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
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
import os
import json
import re
import logging
import requests
import markdown
import time
import io
import random
import hashlib
from datetime import datetime
from dataclasses import dataclass
from itertools import combinations, product
from typing import Iterator

import streamlit as st
import pandas as pd
import PyPDF2                       # For handling PDF files
from collections import Counter

from openai import OpenAI, APIError, APITimeoutError
from gradio_client import Client
from kaggle.api.kaggle_api_extended import KaggleApi
import tempfile
import glob
import shutil

# ─── 추가된 라이브러리(절대 누락 금지) ───────────────────────────────
import pyarrow.parquet as pq
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

# ─── 네트워크 안정화용 라이브러리 ──────────────────────────────────────
import httpx
from httpx import RemoteProtocolError

# ▸ backoff 모듈이 없으면 즉석에서 대체 구현
try:
    import backoff
except ImportError:
    logging.warning("`backoff` 모듈이 없어 간단 대체 데코레이터를 사용합니다.")

    def _simple_backoff_on_exception(exceptions, *args, **kwargs):
        """
        가벼운 지수(backoff=2^n) 재시도 데코레이터.
        backoff.on_exception API의 필수 인자만 흉내냅니다.
        - exceptions : 재시도 대상 예외(tuple 또는 단일)
        - max_tries  : kwargs 로 지정(기본 3)
        - base       : kwargs 로 지정(기본 2, 지수 배수)
        기타 인자는 무시합니다.
        """
        max_tries = kwargs.get("max_tries", 3)
        base      = kwargs.get("base", 2)

        def decorator(fn):
            def wrapper(*f_args, **f_kwargs):
                attempt = 0
                while True:
                    try:
                        return fn(*f_args, **f_kwargs)
                    except exceptions as e:
                        attempt += 1
                        if attempt >= max_tries:
                            raise
                        sleep = base ** attempt
                        logging.info(
                            f"[retry {attempt}/{max_tries}] {fn.__name__} -> {e}{sleep}s 대기"
                        )
                        time.sleep(sleep)
            return wrapper
        return decorator

    class _DummyBackoff:
        on_exception = _simple_backoff_on_exception

    backoff = _DummyBackoff()


# ─────────────────────────────── Environment Variables / Constants ─────────────────────────

OPENAI_API_KEY   = os.getenv("OPENAI_API_KEY", "")
BRAVE_KEY        = os.getenv("SERPHOUSE_API_KEY", "")   # Brave Search API
KAGGLE_USERNAME  = os.getenv("KAGGLE_USERNAME", "")
KAGGLE_KEY       = os.getenv("KAGGLE_KEY", "")
KAGGLE_API_KEY   = KAGGLE_KEY

if not (KAGGLE_USERNAME and KAGGLE_KEY):
    raise RuntimeError("⚠️  KAGGLE_USERNAME과 KAGGLE_KEY 환경변수를 먼저 설정하세요.")

os.environ["KAGGLE_USERNAME"] = KAGGLE_USERNAME
os.environ["KAGGLE_KEY"]      = KAGGLE_KEY

BRAVE_ENDPOINT   = "https://api.search.brave.com/res/v1/web/search"
IMAGE_API_URL    = "http://211.233.58.201:7896"  # 예시 이미지 생성용 API
MAX_TOKENS       = 7999        # 안전한 토큰 한도

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


# ─────────────────────────────── 군사(밀리터리) 전술 데이터셋 로드 ─────────────────
@st.cache_resource
def load_military_dataset():
    """
    mil.parquet (index, scenario_description, attack_reasoning, defense_reasoning)
    """
    path = os.path.join(os.path.dirname(__file__), "mil.parquet")
    if not os.path.exists(path):
        logging.warning("mil.parquet not found – military support disabled.")
        return None
    try:
        df = pq.read_table(path).to_pandas()
        return df
    except Exception as e:
        logging.error(f"Failed to read mil.parquet: {e}")
        return None

MIL_DF = load_military_dataset()

def is_military_query(text: str) -> bool:
    """군사/전술 관련 키워드가 등장하면 True 반환"""
    kw = [
        "군사", "전술", "전투", "전쟁", "작전", "무기", "병력",
        "military", "tactic", "warfare", "battle", "operation"
    ]
    return any(k.lower() in text.lower() for k in kw)

def military_search(query: str, top_k: int = 3):
    """
    mil.parquet의 scenario_description 열과 코사인 유사도 분석하여
    query와 가장 유사한 상위 시나리오를 반환
    """
    if MIL_DF is None:
        return []
    try:
        corpus = MIL_DF["scenario_description"].tolist()
        vec = TfidfVectorizer().fit_transform([query] + corpus)
        sims = cosine_similarity(vec[0:1], vec[1:]).flatten()
        top_idx = sims.argsort()[-top_k:][::-1]
        return MIL_DF.iloc[top_idx][[
            "scenario_description",
            "attack_reasoning",
            "defense_reasoning"
        ]].to_dict("records")
    except Exception as e:
        logging.error(f"military_search error: {e}")
        return []

# ─────────────────────────────── Kaggle Datasets ────────────────────────
KAGGLE_DATASETS = {
    "general_business": {
        "ref": "mohammadgharaei77/largest-2000-global-companies",
        "title": "Largest 2000 Global Companies",
        "subtitle": "Comprehensive data about the world's largest companies",
        "url": "https://www.kaggle.com/datasets/mohammadgharaei77/largest-2000-global-companies",
        "keywords": ["business", "company", "corporation", "enterprise", "global", "비즈니스", "기업", "회사", "글로벌", "기업가치"]
    },
    "global_development": {
        "ref": "michaelmatta0/global-development-indicators-2000-2020",
        "title": "Global Development Indicators (2000-2020)",
        "subtitle": "Economic and social indicators for countries worldwide",
        "url": "https://www.kaggle.com/datasets/michaelmatta0/global-development-indicators-2000-2020",
        "keywords": ["development", "economy", "global", "indicators", "social", "경제", "발전", "지표", "사회", "국가", "글로벌"]
    },
    "startup_ideas": {
        "ref": "rohitsahoo/100-startup-ideas",
        "title": "Startup Idea Generator Dataset",
        "subtitle": "A variety of startup ideas",
        "url": "https://www.kaggle.com/datasets/rohitsahoo/100-startup-ideas",
        "keywords": ["startup", "innovation", "business idea", "entrepreneurship", "스타트업", "창업", "혁신", "아이디어", "기업가"]
    },
    "legal_terms": {
        "ref": "gu05087/korean-legal-terms",
        "title": "Korean Legal Terms",
        "subtitle": "Database of Korean legal terminology",
        "url": "https://www.kaggle.com/datasets/gu05087/korean-legal-terms",
        "keywords": ["legal", "law", "terms", "korean", "legislation", "법률", "법적", "한국", "용어", "규제"]
    },
    "billionaires": {
        "ref": "vincentcampanaro/forbes-worlds-billionaires-list-2024",
        "title": "Forbes World's Billionaires List 2024",
        "subtitle": "Comprehensive data on the world's wealthiest individuals",
        "url": "https://www.kaggle.com/datasets/vincentcampanaro/forbes-worlds-billionaires-list-2024",
        "keywords": ["billionaire", "wealth", "rich", "forbes", "finance", "부자", "억만장자", "포브스", "부", "재테크"]
    },
    "financial_news": {
        "ref": "thedevastator/uncovering-financial-insights-with-the-reuters-2",
        "title": "Reuters Financial News Insights",
        "subtitle": "Financial news and market analysis from Reuters",
        "url": "https://www.kaggle.com/datasets/thedevastator/uncovering-financial-insights-with-the-reuters-2",
        "keywords": ["finance", "market", "stock", "investment", "news", "금융", "시장", "주식", "투자", "뉴스"]
    },
    "ecommerce": {
        "ref": "oleksiimartusiuk/80000-products-e-commerce-data-clean",
        "title": "80,000 Products E-Commerce Data",
        "subtitle": "Clean dataset of e-commerce products information",
        "url": "https://www.kaggle.com/datasets/oleksiimartusiuk/80000-products-e-commerce-data-clean",
        "keywords": ["ecommerce", "product", "retail", "shopping", "online", "이커머스", "제품", "소매", "쇼핑", "온라인"]
    },
    "world_development_indicators": {
        "ref": "georgejdinicola/world-bank-indicators",
        "title": "World Development Indicators",
        "subtitle": "Long-run socio-economic indicators for 200+ countries",
        "url": "https://www.kaggle.com/datasets/georgejdinicola/world-bank-indicators",
        "keywords": [
            "wdi", "macro", "economy", "gdp", "population",
            "개발지표", "거시경제", "세계은행", "경제지표", "인구"
        ]
    },
    "commodity_prices": {
        "ref": "debashish311601/commodity-prices",
        "title": "Commodity Prices (2000-2023)",
        "subtitle": "Daily prices for crude oil, gold, grains, metals, etc.",
        "url": "https://www.kaggle.com/datasets/debashish311601/commodity-prices",
        "keywords": [
            "commodity", "oil", "gold", "raw material", "price",
            "원자재", "유가", "금", "가격", "시장"
        ]
    },
    "world_trade": {
        "ref": "muhammadtalhaawan/world-export-and-import-dataset",
        "title": "World Export & Import Dataset",
        "subtitle": "34-year historical trade flows by country & product",
        "url": "https://www.kaggle.com/datasets/muhammadtalhaawan/world-export-and-import-dataset",
        "keywords": [
            "trade", "export", "import", "commerce", "flow",
            "무역", "수출", "수입", "국제교역", "관세"
        ]
    },
    "us_business_reports": {
        "ref": "census/business-and-industry-reports",
        "title": "US Business & Industry Reports",
        "subtitle": "Key monthly economic indicators from the US Census Bureau",
        "url": "https://www.kaggle.com/datasets/census/business-and-industry-reports",
        "keywords": [
            "us", "economy", "retail sales", "construction", "manufacturing",
            "미국", "경제지표", "소매판매", "산업생산", "건설"
        ]
    },
    "us_industrial_production": {
        "ref": "federalreserve/industrial-production-index",
        "title": "Industrial Production Index (US)",
        "subtitle": "Monthly Fed index for manufacturing, mining & utilities",
        "url": "https://www.kaggle.com/datasets/federalreserve/industrial-production-index",
        "keywords": [
            "industry", "production", "index", "fed", "us",
            "산업생산", "제조업", "미국", "경기", "지수"
        ]
    },
    "us_stock_market": {
        "ref": "borismarjanovic/price-volume-data-for-all-us-stocks-etfs",
        "title": "Huge Stock Market Dataset",
        "subtitle": "Historical prices & volumes for all US stocks and ETFs",
        "url": "https://www.kaggle.com/datasets/borismarjanovic/price-volume-data-for-all-us-stocks-etfs",
        "keywords": [
            "stock", "market", "finance", "equity", "price",
            "주식", "미국증시", "시세", "ETF", "데이터"
        ]
    },
    "company_financials": {
        "ref": "rish59/financial-statements-of-major-companies2009-2023",
        "title": "Financial Statements of Major Companies (2009-2023)",
        "subtitle": "15-year income sheet & balance sheet data for global firms",
        "url": "https://www.kaggle.com/datasets/rish59/financial-statements-of-major-companies2009-2023",
        "keywords": [
            "financials", "income", "balance sheet", "cashflow",
            "재무제표", "매출", "수익성", "기업재무", "포트폴리오"
        ]
    },
    "startup_investments": {
        "ref": "justinas/startup-investments",
        "title": "Crunchbase Startup Investments",
        "subtitle": "Funding rounds & investor info for global startups",
        "url": "https://www.kaggle.com/datasets/justinas/startup-investments",
        "keywords": [
            "startup", "venture", "funding", "crunchbase",
            "투자", "VC", "스타트업", "라운드", "신규진입"
        ]
    },
    "global_energy": {
        "ref": "atharvasoundankar/global-energy-consumption-2000-2024",
        "title": "Global Energy Consumption (2000-2024)",
        "subtitle": "Country-level energy usage by source & sector",
        "url": "https://www.kaggle.com/datasets/atharvasoundankar/global-energy-consumption-2000-2024",
        "keywords": [
            "energy", "consumption", "renewable", "oil", "utility",
            "에너지", "소비", "재생에너지", "전력수요", "화석연료"
        ]
    },
    "co2_emissions": {
        "ref": "ulrikthygepedersen/co2-emissions-by-country",
        "title": "CO₂ Emissions by Country",
        "subtitle": "Annual CO₂ emissions & per-capita data since 1960s",
        "url": "https://www.kaggle.com/datasets/ulrikthygepedersen/co2-emissions-by-country",
        "keywords": [
            "co2", "emission", "climate", "environment", "carbon",
            "탄소배출", "기후변화", "환경", "온실가스", "지속가능"
        ]
    },
    "crop_climate": {
        "ref": "thedevastator/the-relationship-between-crop-production-and-cli",
        "title": "Crop Production & Climate Change",
        "subtitle": "Yield & area stats for wheat, corn, rice, soybean vs climate",
        "url": "https://www.kaggle.com/datasets/thedevastator/the-relationship-between-crop-production-and-cli",
        "keywords": [
            "agriculture", "crop", "climate", "yield", "food",
            "농업", "작물", "기후", "수확량", "식품"
        ]
    },
    "esg_ratings": {
        "ref": "alistairking/public-company-esg-ratings-dataset",
        "title": "Public Company ESG Ratings",
        "subtitle": "Environment, Social & Governance scores for listed firms",
        "url": "https://www.kaggle.com/datasets/alistairking/public-company-esg-ratings-dataset",
        "keywords": [
            "esg", "sustainability", "governance", "csr",
            "환경", "사회", "지배구조", "지속가능", "평가"
        ]
    },
    "global_health": {
        "ref": "malaiarasugraj/global-health-statistics",
        "title": "Global Health Statistics",
        "subtitle": "Comprehensive health indicators & disease prevalence by country",
        "url": "https://www.kaggle.com/datasets/malaiarasugraj/global-health-statistics",
        "keywords": [
            "health", "disease", "life expectancy", "WHO",
            "보건", "질병", "기대수명", "의료", "공중보건"
        ]
    },
    "housing_market": {
        "ref": "atharvasoundankar/global-housing-market-analysis-2015-2024",
        "title": "Global Housing Market Analysis (2015-2024)",
        "subtitle": "House price index, mortgage rates, rent data by country",
        "url": "https://www.kaggle.com/datasets/atharvasoundankar/global-housing-market-analysis-2015-2024",
        "keywords": [
            "housing", "real estate", "price index", "mortgage",
            "부동산", "주택가격", "임대료", "시장", "금리"
        ]
    },
    "pharma_sales": {
        "ref": "milanzdravkovic/pharma-sales-data",
        "title": "Pharma Sales Data (2014-2019)",
        "subtitle": "600k sales records across 8 ATC drug categories",
        "url": "https://www.kaggle.com/datasets/milanzdravkovic/pharma-sales-data",
        "keywords": [
            "pharma", "sales", "drug", "healthcare", "medicine",
            "제약", "의약품", "매출", "헬스케어", "시장"
        ]
    },
    "ev_sales": {
        "ref": "muhammadehsan000/global-electric-vehicle-sales-data-2010-2024",
        "title": "Global EV Sales Data (2010-2024)",
        "subtitle": "Electric vehicle unit sales by region & model year",
        "url": "https://www.kaggle.com/datasets/muhammadehsan000/global-electric-vehicle-sales-data-2010-2024",
        "keywords": [
            "ev", "electric vehicle", "automotive", "mobility",
            "전기차", "판매량", "자동차산업", "친환경모빌리티", "시장성장"
        ]
    },
    "hr_attrition": {
        "ref": "pavansubhasht/ibm-hr-analytics-attrition-dataset",
        "title": "IBM HR Analytics: Attrition & Performance",
        "subtitle": "Employee demographics, satisfaction & attrition flags",
        "url": "https://www.kaggle.com/datasets/pavansubhasht/ibm-hr-analytics-attrition-dataset",
        "keywords": [
            "hr", "attrition", "employee", "people analytics",
            "인사", "이직률", "직원", "HR분석", "조직관리"
        ]
    },
    "employee_satisfaction": {
        "ref": "redpen12/employees-satisfaction-analysis",
        "title": "Employee Satisfaction Survey Data",
        "subtitle": "Department-level survey scores on satisfaction & engagement",
        "url": "https://www.kaggle.com/datasets/redpen12/employees-satisfaction-analysis",
        "keywords": [
            "satisfaction", "engagement", "survey", "workplace",
            "직원만족도", "조직문화", "설문", "근무환경", "HR"
        ]
    },
    "world_bank_indicators": {
        "ref": "georgejdinicola/world-bank-indicators",
        "title": "World Bank Indicators by Topic (1960-Present)",
        "subtitle": "Macro-economic, 사회·인구 통계 등 200+개국 장기 시계열 지표",
        "url": "https://www.kaggle.com/datasets/georgejdinicola/world-bank-indicators",
        "keywords": ["world bank", "development", "economy", "global", "indicator", "세계은행", "경제", "지표", "개발", "거시"]
    },
    "physical_chem_properties": {
        "ref": "ivanyakovlevg/physical-and-chemical-properties-of-substances",
        "title": "Physical & Chemical Properties of Substances",
        "subtitle": "8만여 화합물의 물리·화학 특성 및 분류 정보",
        "url": "https://www.kaggle.com/datasets/ivanyakovlevg/physical-and-chemical-properties-of-substances",
        "keywords": ["chemistry", "materials", "property", "substance", "화학", "물성", "소재", "데이터", "R&D"]
    },
    "global_weather_repository": {
        "ref": "nelgiriyewithana/global-weather-repository",
        "title": "Global Weather Repository",
        "subtitle": "전 세계 기상 관측치(기온·강수·풍속 등) 일별 업데이트",
        "url": "https://www.kaggle.com/datasets/nelgiriyewithana/global-weather-repository",
        "keywords": ["weather", "climate", "meteorology", "global", "forecast", "기상", "날씨", "기후", "관측", "환경"]
    },
    "amazon_best_seller_softwares": {
        "ref": "kaverappa/amazon-best-seller-softwares",
        "title": "Amazon Best Seller – Software Category",
        "subtitle": "아마존 소프트웨어 베스트셀러 순위 및 리뷰 데이터",
        "url": "https://www.kaggle.com/datasets/kaverappa/amazon-best-seller-softwares",
        "keywords": ["amazon", "e-commerce", "software", "review", "ranking", "아마존", "이커머스", "소프트웨어", "베스트셀러", "리뷰"]
    },
    "world_stock_prices": {
        "ref": "nelgiriyewithana/world-stock-prices-daily-updating",
        "title": "World Stock Prices (Daily Updating)",
        "subtitle": "30,000여 글로벌 상장사의 일간 주가·시총·섹터 정보 실시간 갱신",
        "url": "https://www.kaggle.com/datasets/nelgiriyewithana/world-stock-prices-daily-updating",
        "keywords": ["stock", "finance", "market", "equity", "price", "글로벌", "주가", "금융", "시장", "투자"]
    }
}

SUN_TZU_STRATEGIES = [
    {"계": "만천과해", "요약": "평범한 척, 몰래 진행", "조건": "상대가 지켜보고 있을 때", "행동": "루틴·평온함 과시", "목적": "경계 무력화", "예시": "규제기관 눈치 보는 신사업 파일럿"},
    {"계": "위위구조", "요약": "뒤통수 치면 포위 풀린다", "조건": "우리 측이 압박받을 때", "행동": "적 본진 급습", "목적": "압박 해소", "예시": "경쟁사 핵심 고객 뺏기"},
    {"계": "차도살인", "요약": "내 손 더럽히지 마", "조건": "직접 공격 부담", "행동": "제3자 활용", "목적": "책임 전가", "예시": "언론을 통한 경쟁사 비판"},
    {"계": "이일대우", "요약": "우리가 쉬면 적이 지친다", "조건": "상대가 과로 중", "행동": "버티며 체력 보존", "목적": "역전 타이밍 확보", "예시": "협상 지연 후 헐값 인수"},
    {"계": "진화타겁", "요약": "불날 때 주워 담기", "조건": "시장 혼란·위기", "행동": "저가 매수", "목적": "저비용 고이익", "예시": "금융위기 때 우량자산 매입"},
    {"계": "성동격서", "요약": "소음은 왼쪽, 공격은 오른쪽", "조건": "정면 방어 견고", "행동": "가짜 신호 → 우회", "목적": "방어 분산", "예시": "신제품 A 홍보, 실제는 B 확장"},
    {"계": "무중생유", "요약": "없는 것도 있는 척", "조건": "자원 부족", "행동": "허세·연막", "목적": "상대 혼란", "예시": "스타트업 과장 로드맵"},
    {"계": "암도진창", "요약": "뒷문으로 돌아가라", "조건": "우회로 존재", "행동": "비밀 루트 침투", "목적": "허를 찌름", "예시": "관세 피해 제3국 생산"},
    {"계": "격안관화", "요약": "남 싸움 구경", "조건": "두 경쟁자 충돌", "행동": "관망", "목적": "둘 다 소모", "예시": "플랫폼 전쟁 중 중립 유지"},
    {"계": "소리장도", "요약": "웃으며 칼 숨기기", "조건": "친밀 분위기", "행동": "우호 제스처 후 기습", "목적": "경계 붕괴", "예시": "합작 후 핵심 기술 탈취"},
    {"계": "이대도강", "요약": "덜 중요한 걸 내줘라", "조건": "뭔가 잃었을 때", "행동": "부속 희생", "목적": "핵심 보호", "예시": "제품 라인 하나 단종"},
    {"계": "순수견양", "요약": "방치된 것 챙기기", "조건": "경계 허술", "행동": "자연스럽게 수집", "목적": "무혈 이득", "예시": "공공 API 데이터 긁기"},
    {"계": "타초경사", "요약": "풀 쳐서 뱀 나온다", "조건": "적이 숨을 때", "행동": "일부러 소란", "목적": "위치 노출", "예시": "이사회 반대파 의중 파악"},
    {"계": "차시환혼", "요약": "죽은 카드 재활용", "조건": "폐기 자원", "행동": "리브랜딩", "목적": "새 전력 확보", "예시": "실패 앱 재출시"},
    {"계": "조호이산", "요약": "호랑이 산 밖으로", "조건": "강적 거점", "행동": "유인 이동", "목적": "빈집 공략", "예시": "경쟁 VC 행사 유도 후 딜 선점"},
    {"계": "욕금고종", "요약": "잡으려면 놓아줘라", "조건": "인재·적 포획", "행동": "일부러 풀어줌", "목적": "저항 약화", "예시": "핵심 인재 재계약 유도"},
    {"계": "포전인옥", "요약": "벽돌 던져 옥 얻기", "조건": "큰 보상 필요", "행동": "작은 미끼", "목적": "참여 유도", "예시": "무료 → 유료 전환"},
    {"계": "금적금왕", "요약": "도둑 잡으려면 두목부터", "조건": "조직 복잡", "행동": "수뇌 공격", "목적": "조직 붕괴", "예시": "최대 주주 지분 매입"},
    {"계": "부저이지", "요약": "가마 밑 불 끄기", "조건": "적 의존성 존재", "행동": "보급 차단", "목적": "전력 급감", "예시": "핵심 공급업체 선점"},
    {"계": "혼수모어", "요약": "물 흐려 놓고 낚시", "조건": "판세 불투명", "행동": "혼탁 유지", "목적": "어부지리", "예시": "입법 지연 로비"},
    {"계": "금선탈각", "요약": "허물 벗고 도망", "조건": "추적 심함", "행동": "외피만 남김", "목적": "추적 무효", "예시": "부실 자회사 떼어내기"},
    {"계": "관문잡적", "요약": "문 닫고 잡아라", "조건": "퇴로 예측", "행동": "출구 봉쇄", "목적": "완전 포획", "예시": "락업 조항으로 지분 매집"},
    {"계": "원교근공", "요약": "먼 데와 친해지고 가까운 데 친다", "조건": "다국 간 경쟁", "행동": "원거리 동맹", "목적": "단계적 확장", "예시": "원거리 FTA 체결 후 인근 M&A"},
    {"계": "가도벌괵", "요약": "길 빌려 공격", "조건": "중간 세력 장벽", "행동": "통로 명분 → 제압", "목적": "장애 제거", "예시": "총판 빌미 시장 진입"},
    {"계": "투량환주", "요약": "들보 몰래 바꿔치기", "조건": "감시 존재", "행동": "내부 교체", "목적": "인식 왜곡", "예시": "백엔드 갈아끼우기"},
    {"계": "지상매괴", "요약": "뽕나무 가리켜 회초리 욕", "조건": "직접 비판 곤란", "행동": "제3자 지적", "목적": "메시지 전달", "예시": "싱크탱크 보고서 압박"},
    {"계": "가치불전", "요약": "바보 연기", "조건": "상대 의심 많음", "행동": "일부러 허술", "목적": "방심 유도", "예시": "저평가 가이던스"},
    {"계": "상옥추제", "요약": "사다리 걷어차기", "조건": "길 열어준 뒤", "행동": "퇴로 차단", "목적": "고립", "예시": "투자자 초청 후 정보 차단"},
    {"계": "수상개화", "요약": "나무에 꽃 핀 척", "조건": "실력 부족", "행동": "외형 부풀림", "목적": "영향력 확대", "예시": "MOU ·공동 로고 홍보"},
    {"계": "반객위주", "요약": "손님에서 주인으로", "조건": "부차적 위치", "행동": "주도권 장악", "목적": "역전 지휘", "예시": "플랫폼 입점사 자체 마켓"},
    {"계": "미인계", "요약": "매력으로 판단 흐리기", "조건": "유혹 가능", "행동": "감정·매력 활용", "목적": "결정 왜곡", "예시": "지역 투자로 정치인 호감 얻기"},
    {"계": "공성계", "요약": "텅 빈 성문 열어놓기", "조건": "병력 부족", "행동": "과감히 공개", "목적": "상대 의심", "예시": "내부자료 전면 공개"},
    {"계": "반간계", "요약": "가짜 스파이 역이용", "조건": "내부 불신 요소", "행동": "교란 정보", "목적": "분열", "예시": "경쟁사에 가짜 루머"},
    {"계": "고육계", "요약": "살 내주고 뼈 취하기", "조건": "신뢰 상실", "행동": "스스로 손실", "목적": "진정성 증명", "예시": "CEO 보너스 반납"},
    {"계": "연환계", "요약": "사슬로 한꺼번에", "조건": "복수 대상 다수", "행동": "연결 묶기", "목적": "효율 타격", "예시": "패키지 제재안"},
    {"계": "주위상계", "요약": "도망이 상책", "조건": "승산 없음", "행동": "즉시 후퇴", "목적": "손실 최소·재기", "예시": "적자 시장 철수"}
]

physical_transformation_categories = {
    "센서 기능": [
        # 기존 항목 유지
        "시각 센서", "시각 감지", "청각 센서", "청각 감지", "촉각 센서", "촉각 감지",
        "미각 센서", "미각 감지", "후각 센서", "후각 감지", "온도 센서", "온도 감지",
        "습도 센서", "습도 감지", "압력 센서", "압력 감지", "가속도 센서", "가속도 감지",
        "회전 센서", "회전 감지", "근접 센서", "근접 감지", "위치 센서", "위치 감지",
        "운동 센서", "운동 감지", "가스 센서", "가스 감지", "적외선 센서", "적외선 감지",
        "자외선 센서", "자외선 감지", "방사선 센서", "방사선 감지", "자기장 센서", "자기장 감지",
        "전기장 센서", "전기장 감지", "화학물질 센서", "화학물질 감지", "생체신호 센서", "생체신호 감지",
        "진동 센서", "진동 감지", "소음 센서", "소음 감지", "빛 세기 센서", "빛 세기 감지",
        "빛 파장 센서", "빛 파장 감지", "기울기 센서", "기울기 감지", "pH 센서", "pH 감지",
        "전류 센서", "전류 감지", "전압 센서", "전압 감지", "이미지 센서", "이미지 감지",
        "거리 센서", "거리 감지", "깊이 센서", "깊이 감지", "중력 센서", "중력 감지",
        "속도 센서", "속도 감지", "흐름 센서", "흐름 감지", "수위 센서", "수위 감지",
        "탁도 센서", "탁도 감지", "염도 센서", "염도 감지", "금속 감지", "압전 센서",
        "압전 감지", "광전 센서", "광전 감지", "열전대 센서", "열전대 감지", "홀 효과 센서",
        "홀 효과 감지", "초음파 센서", "초음파 감지", "레이더 센서", "레이더 감지",
        "라이다 센서", "라이다 감지", "터치 센서", "터치 감지", "제스처 센서", "제스처 감지",
        "심박 센서", "심박 감지", "혈압 센서", "혈압 감지", "LAN", "WIFI", "블루투스", "생체 인증",
        # 추가 항목
        "다중 스펙트럼 센서", "다중 스펙트럼 감지", "깊이 인식 센서", "깊이 인식 감지",
        "퀀텀 센서", "퀀텀 감지", "웨어러블 센서", "웨어러블 감지", "바이오마커 센서", "바이오마커 감지",
        "임베디드 센서", "임베디드 감지", "IoT 센서 네트워크", "스트레인 센서", "스트레인 감지",
        "경도/연도 센서", "경도/연도 감지", "5G/6G 연결성", "NFC", "양자암호화 통신",
        "스마트 먼지 센서", "환경 센서 그리드", "신경형태학적 센서", "두뇌-기계 인터페이스"
    ],
    "크기와 형태 변화": [
        # 기존 항목 유지
        "부피 늘어남", "부피 줄어듦", "길이 늘어남", "길이 줄어듦", "너비 늘어남", "너비 줄어남",
        "높이 늘어남", "높이 줄어듦", "밀도 변화", "무게 증가", "무게 감소", "모양 변형",
        "상태 변화", "불균등 변형", "복잡한 형태 변형", "비틀림", "꼬임", "불균일한 확장",
        "불균일한 축소", "모서리 둥글게", "모서리 날카롭게", "깨짐", "갈라짐", "여러 조각 나눠짐",
        "물 저항", "먼지 저항", "찌그러짐", "복원", "접힘", "펼쳐짐", "압착", "팽창",
        "늘어남", "수축", "구겨짐", "평평해짐", "뭉개짐", "단단해짐", "말림", "펴짐",
        "꺾임", "구부러짐",
        # 추가 항목
        "4D 프린팅 변형", "형상 기억", "프랙탈 변화", "자가 조립", "자가 복구",
        "기하학적 변환", "모듈화", "스마트 직물 변형", "매트릭스 구조 변형", "프로그래머블 변형",
        "미시 스케일 변형", "거시 스케일 변형", "이방성 변형", "등방성 변형", "선택적 강성 변화",
        "변형률 감응 구조", "형태학적 계산", "위상 변화", "경도 변화", "부드러움 변화"
    ],
    "표면 및 외관 변화": [
        # 기존 항목 유지
        "색상 변화", "질감 변화", "투명 변화", "불투명 변화", "반짝임 변화", "무광 변화",
        "빛 반사 정도 변화", "무늬 변화", "각도에 따른 색상 변화", "빛에 따른 색상 변화",
        "온도에 따른 색상 변화", "홀로그램 효과", "표면 각도별 빛 반사", "표면 모양 변형",
        "초미세 표면 구조 변화", "자가 세정 효과", "얼룩 생성", "패턴 생성", "흐림 변화",
        "선명함 변화", "광택 변화", "윤기 변화", "색조 변화", "채도 변화", "발광",
        "형광", "빛 산란 효과", "빛 흡수 변화", "반투명 효과", "그림자 효과 변화",
        "자외선 반응 변화", "야광 효과",
        # 추가 항목
        "생체모방 표면", "프로그래머블 질감", "촉각 피드백 표면", "열 반응성 표면",
        "초소수성/초친수성 표면", "스마트 코팅", "마찰 계수 변화", "도금 효과", "위장 효과",
        "양자점 효과", "메타표면 효과", "나노 구조화 표면", "전기변색 효과", "광변색 효과",
        "압력변색 효과", "자기변색 효과", "항균 표면", "공기역학적 표면", "자기정렬 패턴", 
        "부착성 변화", "선택적 접착성"
    ],
    "물질의 상태 변화": [
        # 기존 항목 유지
        "고체 전환", "액체 전환", "기체 전환", "결정화", "용해", "산화", "부식",
        "딱딱해짐", "부드러워짐", "특수 상태 전환", "무정형 전환", "결정형 전환", "성분 분리",
        "미세 입자 형성", "미세 입자 분해", "젤 형성", "젤 풀어짐", "준안정 상태 변화",
        "분자 자가 정렬", "분자 자가 분해", "상태변화 지연 현상", "녹음", "굳음",
        "증발", "응축", "승화", "증착", "침전", "부유", "분산", "응집",
        "건조", "습윤", "팽윤", "수축", "동결", "해동", "풍화", "침식",
        "충전", "방전", "결합", "분리", "발효", "부패",
        # 추가 항목
        "초임계 상태 전환", "양자 상태 전환", "메타물질 상태 변화", "프로그래머블 물질 변화",
        "소프트 로봇 물질 변화", "4D 프린팅 물질 변화", "바이오하이브리드 물질 변화",
        "자가 조직화 물질", "자가 순환 물질", "자가 치유 물질", "생분해성 전환",
        "양자얽힘 상태", "위상학적 상태 변화", "비선형 물질 변화", "재료 피로 변화",
        "스마트 유체 상태", "자극 반응성 상태", "형상기억 합금 상태", "초전도 상태"
    ],
    "움직임 특성 변화": [
        # 기존 항목 유지
        "가속", "감속", "일정 속도 유지", "진동", "진동 감소", "부딪힘", "튕김",
        "회전 속도 증가", "회전 속도 감소", "회전 방향 변화", "불규칙 움직임", "멈췄다", "미끄러지는 현상",
        "공진", "반공진", "유체 속 저항 변화", "유체 속 양력 변화", "움직임 저항 변화",
        "복합 진동 움직임", "특수 유체 속 움직임", "회전-이동 연계 움직임", "관성 정지",
        "충격 흡수", "충격 전달", "운동량 보존", "마찰력 변화", "관성 탈출", "불안정 균형",
        "동적 안정성", "흔들림 감쇠", "경로 예측성", "회피 움직임",
        # 추가 항목
        "복합 운동학", "임의의 움직임", "재귀적 움직임", "흉내내는 움직임", "학습된 움직임",
        "자율적 움직임", "군집 움직임", "비선형 움직임", "양자 움직임", "초음파 움직임",
        "비대칭 움직임", "스토캐스틱 움직임", "카오스 움직임", "소프트 로보틱스 움직임",
        "생체모방 움직임", "변형 기반 이동", "유체력학적 추진", "자기장 유도 이동",
        "계층적 움직임 제어", "적응형 움직임 패턴"
    ],
    "구조적 변화": [
        # 기존 항목 유지
        "부품 추가", "부품 제거", "조립", "분해", "접기", "펴기", "변형", "원상복구",
        "최적 구조 변화", "자가 재배열", "자연 패턴 형성", "자연 패턴 소멸", "규칙적 패턴 변화",
        "모듈식 변형", "복잡성 증가 구조", "원래 모양 기억 효과", "시간에 따른 형태 변화",
        "부분 제거", "부분 교체", "결합", "분리", "분할", "통합", "중첩", "겹침",
        "내부 구조 변화", "외부 구조 변화", "중심축 이동", "균형점 변화", "계층 구조 변화",
        "지지 구조 변화", "응력 분산 구조", "충격 흡수 구조", "그리드 구조 변화", "매트릭스 구조 변화",
        "상호 연결성 변화",
        # 추가 항목
        "텐세그리티 구조 변화", "바이오닉 구조", "메타물질 구조", "다중 안정 구조", "자가 진화 구조",
        "자가 학습 구조", "생체모방 구조", "프랙탈 구조", "계층적 구조화", "에너지 흡수 구조",
        "에너지 변환 구조", "적응형 구조", "위상 최적화", "다공성 구조", "기능적 경사 구조",
        "다중 재료 구조", "초경량 구조", "초고강도 구조", "다기능성 구조", "내결함성 구조"
    ],
    "공간 이동": [
        # 기존 항목 유지
        "앞 이동", "뒤 이동", "좌 이동", "우 이동", "위 이동", "아래 이동",
        "세로축 회전(고개 끄덕임)", "가로축 회전(고개 젓기)", "길이축 회전(옆으로 기울임)", "원 운동",
        "나선형 이동", "관성에 의한 미끄러짐", "회전축 변화", "불규칙 회전", "흔들림 운동",
        "포물선 이동", "무중력 부유", "수면 위 부유", "점프", "도약", "슬라이딩", "롤링",
        "자유 낙하", "왕복 운동", "탄성 튕김", "관통", "회피 움직임", "지그재그 이동", "스윙 운동",
        # 추가 항목
        "양자 이동", "차원 간 이동", "가상 공간 이동", "증강 공간 이동", "무인 이동",
        "군집 이동", "경로 최적화 이동", "상황 인식 이동", "생태계 통합 이동", "바이오닉 이동",
        "미시 스케일 이동", "매크로 스케일 이동", "변형 기반 이동", "자기장 유도 이동",
        "로봇 스웜 이동", "다중 지형 적응 이동", "유체동역학적 이동", "자기 추진", "텔레포트 효과",
        "지능형 경로 탐색"
    ],
    "시간 관련 변화": [
        # 기존 항목 유지
        "노화", "풍화", "마모", "부식", "색 바램", "변색", "손상", "회복",
        "수명 주기 변화", "사용자 상호작용에 따른 적응", "학습 기반 형태 최적화", "시간에 따른 물성 변화",
        "집단 기억 효과", "문화적 의미 변화", "지연 반응", "이전 상태 의존 변화", "점진적 시간 변화",
        "진화적 변화", "주기적 재생", "계절 변화 적응", "생체리듬 변화", "생애 주기 단계",
        "성장", "퇴화", "자가 복구", "자가 재생", "자연 순환 적응", "지속성", "일시성",
        "기억 효과", "지연된 작용", "누적 효과",
        # 추가 항목
        "시간 지연 효과", "예측 기반 변화", "학습 기반 변화", "인지적 시간 변화",
        "시간 압축 경험", "시간 확장 경험", "시간적 패턴 감지", "시간적 패턴 생성",
        "계절 인식 변화", "생체 시계 동기화", "시간 기반 프로그래밍", "연대기적 데이터 구조",
        "디지털 노화", "인공 연대기", "시간적 에이징 시뮬레이션", "기능적 수명주기",
        "사용 패턴 적응", "사용자 타임라인 통합", "예측 유지보수", "자가 최적화 타이밍"
    ],
    "빛과 시각 효과": [
        # 기존 항목 유지
        "발광", "소등", "빛 투과", "빛 차단", "빛 산란", "빛 집중", "색상 스펙트럼 변화",
        "빛 회절", "빛 간섭", "홀로그램 생성", "레이저 효과", "빛 편광", "형광", "인광",
        "자외선 발광", "적외선 발광", "광학적 착시", "빛 굴절", "그림자 생성", "그림자 제거",
        "색수차 효과", "무지개 효과", "글로우 효과", "플래시 효과", "조명 패턴", "빔 효과",
        "광 필터 효과", "빛의 방향성 변화", "투영 효과", "빛 감지", "빛 반응", "광도 변화",
        # 추가 항목
        "양자 발광", "메타 광학 효과", "프로그래머블 광학", "시야각 변화", "생체발광 모방",
        "광역학 효과", "퍼셉션 변화 효과", "맥스웰리안 뷰", "광 컴퓨팅 효과", "광유전학 효과",
        "생체 광학 모방", "비선형 광학 효과", "구조색 변화", "자가 발광", "광 결정 효과",
        "양자점 방출", "나노 발광체", "증강 광학", "투명 디스플레이 효과", "광학 위장"
    ],
    "소리와 진동 효과": [
        # 기존 항목 유지
        "소리 발생", "소리 소멸", "음 높낮이 변화", "음량 변화", "음색 변화", "공명",
        "반공명", "음향 진동", "초음파 발생", "저음파 발생", "소리 집중", "소리 분산",
        "음향 반사", "음향 흡수", "음향 도플러 효과", "음파 간섭", "음향 공진", "진동 패턴 변화",
        "타악 효과", "음향 피드백", "음향 차폐", "음향 증폭", "소리 지향성", "소리 왜곡",
        "비트 생성", "배음 생성", "주파수 변조", "음향 충격파", "음향 필터링",
        # 추가 항목
        "메타 음향 효과", "방향성 음향", "3D 음향 효과", "생체음향 모방", "상황별 음향 변화",
        "음향 위장", "음향 투명화", "음향 렌즈", "양자 음향 효과", "초저주파 효과",
        "초고주파 효과", "음파 에너지 수확", "자가 조절 공명", "음향 홀로그래피",
        "공간 음향 매핑", "선택적 음향 필터링", "지향성 초음파", "음파 촉각 피드백",
        "기능적 음향 표면", "구조 공진 조절"
    ],
    "열 관련 변화": [
        # 기존 항목 유지
        "온도 상승", "온도 하강", "열 팽창", "열 수축", "열 전달", "열 차단", "압력 상승",
        "압력 하강", "열 변화에 따른 자화", "엔트로피 변화", "열전기 효과", "자기장에 의한 열 변화",
        "상태 변화 중 열 저장", "상태 변화 중 열 방출", "열 스트레스 발생", "열 스트레스 해소",
        "급격한 온도 변화 영향", "복사 냉각", "복사 가열", "발열", "흡열", "열 분포 변화",
        "열 반사", "열 흡수", "냉각 응축", "열 활성화", "열 변색", "열 팽창 계수 변화",
        "열 안정성 변화", "내열성", "내한성", "자가 발열", "열적 평형", "열적 불균형",
        "열적 변형", "열 분산", "열 집중",
        # 추가 항목
        "열전 효과", "열광 효과", "프로그래머블 열 특성", "상변화 냉각", "상변화 가열",
        "열 유도 기억", "열 광학 효과", "열 음향 효과", "열 기계 효과", "열 화학 반응",
        "양자 열역학 효과", "근적외선 열 효과", "열 조절 표면", "열흐름 제어", "열 방출 최적화",
        "열 캡처 최적화", "자가 조절 온도", "열 스위칭", "열 포커싱", "상변화 재료 활용"
    ],
    "전기 및 자기 변화": [
        # 기존 항목 유지
        "자성 생성", "자성 소멸", "전하량 증가", "전하량 감소", "전기장 생성", "전기장 소멸",
        "자기장 생성", "자기장 소멸", "초전도 상태 전환", "강유전체 특성 변화", "양자 상태 변화",
        "플라즈마 형성", "플라즈마 소멸", "스핀파 전달", "빛에 의한 전기 발생", "압력에 의한 전기 발생",
        "자기장 내 전류 변화", "전기 저항 변화", "전기 전도성 변화", "정전기 발생", "정전기 방전",
        "전자기 유도", "전자기파 방출", "전자기파 흡수", "전기 용량 변화", "자기 이력 현상",
        "전기적 분극", "전자 흐름 방향 변화", "전기적 공명", "전기적 차폐", "전기적 노출",
        "자기 차폐", "자기 노출", "자기장 정렬", "유선(Wire)", "무선(Wireless)",
        # 추가 항목
        "양자 자성", "스핀트로닉스 효과", "마그네토일렉트릭 효과", "토폴로지컬 절연체 특성",
        "초전도 양자 효과", "쿨롱 차단 효과", "조셉슨 효과", "홀 효과 변화", "전자기 투명성",
        "자기 카이랄리티", "전자기 메타표면", "무선 전력 전송", "자기유변학적 효과",
        "전자기 에너지 수확", "전자기 재구성", "퀀텀 터널링", "전자기 차폐", "전자파 흡수 재료",
        "전자 스핀 제어", "고속 스위칭 자성"
    ],
    "화학적 변화": [
        # 기존 항목 유지
        "표면 코팅 변화", "물질 성분 변화", "화학 반응 변화", "촉매 작용 시작/중단",
        "빛에 의한 화학 반응", "전기에 의한 화학 반응", "단분자막 형성", "분자 수준 구조 변화",
        "생체 모방 표면 변화", "환경 반응형 물질 변화", "주기적 화학 반응", "산화", "환원",
        "고분자화", "물 분해", "화합", "방사선 영향", "산-염기 반응", "중화 반응",
        "이온화", "화학적 흡착/탈착", "촉매 효율 변화", "효소 활성 변화", "발색 반응",
        "pH 변화", "화학적 평형 이동", "결합 형성/분해", "용해도 변화",
        # 추가 항목
        "프로그래머블 화학 반응", "자가 촉매 반응", "클릭 케미스트리", "광화학 반응",
        "전기화학 반응", "초분자 화학 반응", "동적 공유 결합", "바이오오쏘고널 화학",
        "화학적 컴퓨팅", "화학적 감지", "화학적 통신", "화학적 기억", "선택적 촉매",
        "메커노케미컬 반응", "에너지 전환 반응", "자기조립 화학", "변화 감지 화학", 
        "화학적 패턴 형성", "화학적 습도 조절", "화학적 정화"
    ],
    "생물학적 변화": [
        # 기존 항목 유지
        "성장/위축", "세포 분열/사멸", "생물 발광", "신진대사 변화", "면역 반응",
        "호르몬 분비", "신경 반응", "유전적 발현", "적응/진화", "생체리듬 변화",
        "재생/치유", "노화/성숙", "생체 모방 변화", "바이오필름 형성", "생물학적 분해",
        "효소 활성화/비활성화", "생물학적 신호 전달", "스트레스 반응", "체온 조절", "생물학적 시계 변화",
        "세포외 기질 변화", "생체 역학적 반응", "세포 운동성", "세포 극성 변화", "영양 상태 변화",
        # 추가 항목
        "합성 생물학 반응", "생물학적 컴퓨팅", "오가노이드 발달", "인공 조직 발달",
        "생체적합성 변화", "면역학적 응답 제어", "후성유전학적 변화", "생물학적 리듬 조절",
        "신경가소성 효과", "세포외 기질 리모델링", "체세포 리프로그래밍", "생체활성 표면 상호작용",
        "생물학적 자가조립", "미생물군집 조절", "생물복합체 형성", "생체 프린팅", 
        "바이오하이브리드 시스템", "세포 분화 조절", "생체신호 증폭", "생화학적 기억 형성"
    ],
    "환경 상호작용": [
        # 기존 항목 유지
        "온도 반응", "습도 반응", "기압 반응", "중력 반응", "자기장 반응",
        "빛 반응", "소리 반응", "화학 물질 감지", "기계적 자극 감지", "전기 자극 반응",
        "방사선 반응", "진동 감지", "pH 반응", "용매 반응", "기체 교환",
        "환경 오염 반응", "날씨 반응", "계절 반응", "일주기 반응", "생태계 상호작용",
        "공생/경쟁 반응", "포식/피식 관계", "군집 형성", "영역 설정", "이주 패턴", "정착 패턴",
        # 추가 항목
        "탄소 포집 및 변환", "생태계 복원 효과", "생물다양성 증진", "순환 경제 상호작용",
        "도시 환경 통합", "스마트 환경 감지", "재생 가능 에너지 연계", "물 순환 상호작용",
        "대기 질 상호작용", "자연 기반 솔루션 통합", "재해 복원력 증진", "기후 변화 적응",
        "환경 정보 네트워크", "생태계 서비스 증진", "자원 순환 최적화", "생태계 균형 유지",
        "환경적 자가 수정", "지속가능한 자원 관리", "생태계 건강 모니터링", "생태 교란 방지"
    ],
    "비즈니스 아이디어": [
        # 기존 항목 유지
        "시장 재정의/신규 시장 개척",
        "비즈니스 모델 혁신/디지털 전환",
        "고객 경험 혁신/서비스 혁신",
        "협력 및 파트너십 강화/생태계 구축",
        "글로벌 확장/지역화 전략",
        "운영 효율성 증대/원가 절감",
        "브랜드 리포지셔닝/이미지 전환",
        "지속 가능한 성장/사회적 가치 창출",
        "데이터 기반 의사결정/AI 도입",
        "신기술 융합/혁신 투자",
        # 추가 항목
        "탄소중립 비즈니스 모델",
        "순환경제 비즈니스 모델",
        "구독 경제 모델",
        "플랫폼 비즈니스 모델",
        "블록체인 기반 비즈니스",
        "메타버스 비즈니스 통합",
        "인간-AI 협업 모델",
        "개인화된 맞춤형 제품/서비스",
        "탈중앙화 자율조직(DAO)",
        "임팩트 투자 모델",
        "사회적 가치 창출 비즈니스",
        "게이미피케이션 비즈니스 모델",
        "프로슈머 참여 모델",
        "지역 기반 마이크로 비즈니스",
        "웰빙/웰니스 중심 비즈니스"
    ],
    
    # 새로운 카테고리 추가
    
    "사용자 인터페이스 및 상호작용": [
        "제스처 인식", "제스처 제어", "음성 인식", "음성 제어", "시선 추적", "시선 제어",
        "촉각 피드백", "햅틱 인터페이스", "뇌-컴퓨터 인터페이스", "증강 현실 인터페이스",
        "가상 현실 인터페이스", "혼합 현실 인터페이스", "주변 인텔리전스", "상황 인식 인터페이스",
        "자연어 처리 인터페이스", "생체인식 인증", "다중 모달 인터페이스", "암묵적 상호작용",
        "명시적 상호작용", "인지적 부하 최소화", "지능형 적응 인터페이스", "감정 인식 인터페이스",
        "소셜 인터페이스", "공간 인터페이스", "신체 증강 인터페이스", "피부 인터페이스",
        "안구 내 인터페이스", "신경 인터페이스", "근전도 인터페이스", "후각 인터페이스"
    ],
    
    "데이터 및 정보 변환": [
        "데이터 시각화", "데이터 청각화", "데이터 촉각화", "실시간 분석", "예측 분석",
        "처방적 분석", "데이터 압축", "데이터 암호화", "데이터 익명화", "데이터 증강",
        "에지 컴퓨팅", "분산 데이터 처리", "양자 데이터 처리", "디지털 트윈", "시맨틱 매핑",
        "정보 필터링", "데이터 표준화", "데이터 융합", "데이터 마이닝", "패턴 인식",
        "비정형 데이터 처리", "실시간 의사결정", "데이터 맥락화", "데이터 품질 향상",
        "데이터 스토리텔링", "셀프 서비스 분석", "예지 분석", "행동 분석", "인지 분석"
    ],
    
    "인지 및 심리적 변화": [
        "주의력 조절", "주의 전환", "공간 인지 변화", "시간 인지 변화", "기억 향상", "기억 조절",
        "정서 변화", "감정 조절", "학습 경험 최적화", "의사결정 지원", "인지 부하 관리",
        "플로우 상태 유도", "창의성 증진", "스트레스 관리", "미적 경험 향상", "자기 인식 증진",
        "동기 부여 최적화", "행동 변화 유도", "인지 편향 감소", "명상 상태 유도", "집중력 향상",
        "마음챙김 유도", "공감 능력 향상", "자아 확장 경험", "윤리적 판단 지원", "인지적 유연성 향상",
        "문제 해결 능력 증진", "학습 전이 촉진", "인지적 증강", "심미적 인식 향상"
    ],
    
    "에너지 변환 및 관리": [
        "에너지 하베스팅", "에너지 저장", "에너지 변환", "에너지 효율 최적화", "분산 에너지 관리",
        "마이크로그리드 통합", "탄소중립 에너지 사용", "재생 에너지 통합", "에너지 자급자족",
        "지능형 에너지 관리", "수요 대응 에너지 제어", "온보드 에너지 생성", "에너지 재활용",
        "에너지 최소화", "제로 에너지 시스템", "열전기 변환", "태양 에너지 변환", "압전 에너지 변환",
        "동작 에너지 변환", "바이오매스 에너지", "수소 에너지 시스템", "유기 태양전지",
        "양자점 태양전지", "고체 배터리", "슈퍼커패시터", "에너지 인터넷", "양방향 그리드"
    ],
    
    "지속가능성 및 환경 영향": [
        "생분해성", "생태복원성", "탄소발자국 저감", "자원 효율성", "수명주기 최적화",
        "순환 설계", "업사이클링 용이성", "폐기물 최소화", "물 효율성", "독성 물질 제거",
        "환경복원 기능", "생태계 서비스 제공", "기후 회복력", "재생 가능 소재 사용", "환경 모니터링 기능",
        "자연 기반 솔루션", "탄소 포집", "환경 정화", "생태계 건강 증진", "식량-에너지-물 넥서스",
        "도시 생태 통합", "녹색 인프라", "블루 인프라", "자원 순환", "자원 공유",
        "재사용성", "수리 가능성", "모듈식 설계", "제로 웨이스트 디자인", "친환경 소재"
    ],
    
    "보안 및 프라이버시": [
        "자가 암호화", "생체인증 보안", "다요소 인증", "탈중앙화 신원 관리", "제로 트러스트 보안",
        "프라이버시 보존 계산", "동형 암호화", "양자 내성 보안", "자가 복구 보안", "행동 기반 보안",
        "물리적 보안 기능", "디지털 워터마킹", "익명화 기능", "프라이버시 필터링", "선택적 정보 공개",
        "블록체인 보안", "인증 메커니즘", "권한 관리", "침입 감지", "침입 방지", "보안 감사",
        "데이터 손실 방지", "버전 관리", "보안 백업", "안전한 복구", "이상 감지", "위협 인텔리전스",
        "취약점 관리", "에지 보안", "안티바이러스", "안티멀웨어"
    ],
    
    "사회적 상호작용 및 협업": [
        "소셜 신호 증폭", "집단 지성 지원", "협업 최적화", "사회적 연결 향상", "커뮤니티 형성 지원",
        "공유 경험 생성", "사회적 학습 촉진", "사회적 관계 가시화", "신뢰 구축 메커니즘",
        "사회적 역할 조정", "문화적 맥락 인식", "언어적 장벽 극복", "포용적 디자인 적용",
        "사회적 영향 증진", "윤리적 상호작용 지원", "책임감 있는 AI", "분산 협업", "원격 협업",
        "크라우드소싱", "공동 창작", "개방형 혁신", "사회적 기업가정신", "행동 변화 디자인",
        "사회적 자본 구축", "공공 참여 증진", "시민 과학", "디지털 포용성", "세대 간 협력"
    ],
    
    "미학 및 감성 경험": [
        "감정 유발 디자인", "미적 만족도 최적화", "감각적 풍요로움", "조화와 균형 경험",
        "개인화된 미적 경험", "문화적 공명", "서사적 경험 디자인", "놀라움과 발견 요소",
        "시간적 미학 변화", "다감각 경험 통합", "감성 기억 형성", "미적 지속성과 변화",
        "예술적 표현 지원", "의미 생성 경험", "상징적 가치 부여", "미적 정체성", "창의적 표현",
        "스토리텔링 요소", "감성적 인텔리전스", "감각 간 시너지", "문화적 표현", "감정적 반응 유도",
        "심미적 패턴 인식", "조형적 언어", "감성적 연결", "예술적 상호작용", "정서적 공명",
        "미적 만족감", "웰빙 디자인", "치유적 경험"
    ]
}

# ──────────────────────────────── 프레임워크 분석 함수들 ─────────────────────────
SWOT_FRAMEWORK = {
    "strengths": {
        "title": "강점 (Strengths)",
        "description": "내부적 긍정 요소 - 조직이 가진 경쟁 우위 요소",
        "prompt_keywords": ["강점", "장점", "우위", "역량", "자산", "전문성", "strength", "advantage"]
    },
    "weaknesses": {
        "title": "약점 (Weaknesses)",
        "description": "내부적 부정 요소 - 개선이 필요한 내부 한계",
        "prompt_keywords": ["약점", "단점", "부족", "한계", "취약점", "weakness", "limitation", "deficit"]
    },
    "opportunities": {
        "title": "기회 (Opportunities)",
        "description": "외부적 긍정 요소 - 활용 가능한 외부 환경 변화",
        "prompt_keywords": ["기회", "가능성", "트렌드", "변화", "성장", "opportunity", "trend", "potential"]
    },
    "threats": {
        "title": "위협 (Threats)",
        "description": "외부적 부정 요소 - 대응이 필요한 외부 위험 요소",
        "prompt_keywords": ["위협", "리스크", "경쟁", "위험", "장벽", "threat", "risk", "competition", "barrier"]
    }
}

PORTER_FRAMEWORK = {
    "rivalry": {
        "title": "기존 경쟁자 간의 경쟁",
        "description": "동일 산업 내 경쟁 강도 분석",
        "prompt_keywords": ["경쟁", "경쟁사", "시장점유율", "가격경쟁", "competition", "rival", "market share"]
    },
    "new_entrants": {
        "title": "신규 진입자의 위협",
        "description": "새로운 기업의 시장 진입 난이도 분석",
        "prompt_keywords": ["진입장벽", "신규", "스타트업", "entry barrier", "newcomer", "startup"]
    },
    "substitutes": {
        "title": "대체재의 위협",
        "description": "대체 가능한 제품/서비스의 위협 분석",
        "prompt_keywords": ["대체재", "대안", "substitute", "alternative", "replacement"]
    },
    "buyer_power": {
        "title": "구매자의 교섭력",
        "description": "고객의 가격 협상력 분석",
        "prompt_keywords": ["고객", "구매자", "가격민감도", "협상력", "customer", "buyer power"]
    },
    "supplier_power": {
        "title": "공급자의 교섭력",
        "description": "공급업체의 가격/조건 협상력 분석",
        "prompt_keywords": ["공급자", "벤더", "원재료", "supplier", "vendor", "raw material"]
    }
}

BCG_FRAMEWORK = {
    "stars": {
        "title": "스타 (Stars)",
        "description": "높은 성장률, 높은 시장점유율 - 추가 투자 필요",
        "prompt_keywords": ["성장", "점유율", "중점", "투자", "star", "growth", "investment"]
    },
    "cash_cows": {
        "title": "현금젖소 (Cash Cows)",
        "description": "낮은 성장률, 높은 시장점유율 - 현금흐름 창출",
        "prompt_keywords": ["안정", "수익", "현금", "전통", "cash cow", "profit", "mature"]
    },
    "question_marks": {
        "title": "물음표 (Question Marks)",
        "description": "높은 성장률, 낮은 시장점유율 - 선택적 투자/철수",
        "prompt_keywords": ["가능성", "위험", "불확실", "잠재", "question mark", "uncertain", "potential"]
    },
    "dogs": {
        "title": "개 (Dogs)",
        "description": "낮은 성장률, 낮은 시장점유율 - 철수 고려",
        "prompt_keywords": ["회수", "철수", "저성장", "비효율", "dog", "divest", "low growth"]
    }
}

BUSINESS_FRAMEWORKS = {
    "sunzi": "손자병법 36계",
    "swot": "SWOT 분석",
    "porter": "Porter의 5 Forces",
    "bcg": "BCG 매트릭스"
}

@dataclass
class Category:
    """통일된 카테고리 및 항목 구조"""
    name_ko: str
    name_en: str
    tags: list[str]
    items: list[str]

def analyze_with_swot(prompt: str) -> dict:
    prompt_lower = prompt.lower()
    results = {}
    for category, info in SWOT_FRAMEWORK.items():
        score = sum(1 for keyword in info["prompt_keywords"] if keyword.lower() in prompt_lower)
        keywords = []
        for keyword in info["prompt_keywords"]:
            if keyword.lower() in prompt_lower:
                pattern = f".{{0,15}}{keyword}.{{0,15}}"
                matches = re.findall(pattern, prompt_lower, re.IGNORECASE)
                for match in matches[:2]:
                    keywords.append(match.strip())
        results[category] = {
            "title": info["title"],
            "description": info["description"],
            "score": score,
            "keywords": keywords[:5]
        }
    return results

def analyze_with_porter(prompt: str) -> dict:
    prompt_lower = prompt.lower()
    results = {}
    for category, info in PORTER_FRAMEWORK.items():
        score = sum(1 for keyword in info["prompt_keywords"] if keyword.lower() in prompt_lower)
        keywords = []
        for keyword in info["prompt_keywords"]:
            if keyword.lower() in prompt_lower:
                pattern = f".{{0,15}}{keyword}.{{0,15}}"
                matches = re.findall(pattern, prompt_lower, re.IGNORECASE)
                for match in matches[:2]:
                    keywords.append(match.strip())
        results[category] = {
            "title": info["title"],
            "description": info["description"],
            "score": score,
            "keywords": keywords[:5]
        }
    return results

def analyze_with_bcg(prompt: str) -> dict:
    prompt_lower = prompt.lower()
    results = {}
    for category, info in BCG_FRAMEWORK.items():
        score = sum(1 for keyword in info["prompt_keywords"] if keyword.lower() in prompt_lower)
        keywords = []
        for keyword in info["prompt_keywords"]:
            if keyword.lower() in prompt_lower:
                pattern = f".{{0,15}}{keyword}.{{0,15}}"
                matches = re.findall(pattern, prompt_lower, re.IGNORECASE)
                for match in matches[:2]:
                    keywords.append(match.strip())
        results[category] = {
            "title": info["title"],
            "description": info["description"],
            "score": score,
            "keywords": keywords[:5]
        }
    return results

def format_business_framework_analysis(framework_type: str, analysis_result: dict) -> str:
    if not analysis_result:
        return ""
    titles = {
        'swot': '# SWOT 분석 결과',
        'porter': '# Porter의 5 Forces 분석 결과',
        'bcg': '# BCG 매트릭스 분석 결과'
    }
    md = f"{titles.get(framework_type, '# 경영 프레임워크 분석')}\n\n"
    md += "각 요소별 텍스트 분석 점수와 관련 키워드입니다.\n\n"
    for category, info in analysis_result.items():
        md += f"## {info['title']}\n\n"
        md += f"{info['description']}\n\n"
        md += f"**관련성 점수**: {info['score']}\n\n"
        if info['keywords']:
            md += "**관련 키워드 및 컨텍스트**:\n"
            for keyword in info['keywords']:
                md += f"- *{keyword}*\n"
            md += "\n"
        else:
            md += "관련 키워드가 발견되지 않았습니다.\n\n"
    return md

# ──────────────────────────────── 마크다운 → HTML 변환 ─────────────────────────
def md_to_html(md_text: str, title: str = "Output") -> str:
    html_content = markdown.markdown(
        md_text,
        extensions=['tables', 'fenced_code', 'codehilite']
    )
    return f"""<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>{title}</title>
    <style>
        body {{
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }}
        h1, h2, h3, h4, h5, h6 {{
            margin-top: 24px;
            margin-bottom: 16px;
            font-weight: 600;
            line-height: 1.25;
        }}
        h1 {{ font-size: 2em; color: #0366d6; }}
        h2 {{ font-size: 1.5em; color: #0366d6; border-bottom: 1px solid #eaecef; padding-bottom: .3em; }}
        h3 {{ font-size: 1.25em; color: #0366d6; }}
        p, ul, ol {{ margin-bottom: 16px; }}
        a {{ color: #0366d6; text-decoration: none; }}
        a:hover {{ text-decoration: underline; }}
        code {{
            font-family: SFMono-Regular, Consolas, "Liberation Mono", Menlo, monospace;
            background-color: rgba(27, 31, 35, 0.05);
            border-radius: 3px;
            font-size: 85%;
            padding: 0.2em 0.4em;
        }}
        pre {{
            background-color: #f6f8fa;
            border-radius: 3px;
            font-size: 85%;
            line-height: 1.45;
            overflow: auto;
            padding: 16px;
        }}
        pre code {{
            background-color: transparent;
            padding: 0;
        }}
        blockquote {{
            border-left: 4px solid #dfe2e5;
            color: #6a737d;
            margin: 0;
            padding: 0 1em;
        }}
        table {{
            border-collapse: collapse;
            width: 100%;
            margin-bottom: 16px;
        }}
        table th, table td {{
            border: 1px solid #dfe2e5;
            padding: 6px 13px;
        }}
        table th {{
            background-color: #f6f8fa;
            font-weight: 600;
        }}
        img {{
            max-width: 100%;
            height: auto;
        }}
        hr {{
            border: 0;
            height: 1px;
            background-color: #dfe2e5;
            margin: 24px 0;
        }}
    </style>
</head>
<body>
    {html_content}
    <hr>
    <footer>
        <p><small>Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} |
        Created by <a href="https://discord.gg/openfreeai" target="_blank">VIDraft</a>
        </small></p>
    </footer>
</body>
</html>
"""

# ──────────────────────────────── 업로드 파일 처리 함수 ─────────────────────
def process_text_file(uploaded_file):
    try:
        content = uploaded_file.read().decode('utf-8')
        return f"""# 업로드된 텍스트 파일: {uploaded_file.name}

{content}
"""
    except Exception as e:
        logging.error(f"텍스트 파일 처리 오류: {str(e)}")
        return f"**Error processing {uploaded_file.name}**: {str(e)}"

def process_csv_file(uploaded_file):
    try:
        df = pd.read_csv(uploaded_file)
        return f"""# 업로드된 CSV 파일: {uploaded_file.name}

## 기본 정보
- 행 수: {df.shape[0]}
- 열 수: {df.shape[1]}
- 열 이름: {', '.join(df.columns.tolist())}

## 첫 5행 데이터 미리보기
{df.head(5).to_markdown(index=False)}

## 기본 통계
{df.describe().to_markdown()}
"""
    except Exception as e:
        logging.error(f"CSV 파일 처리 오류: {str(e)}")
        return f"**Error processing {uploaded_file.name}**: {str(e)}"

def process_pdf_file(uploaded_file):
    try:
        file_bytes = uploaded_file.read()
        pdf_file   = io.BytesIO(file_bytes)
        reader     = PyPDF2.PdfReader(pdf_file, strict=False)

        pages_preview = []
        for page_num in range(min(5, len(reader.pages))):
            page = reader.pages[page_num]
            pages_preview.append(f"--- Page {page_num+1} ---\n{page.extract_text()}")

        preview_text = "\n\n".join(pages_preview)
        return f"""# 업로드된 PDF 파일: {uploaded_file.name}

## 기본 정보
- 총 페이지 수: {len(reader.pages)}

## 처음 5개 페이지 내용 미리보기
{preview_text}
"""
    except Exception as e:
        logging.error(f"PDF 파일 처리 오류: {str(e)}")
        return f"**Error processing {uploaded_file.name}**: {str(e)}"

def process_uploaded_files(uploaded_files):
    """Process all uploaded files and return their content as markdown."""
    if not uploaded_files:
        return ""
    file_contents = []
    for file in uploaded_files:
        try:
            ext = file.name.split('.')[-1].lower()
            if ext == 'txt':
                file_contents.append(process_text_file(file))
                file.seek(0)
            elif ext == 'csv':
                file_contents.append(process_csv_file(file))
                file.seek(0)
            elif ext == 'pdf':
                file_contents.append(process_pdf_file(file))
                file.seek(0)
            else:
                file_contents.append(
                    f"# Unsupported file: {file.name}\n\nThis file type is not supported for processing."
                )
        except Exception as e:
            logging.error(f"파일 처리 오류 {file.name}: {str(e)}")
            file_contents.append(f"# Error processing file: {file.name}\n\n{str(e)}")

    return "\n\n# 사용자 업로드 파일 분석\n\n" + "\n\n---\n\n".join(file_contents)

# ──────────────────────────────── 이미지 생성 함수 ──────────────────────
def generate_image(prompt: str):
    if not prompt:
        return None, None
    try:
        clean_prompt = prompt.strip("\"'").strip()
        if len(clean_prompt) < 3:
            return None, None
        logging.info(f"Sending image generation request with prompt: {clean_prompt}")

        res = Client(IMAGE_API_URL).predict(
            prompt=clean_prompt,
            width=768,
            height=768,
            guidance=3.5,
            inference_steps=30,
            seed=3,
            do_img2img=False,
            init_image=None,
            image2image_strength=0.8,
            resize_img=True,
            api_name="/generate_image"
        )
        if res and len(res) >= 2 and res[0]:
            logging.info("Successfully received image data")
            return res[0], clean_prompt
        else:
            logging.warning(f"Invalid response format from image API: {res}")
            return None, None
    except Exception as e:
        logging.error(f"Image generation error: {str(e)}", exc_info=True)
        return None, None

# ──────────────────────────────── Kaggle API 관련 ───────────────────────
@st.cache_resource
def check_kaggle_availability():
    if not KAGGLE_API_KEY:
        logging.warning("Kaggle API를 사용할 수 없습니다. (KAGGLE_KEY가 비어 있음)")
        return False
    return True

def extract_kaggle_search_keywords(prompt, top=3):
    clean_text = re.sub(r'[^\w\s]', ' ', prompt.lower())
    stop_words = {
        'the', 'a', 'an', 'in', 'on', 'at', 'of', 'for', 'to', 'by',
        '와', '과', '은', '는', '이', '가', '을', '를', '에', '에서', '으로'
    }
    words = [word for word in clean_text.split() if word not in stop_words and len(word) > 1]
    word_freq = Counter(words)
    top_words = [word for word, _ in word_freq.most_common(top)]
    if not top_words and words:
        top_words = words[:min(top, len(words))]
    return " ".join(top_words)

def search_kaggle_datasets(query: str, top: int = 5) -> list[dict]:
    if not query:
        return []
    q_tokens = set(re.findall(r'[a-zA-Z가-힣]{2,}', query.lower()))
    scored = []
    for ds in KAGGLE_DATASETS.values():
        tokens = set(t.lower() for t in ds["keywords"])
        score  = len(q_tokens & tokens)
        title_hit = any(tok in ds["title"].lower() for tok in q_tokens)
        sub_hit   = any(tok in ds["subtitle"].lower() for tok in q_tokens)
        if title_hit:
            score += 2
        if sub_hit:
            score += 1
        if score > 0:
            scored.append((score, ds))
    scored.sort(key=lambda x: (-x[0], x[1]["ref"]))
    return [ds for _, ds in scored[:top]]

@st.cache_data
def download_and_analyze_dataset(dataset_ref: str, max_rows: int = 1000):
    if not (os.getenv("KAGGLE_USERNAME") and os.getenv("KAGGLE_KEY")):
        return "Kaggle API 인증정보가 없습니다."
    api = KaggleApi()
    api.authenticate()
    tmpdir = tempfile.mkdtemp()
    try:
        api.dataset_download_files(dataset_ref, path=tmpdir, unzip=True)
    except Exception as e:
        logging.error(f"Dataset download failed ({dataset_ref}): {e}")
        shutil.rmtree(tmpdir)
        return f"데이터셋 다운로드 오류: {e}"

    csv_files = glob.glob(f"{tmpdir}/**/*.csv", recursive=True)
    if not csv_files:
        shutil.rmtree(tmpdir)
        return "CSV 파일을 찾을 수 없습니다."

    try:
        df = pd.read_csv(csv_files[0], nrows=max_rows)
        analysis = {
            "shape": df.shape,
            "columns": df.columns.tolist(),
            "head": df.head().to_dict("records"),
            "describe": df.describe().to_dict(),
            "missing_values": df.isnull().sum().to_dict()
        }
    except Exception as e:
        analysis = f"CSV 파싱 오류: {e}"

    shutil.rmtree(tmpdir)
    return analysis

def format_kaggle_analysis_markdown_multi(analyses: list[dict]) -> str:
    """
    여러 Kaggle 데이터셋(최대 3개) 메타‧분석 결과를 한꺼번에 마크다운으로 반환
    analyses = [ {"meta": {...}, "analysis": {... or str}}, ... ]
    """
    if not analyses:
        return "# Kaggle 데이터셋\n\n관련 데이터셋을 찾을 수 없습니다.\n\n"
    md = "# Kaggle 데이터셋 분석 결과\n\n"
    md += "다음 데이터셋을 검토하여 아이디어 형성에 참고하세요.\n\n"
    for i, item in enumerate(analyses, 1):
        ds  = item["meta"]
        ana = item["analysis"]
        md += f"## {i}. {ds['title']}\n\n"
        md += f"{ds['subtitle']}\n\n"
        md += f"- **참조** : {ds['ref']}\n"
        md += f"- **URL** : [{ds['url']}]({ds['url']})\n\n"
        if isinstance(ana, dict):
            md += f"**행 × 열** : {ana['shape'][0]} × {ana['shape'][1]}\n\n"
            md += "<details><summary>미리보기 & 통계 (펼치기)</summary>\n\n"
            try:
                md += pd.DataFrame(ana["head"]).to_markdown(index=False) + "\n\n"
            except:
                pass
            try:
                md += pd.DataFrame(ana["describe"]).to_markdown() + "\n\n"
            except:
                pass
            md += "</details>\n\n"
        else:
            md += f"{ana}\n\n"
        md += "---\n\n"
    return md

# ──────────────────────────────── OpenAI Client ──────────────────────────
@st.cache_resource
def get_openai_client():
    if not OPENAI_API_KEY:
        raise RuntimeError("⚠️ OPENAI_API_KEY 환경 변수가 설정되지 않았습니다.")
    return OpenAI(
        api_key=OPENAI_API_KEY,
        timeout=60.0,
        max_retries=3
    )

# ──────────────────────────────── 의사결정 목적/제약 식별 (이제 디자인/발명 목적) ─────────────────────
def identify_decision_purpose(prompt: str) -> dict:
    """
    디자인/발명과 관련된 주요 목적이나 제약을 대략적으로 식별.
    (기존의 의사결정 목적/제약 식별 로직을 재활용하되,
     design/invention 관련 키워드도 추가로 고려할 수 있음.)
    """
    purpose_patterns = {
        'cost_reduction': [r'비용(\s*절감)?', r'예산', r'효율', r'저렴', r'경제', r'cost', r'saving', r'budget'],
        'innovation': [r'혁신', r'새로운', r'창의', r'개발', r'발명', r'innovation', r'creative', r'develop'],
        'risk_management': [r'위험', r'리스크', r'안전', r'예방', r'대비', r'risk', r'safety', r'prevent'],
        'growth': [r'성장', r'확장', r'증가', r'확대', r'매출', r'growth', r'expand', r'increase', r'scale'],
        'customer': [r'고객', r'사용자', r'만족', r'경험', r'서비스', r'customer', r'user', r'experience']
    }
    constraint_patterns = {
        'time': [r'시간', r'빠르게', r'긴급', r'마감', r'기한', r'time', r'deadline', r'urgent'],
        'budget': [r'저예산', r'자금', r'투자', r'재정', r'budget', r'finance', r'fund', r'investment'],
        'resources': [r'자원', r'인력', r'장비', r'제한', r'resource', r'staff', r'equipment', r'limited'],
        'regulation': [r'규제', r'법률', r'규정', r'준수', r'법적', r'regulation', r'legal', r'compliance']
    }
    purpose_scores = {}
    for purpose, patterns in purpose_patterns.items():
        score = sum(1 for pattern in patterns if re.search(pattern, prompt, re.IGNORECASE))
        if score > 0:
            purpose_scores[purpose] = score
    constraint_scores = {}
    for constraint, patterns in constraint_patterns.items():
        score = sum(1 for pattern in patterns if re.search(pattern, prompt, re.IGNORECASE))
        if score > 0:
            constraint_scores[constraint] = score
    main_purposes = sorted(purpose_scores.items(), key=lambda x: x[1], reverse=True)[:2]
    main_constraints = sorted(constraint_scores.items(), key=lambda x: x[1], reverse=True)[:2]
    return {
        'purposes': main_purposes,
        'constraints': main_constraints,
        'all_purpose_scores': purpose_scores,
        'all_constraint_scores': constraint_scores
    }

# ──────────────────────────────── 카테고리 유틸 ─────────────────────────
def keywords(text: str, top: int = 8) -> str:
    words = re.findall(r'\b[a-zA-Z가-힣]{2,}\b', text.lower())
    stopwords = {
        'the', 'a', 'an', 'of', 'to', 'in', 'for', 'on', 'by', 'and', 'is', 'are', 'was', 'were',
        'be', 'been', 'being', 'with', 'as', 'at', 'that', 'this', 'these', 'those', 'from', 'not',
        '이', '그', '저', '것', '수', '등', '를', '을', '에', '에서', '그리고', '하는', '있는', '것은',
        '있다', '그것', '또한', '또', '및', '이런', '그런', '무엇', '어떤', '많은', '한', '두', '몇'
    }
    words = [word for word in words if word not in stopwords]
    word_freq = {}
    for word in words:
        word_freq[word] = word_freq.get(word, 0) + 1
    sorted_words = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)
    top_words = [word for word, _ in sorted_words[:top]]
    return ' '.join(top_words)

def compute_relevance_scores(prompt: str, categories: list[Category]) -> dict:
    """
    디자인/발명 관점에서, 입력 프롬프트가 어떤 카테고리의 항목들과 관련성이 높은지 스코어링.
    """
    prompt_lower = prompt.lower()
    prompt_tokens = set(re.findall(r'\b[a-zA-Z가-힣]{2,}\b', prompt_lower))
    purpose_keywords = {
        'cost_reduction': ['비용', '절감', '효율', '예산', 'cost', 'saving', 'budget', 'efficiency'],
        'innovation': ['혁신', '창의', '신규', '개발', 'innovation', 'creative', 'novel', 'development', '발명', '디자인'],
        'risk_management': ['위험', '리스크', '관리', '예방', 'risk', 'management', 'prevention', 'mitigation'],
        'growth': ['성장', '확장', '증가', '규모', 'growth', 'expansion', 'increase', 'scale'],
        'customer': ['사용자', '고객', '만족', '경험', 'user', 'customer', 'satisfaction', 'experience']
    }
    purpose_scores = {}
    for purpose, keywords_ in purpose_keywords.items():
        score = sum(1 for kw in keywords_ if kw in prompt_lower)
        if score > 0:
            purpose_scores[purpose] = score
    main_purpose = max(purpose_scores.items(), key=lambda x: x[1])[0] if purpose_scores else None

    relevance_scores = {}
    for category in categories:
        cat_score = sum(1 for tag in category.tags if tag in prompt_lower) * 0.5
        if category.name_ko in prompt or category.name_en.lower() in prompt_lower:
            cat_score += 1

        # 약간의 목적별 가중치 적용
        if main_purpose:
            purpose_category_weights = {
                'cost_reduction': {
            # 기존 항목
                    '구조적 변화': 1.5, '화학적 변화': 1.3, '비즈니스 아이디어': 1.5,
                    'Structural Change': 1.5, 'Chemical Change': 1.3, 'Business Ideas': 1.5,
        # 추가 항목
                    '에너지 변환 및 관리': 1.6, '데이터 및 정보 변환': 1.4, '지속가능성 및 환경 영향': 1.3,
                    'Energy Conversion and Management': 1.6, 'Data and Information Transformation': 1.4, 
                    'Sustainability and Environmental Impact': 1.3
                },
                'innovation': {
                    # 기존 항목
                    '센서 기능': 1.5, '표면 및 외관 변화': 1.3, '비즈니스 아이디어': 1.5,
                    'Sensor Functions': 1.5, 'Surface and Appearance Change': 1.3, 'Business Ideas': 1.5,
        # 추가 항목
                    '사용자 인터페이스 및 상호작용': 1.6, '데이터 및 정보 변환': 1.4, '인지 및 심리적 변화': 1.3,
                    'User Interface and Interaction': 1.6, 'Data and Information Transformation': 1.4,
                    'Cognitive and Psychological Changes': 1.3
                },
                'risk_management': {
        # 기존 항목
                    '환경 상호작용': 1.5, '시간 관련 변화': 1.3, '비즈니스 아이디어': 1.4,
                    'Environmental Interaction': 1.5, 'Time-Related Change': 1.3, 'Business Ideas': 1.4,
                # 추가 항목
                    '보안 및 프라이버시': 1.7, '지속가능성 및 환경 영향': 1.5, '데이터 및 정보 변환': 1.4,
                    'Security and Privacy': 1.7, 'Sustainability and Environmental Impact': 1.5,
                    'Data and Information Transformation': 1.4
                },
                'growth': {
        # 기존 항목
                    '크기와 형태 변화': 1.4, '비즈니스 아이디어': 1.6, '구조적 변화': 1.3,
                    'Size and Shape Change': 1.4, 'Business Ideas': 1.6, 'Structural Change': 1.3,
        # 추가 항목
                    '사회적 상호작용 및 협업': 1.5, '데이터 및 정보 변환': 1.4, '사용자 인터페이스 및 상호작용': 1.3,
                    'Social Interaction and Collaboration': 1.5, 'Data and Information Transformation': 1.4,
                    'User Interface and Interaction': 1.3
                },
                'customer': {
        # 기존 항목
                    '표면 및 외관 변화': 1.5, '센서 기능': 1.4, '빛과 시각 효과': 1.3, '비즈니스 아이디어': 1.4,
                    'Surface and Appearance Change': 1.5, 'Sensor Functions': 1.4,
                    'Light and Visual Effects': 1.3, 'Business Ideas': 1.4,
                # 추가 항목
                    '사용자 인터페이스 및 상호작용': 1.7, '미학 및 감성 경험': 1.6, '인지 및 심리적 변화': 1.5,
                    '사회적 상호작용 및 협업': 1.4,
                    'User Interface and Interaction': 1.7, 'Aesthetics and Emotional Experience': 1.6,
                    'Cognitive and Psychological Changes': 1.5, 'Social Interaction and Collaboration': 1.4
                }
            }
            if category.name_ko in purpose_category_weights.get(main_purpose, {}):
                cat_score *= purpose_category_weights[main_purpose][category.name_ko]
            elif category.name_en in purpose_category_weights.get(main_purpose, {}):
                cat_score *= purpose_category_weights[main_purpose][category.name_en]

        # 항목별 토큰 매칭
        for item in category.items:
            item_score = cat_score
            item_tokens = set(re.findall(r'\b[a-zA-Z가-힣]{2,}\b', item.lower()))
            matches = item_tokens.intersection(prompt_tokens)
            if matches:
                item_score += len(matches) * 0.3
            if item_score > 0:
                relevance_scores[(category.name_ko, item)] = item_score
    return relevance_scores

def compute_score(weight: int, impact: int, confidence: float) -> float:
    return round(weight * impact * confidence, 2)

def generate_comparison_matrix(
    categories: list[Category],
    relevance_scores: dict = None,
    max_depth: int = 3,
    max_combinations: int = 100,
    relevance_threshold: float = 0.2
) -> list[tuple]:
    """
    여러 카테고리의 요소를 복합적으로 조합한 '아이디어' 후보를 뽑아내는 매트릭스.
    (본래 의사결정 매트릭스였으나, 디자인/발명에 맞게 재활용)
    """
    if relevance_scores is None:
        pool = [(c.name_ko, item) for c in categories for item in c.items]
        basic_combos = []
        for depth in range(2, max_depth + 1):
            for combo in combinations(pool, depth):
                basic_combos.append((1, 1, 1.0, 1.0, combo))
                if len(basic_combos) >= max_combinations:
                    break
        return basic_combos[:max_combinations]

    filtered_pool = [
        (cat, item) for (cat, item), score in relevance_scores.items()
        if score >= relevance_threshold
    ]
    if not filtered_pool:
        pool = [(c.name_ko, i) for c in categories for i in c.items]
        if len(pool) > 200:
            import random
            filtered_pool = random.sample(pool, 200)
        else:
            filtered_pool = pool

    evaluated_combinations = []
    for depth in range(2, max_depth + 1):
        for combo in combinations(filtered_pool, depth):
            if len({item[0] for item in combo}) == depth:
                combo_relevance = sum(relevance_scores.get((item[0], item[1]), 0) for item in combo) / depth
                weight = min(5, max(1, int(combo_relevance * 2)))
                impact = min(5, depth)
                confidence = min(1.0, combo_relevance / 2.5)
                total_score = compute_score(weight, impact, confidence)
                evaluated_combinations.append((weight, impact, confidence, total_score, combo))
    evaluated_combinations.sort(key=lambda x: x[3], reverse=True)
    return evaluated_combinations[:max_combinations]

# ──────────────────────────────── Diverse Matrix Generator ────────────────────
def smart_weight(cat_name, item, relevance, global_cnt, T):
    rare_boost = 1 / (global_cnt.get(item, 0) + 0.5)
    noise = random.random() ** (1 / T)  # T가 클수록 noise가 1에 가까움
    relevance_weight = 1 - (T - 0.1) / 3.0
    return ((relevance * relevance_weight) + 0.1) * rare_boost * noise

def generate_random_comparison_matrix(
    categories: list[Category],
    relevance_scores: dict | None = None,
    k_cat=(8, 12),
    n_item=(6, 10),
    depth_range=(3, 6),
    max_combos=1000,
    seed: int | None = None,
    T: float = 1.3,
):
    """
    다양성 있게 여러 카테고리/항목들을 조합하여 무작위 매트릭스를 생성.
    (디자인/발명 아이디어 확장 시 유용)
    """
    if seed is None:
        seed = random.randrange(2 ** 32)
    random.seed(seed)
    if "GLOBAL_PICK_COUNT" not in st.session_state:
        st.session_state.GLOBAL_PICK_COUNT = {}
    global_cnt = st.session_state.GLOBAL_PICK_COUNT

    k = random.randint(*k_cat)
    sampled_cats = random.sample(categories, k)
    pool = []
    for cat in sampled_cats:
        items   = cat.items
        weights = [
            smart_weight(
                cat.name_ko,
                it,
                relevance_scores.get((cat.name_ko, it), 0.05) if relevance_scores else 0.05,
                global_cnt,
                T
            )
            for it in items
        ]
        n = min(len(items), random.randint(*n_item))
        sampled_items = random.choices(items, weights=weights, k=n)
        for it in sampled_items:
            global_cnt[it] = global_cnt.get(it, 0) + 1
            pool.append((cat.name_ko, it))
    combos = []
    for d in range(depth_range[0], depth_range[1] + 1):
        for combo in combinations(pool, d):
            if len({c for c, _ in combo}) != d:
                continue
            w = sum(relevance_scores.get((c, i), 0.2) if relevance_scores else 1 for c, i in combo) / d
            imp  = d
            conf = 0.5 + random.random() * 0.5
            total = compute_score(w, imp, conf)
            combos.append((w, imp, conf, total, combo))
    combos.sort(key=lambda x: x[3], reverse=True)
    return combos[:max_combos]

# ──────────────────────────────── PHYS_CATEGORIES ────────────────────────
PHYS_CATEGORIES: list[Category] = [
    # 기존 카테고리 유지
    Category(
        name_ko="센서 기능",
        name_en="Sensor Functions",
        tags=["sensor", "detection", "감지"],
        items=physical_transformation_categories["센서 기능"]
    ),
    Category(
        name_ko="크기와 형태 변화",
        name_en="Size and Shape Change",
        tags=["shape", "geometry", "크기"],
        items=physical_transformation_categories["크기와 형태 변화"]
    ),
    Category(
        name_ko="표면 및 외관 변화",
        name_en="Surface and Appearance Change",
        tags=["surface", "appearance", "표면"],
        items=physical_transformation_categories["표면 및 외관 변화"]
    ),
    Category(
        name_ko="물질의 상태 변화",
        name_en="Material State Change",
        tags=["material", "state", "상태"],
        items=physical_transformation_categories["물질의 상태 변화"]
    ),
    Category(
        name_ko="움직임 특성 변화",
        name_en="Movement Characteristics Change",
        tags=["motion", "dynamics", "움직임"],
        items=physical_transformation_categories["움직임 특성 변화"]
    ),
    Category(
        name_ko="구조적 변화",
        name_en="Structural Change",
        tags=["structure", "form", "구조"],
        items=physical_transformation_categories["구조적 변화"]
    ),
    Category(
        name_ko="공간 이동",
        name_en="Spatial Movement",
        tags=["movement", "space", "이동"],
        items=physical_transformation_categories["공간 이동"]
    ),
    Category(
        name_ko="시간 관련 변화",
        name_en="Time-Related Change",
        tags=["time", "aging", "시간"],
        items=physical_transformation_categories["시간 관련 변화"]
    ),
    Category(
        name_ko="빛과 시각 효과",
        name_en="Light and Visual Effects",
        tags=["light", "visual", "빛"],
        items=physical_transformation_categories["빛과 시각 효과"]
    ),
    Category(
        name_ko="소리와 진동 효과",
        name_en="Sound and Vibration Effects",
        tags=["sound", "vibration", "소리"],
        items=physical_transformation_categories["소리와 진동 효과"]
    ),
    Category(
        name_ko="열 관련 변화",
        name_en="Thermal Changes",
        tags=["heat", "thermal", "온도"],
        items=physical_transformation_categories["열 관련 변화"]
    ),
    Category(
        name_ko="전기 및 자기 변화",
        name_en="Electrical and Magnetic Changes",
        tags=["electric", "magnetic", "전기"],
        items=physical_transformation_categories["전기 및 자기 변화"]
    ),
    Category(
        name_ko="화학적 변화",
        name_en="Chemical Change",
        tags=["chemical", "reaction", "화학"],
        items=physical_transformation_categories["화학적 변화"]
    ),
    Category(
        name_ko="생물학적 변화",
        name_en="Biological Change",
        tags=["bio", "living", "생물"],
        items=physical_transformation_categories["생물학적 변화"]
    ),
    Category(
        name_ko="환경 상호작용",
        name_en="Environmental Interaction",
        tags=["environment", "interaction", "환경"],
        items=physical_transformation_categories["환경 상호작용"]
    ),
    Category(
        name_ko="비즈니스 아이디어",
        name_en="Business Ideas",
        tags=["business", "idea", "비즈니스"],
        items=physical_transformation_categories["비즈니스 아이디어"]
    ),
    
    # 새로 추가된 카테고리
    Category(
        name_ko="사용자 인터페이스 및 상호작용",
        name_en="User Interface and Interaction",
        tags=["interface", "interaction", "인터페이스"],
        items=physical_transformation_categories["사용자 인터페이스 및 상호작용"]
    ),
    Category(
        name_ko="데이터 및 정보 변환",
        name_en="Data and Information Transformation",
        tags=["data", "information", "데이터"],
        items=physical_transformation_categories["데이터 및 정보 변환"]
    ),
    Category(
        name_ko="인지 및 심리적 변화",
        name_en="Cognitive and Psychological Changes",
        tags=["cognitive", "psychology", "인지"],
        items=physical_transformation_categories["인지 및 심리적 변화"]
    ),
    Category(
        name_ko="에너지 변환 및 관리",
        name_en="Energy Conversion and Management",
        tags=["energy", "power", "에너지"],
        items=physical_transformation_categories["에너지 변환 및 관리"]
    ),
    Category(
        name_ko="지속가능성 및 환경 영향",
        name_en="Sustainability and Environmental Impact",
        tags=["sustainability", "eco", "지속가능"],
        items=physical_transformation_categories["지속가능성 및 환경 영향"]
    ),
    Category(
        name_ko="보안 및 프라이버시",
        name_en="Security and Privacy",
        tags=["security", "privacy", "보안"],
        items=physical_transformation_categories["보안 및 프라이버시"]
    ),
    Category(
        name_ko="사회적 상호작용 및 협업",
        name_en="Social Interaction and Collaboration",
        tags=["social", "collaboration", "협업"],
        items=physical_transformation_categories["사회적 상호작용 및 협업"]
    ),
    Category(
        name_ko="미학 및 감성 경험",
        name_en="Aesthetics and Emotional Experience",
        tags=["aesthetics", "emotion", "감성"],
        items=physical_transformation_categories["미학 및 감성 경험"]
    )
]
# ──────────────────────────────── (중간 부분 생략 없이) ──────────────────────────

def get_idea_system_prompt(selected_category: str | None = None,
                           selected_frameworks: list | None = None) -> str:
    """
    디자인/발명 목적을 위해 더욱 강화된 시스템 프롬프트.
    - 사용자 요청: "가장 우수한 10가지 아이디어"를 상세 설명
    - 결과 출력에 '가장 우수한 10가지 아이디어'에 포함되지 않은 '부가 아이디어' 30가지 리스트(한줄씩)도 설명
    - 결과 출력 시, 이미지 생성 자동화
    - Kaggle + 웹 검색 출처 제시
    """
    cat_clause = (
        f'\n**추가 지침**: 선택된 카테고리 "{selected_category}"를 특별히 우선하여 고려하세요.\n'
    ) if selected_category else ""
    if not selected_frameworks:
        selected_frameworks = []
    framework_instruction   = "\n\n### (선택된 기타 분석 프레임워크)\n"
    for fw in selected_frameworks:
        if fw == "sunzi":
            framework_instruction += "- 손자병법 36계\n"
        elif fw == "swot":
            framework_instruction += "- SWOT 분석\n"
        elif fw == "porter":
            framework_instruction += "- Porter의 5 Forces\n"
        elif fw == "bcg":
            framework_instruction += "- BCG 매트릭스\n"
    # 핵심: "가장 우수한 10가지 아이디어를 아주 상세하게" + "각 아이디어별 이미지 프롬프트" + "출처 제시"
    base_prompt = f"""
당신은 창의적 디자인/발명 전문가 AI입니다.
사용자가 입력한 주제를 분석하여,
**"가장 우수한 5가지 디자인/발명 아이디어"**를 도출하시오.
각 아이디어는 다음 요구를 충족해야 합니다:
1) **아주 상세하게** 설명하여, 독자가 머릿속에 이미지를 그릴 수 있을 정도로 구체적으로 서술  
2) **이미지 프롬프트**도 함께 제시하여, 자동 이미지 생성이 되도록 하라  
   - 예: `### 이미지 프롬프트\\n한 줄 영문 문구`  
3) **Kaggle 데이터셋**, **웹 검색**을 활용한 통찰(또는 참조)이 있으면 반드시 결과에 언급  
4) 최종 출력의 마지막에 **"출처"** 섹션을 만들고,  
   - 웹 검색(Brave)에서 참조한 URL 3~5개  
   - Kaggle 데이터셋 이름/URL(있다면)  
   - 그 밖의 참고 자료
5) **부가 아이디어** 5가지에 포함되지 않은 다음 순서 10개를 자세하게 작성하여 긴 한줄로 각 라인별로 설명/출력   
   - 예: `#### 부가 아이디어 X:\\n한 줄 한글 문구`  
   
{framework_instruction}

## 아이디어 평가 기준
아이디어 선정 시 다음 기준으로 평가하고 점수화하여 순위를 매기십시오:
1. **혁신성** (30%): 기존 솔루션과의 차별성, 독창성, 기술적 진보성
2. **실현 가능성** (25%): 기술적, 경제적 실현 가능성, 구현 난이도
3. **시장 잠재력** (20%): 타겟 시장 규모, 성장 가능성, 수익성, ROI
4. **사회적 영향력** (15%): 사회, 환경적 문제 해결 기여도, 삶의 질 향상 정도
5. **확장성** (10%): 다양한 상황/시장으로 확장 가능성, 융합 가능성

출력은 반드시 **한국어**로 하며, 아래 구조를 준수하십시오:
1. **주제 요약** (사용자 질문 요약 및 분석 접근 방식 - 300자 이내)
2. **Top 5 아이디어 개요** (5개 아이디어 요약 및 선정 이유 간략히 - 400단어 이내)
3. **Top 5 아이디어 상세**
   - 각 아이디어는 다음 체계적인 구조로 전개하십시오:
     - ### 아이디어 X: [아이디어명] (종합 점수: x.x/10)
     - #### 핵심 개념
       * 아이디어의 핵심 원리와 작동 메커니즘을 400자 이상 상세히 설명
       * 해결하고자 하는 구체적인 문제와 그 사회적/경제적 중요성
       * 기존 솔루션 대비 혁신적인 차별점 3가지 이상 명확히 제시
       * 핵심 가치 제안(Value Proposition) 명확히 정의
     - #### 상세 설계 및 기술적 구현
       * 구체적인 구성요소, 디자인 특성, 제작 방법 등 기술적 세부사항 설명
       * 치수, 재료, 작동 원리 등 실현 가능한 상세 정보 제공
       * 핵심 기술적 도전과제 3가지 이상과 각각에 대한 해결 방안
       * 특허 가능성이 있는 고유 기술 요소 설명
       * 필요한 핵심 기술 및 리소스 목록
     - #### 사용 시나리오 및 사용자 경험
       * 최소 3가지 이상의 실제 사용 상황 시나리오를 스토리텔링 방식으로 설명
       * 주요 사용자 페르소나 2개 이상 구체적으로 정의
       * 사용자 여정(User Journey)을 단계별로 시각적으로 묘사
       * 사용자 경험의 핵심 가치와 감성적 연결점 설명
       * 잠재적 사용자 피드백 예측 및 대응 방안
     - #### 시장 분석 및 비즈니스 모델
       * 타겟 시장 규모(TAM, SAM, SOM)와 성장률 추정
       * 주요 고객 세그먼트 분석 및 구체적인 니즈 연결
       * 경쟁 제품/서비스 5개 이상과의 상세 비교표 및 경쟁 우위점
       * 수익 모델 및 수익 흐름 상세 설명
       * 시장 진입 전략 및 초기 마케팅 접근법
       * 확장 가능한 비즈니스 모델 캔버스 요소 분석
     - #### 구현 로드맵 및 자원 계획
       * 실현을 위한 단계별 계획(개념증명, 프로토타입, 테스트, 생산 등)
       * 6개월, 1년, 3년 단위의 구체적인 개발 일정 및 주요 마일스톤
       * 필요한 핵심 인재/팀 구성 및 역할
       * 초기 투자 예상액 및 자금조달 전략
       * 주요 파트너십 및 외부 협력 필요사항
       * 품질 관리 및 성과 측정 지표
     - #### SWOT 분석
       * 강점(Strengths): 이 아이디어만의 독특한 강점 5가지 이상과 그 이유
       * 약점(Weaknesses): 잠재적 약점 3가지 이상 및 이를 극복하기 위한 구체적인 방안
       * 기회(Opportunities): 외부 환경(기술, 시장, 정책 등)에서 발생하는 기회 요소 4가지 이상
       * 위협(Threats): 성공을 방해할 수 있는 외부 요인 3가지 이상과 각각에 대한 구체적 대응책
      각 상세히 작성
   - 각 아이디어는 이 구조로 10개 아이디어 모두 동일하게 작성하라:
   
4. **부가적 통찰** (선택된 프레임워크 분석 결과)
5. **부가 아이디어** (TOP 5에 해당하지 않는 10가지 아이디어, 각각 한 줄로 간결하게 설명하되 해당 아이디어의 핵심 가치와 혁신점을 포함)
   - 예: `#### 부가 아이디어 X:\\n 한 줄로 자세한 한글 문구`  
6. **출처** (웹검색 링크, Kaggle 데이터셋 등)
{cat_clause}
아무리 길어도 이 요구사항을 준수하고, **오직 최종 완성된 답변**만 출력하십시오.
(내부 사고 과정은 감춥니다.)
"""
    return base_prompt.strip()

# ──────────────────────────────── 나머지 코드 (웹검색, kaggle, 이미지 생성 등) ──────────────────────────

@st.cache_data(ttl=3600)
def brave_search(query: str, count: int = 20):
    if not BRAVE_KEY:
        raise RuntimeError("⚠️ SERPHOUSE_API_KEY (Brave API Key) 환경 변수가 비어있습니다.")
    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:
                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}")
            time.sleep(1)
    return []

def mock_results(query: str) -> str:
    ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    return (
        f"# Fallback Search Content (Generated: {ts})\n\n"
        f"The web search API request failed. Please generate the invention/design ideas based on '{query}' using general knowledge.\n\n"
        f"You may consider aspects such as:\n\n"
        f"- Basic concept or definition of {query}\n"
        f"- Potential expansions or improvements\n"
        f"- Category-based transformations\n\n"
        f"Note: This is fallback text, not real-time data.\n\n"
    )

def do_web_search(query: str) -> str:
    try:
        arts = brave_search(query, 20)
        if not arts:
            logging.warning("No search results from Brave. Using fallback.")
            return mock_results(query)
        hdr = "# Web Search Results\nUse the information below to spark new design/invention insights.\n\n"
        body = "\n".join(
            f"### Result {a['index']}: {a['title']}\n\n{a['snippet']}\n\n**Source**: [{a['displayed_link']}]({a['link']})\n\n---\n"
            for a in arts
        )
        return hdr + body
    except Exception as e:
        logging.error(f"Web search process failed: {str(e)}")
        return mock_results(query)

# ──────────────────────────────── (신규) 디자인/발명 아이디어 처리 함수 ─────────────────
def process_invention_ideas(keyword: str):
    """
    (이전에는 별도 버튼/프롬프트가 있었으나,
     이제 메인 프롬프트로 일원화되어 사실상 사용되지 않을 수도 있음.)
    """
    if not keyword.strip():
        st.warning("키워드를 입력하세요.")
        return

    st.info(f"디자인/발명 아이디어 생성 중... (키워드: **{keyword}**)")

    # 모든 카테고리와 항목을 리스트업
    categories_text = []
    for cat_name, items in physical_transformation_categories.items():
        joined_items = ", ".join(items)
        categories_text.append(f"- {cat_name}: {joined_items}")
    categories_joined = "\n".join(categories_text)

    prompt = f"""
당신은 디자인/발명 전문가입니다.
키워드: "{keyword}"
아래는 카테고리+항목 목록입니다.
{categories_joined}

이 키워드를 각 항목과 결합한 아이디어를 생각하고,
타당한 것과 배제할 것을 분류하여 마크다운으로 출력하세요.
"""
    try:
        client = get_openai_client()
        with st.spinner("Generating invention ideas..."):
            response = client.chat.completions.create(
                model="gpt-4.1-mini",
                messages=[{"role": "user", "content": prompt}],
                temperature=0.9,
                max_tokens=2500,
            )
        result_text = response.choices[0].message.content
        st.markdown(result_text)
    except Exception as e:
        st.error(f"오류 발생: {e}")

# ──────────────────────────────── Streamlit 메인 앱 ──────────────────────
def idea_generator_app():
    st.title("Ilúvatar(일루바타르) : Creative Design & Invention AI")
    st.caption("이 시스템은 빅데이터를 자율적으로 수집·분석하여, 복합적인 디자인/발명 아이디어를 제안합니다.")

    default_vals = {
        "ai_model": "gpt-4.1-mini",
        "messages": [],
        "auto_save": True,
        "generate_image": True,
        "web_search_enabled": True,
        "kaggle_enabled": True,
        "selected_frameworks": [],
        "GLOBAL_PICK_COUNT": {},
        "_skip_dup_idx": None
    }
    for k, v in default_vals.items():
        if k not in st.session_state:
            st.session_state[k] = v

    sb = st.sidebar
    st.session_state.temp = sb.slider(
        "Diversity temperature", 0.1, 3.0, 1.3, 0.1,
        help="0.1 = 매우 보수적, 3.0 = 매우 창의/무작위"
    )

    sb.title("Settings")
    sb.toggle("Auto Save", key="auto_save")
    sb.toggle("Auto Image Generation", key="generate_image")

    st.session_state.web_search_enabled = sb.toggle(
        "Use Web Search", value=st.session_state.web_search_enabled
    )
    st.session_state.kaggle_enabled = sb.toggle(
        "Use Kaggle Datasets", value=st.session_state.kaggle_enabled
    )

    if st.session_state.web_search_enabled:
        sb.info("✅ Web search results enabled")
    if st.session_state.kaggle_enabled:
        if KAGGLE_KEY:
            sb.info("✅ Kaggle data integration enabled")
        else:
            sb.error("⚠️ KAGGLE_KEY not set.")
            st.session_state.kaggle_enabled = False

    # (디자인/발명용 사이드바 항목은 삭제됨, 메인 prompt에서 처리)

    # 예시 주제
    example_topics = {
        "example1": "'고양이 장난감' 디자인",
        "example2": "재밍 대응 가능한 드론 디자인",
        "example3": "사용자 인터페이스(UI/UX) 혁신을 위한 웨어러블 기기 아이디어"
    }
    sb.subheader("Example Topics")
    c1, c2, c3 = sb.columns(3)
    if c1.button("고양이 장난감", key="ex1"):
        process_example(example_topics["example1"])
    if c2.button("재밍 대응 드론", key="ex2"):
        process_example(example_topics["example2"])
    if c3.button("UI/UX 혁신", key="ex3"):
        process_example(example_topics["example3"])

    # 대화 히스토리 다운로드
    latest_ideas = next(
        (m["content"] for m in reversed(st.session_state.messages)
         if m["role"] == "assistant" and m["content"].strip()),
        None
    )
    if latest_ideas:
        title_match = re.search(r"# (.*?)(\n|$)", latest_ideas)
        title = (title_match.group(1) if title_match else "design_invention").strip()
        sb.subheader("Download Latest Ideas")
        d1, d2 = sb.columns(2)
        d1.download_button("Download as Markdown", latest_ideas,
                           file_name=f"{title}.md", mime="text/markdown")
        d2.download_button("Download as HTML", md_to_html(latest_ideas, title),
                           file_name=f"{title}.html", mime="text/html")

    # 대화 히스토리 로드/저장
    up = sb.file_uploader("Load Conversation (.json)", type=["json"], key="json_uploader")
    if up:
        try:
            st.session_state.messages = json.load(up)
            sb.success("Conversation history loaded successfully")
        except Exception as e:
            sb.error(f"Failed to load: {e}")

    if sb.button("Download Conversation as JSON"):
        sb.download_button(
            "Save JSON",
            data=json.dumps(st.session_state.messages, ensure_ascii=False, indent=2),
            file_name="chat_history.json",
            mime="application/json"
        )

    # 파일 업로드
    st.subheader("File Upload (Optional)")
    uploaded_files = st.file_uploader(
        "Upload reference files (txt, csv, pdf)",
        type=["txt", "csv", "pdf"],
        accept_multiple_files=True,
        key="file_uploader"
    )
    if uploaded_files:
        st.success(f"{len(uploaded_files)} files uploaded.")
        with st.expander("Preview Uploaded Files", expanded=False):
            for idx, file in enumerate(uploaded_files):
                st.write(f"**File Name:** {file.name}")
                ext = file.name.split('.')[-1].lower()
                try:
                    if ext == 'txt':
                        preview = file.read(1000).decode('utf-8', errors='ignore')
                        file.seek(0)
                        st.text_area("Preview", preview + ("..." if len(preview) >= 1000 else ""), height=150)
                    elif ext == 'csv':
                        df = pd.read_csv(file)
                        file.seek(0)
                        st.dataframe(df.head(5))
                    elif ext == 'pdf':
                        reader = PyPDF2.PdfReader(io.BytesIO(file.read()), strict=False)
                        file.seek(0)
                        pg_txt = reader.pages[0].extract_text() if reader.pages else "(No text)"
                        st.text_area("Preview", (pg_txt[:500] + "...") if pg_txt else "(No text)", height=150)
                except Exception as e:
                    st.error(f"Preview failed: {e}")
                if idx < len(uploaded_files) - 1:
                    st.divider()

    # 이미 렌더된 메시지(중복 방지)
    skip_idx = st.session_state.get("_skip_dup_idx")
    for i, m in enumerate(st.session_state.messages):
        if skip_idx is not None and i == skip_idx:
            continue
        with st.chat_message(m["role"]):
            st.markdown(m["content"])
            if "image" in m:
                st.image(m["image"], caption=m.get("image_caption", ""))
    st.session_state["_skip_dup_idx"] = None

    # 메인 채팅 입력
    prompt = st.chat_input("새로운 디자인/발명 아이디어가 필요하신가요? 여기에 상황이나 목표를 작성하세요!")
    if prompt:
        process_input(prompt, uploaded_files)

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

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

def process_input(prompt: str, uploaded_files):
    """
    메인 채팅 입력을 받아 디자인/발명 아이디어를 생성한다.
    스트리밍 실패(RemoteProtocolError 등) 시 backoff 재시도 후
    최종적으로 non-stream 호출로 폴백.
    """
    # ─── 대화 기록 중복 방지 ──────────────────────────────
    if not any(m["role"] == "user" and m["content"] == prompt for m in st.session_state.messages):
        st.session_state.messages.append({"role": "user", "content": prompt})
    with st.chat_message("user"):
        st.markdown(prompt)

    for i in range(len(st.session_state.messages) - 1):
        if (st.session_state.messages[i]["role"] == "user"
            and st.session_state.messages[i]["content"] == prompt
            and st.session_state.messages[i + 1]["role"] == "assistant"):
            return

    # ─── 결과 생성 ───────────────────────────────────────
    with st.chat_message("assistant"):
        status = st.status("Preparing to generate invention ideas…")
        stream_placeholder = st.empty()
        full_response = ""

        try:
            client = get_openai_client()
            status.update(label="Initializing model…")

            selected_cat        = st.session_state.get("category_focus", None)
            selected_frameworks = st.session_state.get("selected_frameworks", [])
            sys_prompt = get_idea_system_prompt(
                selected_category=selected_cat,
                selected_frameworks=selected_frameworks
            )

            def category_context(sel):
                if sel:
                    return json.dumps({sel: physical_transformation_categories[sel]}, ensure_ascii=False)
                return "ALL_CATEGORIES: " + ", ".join(physical_transformation_categories.keys())

            use_web_search = st.session_state.web_search_enabled
            use_kaggle     = st.session_state.kaggle_enabled
            has_uploaded   = bool(uploaded_files)

            search_content = kaggle_content = file_content = mil_content = None

            # ① 웹 검색
            if use_web_search:
                status.update(label="Searching the web…")
                with st.spinner("Searching…"):
                    search_content = do_web_search(keywords(prompt, top=5))

            # ② Kaggle
            if use_kaggle and check_kaggle_availability():
                status.update(label="Kaggle 데이터셋 분석 중…")
                with st.spinner("Searching Kaggle…"):
                    kaggle_kw = extract_kaggle_search_keywords(prompt)
                    try:
                        datasets = search_kaggle_datasets(kaggle_kw)
                    except Exception as e:
                        logging.warning(f"search_kaggle_datasets 오류 무시: {e}")
                        datasets = []
                    analyses = []
                    if datasets:
                        status.update(label="Downloading & analysing datasets…")
                        for ds in datasets:
                            try:
                                ana = download_and_analyze_dataset(ds["ref"])
                            except Exception as e:
                                logging.error(f"Kaggle 분석 오류({ds['ref']}) : {e}")
                                ana = f"데이터셋 분석 오류: {e}"
                            analyses.append({"meta": ds, "analysis": ana})
                    if analyses:
                        kaggle_content = format_kaggle_analysis_markdown_multi(analyses)

            # ③ 파일 업로드
            if has_uploaded:
                status.update(label="Reading uploaded files…")
                with st.spinner("Processing files…"):
                    file_content = process_uploaded_files(uploaded_files)

            # ④ 군사 전술 데이터
            if is_military_query(prompt):
                status.update(label="Searching military tactics dataset…")
                with st.spinner("Loading military insights…"):
                    mil_rows = military_search(prompt)
                if mil_rows:
                    mil_content = "# Military Tactics Dataset Reference\n\n"
                    for i, row in enumerate(mil_rows, 1):
                        mil_content += (
                            f"### Case {i}\n"
                            f"**Scenario:** {row['scenario_description']}\n\n"
                            f"**Attack Reasoning:** {row['attack_reasoning']}\n\n"
                            f"**Defense Reasoning:** {row['defense_reasoning']}\n\n---\n"
                        )

            # ─── 유저 콘텐츠 구성 ──────────────────────────
            user_content = prompt
            for extra in (search_content, kaggle_content, file_content, mil_content):
                if extra:
                    user_content += "\n\n" + extra

            # ─── 내부 분석 ───────────────────────────────
            status.update(label="분석 중…")
            decision_purpose = identify_decision_purpose(prompt)
            relevance_scores = compute_relevance_scores(prompt, PHYS_CATEGORIES)

            status.update(label="카테고리 조합 아이디어 생성 중…")
            T = st.session_state.temp
            k_cat_range  = (4, 8) if T < 1.0 else (6, 10) if T < 2.0 else (8, 12)
            n_item_range = (2, 4) if T < 1.0 else (3, 6) if T < 2.0 else (4, 8)
            depth_range  = (2, 3) if T < 1.0 else (2, 5) if T < 2.0 else (2, 6)
            combos = generate_random_comparison_matrix(
                PHYS_CATEGORIES,
                relevance_scores,
                k_cat=k_cat_range,
                n_item=n_item_range,
                depth_range=depth_range,
                seed=hash(prompt) & 0xFFFFFFFF,
                T=T,
            )

            combos_table = "| 조합 | 가중치 | 영향도 | 신뢰도 | 총점 |\n|------|--------|--------|--------|-----|\n"
            for w, imp, conf, tot, cmb in combos:
                combo_str = " + ".join(f"{c[0]}-{c[1]}" for c in cmb)
                combos_table += f"| {combo_str} | {w} | {imp} | {conf:.1f} | {tot} |\n"

            purpose_info = "\n\n## 디자인/발명 목표 분석\n"
            if decision_purpose['purposes']:
                purpose_info += "### 핵심 목적\n"
                for p, s in decision_purpose['purposes']:
                    purpose_info += f"- **{p}** (관련성: {s})\n"
            if decision_purpose['constraints']:
                purpose_info += "\n### 제약 조건\n"
                for c, s in decision_purpose['constraints']:
                    purpose_info += f"- **{c}** (관련성: {s})\n"

            # ─── 프레임워크 분석 (옵션) ────────────────────
            framework_contents = []
            for fw in selected_frameworks:
                if fw == "swot":
                    framework_contents.append(
                        format_business_framework_analysis("swot", analyze_with_swot(prompt))
                    )
                elif fw == "porter":
                    framework_contents.append(
                        format_business_framework_analysis("porter", analyze_with_porter(prompt))
                    )
                elif fw == "bcg":
                    framework_contents.append(
                        format_business_framework_analysis("bcg", analyze_with_bcg(prompt))
                    )

            if framework_contents:
                user_content += "\n\n## (Optional) 기타 프레임워크 분석\n\n" + "\n\n".join(framework_contents)

            user_content += f"\n\n## 카테고리 매트릭스 분석{purpose_info}\n{combos_table}"

            status.update(label="Generating final design/invention ideas…")

            api_messages = [
                {"role": "system", "content": sys_prompt},
                {"role": "system", "name": "category_db", "content": category_context(selected_cat)},
                {"role": "user",   "content": user_content},
            ]

            # ─── OpenAI Chat 호출 (backoff 재시도) ─────────────────
            @backoff.on_exception(
                (RemoteProtocolError, APITimeoutError, APIError), max_tries=3
            )
            def safe_stream():
                return client.chat.completions.create(
                    model="gpt-4.1-mini",
                    messages=api_messages,
                    temperature=1,
                    max_tokens=MAX_TOKENS,
                    top_p=1,
                    stream=True
                )


            try:
                stream = safe_stream()
                for chunk in stream:
                    if chunk.choices and chunk.choices[0].delta.content:
                        full_response += chunk.choices[0].delta.content
                        stream_placeholder.markdown(full_response + "▌")
            except (RemoteProtocolError, APITimeoutError, APIError) as stream_err:
                logging.warning(f"스트리밍 실패, non-stream 폴백: {stream_err}")
                resp = client.chat.completions.create(
                    model="gpt-4.1-mini",
                    messages=api_messages,
                    temperature=1,
                    max_tokens=MAX_TOKENS,
                    top_p=1,
                    stream=False
                )
                full_response = resp.choices[0].message.content
                stream_placeholder.markdown(full_response)

            status.update(label="Invention ideas created!", state="complete")

            # ─── 이미지 생성 ────────────────────────────────
            img_data = img_caption = None
            if st.session_state.generate_image and full_response:
                match = re.search(r"###\s*이미지\s*프롬프트\s*\n+([^\n]+)", full_response, re.I)
                if not match:
                    match = re.search(r"Image\s+Prompt\s*[:\-]\s*([^\n]+)", full_response, re.I)
                if match:
                    raw_prompt = re.sub(r'[\r\n"\'\\]', " ", match.group(1)).strip()
                    with st.spinner("Generating illustrative image…"):
                        img_data, img_caption = generate_image(raw_prompt)
                    if img_data:
                        st.image(img_data, caption=f"Visualized Concept – {img_caption}")

            # ─── 세션 메시지 저장 ─────────────────────────────
            answer_msg = {"role": "assistant", "content": full_response}
            if img_data:
                answer_msg["image"]         = img_data
                answer_msg["image_caption"] = img_caption
            st.session_state["_skip_dup_idx"] = len(st.session_state.messages)
            st.session_state.messages.append(answer_msg)

            # ─── 다운로드 옵션 ──────────────────────────────
            st.subheader("Download This Output")
            col_md, col_html = st.columns(2)
            col_md.download_button(
                "Markdown",
                data=full_response,
                file_name=f"{prompt[:30]}.md",
                mime="text/markdown"
            )
            col_html.download_button(
                "HTML",
                data=md_to_html(full_response, prompt[:30]),
                file_name=f"{prompt[:30]}.html",
                mime="text/html"
            )

            if st.session_state.auto_save:
                fn = f"chat_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("process_input error", exc_info=True)
            st.error(f"⚠️ 작업 중 오류가 발생했습니다: {e}")
            st.session_state.messages.append(
                {"role": "assistant", "content": f"⚠️ 오류: {e}"}
            )


def main():
    idea_generator_app()

if __name__ == "__main__":
    main()