File size: 56,711 Bytes
5a32b6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
ํ—ˆ๊น…ํŽ˜์ด์Šค ๋ฐฐํฌ์šฉ Agentic AI ๊ธ€๋กœ๋ฒŒ ํŒŒํŠธ๋„ˆ DB ๋ถ„์„ ๋Œ€์‹œ๋ณด๋“œ
โœ… Gmail SMTP ์ด๋ฉ”์ผ ๋ฐœ์†ก
โœ… ํŒŒ์Šคํ…”ํ†ค ์ฐจํŠธ ์ƒ‰์ƒ
โœ… ์ƒํƒœ๊ณ„๋ณ„ ์ตœ์ ํ™”๋œ ๋Œ€์‹œ๋ณด๋“œ
โœ… jeongkee10@gmission.com ์ˆ˜์‹ 
"""

import os
import subprocess
import sys
import datetime
import traceback
import gc
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import ssl
import re

# ํŒจํ‚ค์ง€ ์„ค์น˜ ํ•จ์ˆ˜
def install_packages():
    packages = ['gradio>=4.0.0', 'plotly>=5.0.0', 'pandas>=2.0.0', 'openpyxl>=3.0.0']
    for package in packages:
        try:
            pkg_name = package.split('>=')[0]
            __import__(pkg_name)
        except ImportError:
            print(f"Installing {package}...")
            subprocess.check_call([sys.executable, "-m", "pip", "install", package])

# ํŒจํ‚ค์ง€ ์„ค์น˜ ์‹คํ–‰
try:
    install_packages()
    print("โœ… ํŒจํ‚ค์ง€ ์„ค์น˜ ์™„๋ฃŒ")
except Exception as e:
    print(f"โš ๏ธ ํŒจํ‚ค์ง€ ์„ค์น˜ ์˜ค๋ฅ˜: {e}")

import pandas as pd
import gradio as gr

# Gradio ๋ฒ„์ „ ํ˜ธํ™˜์„ฑ ํ™•์ธ
try:
    gradio_version = gr.__version__
    print(f"โœ… Gradio ๋ฒ„์ „: {gradio_version}")
except:
    print("โš ๏ธ Gradio ๋ฒ„์ „ ํ™•์ธ ๋ถˆ๊ฐ€")

try:
    import plotly.express as px
    import plotly.graph_objects as go
    from plotly.subplots import make_subplots
    PLOTLY_AVAILABLE = True
    print("โœ… Plotly ์‚ฌ์šฉ ๊ฐ€๋Šฅ")
except ImportError:
    print("โš ๏ธ Plotly ์—†์Œ - ์ฐจํŠธ ๊ธฐ๋Šฅ ์ œํ•œ")
    PLOTLY_AVAILABLE = False

from typing import Tuple, List, Dict, Any, Optional

# ==================== ์„ค์ • ๋ฐ ์ƒ‰์ƒ ์ •์˜ ====================

# ํŒŒ์Šคํ…”ํ†ค ์ƒ‰์ƒ ํŒ”๋ ˆํŠธ
PASTEL_COLORS = {
    'primary_palette': ['#FFB3BA', '#FFDFBA', '#FFFFBA', '#BAFFC9', '#BAE1FF', '#E5BAFF', '#FFBAE5'],
    'secondary_palette': ['#FFD6D6', '#FFEBD6', '#FFFFD6', '#D6FFE0', '#D6EBFF', '#E0D6FF', '#FFD6EB'],
    'ecosystem_colors': {
        'Infra': '#FFB3BA',  # ํŒŒ์Šคํ…” ํ•‘ํฌ
        'Foundation Model': '#BAFFC9',  # ํŒŒ์Šคํ…” ๊ทธ๋ฆฐ
        'Platform / Agentic AI Pipeline': '#BAE1FF',  # ํŒŒ์Šคํ…” ๋ธ”๋ฃจ
        'Application': '#FFDFBA',  # ํŒŒ์Šคํ…” ์˜ค๋ Œ์ง€
        '์ „์ฒด': '#E5BAFF'  # ํŒŒ์Šคํ…” ํผํ”Œ
    },
    'importance_colors': {
        5: '#FFB3BA',  # S๊ธ‰ - ํŒŒ์Šคํ…” ํ•‘ํฌ
        4: '#FFDFBA',  # A๊ธ‰ - ํŒŒ์Šคํ…” ์˜ค๋ Œ์ง€
        3: '#BAE1FF',  # B๊ธ‰ - ํŒŒ์Šคํ…” ๋ธ”๋ฃจ
        2: '#BAFFC9',  # C๊ธ‰ - ํŒŒ์Šคํ…” ๊ทธ๋ฆฐ
        1: '#E5E5E5'   # D๊ธ‰ - ํŒŒ์Šคํ…” ๊ทธ๋ ˆ์ด
    }
}

# ์ƒํƒœ๊ณ„ ์นดํ…Œ๊ณ ๋ฆฌ
ECOSYSTEM_CATEGORIES = [
    "์ „์ฒด",
    "Infra",
    "Foundation Model",
    "Platform / Agentic AI Pipeline",
    "Application"
]

# ์ƒํƒœ๊ณ„๋ณ„ ์ตœ์ ํ™”๋œ ์ปฌ๋Ÿผ ๋งคํ•‘
ECOSYSTEM_OPTIMIZED_COLUMNS = {
    'Infra': {
        'primary': ['๊ธฐ์—…๋ช…', '์ค‘์š”๋„', 'HQ_๊ตญ๊ฐ€', '์„ค๋ฆฝ์—ฐ๋„', 'PrimaryLLM', 'LLM_Deployment', '์ฃผ์š”์ œํ’ˆ'],
        'charts': ['์ค‘์š”๋„_๋ถ„ํฌ', '๊ตญ๊ฐ€๋ณ„_๋ถ„ํฌ', '์„ค๋ฆฝ์—ฐ๋„_๋ถ„ํฌ', 'LLM_๋ฐฐํฌ๋ฐฉ์‹'],
        'focus': 'infrastructure and deployment capabilities'
    },
    'Foundation Model': {
        'primary': ['๊ธฐ์—…๋ช…', '์ค‘์š”๋„', 'HQ_๊ตญ๊ฐ€', 'PrimaryLLM', 'OpenSource์—ฌ๋ถ€', 'LLM_Deployment', '์ฐฝ์—…์ž'],
        'charts': ['์ค‘์š”๋„_๋ถ„ํฌ', 'OpenSource_๋ถ„ํฌ', 'LLM_์ข…๋ฅ˜', '๊ตญ๊ฐ€๋ณ„_๋ถ„ํฌ'],
        'focus': 'model development and open-source contributions'
    },
    'Platform / Agentic AI Pipeline': {
        'primary': ['๊ธฐ์—…๋ช…', '์ค‘์š”๋„', 'Application_Domain', 'PrimaryLLM', 'STT_TTS์ง€์›', 'TargetCustomer', 'PricingModel'],
        'charts': ['์ค‘์š”๋„_๋ถ„ํฌ', '์‘์šฉ๋„๋ฉ”์ธ_๋ถ„ํฌ', 'STT_TTS_์ง€์›', 'ํƒ€๊ฒŸ๊ณ ๊ฐ'],
        'focus': 'platform integration and agentic workflows'
    },
    'Application': {
        'primary': ['๊ธฐ์—…๋ช…', '์ค‘์š”๋„', 'Application_Domain', 'TargetCustomer', 'PricingModel', 'KoreaSupport', 'STT_TTS์ง€์›'],
        'charts': ['์ค‘์š”๋„_๋ถ„ํฌ', '์‘์šฉ๋„๋ฉ”์ธ_๋ถ„ํฌ', '๊ฐ€๊ฒฉ์ •์ฑ…', 'ํ•œ๊ตญ์ง€์›'],
        'focus': 'end-user applications and market solutions'
    }
}

# ์ปฌ๋Ÿผ ๋งคํ•‘
EXACT_COLUMN_MAPPING = {
    '๊ธฐ์—…๋ช…': ['๊ธฐ์—…๋ช…', 'CompanyName', 'company', 'name'],
    '์ค‘์š”๋„': ['์ค‘์š”๋„', 'Importance', 'Priority'],
    'Ecosystem_Category': ['Ecosystem Category', 'Ecosystem_Category'],
    'HQ_๊ตญ๊ฐ€': ['HQ_๊ตญ๊ฐ€', 'HQ_Country', 'Country'],
    '์„ค๋ฆฝ์—ฐ๋„': ['์„ค๋ฆฝ์—ฐ๋„', 'FoundedYear', 'Founded'],
    '์ฃผ์š”ํˆฌ์ž์ž': ['์ฃผ์š”ํˆฌ์ž์ž', 'KeyInvestors', 'Investors'],
    '๊ธฐ์—…๊ฐœ์š”': ['๊ธฐ์—…๊ฐœ์š”', 'CompanySummary', 'Summary'],
    '์›น์‚ฌ์ดํŠธ': ['์›น์‚ฌ์ดํŠธ', 'Website', 'WebsiteURL'],
    '๋ฌธ์˜URL': ['๋ฌธ์˜URL', 'ContactURL', 'Contact_URL'],
    '์ด๋ฉ”์ผ': ['์ด๋ฉ”์ผ', 'Email', 'EmailAddress'],
    '์ „ํ™”๋ฒˆํ˜ธ': ['์ „ํ™”๋ฒˆํ˜ธ', 'PhoneNumber', 'phone'],
    'HQ_๋„์‹œ': ['HQ_๋„์‹œ', 'HQ_City', 'City'],
    '์ฐฝ์—…์ž': ['์ฐฝ์—…์ž', 'Founders', 'founder'],
    'Application_Domain': ['Application_Domain', 'Application Domain'],
    'PrimaryLLM': ['PrimaryLLM', 'Primary LLM'],
    'LLM_Deployment': ['LLM_Deployment', 'LLM Deployment'],
    'OpenSource์—ฌ๋ถ€': ['OpenSource์—ฌ๋ถ€', 'OpenSource'],
    '์ฃผ์š”์ œํ’ˆ': ['์ฃผ์š”์ œํ’ˆ', 'KeyProducts', 'Products'],
    'STT_TTS์ง€์›': ['STT_TTS์ง€์›', 'STT_TTS'],
    'TargetCustomer': ['TargetCustomer', 'Target Customer'],
    'PricingModel': ['PricingModel', 'Pricing Model'],
    'KoreaSupport': ['KoreaSupport', 'Korea Support'],
    'PartnershipProgram': ['PartnershipProgram', 'Partnership Program']
}

# ==================== Gmail SMTP ์ด๋ฉ”์ผ ์‹œ์Šคํ…œ ====================

class GmailEmailSystem:
    def __init__(self):
        self.email_history = []
        self.smtp_server = "smtp.gmail.com"
        self.port = 587

        # ํ—ˆ๊น…ํŽ˜์ด์Šค Secrets์—์„œ ์ด๋ฉ”์ผ ์ •๋ณด ๊ฐ€์ ธ์˜ค๊ธฐ
        self.gmail_email = os.getenv("GMAIL_EMAIL", "")
        self.gmail_password = os.getenv("GMAIL_PASSWORD", "")
        self.recipient_email = os.getenv("RECIPIENT_EMAIL", "jeongkee10@gmission.com")

        print(f"๐Ÿ“ง Gmail ์„ค์ •: {self.gmail_email[:5] if self.gmail_email else '๋ฏธ์„ค์ •'}***@gmail.com โ†’ {self.recipient_email}")

    def validate_email(self, email: str) -> bool:
        """์ด๋ฉ”์ผ ์ฃผ์†Œ ์œ ํšจ์„ฑ ๊ฒ€์ฆ"""
        pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
        return re.match(pattern, email) is not None

    def send_email(self, subject: str, body: str, company_name: str, target_email: str) -> Tuple[bool, str]:
        """Gmail SMTP๋ฅผ ํ†ตํ•œ ์‹ค์ œ ์ด๋ฉ”์ผ ๋ฐœ์†ก"""
        try:
            if not self.gmail_email or not self.gmail_password:
                return False, "Gmail ๊ณ„์ • ์ •๋ณด๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค. ํ—ˆ๊น…ํŽ˜์ด์Šค Secrets๋ฅผ ํ™•์ธํ•˜์„ธ์š”."

            if not self.validate_email(target_email):
                return False, f"์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ์ด๋ฉ”์ผ ์ฃผ์†Œ: {target_email}"

            # ์ด๋ฉ”์ผ ๋ฉ”์‹œ์ง€ ์ƒ์„ฑ
            message = MIMEMultipart()
            message["From"] = self.gmail_email
            message["To"] = self.recipient_email  # ํ•ญ์ƒ jeongkee10@gmission.com์œผ๋กœ ๋ฐœ์†ก
            message["Subject"] = f"[ํŒŒํŠธ๋„ˆ์‹ญ ์ œ์•ˆ] {subject}"

            # ์ด๋ฉ”์ผ ๋ณธ๋ฌธ (์›๋ณธ ๋Œ€์ƒ๊ณผ ๋‚ด์šฉ ํฌํ•จ)
            enhanced_body = f"""
G-Mission ํŒŒํŠธ๋„ˆ์‹ญ ํŒ€์—๊ฒŒ,

๋‹ค์Œ ๊ธฐ์—…์— ๋Œ€ํ•œ ํŒŒํŠธ๋„ˆ์‹ญ ์ œ์•ˆ์„œ๊ฐ€ ๋Œ€์‹œ๋ณด๋“œ์—์„œ ์ƒ์„ฑ๋˜์—ˆ์Šต๋‹ˆ๋‹ค:

์›๋ณธ ๋Œ€์ƒ ๊ธฐ์—…: {company_name}
์›๋ณธ ์ด๋ฉ”์ผ ์ฃผ์†Œ: {target_email}
์ƒ์„ฑ ์‹œ๊ฐ„: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

=== ํŒŒํŠธ๋„ˆ์‹ญ ์ œ์•ˆ ๋‚ด์šฉ ===

{body}

=== ๋‹ค์Œ ๋‹จ๊ณ„ ===
1. ์ œ์•ˆ ๋‚ด์šฉ ๊ฒ€ํ† 
2. ํ•„์š”์‹œ ๋‚ด์šฉ ์ˆ˜์ •
3. {target_email}๋กœ ์ง์ ‘ ๋ฐœ์†ก
4. ๊ฒฐ๊ณผ ์ถ”์  ๋ฐ ๊ด€๋ฆฌ

---
์ด ์ด๋ฉ”์ผ์€ Agentic AI ํŒŒํŠธ๋„ˆ DB ๋ถ„์„ ๋Œ€์‹œ๋ณด๋“œ์—์„œ ์ž๋™ ์ƒ์„ฑ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.
"""

            message.attach(MIMEText(enhanced_body, "plain", "utf-8"))

            # Gmail SMTP ์„œ๋ฒ„ ์—ฐ๊ฒฐ ๋ฐ ๋ฐœ์†ก
            context = ssl.create_default_context()
            with smtplib.SMTP(self.smtp_server, self.port) as server:
                server.starttls(context=context)
                server.login(self.gmail_email, self.gmail_password)
                server.sendmail(self.gmail_email, self.recipient_email, message.as_string())

            # ๋ฐœ์†ก ๊ธฐ๋ก
            self.record_email_send(company_name, target_email, subject, body[:100])

            return True, f"โœ… ์ด๋ฉ”์ผ์ด {self.recipient_email}๋กœ ์„ฑ๊ณต์ ์œผ๋กœ ๋ฐœ์†ก๋˜์—ˆ์Šต๋‹ˆ๋‹ค!"

        except smtplib.SMTPAuthenticationError:
            return False, "โŒ Gmail ์ธ์ฆ ์‹คํŒจ. ์•ฑ ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ํ™•์ธํ•˜์„ธ์š”."
        except smtplib.SMTPException as e:
            return False, f"โŒ SMTP ์˜ค๋ฅ˜: {str(e)}"
        except Exception as e:
            return False, f"โŒ ์ด๋ฉ”์ผ ๋ฐœ์†ก ์‹คํŒจ: {str(e)}"

    def create_partnership_email(self, company_name: str, email: str, ecosystem_category: str,
                               importance: int = 3, country: str = "", website: str = "") -> Tuple[str, str, str]:
        """๊ฐœ์„ ๋œ ํŒŒํŠธ๋„ˆ์‹ญ ์ด๋ฉ”์ผ ์ƒ์„ฑ"""
        try:
            if not email or '@' not in str(email) or str(email) in ['์ •๋ณด ์—†์Œ', 'N/A']:
                return "", "", ""

            # ์ƒํƒœ๊ณ„๋ณ„ ๋งž์ถค ์ œ๋ชฉ
            ecosystem_subjects = {
                "Infra": f"Infrastructure Partnership Opportunity - {company_name} & G-Mission",
                "Foundation Model": f"AI Foundation Model Collaboration - {company_name} & G-Mission",
                "Platform / Agentic AI Pipeline": f"Agentic AI Platform Partnership - {company_name} & G-Mission",
                "Application": f"AI Application Partnership Proposal - {company_name} & G-Mission"
            }

            subject = ecosystem_subjects.get(ecosystem_category,
                                           f"Strategic AI Partnership Proposal - {company_name} & G-Mission")

            # ์ค‘์š”๋„๋ณ„ ์ ‘๊ทผ ๋ฐฉ์‹
            importance_approaches = {
                5: "We have identified your company as a top-tier strategic partner",
                4: "We have identified your company as a key strategic partner",
                3: "We have identified your company as a promising strategic partner",
                2: "We are interested in exploring partnership opportunities",
                1: "We would like to discuss potential collaboration opportunities"
            }

            approach = importance_approaches.get(int(importance),
                                               "We are interested in exploring partnership opportunities")

            # ์ƒํƒœ๊ณ„๋ณ„ ํ˜‘๋ ฅ ๋ฐฉ์•ˆ
            ecosystem_focus = {
                "Infra": """
INFRASTRUCTURE COLLABORATION FOCUS:
โ€ข AI compute infrastructure optimization and resource sharing
โ€ข Cloud deployment strategies for Korean market
โ€ข Hardware-software integration solutions
โ€ข Scalable AI infrastructure development""",

                "Foundation Model": """
FOUNDATION MODEL COLLABORATION FOCUS:
โ€ข Korean language model development and fine-tuning
โ€ข Model licensing and technology transfer opportunities
โ€ข Joint research in multilingual AI capabilities
โ€ข Open-source collaboration initiatives""",

                "Platform / Agentic AI Pipeline": """
PLATFORM INTEGRATION FOCUS:
โ€ข API integration and interoperability solutions
โ€ข Agentic workflow automation partnerships
โ€ข Platform ecosystem development
โ€ข Enterprise AI orchestration solutions""",

                "Application": """
APPLICATION PARTNERSHIP FOCUS:
โ€ข Market-specific AI application development
โ€ข Customer success case studies and joint marketing
โ€ข Industry-vertical solution partnerships
โ€ข Korean market entry and expansion strategies"""
            }

            collaboration_details = ecosystem_focus.get(ecosystem_category,
                                                       "โ€ข Strategic technology partnership development")

            current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

            body = f"""Dear {company_name} Partnership Team,

Greetings from G-Mission!

{approach} in the '{ecosystem_category}' space through our comprehensive analysis of 155+ global Agentic AI companies.

{collaboration_details}

KEY PARTNERSHIP OPPORTUNITIES:
โ€ข Technology integration and joint product development
โ€ข Market expansion in Korea and APAC region
โ€ข Strategic alliance in enterprise AI solutions
โ€ข Investment and business development collaboration

ABOUT G-MISSION:
G-Mission is a leading AI technology company focused on developing innovative solutions for the Korean and APAC markets. We specialize in enterprise AI implementations and strategic partnerships with global technology leaders.

NEXT STEPS:
We would be delighted to schedule an introductory partnership discussion to explore mutual opportunities. Our team can share detailed market insights, partnership frameworks, and collaboration proposals tailored to your strategic objectives.

Would you be available for a partnership discussion in the coming weeks?

Best regards,

G-Mission Partnership Development Team
Email: jeongkee10@gmission.com
Website: https://gmission.com

---
This partnership proposal was generated through our Agentic AI Global Partner Database Analysis.
Generated on: {current_time}
Analysis Confidence: {"High" if importance >= 4 else "Medium" if importance >= 3 else "Standard"}"""

            return subject, body, str(email)

        except Exception as e:
            print(f"์ด๋ฉ”์ผ ์ƒ์„ฑ ์˜ค๋ฅ˜: {e}")
            return "", "", ""

    def record_email_send(self, company_name: str, email: str, subject: str, body_preview: str) -> bool:
        """์ด๋ฉ”์ผ ๋ฐœ์†ก ๊ธฐ๋ก"""
        try:
            record = {
                'timestamp': datetime.datetime.now(),
                'company_name': str(company_name),
                'target_email': str(email),
                'subject': str(subject),
                'body_preview': str(body_preview),
                'recipient': self.recipient_email,
                'status': '๋ฐœ์†ก ์™„๋ฃŒ',
                'send_date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            }

            self.email_history.append(record)
            return True
        except:
            return False

    def get_email_history_text(self) -> str:
        """์ด๋ฉ”์ผ ๋ฐœ์†ก ์ด๋ ฅ ๋ฐ˜ํ™˜"""
        if not self.email_history:
            return """๐Ÿ“ง **์ด๋ฉ”์ผ ๋ฐœ์†ก ํ˜„ํ™ฉ**

์•„์ง ๋ฐœ์†ก๋œ ์ด๋ฉ”์ผ์ด ์—†์Šต๋‹ˆ๋‹ค.

**์‚ฌ์šฉ ๋ฐฉ๋ฒ•:**
1. ๊ธฐ์—… ๋ถ„์„ ์‹คํ–‰
2. ๐Ÿ“ง ์ด๋ฉ”์ผ ํƒญ์—์„œ ๋‚ด์šฉ ํ™•์ธ/์ˆ˜์ •
3. '์‹ค์ œ ์ด๋ฉ”์ผ ๋ฐœ์†ก' ๋ฒ„ํŠผ ํด๋ฆญ
4. ์ด๋ฉ”์ผ์ด jeongkee10@gmission.com์œผ๋กœ ๋ฐœ์†ก๋ฉ๋‹ˆ๋‹ค"""

        history_text = f"๐Ÿ“ง **์ด๋ฉ”์ผ ๋ฐœ์†ก ํ˜„ํ™ฉ** (์ด {len(self.email_history)}๊ฑด)\n\n"

        for i, record in enumerate(reversed(self.email_history), 1):
            history_text += f"""
**{i}. {record['company_name']}**
- ๋ฐœ์†ก์ผ์‹œ: {record['send_date']}
- ๋Œ€์ƒ ์ด๋ฉ”์ผ: {record['target_email']}
- ์‹ค์ œ ์ˆ˜์‹ : {record['recipient']}
- ์ œ๋ชฉ: {record['subject'][:50]}...
- ์ƒํƒœ: โœ… {record['status']}

---
"""

        return history_text

# ==================== ๋ฐ์ดํ„ฐ ์ฒ˜๋ฆฌ ์‹œ์Šคํ…œ ====================

class OptimizedDataProcessor:
    @staticmethod
    def find_column_mapping(df_columns: List[str]) -> Dict[str, str]:
        """์ปฌ๋Ÿผ ๋งคํ•‘ ์ฐพ๊ธฐ"""
        mapping = {}
        for standard_name, possible_names in EXACT_COLUMN_MAPPING.items():
            for possible_name in possible_names:
                if possible_name in df_columns:
                    mapping[standard_name] = possible_name
                    break
        return mapping

    @staticmethod
    def safe_numeric_conversion(series: pd.Series) -> pd.Series:
        """์•ˆ์ „ํ•œ ์ˆซ์ž ๋ณ€ํ™˜"""
        try:
            processed = series.astype(str).copy()
            processed = processed.replace(['์ •๋ณด ์—†์Œ', 'nan', 'null', 'NaN', '', 'N/A'], '0')
            grade_mapping = {'S': '5', 'A': '4', 'B': '3', 'C': '2', 'D': '1'}
            processed = processed.replace(grade_mapping)
            processed = processed.str.replace(r'[^\d.]', '', regex=True).replace('', '0')
            return pd.to_numeric(processed, errors='coerce').fillna(0)
        except:
            return pd.Series([0] * len(series))

    @staticmethod
    def process_data(df: pd.DataFrame) -> pd.DataFrame:
        """๋ฐ์ดํ„ฐ ์ฒ˜๋ฆฌ ๋ฉ”์ธ ํ•จ์ˆ˜"""
        try:
            if df is None or df.empty:
                return pd.DataFrame()

            column_mapping = OptimizedDataProcessor.find_column_mapping(df.columns.tolist())
            processed_df = pd.DataFrame()

            for standard_name, original_name in column_mapping.items():
                if original_name in df.columns:
                    processed_df[standard_name] = df[original_name].copy()

            # ํ•„์ˆ˜ ์ปฌ๋Ÿผ ๋ณด์žฅ
            if '๊ธฐ์—…๋ช…' not in processed_df.columns:
                processed_df['๊ธฐ์—…๋ช…'] = df.iloc[:, 1] if len(df.columns) > 1 else [f"๊ธฐ์—…_{i+1}" for i in range(len(df))]

            if 'Ecosystem_Category' not in processed_df.columns:
                processed_df['Ecosystem_Category'] = '๋ฏธ๋ถ„๋ฅ˜'

            # ์ค‘์š”๋„ ์ฒ˜๋ฆฌ
            if '์ค‘์š”๋„' in processed_df.columns:
                processed_df['์ค‘์š”๋„'] = OptimizedDataProcessor.safe_numeric_conversion(processed_df['์ค‘์š”๋„'])
                processed_df['์ค‘์š”๋„๋“ฑ๊ธ‰'] = processed_df['์ค‘์š”๋„'].apply(
                    lambda x: 'S๊ธ‰ (์ตœ์šฐ์„ )' if x == 5 else
                             'A๊ธ‰ (ํ•ต์‹ฌ)' if x == 4 else
                             'B๊ธ‰ (์œ ๋ง)' if x == 3 else
                             'C๊ธ‰ (๊ด€์‹ฌ)' if x == 2 else
                             'D๊ธ‰ (์ฐธ๊ณ )' if x == 1 else '๋ฏธ๋ถ„๋ฅ˜'
                )

            processed_df = processed_df.fillna('์ •๋ณด ์—†์Œ')

            # ๋ฉ”๋ชจ๋ฆฌ ์ตœ์ ํ™”
            for col in processed_df.columns:
                if processed_df[col].dtype == 'object':
                    processed_df[col] = processed_df[col].astype('category')

            return processed_df

        except Exception as e:
            print(f"๋ฐ์ดํ„ฐ ์ฒ˜๋ฆฌ ์˜ค๋ฅ˜: {e}")
            return df if df is not None else pd.DataFrame()

# ==================== ํŒŒ์Šคํ…”ํ†ค ์ฐจํŠธ ์ƒ์„ฑ ์‹œ์Šคํ…œ ====================

class PastelChartGenerator:
    @staticmethod
    def create_ecosystem_optimized_charts(df: pd.DataFrame, ecosystem_filter: str = "์ „์ฒด") -> Tuple[Any, Any, Any, Any, str]:
        """์ƒํƒœ๊ณ„๋ณ„ ์ตœ์ ํ™”๋œ ํŒŒ์Šคํ…”ํ†ค ์ฐจํŠธ ์ƒ์„ฑ"""
        try:
            if not PLOTLY_AVAILABLE or df is None or df.empty:
                return None, None, None, None, "๋ฐ์ดํ„ฐ๊ฐ€ ์—†๊ฑฐ๋‚˜ Plotly๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."

            # ๋ฐ์ดํ„ฐ ํ•„ํ„ฐ๋ง
            if ecosystem_filter != "์ „์ฒด":
                filtered_df = df[df['Ecosystem_Category'] == ecosystem_filter].copy()
                filter_info = f"'{ecosystem_filter}' ์ƒํƒœ๊ณ„"
            else:
                filtered_df = df.copy()
                filter_info = "์ „์ฒด ์ƒํƒœ๊ณ„"

            if filtered_df.empty:
                return None, None, None, None, f"{ecosystem_filter} ์นดํ…Œ๊ณ ๋ฆฌ์— ๊ธฐ์—…์ด ์—†์Šต๋‹ˆ๋‹ค."

            # ์š”์•ฝ ์ •๋ณด ์ƒ์„ฑ
            total_companies = len(filtered_df)
            s_grade = len(filtered_df[filtered_df['์ค‘์š”๋„'] == 5]) if '์ค‘์š”๋„' in filtered_df.columns else 0
            a_grade = len(filtered_df[filtered_df['์ค‘์š”๋„'] == 4]) if '์ค‘์š”๋„' in filtered_df.columns else 0
            countries = filtered_df['HQ_๊ตญ๊ฐ€'].nunique() if 'HQ_๊ตญ๊ฐ€' in filtered_df.columns else 0

            # ์ƒํƒœ๊ณ„๋ณ„ ํŠนํ™” ๋ถ„์„
            ecosystem_focus = ECOSYSTEM_OPTIMIZED_COLUMNS.get(ecosystem_filter, {}).get('focus', 'comprehensive analysis')

            summary_text = f"""### ๐Ÿ“Š {filter_info} ๋ถ„์„ ์š”์•ฝ

**์ด ๊ธฐ์—… ์ˆ˜:** {total_companies:,}๊ฐœ
**S๊ธ‰ ์ตœ์šฐ์„  ๊ธฐ์—…:** {s_grade}๊ฐœ
**A๊ธ‰ ํ•ต์‹ฌ ๊ธฐ์—…:** {a_grade}๊ฐœ
**์ฐธ์—ฌ ๊ตญ๊ฐ€:** {countries}๊ฐœ๊ตญ

**๋ถ„์„ ํฌ์ปค์Šค:** {ecosystem_focus}
**์ „๋žต์  ๊ธฐํšŒ:** {s_grade + a_grade}๊ฐœ ํ•ต์‹ฌ ๊ธฐ์—…์ด ์ „์ฒด์˜ {((s_grade + a_grade) / total_companies * 100):.1f}%"""

            # 1. ์ƒํƒœ๊ณ„๋ณ„ ํŒŒ์Šคํ…”ํ†ค ๋ถ„ํฌ ์ฐจํŠธ
            if ecosystem_filter == "์ „์ฒด":
                ecosystem_counts = filtered_df['Ecosystem_Category'].value_counts()
                ecosystem_colors = [PASTEL_COLORS['ecosystem_colors'].get(eco, PASTEL_COLORS['primary_palette'][i % 7])
                                  for i, eco in enumerate(ecosystem_counts.index)]

                fig1 = px.pie(
                    values=ecosystem_counts.values,
                    names=ecosystem_counts.index,
                    title=f"๐Ÿ—๏ธ ์ƒํƒœ๊ณ„๋ณ„ ๊ธฐ์—… ๋ถ„ํฌ (์ด {total_companies}๊ฐœ)",
                    color_discrete_sequence=ecosystem_colors
                )
                fig1.update_traces(textposition='inside', textinfo='percent+label',
                                 textfont=dict(size=12, color='white'))
            else:
                fig1 = go.Figure(data=[go.Pie(
                    labels=[ecosystem_filter],
                    values=[total_companies],
                    marker_colors=[PASTEL_COLORS['ecosystem_colors'].get(ecosystem_filter, '#E5BAFF')],
                    textinfo='value+label',
                    textfont=dict(size=14, color='white')
                )])
                fig1.update_layout(title=f"๐Ÿ—๏ธ {ecosystem_filter} ์ƒํƒœ๊ณ„ ({total_companies}๊ฐœ ๊ธฐ์—…)")

            fig1.update_layout(
                font=dict(size=14),
                plot_bgcolor='rgba(0,0,0,0)',
                paper_bgcolor='rgba(0,0,0,0)',
                height=400
            )

            # 2. ์ค‘์š”๋„๋ณ„ ํŒŒ์Šคํ…”ํ†ค ๋ถ„ํฌ ์ฐจํŠธ
            if '์ค‘์š”๋„' in filtered_df.columns:
                importance_counts = filtered_df['์ค‘์š”๋„'].value_counts().sort_index(ascending=False)
                grade_names = {5: 'S๊ธ‰', 4: 'A๊ธ‰', 3: 'B๊ธ‰', 2: 'C๊ธ‰', 1: 'D๊ธ‰'}

                if not importance_counts.empty:
                    x_labels = [grade_names.get(grade, f'{grade}๊ธ‰') for grade in importance_counts.index]
                    y_values = importance_counts.values
                    bar_colors = [PASTEL_COLORS['importance_colors'].get(grade, '#E5E5E5')
                                for grade in importance_counts.index]

                    fig2 = go.Figure(data=[
                        go.Bar(x=x_labels, y=y_values,
                              marker_color=bar_colors,
                              text=y_values, textposition='auto',
                              textfont=dict(size=12, color='black'))
                    ])
                    fig2.update_layout(
                        title=f"โญ {filter_info} ์ค‘์š”๋„๋ณ„ ๋ถ„ํฌ",
                        xaxis_title="์ค‘์š”๋„ ๋“ฑ๊ธ‰",
                        yaxis_title="๊ธฐ์—… ์ˆ˜",
                        font=dict(size=14),
                        plot_bgcolor='rgba(0,0,0,0)',
                        paper_bgcolor='rgba(0,0,0,0)',
                        height=400
                    )
                else:
                    fig2 = go.Figure()
            else:
                fig2 = go.Figure()

            # 3. ์ƒํƒœ๊ณ„๋ณ„ ์ตœ์ ํ™”๋œ ์ถ”๊ฐ€ ์ฐจํŠธ
            fig3 = PastelChartGenerator.create_ecosystem_specific_chart(filtered_df, ecosystem_filter)

            # 4. ์ƒํƒœ๊ณ„๋ณ„ ์ƒ์„ธ ๋ถ„์„ ์ฐจํŠธ
            fig4 = PastelChartGenerator.create_detailed_analysis_chart(filtered_df, ecosystem_filter)

            return fig1, fig2, fig3, fig4, summary_text

        except Exception as e:
            print(f"์ฐจํŠธ ์ƒ์„ฑ ์˜ค๋ฅ˜: {e}")
            return None, None, None, None, f"์ฐจํŠธ ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜: {str(e)}"

    @staticmethod
    def create_ecosystem_specific_chart(df: pd.DataFrame, ecosystem_filter: str) -> Any:
        """์ƒํƒœ๊ณ„๋ณ„ ํŠนํ™” ์ฐจํŠธ ์ƒ์„ฑ"""
        try:
            if ecosystem_filter == "Infra":
                # ์ธํ”„๋ผ: LLM ๋ฐฐํฌ ๋ฐฉ์‹ ๋ถ„ํฌ
                if 'LLM_Deployment' in df.columns:
                    deployment_counts = df['LLM_Deployment'].value_counts().head(8)
                    if not deployment_counts.empty:
                        fig = px.bar(
                            x=deployment_counts.index,
                            y=deployment_counts.values,
                            title="๐Ÿš€ LLM ๋ฐฐํฌ ๋ฐฉ์‹ ๋ถ„ํฌ",
                            color_discrete_sequence=PASTEL_COLORS['primary_palette']
                        )
                        fig.update_layout(xaxis_title="๋ฐฐํฌ ๋ฐฉ์‹", yaxis_title="๊ธฐ์—… ์ˆ˜")
                        return fig

            elif ecosystem_filter == "Foundation Model":
                # ํŒŒ์šด๋ฐ์ด์…˜ ๋ชจ๋ธ: ์˜คํ”ˆ์†Œ์Šค ์—ฌ๋ถ€ ๋ถ„ํฌ
                if 'OpenSource์—ฌ๋ถ€' in df.columns:
                    opensource_counts = df['OpenSource์—ฌ๋ถ€'].value_counts()
                    if not opensource_counts.empty:
                        fig = px.pie(
                            values=opensource_counts.values,
                            names=opensource_counts.index,
                            title="๐Ÿ”“ ์˜คํ”ˆ์†Œ์Šค ์—ฌ๋ถ€ ๋ถ„ํฌ",
                            color_discrete_sequence=PASTEL_COLORS['secondary_palette']
                        )
                        return fig

            elif ecosystem_filter == "Platform / Agentic AI Pipeline":
                # ํ”Œ๋žซํผ: ์‘์šฉ ๋„๋ฉ”์ธ ๋ถ„ํฌ
                if 'Application_Domain' in df.columns:
                    domain_counts = df['Application_Domain'].value_counts().head(10)
                    if not domain_counts.empty:
                        fig = px.bar(
                            x=domain_counts.values,
                            y=domain_counts.index,
                            orientation='h',
                            title="๐ŸŽฏ ์‘์šฉ ๋„๋ฉ”์ธ๋ณ„ ๋ถ„ํฌ",
                            color_discrete_sequence=PASTEL_COLORS['primary_palette']
                        )
                        fig.update_layout(xaxis_title="๊ธฐ์—… ์ˆ˜", yaxis_title="์‘์šฉ ๋„๋ฉ”์ธ")
                        return fig

            elif ecosystem_filter == "Application":
                # ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜: ํƒ€๊ฒŸ ๊ณ ๊ฐ ๋ถ„ํฌ
                if 'TargetCustomer' in df.columns:
                    customer_counts = df['TargetCustomer'].value_counts().head(8)
                    if not customer_counts.empty:
                        fig = px.bar(
                            x=customer_counts.index,
                            y=customer_counts.values,
                            title="๐Ÿ‘ฅ ํƒ€๊ฒŸ ๊ณ ๊ฐ๋ณ„ ๋ถ„ํฌ",
                            color_discrete_sequence=PASTEL_COLORS['primary_palette']
                        )
                        fig.update_layout(xaxis_title="ํƒ€๊ฒŸ ๊ณ ๊ฐ", yaxis_title="๊ธฐ์—… ์ˆ˜")
                        return fig

            else:
                # ์ „์ฒด: ๊ตญ๊ฐ€๋ณ„ ๋ถ„ํฌ
                if 'HQ_๊ตญ๊ฐ€' in df.columns:
                    country_counts = df['HQ_๊ตญ๊ฐ€'].value_counts().head(10)
                    if not country_counts.empty:
                        fig = px.bar(
                            x=country_counts.values,
                            y=country_counts.index,
                            orientation='h',
                            title="๐ŸŒ ์ฃผ์š” ๊ตญ๊ฐ€๋ณ„ ๊ธฐ์—… ์ˆ˜",
                            color_discrete_sequence=PASTEL_COLORS['primary_palette']
                        )
                        fig.update_layout(xaxis_title="๊ธฐ์—… ์ˆ˜", yaxis_title="๊ตญ๊ฐ€")
                        return fig

            return go.Figure()

        except Exception as e:
            print(f"์ƒํƒœ๊ณ„๋ณ„ ์ฐจํŠธ ์ƒ์„ฑ ์˜ค๋ฅ˜: {e}")
            return go.Figure()

    @staticmethod
    def create_detailed_analysis_chart(df: pd.DataFrame, ecosystem_filter: str) -> Any:
        """์ƒ์„ธ ๋ถ„์„ ์ฐจํŠธ ์ƒ์„ฑ"""
        try:
            if ecosystem_filter == "Infra":
                # ์ธํ”„๋ผ: ์„ค๋ฆฝ์—ฐ๋„๋ณ„ ๋ถ„ํฌ
                if '์„ค๋ฆฝ์—ฐ๋„' in df.columns:
                    years = df['์„ค๋ฆฝ์—ฐ๋„'][df['์„ค๋ฆฝ์—ฐ๋„'] > 0]
                    if not years.empty:
                        fig = px.histogram(
                            x=years,
                            nbins=20,
                            title="๐Ÿ“… ์„ค๋ฆฝ์—ฐ๋„๋ณ„ ๋ถ„ํฌ",
                            color_discrete_sequence=[PASTEL_COLORS['ecosystem_colors']['Infra']]
                        )
                        fig.update_layout(xaxis_title="์„ค๋ฆฝ์—ฐ๋„", yaxis_title="๊ธฐ์—… ์ˆ˜")
                        return fig

            elif ecosystem_filter == "Foundation Model":
                # ํŒŒ์šด๋ฐ์ด์…˜ ๋ชจ๋ธ: PrimaryLLM ๋ถ„ํฌ
                if 'PrimaryLLM' in df.columns:
                    llm_counts = df['PrimaryLLM'].value_counts().head(8)
                    if not llm_counts.empty:
                        fig = px.bar(
                            x=llm_counts.index,
                            y=llm_counts.values,
                            title="๐Ÿค– ์ฃผ์š” LLM ๋ชจ๋ธ ๋ถ„ํฌ",
                            color_discrete_sequence=PASTEL_COLORS['primary_palette']
                        )
                        fig.update_layout(xaxis_title="LLM ๋ชจ๋ธ", yaxis_title="๊ธฐ์—… ์ˆ˜")
                        return fig

            elif ecosystem_filter == "Platform / Agentic AI Pipeline":
                # ํ”Œ๋žซํผ: STT/TTS ์ง€์› ํ˜„ํ™ฉ
                if 'STT_TTS์ง€์›' in df.columns:
                    stt_counts = df['STT_TTS์ง€์›'].value_counts()
                    if not stt_counts.empty:
                        fig = px.pie(
                            values=stt_counts.values,
                            names=stt_counts.index,
                            title="๐ŸŽค STT/TTS ์ง€์› ํ˜„ํ™ฉ",
                            color_discrete_sequence=PASTEL_COLORS['secondary_palette']
                        )
                        return fig

            elif ecosystem_filter == "Application":
                # ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜: ํ•œ๊ตญ ์ง€์› ํ˜„ํ™ฉ
                if 'KoreaSupport' in df.columns:
                    korea_counts = df['KoreaSupport'].value_counts()
                    if not korea_counts.empty:
                        fig = px.pie(
                            values=korea_counts.values,
                            names=korea_counts.index,
                            title="๐Ÿ‡ฐ๐Ÿ‡ท ํ•œ๊ตญ ์‹œ์žฅ ์ง€์› ํ˜„ํ™ฉ",
                            color_discrete_sequence=PASTEL_COLORS['primary_palette']
                        )
                        return fig

            else:
                # ์ „์ฒด: ์ค‘์š”๋„์™€ ์„ค๋ฆฝ์—ฐ๋„ ์ƒ๊ด€๊ด€๊ณ„
                if '์ค‘์š”๋„' in df.columns and '์„ค๋ฆฝ์—ฐ๋„' in df.columns:
                    valid_data = df[(df['์ค‘์š”๋„'] > 0) & (df['์„ค๋ฆฝ์—ฐ๋„'] > 0)]
                    if not valid_data.empty:
                        fig = px.scatter(
                            valid_data,
                            x='์„ค๋ฆฝ์—ฐ๋„',
                            y='์ค‘์š”๋„',
                            size=[10] * len(valid_data),
                            title="๐Ÿ“Š ์„ค๋ฆฝ์—ฐ๋„ vs ์ค‘์š”๋„ ๋ถ„ํฌ",
                            color_discrete_sequence=[PASTEL_COLORS['ecosystem_colors']['์ „์ฒด']]
                        )
                        fig.update_layout(xaxis_title="์„ค๋ฆฝ์—ฐ๋„", yaxis_title="์ค‘์š”๋„")
                        return fig

            return go.Figure()

        except Exception as e:
            print(f"์ƒ์„ธ ๋ถ„์„ ์ฐจํŠธ ์ƒ์„ฑ ์˜ค๋ฅ˜: {e}")
            return go.Figure()

# ==================== ๊ธฐ์—… ๋ถ„์„ ์‹œ์Šคํ…œ ====================

def analyze_company_comprehensive(df: pd.DataFrame, company_name: str, email_system: GmailEmailSystem) -> Tuple[str, str, str, str]:
    """์ข…ํ•ฉ์ ์ธ ๊ธฐ์—… ๋ถ„์„ (์ƒํƒœ๊ณ„๋ณ„ ์ตœ์ ํ™”)"""
    try:
        if df is None or df.empty or not company_name:
            return "๊ธฐ์—…์„ ์„ ํƒํ•ด์ฃผ์„ธ์š”.", "", "", ""

        # ๊ธฐ์—… ๋ฐ์ดํ„ฐ ์ฐพ๊ธฐ
        company_data = df[df['๊ธฐ์—…๋ช…'] == company_name]
        if company_data.empty:
            return f"'{company_name}' ๊ธฐ์—…์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.", "", "", ""

        data = company_data.iloc[0]

        def safe_get(field, default='์ •๋ณด ์—†์Œ'):
            value = data.get(field, default)
            if pd.isna(value) or str(value).strip() in ['', 'nan', 'NaN', 'N/A']:
                return default
            return str(value)

        # ๊ธฐ์—… ์ •๋ณด ์ถ”์ถœ
        company_name_clean = safe_get('๊ธฐ์—…๋ช…')
        ecosystem_cat = safe_get('Ecosystem_Category')
        importance = safe_get('์ค‘์š”๋„', 0)
        importance_grade = safe_get('์ค‘์š”๋„๋“ฑ๊ธ‰', '๋ฏธ๋ถ„๋ฅ˜')
        email_address = safe_get('์ด๋ฉ”์ผ')
        country = safe_get('HQ_๊ตญ๊ฐ€')
        website = safe_get('์›น์‚ฌ์ดํŠธ')

        # ์ƒํƒœ๊ณ„๋ณ„ ์ตœ์ ํ™”๋œ ๋ถ„์„
        optimized_info = ECOSYSTEM_OPTIMIZED_COLUMNS.get(ecosystem_cat, {})
        primary_columns = optimized_info.get('primary', [])
        focus_area = optimized_info.get('focus', 'comprehensive business analysis')

        # ์•ก์…˜ ์ถ”์ฒœ
        action_recommendations = {
            5: "๐Ÿš€ **์ตœ์šฐ์„  ํ˜‘๋ ฅ ์ถ”์ง„** - S๊ธ‰ ์ „๋žต์  ํŒŒํŠธ๋„ˆ๋กœ ์ฆ‰์‹œ ํŒŒํŠธ๋„ˆ์‹ญ ๊ฐœ์‹œ",
            4: "๐ŸŽฏ **ํ•ต์‹ฌ ํŒŒํŠธ๋„ˆ์‹ญ ๊ฐœ๋ฐœ** - A๊ธ‰ ์ค‘์š” ๊ธฐ์—…์œผ๋กœ ์ƒ์„ธ ํ˜‘๋ ฅ ๋ฐฉ์•ˆ ์ˆ˜๋ฆฝ",
            3: "๐Ÿค **์ „์ˆ ์  ํ˜‘๋ ฅ ๊ฒ€ํ† ** - B๊ธ‰ ์œ ๋ง ํŒŒํŠธ๋„ˆ๋กœ ๋‹จ๊ณ„์  ์ ‘๊ทผ",
            2: "๐Ÿ‘€ **์‹œ์žฅ ๋™ํ–ฅ ๋ชจ๋‹ˆํ„ฐ๋ง** - C๊ธ‰ ๊ด€์‹ฌ ๊ธฐ์—…์œผ๋กœ ์ง€์† ๊ด€์ฐฐ",
            1: "๐Ÿ“‹ **์ •๋ณด ์ˆ˜์ง‘ ๋ฐ ๋ถ„์„** - D๊ธ‰ ์ฐธ๊ณ  ๊ธฐ์—…์œผ๋กœ ๊ธฐ๋ณธ ์ •๋ณด ์ถ•์ "
        }

        try:
            importance_num = float(importance)
            action_recommendation = action_recommendations.get(int(importance_num), "๐Ÿ“‹ **๊ธฐ๋ณธ ์ •๋ณด ์ˆ˜์ง‘**")
        except:
            action_recommendation = "๐Ÿ“‹ **๊ธฐ๋ณธ ์ •๋ณด ์ˆ˜์ง‘**"

        # ์ƒํƒœ๊ณ„๋ณ„ ์ƒ์„ธ ๋ถ„์„ ์ƒ์„ฑ
        ecosystem_analysis = generate_ecosystem_specific_analysis(data, ecosystem_cat, primary_columns)

        # ์ตœ์ข… ๋ถ„์„ ๊ฒฐ๊ณผ
        analysis = f"""# ๐Ÿข {company_name_clean} ์ข…ํ•ฉ ๋ถ„์„

## โœ… ์ƒํƒœ๊ณ„๋ณ„ ์ตœ์ ํ™” ๋ถ„์„ ์™„๋ฃŒ!

## โญ ์ „๋žต์  ํ‰๊ฐ€
- **์ „๋žต์  ์ค‘์š”๋„:** {importance}/5์  ({importance_grade})
- **์ƒํƒœ๊ณ„ ๋ถ„๋ฅ˜:** {ecosystem_cat}
- **๋ถ„์„ ํฌ์ปค์Šค:** {focus_area}
- **๊ถŒ์žฅ ์•ก์…˜:** {action_recommendation}

---

## ๐Ÿ“ ๊ธฐ์—… ๊ธฐ๋ณธ ์ •๋ณด
- **๋ณธ์‚ฌ ์œ„์น˜:** {country} - {safe_get('HQ_๋„์‹œ')}
- **์„ค๋ฆฝ ์—ฐ๋„:** {safe_get('์„ค๋ฆฝ์—ฐ๋„')}
- **์ฐฝ์—…์ž:** {safe_get('์ฐฝ์—…์ž')}
- **์ฃผ์š” ํˆฌ์ž์ž:** {safe_get('์ฃผ์š”ํˆฌ์ž์ž')}

## ๐ŸŽฏ ๊ธฐ์—… ๊ฐœ์š”
{safe_get('๊ธฐ์—…๊ฐœ์š”')}

{ecosystem_analysis}

## ๐Ÿ”— ์—ฐ๋ฝ์ฒ˜ ๋ฐ ์›น ์ •๋ณด
- **๊ณต์‹ ์›น์‚ฌ์ดํŠธ:** {website}
- **๋ฌธ์˜ ํŽ˜์ด์ง€:** {safe_get('๋ฌธ์˜URL')}
- **์ด๋ฉ”์ผ:** {email_address}
- **์ „ํ™”๋ฒˆํ˜ธ:** {safe_get('์ „ํ™”๋ฒˆํ˜ธ')}

---

## ๐Ÿ’ก ๋งž์ถคํ˜• ํŒŒํŠธ๋„ˆ์‹ญ ์ „๋žต

{generate_partnership_strategy(ecosystem_cat, int(importance) if str(importance).isdigit() else 3)}

---

**โœจ ์ด๋ฉ”์ผ ํƒญ์œผ๋กœ ์ด๋™ํ•˜๋ฉด ์ž๋™ ์ƒ์„ฑ๋œ ๋งž์ถคํ˜• ํŒŒํŠธ๋„ˆ์‹ญ ์ด๋ฉ”์ผ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค!**
**๐Ÿ“ง '์‹ค์ œ ์ด๋ฉ”์ผ ๋ฐœ์†ก' ๋ฒ„ํŠผ์œผ๋กœ jeongkee10@gmission.com์— ์ด๋ฉ”์ผ์„ ๋ฐœ์†กํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.**"""

        # ์ด๋ฉ”์ผ ์ž๋™ ์ƒ์„ฑ
        if email_address != '์ •๋ณด ์—†์Œ' and '@' in email_address:
            subject, body, recipient = email_system.create_partnership_email(
                company_name_clean, email_address, ecosystem_cat, int(importance) if str(importance).isdigit() else 3, country, website
            )
            return analysis, subject, body, recipient
        else:
            return analysis, "", "", ""

    except Exception as e:
        error_msg = f"๊ธฐ์—… ๋ถ„์„ ์˜ค๋ฅ˜: {str(e)}"
        print(error_msg)
        return error_msg, "", "", ""

def generate_ecosystem_specific_analysis(data, ecosystem_cat: str, primary_columns: List[str]) -> str:
    """์ƒํƒœ๊ณ„๋ณ„ ํŠนํ™” ๋ถ„์„ ์ƒ์„ฑ"""
    def safe_get(field, default='์ •๋ณด ์—†์Œ'):
        value = data.get(field, default)
        if pd.isna(value) or str(value).strip() in ['', 'nan', 'NaN', 'N/A']:
            return default
        return str(value)

    if ecosystem_cat == "Infra":
        return f"""
## ๐Ÿ—๏ธ ์ธํ”„๋ผ ์ƒํƒœ๊ณ„ ์ „๋ฌธ ๋ถ„์„
- **์ฃผ์š” LLM:** {safe_get('PrimaryLLM')}
- **๋ฐฐํฌ ๋ฐฉ์‹:** {safe_get('LLM_Deployment')}
- **์ฃผ์š” ์ œํ’ˆ/์„œ๋น„์Šค:** {safe_get('์ฃผ์š”์ œํ’ˆ')}
- **ํŒŒํŠธ๋„ˆ์‹ญ ํ”„๋กœ๊ทธ๋žจ:** {safe_get('PartnershipProgram')}

**์ธํ”„๋ผ ํŠนํ™” ํ˜‘๋ ฅ ๋ฐฉ์•ˆ:**
โ€ข GPU/ํด๋ผ์šฐ๋“œ ๋ฆฌ์†Œ์Šค ๊ณต๋™ ํ™œ์šฉ ๋ฐ ์ตœ์ ํ™”
โ€ข AI ์›Œํฌ๋กœ๋“œ ๋ฐฐํฌ ๋ฐ ์Šค์ผ€์ผ๋ง ๊ธฐ์ˆ  ํ˜‘๋ ฅ
โ€ข ํ•œ๊ตญ ๋ฐ์ดํ„ฐ์„ผํ„ฐ ๋ฐ ์—ฃ์ง€ ์ปดํ“จํŒ… ๊ตฌ์ถ•
โ€ข ๊ณ ์„ฑ๋Šฅ AI ์ธํ”„๋ผ ๊ณต๋™ ๊ฐœ๋ฐœ"""

    elif ecosystem_cat == "Foundation Model":
        return f"""
## ๐Ÿค– ํŒŒ์šด๋ฐ์ด์…˜ ๋ชจ๋ธ ์ƒํƒœ๊ณ„ ์ „๋ฌธ ๋ถ„์„
- **์ฃผ์š” LLM:** {safe_get('PrimaryLLM')}
- **์˜คํ”ˆ์†Œ์Šค ์—ฌ๋ถ€:** {safe_get('OpenSource์—ฌ๋ถ€')}
- **๋ฐฐํฌ ๋ฐฉ์‹:** {safe_get('LLM_Deployment')}
- **ํƒ€๊ฒŸ ๊ณ ๊ฐ:** {safe_get('TargetCustomer')}

**ํŒŒ์šด๋ฐ์ด์…˜ ๋ชจ๋ธ ํŠนํ™” ํ˜‘๋ ฅ ๋ฐฉ์•ˆ:**
โ€ข ํ•œ๊ตญ์–ด ํŠนํ™” ๋ชจ๋ธ ๊ณต๋™ ๊ฐœ๋ฐœ ๋ฐ Fine-tuning
โ€ข ๋ชจ๋ธ ๋ผ์ด์„ผ์‹ฑ ๋ฐ ๊ธฐ์ˆ  ์ด์ „ ํ˜‘๋ ฅ
โ€ข ๋ฉ€ํ‹ฐ๋ชจ๋‹ฌ AI ๋ชจ๋ธ ๊ณต๋™ ์—ฐ๊ตฌ
โ€ข ์˜คํ”ˆ์†Œ์Šค ์ƒํƒœ๊ณ„ ๊ธฐ์—ฌ ๋ฐ ํ˜‘๋ ฅ"""

    elif ecosystem_cat == "Platform / Agentic AI Pipeline":
        return f"""
## ๐Ÿ”— ํ”Œ๋žซํผ/์—์ด์ „ํ‹ฑ AI ํŒŒ์ดํ”„๋ผ์ธ ์ „๋ฌธ ๋ถ„์„
- **์‘์šฉ ๋„๋ฉ”์ธ:** {safe_get('Application_Domain')}
- **STT/TTS ์ง€์›:** {safe_get('STT_TTS์ง€์›')}
- **ํƒ€๊ฒŸ ๊ณ ๊ฐ:** {safe_get('TargetCustomer')}
- **๊ฐ€๊ฒฉ ์ •์ฑ…:** {safe_get('PricingModel')}

**ํ”Œ๋žซํผ ํŠนํ™” ํ˜‘๋ ฅ ๋ฐฉ์•ˆ:**
โ€ข API ์—ฐ๋™ ๋ฐ ์ƒํ˜ธ ์šด์šฉ์„ฑ ํ™•๋ณด
โ€ข ์—์ด์ „ํ‹ฑ ์›Œํฌํ”Œ๋กœ์šฐ ์ž๋™ํ™” ํ”Œ๋žซํผ ๊ตฌ์ถ•
โ€ข ์—”ํ„ฐํ”„๋ผ์ด์ฆˆ AI ์˜ค์ผ€์ŠคํŠธ๋ ˆ์ด์…˜ ์†”๋ฃจ์…˜
โ€ข ํ†ตํ•ฉ ํ”Œ๋žซํผ ์ƒํƒœ๊ณ„ ๊ณต๋™ ๊ฐœ๋ฐœ"""

    elif ecosystem_cat == "Application":
        return f"""
## ๐Ÿ“ฑ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์ƒํƒœ๊ณ„ ์ „๋ฌธ ๋ถ„์„
- **์‘์šฉ ๋„๋ฉ”์ธ:** {safe_get('Application_Domain')}
- **ํƒ€๊ฒŸ ๊ณ ๊ฐ:** {safe_get('TargetCustomer')}
- **๊ฐ€๊ฒฉ ์ •์ฑ…:** {safe_get('PricingModel')}
- **ํ•œ๊ตญ ์ง€์›:** {safe_get('KoreaSupport')}

**์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ํŠนํ™” ํ˜‘๋ ฅ ๋ฐฉ์•ˆ:**
โ€ข ์‚ฐ์—…๋ณ„ ๋งž์ถคํ˜• AI ์†”๋ฃจ์…˜ ๊ณต๋™ ๊ฐœ๋ฐœ
โ€ข ํ•œ๊ตญ ์‹œ์žฅ ์ง„์ถœ ๋ฐ ํ˜„์ง€ํ™” ํ˜‘๋ ฅ
โ€ข B2B/B2C ๊ณ ๊ฐ ์‚ฌ๋ก€ ๊ณต์œ  ๋ฐ ๊ณต๋™ ๋งˆ์ผ€ํŒ…
โ€ข ์‹ค์ œ ๋น„์ฆˆ๋‹ˆ์Šค ์ ์šฉ ์‚ฌ๋ก€ ๊ตฌ์ถ•"""

    else:
        return f"""
## ๐Ÿ” ์ข…ํ•ฉ ๊ธฐ์ˆ  ๋ถ„์„
- **์ฃผ์š” ๊ธฐ์ˆ :** {safe_get('์ฃผ์š”์ œํ’ˆ')}
- **์‘์šฉ ๋ถ„์•ผ:** {safe_get('Application_Domain')}
- **์‹œ์žฅ ์ ‘๊ทผ:** {safe_get('TargetCustomer')}

**์ข…ํ•ฉ ํ˜‘๋ ฅ ๋ฐฉ์•ˆ:**
โ€ข ๊ธฐ์ˆ  ํ†ตํ•ฉ ๋ฐ ๊ณต๋™ ๊ฐœ๋ฐœ
โ€ข ์‹œ์žฅ ํ™•์žฅ ์ „๋žต ํ˜‘๋ ฅ
โ€ข ํ˜์‹  ์ƒํƒœ๊ณ„ ๊ตฌ์ถ•"""

def generate_partnership_strategy(ecosystem_cat: str, importance: int) -> str:
    """ํŒŒํŠธ๋„ˆ์‹ญ ์ „๋žต ์ƒ์„ฑ"""
    strategies = {
        "Infra": """
**์ธํ”„๋ผ ํŒŒํŠธ๋„ˆ์‹ญ ์ „๋žต:**
1. **๊ธฐ์ˆ  ํ˜‘๋ ฅ**: ํด๋ผ์šฐ๋“œ ์ธํ”„๋ผ ๊ณต๋™ ๊ตฌ์ถ• ๋ฐ ์ตœ์ ํ™”
2. **์‹œ์žฅ ์ง„์ถœ**: ํ•œ๊ตญ/APAC ๋ฐ์ดํ„ฐ์„ผํ„ฐ ํ™•์žฅ ํ˜‘๋ ฅ
3. **ํˆฌ์ž ํ˜‘๋ ฅ**: ์ธํ”„๋ผ ํˆฌ์ž ํŽ€๋“œ ๊ณต๋™ ์กฐ์„ฑ
4. **ํ‘œ์ค€ํ™”**: AI ์ธํ”„๋ผ ํ‘œ์ค€ ๊ฐœ๋ฐœ ๊ณต๋™ ์ฐธ์—ฌ""",

        "Foundation Model": """
**ํŒŒ์šด๋ฐ์ด์…˜ ๋ชจ๋ธ ํŒŒํŠธ๋„ˆ์‹ญ ์ „๋žต:**
1. **๊ธฐ์ˆ  ํ˜‘๋ ฅ**: ํ•œ๊ตญ์–ด LLM ๊ณต๋™ ๊ฐœ๋ฐœ ๋ฐ ์ตœ์ ํ™”
2. **๋ผ์ด์„ผ์‹ฑ**: ๋ชจ๋ธ ๊ธฐ์ˆ  ์ด์ „ ๋ฐ ๋ผ์ด์„ผ์‹ฑ ํ˜‘๋ ฅ
3. **์—ฐ๊ตฌ ํ˜‘๋ ฅ**: ๊ณต๋™ ์—ฐ๊ตฌ์†Œ ์„ค๋ฆฝ ๋ฐ ์ธ์žฌ ๊ต๋ฅ˜
4. **์ƒํƒœ๊ณ„**: ์˜คํ”ˆ์†Œ์Šค ๊ธฐ์—ฌ ๋ฐ ์ปค๋ฎค๋‹ˆํ‹ฐ ๊ตฌ์ถ•""",

        "Platform / Agentic AI Pipeline": """
**ํ”Œ๋žซํผ ํŒŒํŠธ๋„ˆ์‹ญ ์ „๋žต:**
1. **ํ†ตํ•ฉ ํ˜‘๋ ฅ**: API ์ƒํ˜ธ ์—ฐ๋™ ๋ฐ ํ”Œ๋žซํผ ํ†ตํ•ฉ
2. **์†”๋ฃจ์…˜**: ์—”ํ„ฐํ”„๋ผ์ด์ฆˆ AI ์†”๋ฃจ์…˜ ๊ณต๋™ ๊ฐœ๋ฐœ
3. **๋งˆ์ผ€ํŒ…**: ๊ณต๋™ ๊ณ ๊ฐ ํ™•๋ณด ๋ฐ ์‹œ์žฅ ๊ฐœ์ฒ™
4. **ํ‘œ์ค€ํ™”**: ์—์ด์ „ํ‹ฑ AI ํ‘œ์ค€ ๋ฐ ํ”„๋กœํ† ์ฝœ ๊ฐœ๋ฐœ""",

        "Application": """
**์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ํŒŒํŠธ๋„ˆ์‹ญ ์ „๋žต:**
1. **ํ˜„์ง€ํ™”**: ํ•œ๊ตญ ์‹œ์žฅ ๋งž์ถคํ˜• ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ๊ฐœ๋ฐœ
2. **๊ณ ๊ฐ ํ™•๋ณด**: ๊ณต๋™ ์„ธ์ผ์ฆˆ ๋ฐ ๋งˆ์ผ€ํŒ… ํ˜‘๋ ฅ
3. **์‚ฌ๋ก€ ๊ตฌ์ถ•**: ์„ฑ๊ณต ์‚ฌ๋ก€ ๊ณต๋™ ๊ฐœ๋ฐœ ๋ฐ ํ™๋ณด
4. **ํˆฌ์ž**: ํ›„์† ํˆฌ์ž ๋ฐ ์‚ฌ์—… ํ™•์žฅ ํ˜‘๋ ฅ"""
    }

    base_strategy = strategies.get(ecosystem_cat, "**์ข…ํ•ฉ ํŒŒํŠธ๋„ˆ์‹ญ ์ „๋žต:** ๊ธฐ์ˆ , ์‹œ์žฅ, ํˆฌ์ž ์ „๋ฐฉ์œ„ ํ˜‘๋ ฅ")

    if importance >= 4:
        priority = "\n\n**๐Ÿš€ ์ตœ์šฐ์„  ์ถ”์ง„ ๊ถŒ์žฅ:** ์ฆ‰์‹œ ํŒŒํŠธ๋„ˆ์‹ญ ๊ฐœ์‹œ ๋ฐ ์ „๋‹ดํŒ€ ๊ตฌ์„ฑ"
    elif importance >= 3:
        priority = "\n\n**๐ŸŽฏ ์ค‘์  ๊ฒ€ํ†  ๊ถŒ์žฅ:** ๋‹จ๊ณ„๋ณ„ ํ˜‘๋ ฅ ๋ฐฉ์•ˆ ์ˆ˜๋ฆฝ ๋ฐ ํŒŒ์ผ๋Ÿฟ ํ”„๋กœ์ ํŠธ ์ง„ํ–‰"
    else:
        priority = "\n\n**๐Ÿ‘€ ์ง€์† ๋ชจ๋‹ˆํ„ฐ๋ง:** ์‹œ์žฅ ๋™ํ–ฅ ๊ด€์ฐฐ ๋ฐ ๊ธฐํšŒ ๋ฐœ๊ตด"

    return base_strategy + priority

# ==================== ํŒŒ์ผ ์ฒ˜๋ฆฌ ====================

def process_uploaded_file(file):
    """ํŒŒ์ผ ์—…๋กœ๋“œ ์ฒ˜๋ฆฌ"""
    if file is None:
        return None, "ํŒŒ์ผ์„ ์—…๋กœ๋“œํ•ด์ฃผ์„ธ์š”."

    try:
        file_path = file.name if hasattr(file, 'name') else str(file)

        if file_path.endswith('.csv'):
            df = pd.read_csv(file_path, encoding='utf-8-sig')
        elif file_path.endswith(('.xlsx', '.xls')):
            df = pd.read_excel(file_path)
        else:
            return None, "CSV ๋˜๋Š” Excel ํŒŒ์ผ์„ ์—…๋กœ๋“œํ•ด์ฃผ์„ธ์š”."

        if df.empty:
            return None, "๋นˆ ํŒŒ์ผ์ž…๋‹ˆ๋‹ค."

        processed_df = OptimizedDataProcessor.process_data(df)
        success_msg = f"โœ… ํŒŒ์ผ ์ฒ˜๋ฆฌ ์™„๋ฃŒ!\n- ์ด ๊ธฐ์—… ์ˆ˜: {len(processed_df):,}๊ฐœ\n- ์ปฌ๋Ÿผ ์ˆ˜: {len(processed_df.columns)}๊ฐœ"

        # ๋ฉ”๋ชจ๋ฆฌ ์ตœ์ ํ™”
        del df
        gc.collect()

        return processed_df, success_msg

    except Exception as e:
        return None, f"ํŒŒ์ผ ์ฒ˜๋ฆฌ ์˜ค๋ฅ˜: {str(e)}"

# ==================== ๋ฉ”์ธ ๋Œ€์‹œ๋ณด๋“œ ====================

def create_huggingface_dashboard():
    """ํ—ˆ๊น…ํŽ˜์ด์Šค ๋ฐฐํฌ์šฉ ๋ฉ”์ธ ๋Œ€์‹œ๋ณด๋“œ"""

    # Gmail ์ด๋ฉ”์ผ ์‹œ์Šคํ…œ ์ดˆ๊ธฐํ™”
    email_system = GmailEmailSystem()

    # ์ปค์Šคํ…€ CSS
    custom_css = """
    .gradio-container {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif !important;
        max-width: 1400px !important;
        margin: 0 auto !important;
    }
    .ecosystem-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 10px;
        padding: 20px;
        margin: 10px;
        color: white;
    }
    .pastel-btn {
        background: linear-gradient(135deg, #FFB3BA 0%, #FFDFBA 100%);
        border: none;
        border-radius: 8px;
        color: #333;
        font-weight: bold;
    }
    """

    with gr.Blocks(
        theme=gr.themes.Soft(primary_hue="blue", secondary_hue="cyan"),
        title="G-Mission Agentic AI Partner Database",
        css=custom_css
    ) as demo:

        # ํ—ค๋”
        gr.Markdown("""
        # ๐Ÿš€ G-Mission Agentic AI ๊ธ€๋กœ๋ฒŒ ํŒŒํŠธ๋„ˆ DB ๋ถ„์„ ๋Œ€์‹œ๋ณด๋“œ

        ### โœ… ํ—ˆ๊น…ํŽ˜์ด์Šค ๋ฐฐํฌ ์™„๋ฃŒ | โœ… Gmail SMTP ์ด๋ฉ”์ผ | โœ… ํŒŒ์Šคํ…”ํ†ค ์ฐจํŠธ | โœ… ์ƒํƒœ๊ณ„๋ณ„ ์ตœ์ ํ™”

        **155๊ฐœ ๊ธ€๋กœ๋ฒŒ Agentic AI ๊ธฐ์—… ์™„๋ฒฝ ๋ถ„์„** | **์‹ค์‹œ๊ฐ„ ํŒŒํŠธ๋„ˆ์‹ญ ์ด๋ฉ”์ผ ๋ฐœ์†ก**

        **์ฃผ์š” ๊ธฐ๋Šฅ:**
        - ๐ŸŽจ **ํŒŒ์Šคํ…”ํ†ค ์‹œ๊ฐํ™”**: ์ƒํƒœ๊ณ„๋ณ„ ๋งž์ถค ์ƒ‰์ƒ์œผ๋กœ ์ง๊ด€์  ๋ถ„์„
        - ๐Ÿ—๏ธ **์ƒํƒœ๊ณ„๋ณ„ ์ตœ์ ํ™”**: Infra, Foundation Model, Platform, Application ํŠนํ™” ๋ถ„์„
        - ๐Ÿ“ง **Gmail SMTP ์—ฐ๋™**: jeongkee10@gmission.com์œผ๋กœ ์‹ค์‹œ๊ฐ„ ์ด๋ฉ”์ผ ๋ฐœ์†ก
        - ๐ŸŽฏ **๋งž์ถคํ˜• ํŒŒํŠธ๋„ˆ์‹ญ**: ๊ธฐ์—…๋ณ„/์ƒํƒœ๊ณ„๋ณ„ ์ตœ์ ํ™”๋œ ํ˜‘๋ ฅ ์ œ์•ˆ
        """)

        # ์ƒํƒœ ๋ณ€์ˆ˜
        df_state = gr.State(value=None)

        # ํŒŒ์ผ ์—…๋กœ๋“œ
        with gr.Row():
            with gr.Column():
                file_upload = gr.File(
                    label="๐Ÿ“ Agentic AI ๊ธฐ์—… ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์—…๋กœ๋“œ",
                    file_types=['.csv', '.xlsx', '.xls'],
                    file_count="single"
                )
                upload_status = gr.Markdown("๐Ÿ“‹ **ํ˜„์žฌ ์ƒํƒœ:** ํŒŒ์ผ์„ ์—…๋กœ๋“œํ•ด์ฃผ์„ธ์š”.")

        # ๋ฉ”์ธ ํƒญ
        with gr.Tabs():
            # ํƒญ 1: ํŒŒ์Šคํ…”ํ†ค ์‹œ์žฅ ๋ถ„์„
            with gr.TabItem("๐ŸŽจ ํŒŒ์Šคํ…”ํ†ค ์‹œ์žฅ ๋ถ„์„"):
                with gr.Row():
                    with gr.Column(scale=1):
                        market_ecosystem_filter = gr.Dropdown(
                            choices=ECOSYSTEM_CATEGORIES,
                            value="์ „์ฒด",
                            label="๐Ÿ—๏ธ ์ƒํƒœ๊ณ„ ํ•„ํ„ฐ",
                            info="ํŠน์ • ์ƒํƒœ๊ณ„ ์„ ํƒ ์‹œ ํ•ด๋‹น ์˜์—ญ์— ์ตœ์ ํ™”๋œ ๋ถ„์„ ์ œ๊ณต"
                        )
                        market_analysis_btn = gr.Button(
                            "๐ŸŽจ ํŒŒ์Šคํ…”ํ†ค ๋ถ„์„ ์‹คํ–‰",
                            variant="primary",
                            size="lg"
                        )

                        market_summary = gr.Markdown(
                            "์ƒํƒœ๊ณ„๋ฅผ ์„ ํƒํ•˜๊ณ  ๋ถ„์„์„ ์‹คํ–‰ํ•˜๋ฉด ๋งž์ถคํ˜• ์š”์•ฝ์ด ํ‘œ์‹œ๋ฉ๋‹ˆ๋‹ค.",
                            label="๐Ÿ“Š ๋ถ„์„ ์š”์•ฝ"
                        )

                with gr.Row():
                    with gr.Column():
                        chart1 = gr.Plot(label="๐Ÿ—๏ธ ์ƒํƒœ๊ณ„๋ณ„ ๋ถ„ํฌ")
                    with gr.Column():
                        chart2 = gr.Plot(label="โญ ์ค‘์š”๋„๋ณ„ ๋ถ„ํฌ")

                with gr.Row():
                    with gr.Column():
                        chart3 = gr.Plot(label="๐ŸŽฏ ์ƒํƒœ๊ณ„๋ณ„ ํŠนํ™” ๋ถ„์„")
                    with gr.Column():
                        chart4 = gr.Plot(label="๐Ÿ“Š ์ƒ์„ธ ๋ถ„์„")

            # ํƒญ 2: ์ƒํƒœ๊ณ„๋ณ„ ์ตœ์ ํ™” ๊ธฐ์—… ๋ถ„์„
            with gr.TabItem("๐Ÿข ์ƒํƒœ๊ณ„๋ณ„ ์ตœ์ ํ™” ๊ธฐ์—… ๋ถ„์„"):
                with gr.Row():
                    with gr.Column(scale=1):
                        ecosystem_filter_company = gr.Dropdown(
                            choices=ECOSYSTEM_CATEGORIES,
                            value="์ „์ฒด",
                            label="๐Ÿ—๏ธ ์ƒํƒœ๊ณ„๋ณ„ ํ•„ํ„ฐ๋ง",
                            info="๊ฐ ์ƒํƒœ๊ณ„์— ์ตœ์ ํ™”๋œ ์ปฌ๋Ÿผ๊ณผ ๋ถ„์„ ์ œ๊ณต"
                        )

                        company_dropdown = gr.Dropdown(
                            choices=[],
                            label="๐Ÿข ๊ธฐ์—… ์„ ํƒ",
                            info="์ƒํƒœ๊ณ„๋ณ„ ํ•„ํ„ฐ๋ง ํ›„ ๊ธฐ์—… ์„ ํƒ"
                        )

                        analyze_company_btn = gr.Button(
                            "๐Ÿ” ์ƒํƒœ๊ณ„๋ณ„ ์ตœ์ ํ™” ๋ถ„์„ ์‹คํ–‰",
                            variant="primary",
                            size="lg"
                        )

                        # ์ƒํƒœ๊ณ„๋ณ„ ์ •๋ณด ํ‘œ์‹œ
                        ecosystem_info = gr.Markdown(
                            """### ๐Ÿ—๏ธ ์ƒํƒœ๊ณ„๋ณ„ ์ตœ์ ํ™” ์ •๋ณด

**Infra**: LLM ๋ฐฐํฌ, ์ธํ”„๋ผ ๊ธฐ์ˆ , ํŒŒํŠธ๋„ˆ์‹ญ ํ”„๋กœ๊ทธ๋žจ
**Foundation Model**: LLM ๋ชจ๋ธ, ์˜คํ”ˆ์†Œ์Šค, ๊ธฐ์ˆ  ์ด์ „
**Platform**: ์‘์šฉ๋„๋ฉ”์ธ, STT/TTS, ํƒ€๊ฒŸ๊ณ ๊ฐ, ๊ฐ€๊ฒฉ์ •์ฑ…
**Application**: ํƒ€๊ฒŸ๊ณ ๊ฐ, ๊ฐ€๊ฒฉ์ •์ฑ…, ํ•œ๊ตญ์ง€์›, ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜""",
                            label="์ƒํƒœ๊ณ„๋ณ„ ํŠนํ™” ์ •๋ณด"
                        )

                    with gr.Column(scale=2):
                        company_analysis = gr.Markdown(
                            """# ๐Ÿข ์ƒํƒœ๊ณ„๋ณ„ ์ตœ์ ํ™” ๊ธฐ์—… ๋ถ„์„

์ƒํƒœ๊ณ„๋ฅผ ์„ ํƒํ•˜๊ณ  ๊ธฐ์—…์„ ์„ ํƒํ•œ ํ›„ ๋ถ„์„์„ ์‹คํ–‰ํ•˜๋ฉด:

**๐ŸŽฏ ์ƒํƒœ๊ณ„๋ณ„ ํŠนํ™” ๋ถ„์„:**
- **Infra**: ์ธํ”„๋ผ ๊ธฐ์ˆ , ๋ฐฐํฌ ๋ฐฉ์‹, ํŒŒํŠธ๋„ˆ์‹ญ ์ค‘์‹ฌ ๋ถ„์„
- **Foundation Model**: LLM ๋ชจ๋ธ, ์˜คํ”ˆ์†Œ์Šค, ๊ธฐ์ˆ ๋ ฅ ์ค‘์‹ฌ ๋ถ„์„
- **Platform**: ํ”Œ๋žซํผ ํ†ตํ•ฉ, API, ์—์ด์ „ํ‹ฑ ํŒŒ์ดํ”„๋ผ์ธ ์ค‘์‹ฌ ๋ถ„์„
- **Application**: ์‹ค์ œ ์‘์šฉ, ์‹œ์žฅ ์ ‘๊ทผ, ๊ณ ๊ฐ ์ค‘์‹ฌ ๋ถ„์„

**โœจ ๊ฐ ์ƒํƒœ๊ณ„์— ์ตœ์ ํ™”๋œ ๋งž์ถคํ˜• ํŒŒํŠธ๋„ˆ์‹ญ ์ „๋žต์ด ์ œ๊ณต๋ฉ๋‹ˆ๋‹ค!**""",
                            label="๊ธฐ์—… ์ƒ์„ธ ๋ถ„์„"
                        )

            # ํƒญ 3: Gmail SMTP ์ด๋ฉ”์ผ ์‹œ์Šคํ…œ
            with gr.TabItem("๐Ÿ“ง Gmail SMTP ์ด๋ฉ”์ผ"):
                with gr.Row():
                    with gr.Column():
                        gr.Markdown("""## ๐Ÿ“ง Gmail SMTP ์ด๋ฉ”์ผ ์‹œ์Šคํ…œ

**์„ค์ • ์ƒํƒœ:**
- ๐Ÿ“ง Gmail ๊ณ„์ •: ํ—ˆ๊น…ํŽ˜์ด์Šค Secrets์—์„œ ๋กœ๋“œ
- ๐ŸŽฏ ์ˆ˜์‹  ์ด๋ฉ”์ผ: jeongkee10@gmission.com (๊ณ ์ •)
- ๐Ÿ” ๋ณด์•ˆ: Gmail ์•ฑ ๋น„๋ฐ€๋ฒˆํ˜ธ ์‚ฌ์šฉ

**์‚ฌ์šฉ ๋ฐฉ๋ฒ•:**
1. ๊ธฐ์—… ๋ถ„์„ ์‹คํ–‰ โ†’ ์ด๋ฉ”์ผ ์ž๋™ ์ƒ์„ฑ
2. ์•„๋ž˜์—์„œ ์ด๋ฉ”์ผ ๋‚ด์šฉ ํ™•์ธ/์ˆ˜์ •
3. '์‹ค์ œ ์ด๋ฉ”์ผ ๋ฐœ์†ก' ๋ฒ„ํŠผ ํด๋ฆญ
4. jeongkee10@gmission.com์œผ๋กœ ์ด๋ฉ”์ผ ๋ฐœ์†ก๋จ""")

                        # ์ด๋ฉ”์ผ ํ•„๋“œ๋“ค
                        email_recipient = gr.Textbox(
                            label="๐Ÿ“ง ๋Œ€์ƒ ๊ธฐ์—… ์ด๋ฉ”์ผ (์ฐธ์กฐ์šฉ)",
                            placeholder="๊ธฐ์—… ๋ถ„์„ ํ›„ ์ž๋™ ์ž…๋ ฅ๋ฉ๋‹ˆ๋‹ค",
                            interactive=True
                        )

                        email_subject = gr.Textbox(
                            label="๐Ÿ“ง ์ด๋ฉ”์ผ ์ œ๋ชฉ (์ˆ˜์ • ๊ฐ€๋Šฅ)",
                            placeholder="๊ธฐ์—… ๋ถ„์„ ํ›„ ์ž๋™ ์ƒ์„ฑ๋ฉ๋‹ˆ๋‹ค",
                            interactive=True
                        )

                        email_body = gr.Textbox(
                            label="๐Ÿ“ง ์ด๋ฉ”์ผ ๋‚ด์šฉ (์ˆ˜์ • ๊ฐ€๋Šฅ)",
                            lines=15,
                            placeholder="๊ธฐ์—… ๋ถ„์„ ํ›„ ์ƒํƒœ๊ณ„๋ณ„ ๋งž์ถคํ˜• ์ด๋ฉ”์ผ์ด ์ž๋™ ์ƒ์„ฑ๋ฉ๋‹ˆ๋‹ค",
                            interactive=True
                        )

                        # ์‹ค์ œ ์ด๋ฉ”์ผ ๋ฐœ์†ก ๋ฒ„ํŠผ
                        real_email_send_btn = gr.Button(
                            "๐Ÿ“ง ์‹ค์ œ Gmail๋กœ ์ด๋ฉ”์ผ ๋ฐœ์†ก (โ†’ jeongkee10@gmission.com)",
                            variant="primary",
                            size="lg"
                        )

                        email_send_status = gr.Markdown(
                            """### ๐Ÿ“ง ์ด๋ฉ”์ผ ๋ฐœ์†ก ์•ˆ๋‚ด

๊ธฐ์—… ๋ถ„์„์„ ์‹คํ–‰ํ•˜๋ฉด ํ•ด๋‹น ๊ธฐ์—…์— ๋งž๋Š” ๋งž์ถคํ˜• ํŒŒํŠธ๋„ˆ์‹ญ ์ด๋ฉ”์ผ์ด ์ž๋™ ์ƒ์„ฑ๋ฉ๋‹ˆ๋‹ค.
๋‚ด์šฉ์„ ํ™•์ธ/์ˆ˜์ •ํ•œ ํ›„ '์‹ค์ œ Gmail๋กœ ์ด๋ฉ”์ผ ๋ฐœ์†ก' ๋ฒ„ํŠผ์„ ํด๋ฆญํ•˜๋ฉด
**jeongkee10@gmission.com**์œผ๋กœ ์ด๋ฉ”์ผ์ด ๋ฐœ์†ก๋ฉ๋‹ˆ๋‹ค.

**๋ฐœ์†ก๋˜๋Š” ์ด๋ฉ”์ผ์—๋Š”:**
- ์›๋ณธ ๋Œ€์ƒ ๊ธฐ์—… ์ •๋ณด
- ํŒŒํŠธ๋„ˆ์‹ญ ์ œ์•ˆ ๋‚ด์šฉ
- ๋‹ค์Œ ๋‹จ๊ณ„ ๊ฐ€์ด๋“œ
- ๋Œ€์‹œ๋ณด๋“œ ๋งํฌ๊ฐ€ ํฌํ•จ๋ฉ๋‹ˆ๋‹ค.""",
                            label="๋ฐœ์†ก ์ƒํƒœ"
                        )

            # ํƒญ 4: ์ด๋ฉ”์ผ ๋ฐœ์†ก ํ˜„ํ™ฉ
            with gr.TabItem("๐Ÿ“ง ์ด๋ฉ”์ผ ๋ฐœ์†ก ํ˜„ํ™ฉ"):
                with gr.Column():
                    refresh_email_btn = gr.Button(
                        "๐Ÿ”„ ๋ฐœ์†ก ํ˜„ํ™ฉ ์ƒˆ๋กœ๊ณ ์นจ",
                        variant="primary"
                    )

                    email_history_display = gr.Markdown(
                        email_system.get_email_history_text(),
                        label="๐Ÿ“ง ์ด๋ฉ”์ผ ๋ฐœ์†ก ์ด๋ ฅ"
                    )

        # ==================== ์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ ====================

        # 1. ํŒŒ์ผ ์—…๋กœ๋“œ
        def handle_file_upload(file):
            try:
                df, status = process_uploaded_file(file)
                if df is not None:
                    company_names = sorted(df['๊ธฐ์—…๋ช…'].unique().tolist())
                    return (
                        df,
                        status,
                        gr.update(choices=company_names, value=None)
                    )
                else:
                    return None, status, gr.update(choices=[], value=None)
            except Exception as e:
                return None, f"ํŒŒ์ผ ์—…๋กœ๋“œ ์˜ค๋ฅ˜: {str(e)}", gr.update(choices=[], value=None)

        file_upload.upload(
            fn=handle_file_upload,
            inputs=[file_upload],
            outputs=[df_state, upload_status, company_dropdown]
        )

        # 2. ํŒŒ์Šคํ…”ํ†ค ์‹œ์žฅ ๋ถ„์„
        def handle_market_analysis(df, ecosystem_filter):
            try:
                if df is None or df.empty:
                    return None, None, None, None, "๋ฐ์ดํ„ฐ ํŒŒ์ผ์„ ์—…๋กœ๋“œํ•ด์ฃผ์„ธ์š”."

                return PastelChartGenerator.create_ecosystem_optimized_charts(df, ecosystem_filter)
            except Exception as e:
                return None, None, None, None, f"์‹œ์žฅ ๋ถ„์„ ์˜ค๋ฅ˜: {str(e)}"

        market_analysis_btn.click(
            fn=handle_market_analysis,
            inputs=[df_state, market_ecosystem_filter],
            outputs=[chart1, chart2, chart3, chart4, market_summary]
        )

        # 3. ์ƒํƒœ๊ณ„๋ณ„ ๊ธฐ์—… ํ•„ํ„ฐ๋ง
        def update_company_dropdown(df, ecosystem_filter):
            try:
                if df is None or df.empty:
                    return gr.update(choices=[])

                if ecosystem_filter != "์ „์ฒด":
                    filtered_df = df[df['Ecosystem_Category'] == ecosystem_filter]
                else:
                    filtered_df = df

                company_names = sorted(filtered_df['๊ธฐ์—…๋ช…'].unique().tolist())
                return gr.update(choices=company_names, value=None)
            except Exception as e:
                return gr.update(choices=[])

        ecosystem_filter_company.change(
            fn=update_company_dropdown,
            inputs=[df_state, ecosystem_filter_company],
            outputs=[company_dropdown]
        )

        # 4. ๐Ÿ”ฅ ํ•ต์‹ฌ: ์ƒํƒœ๊ณ„๋ณ„ ์ตœ์ ํ™” ๊ธฐ์—… ๋ถ„์„ + ์ด๋ฉ”์ผ ์ž๋™ ์ƒ์„ฑ
        analyze_company_btn.click(
            fn=lambda df, company: analyze_company_comprehensive(df, company, email_system),
            inputs=[df_state, company_dropdown],
            outputs=[
                company_analysis,    # ๊ธฐ์—… ๋ถ„์„ ๊ฒฐ๊ณผ
                email_subject,       # ์ด๋ฉ”์ผ ์ œ๋ชฉ ์ž๋™ ์ž…๋ ฅ
                email_body,          # ์ด๋ฉ”์ผ ๋‚ด์šฉ ์ž๋™ ์ž…๋ ฅ
                email_recipient      # ๋ฐ›๋Š” ์‚ฌ๋žŒ ์ž๋™ ์ž…๋ ฅ
            ]
        )

        # 5. ์‹ค์ œ Gmail ์ด๋ฉ”์ผ ๋ฐœ์†ก
        def handle_real_email_send(recipient, subject, body):
            try:
                if not recipient or '@' not in recipient:
                    return "์˜ฌ๋ฐ”๋ฅธ ๋Œ€์ƒ ๊ธฐ์—… ์ด๋ฉ”์ผ ์ฃผ์†Œ๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค."

                if not subject or not body:
                    return "์ด๋ฉ”์ผ ์ œ๋ชฉ๊ณผ ๋‚ด์šฉ์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."

                # ํšŒ์‚ฌ๋ช… ์ถ”์ถœ
                company_name = recipient.split('@')[0].capitalize()

                # ์‹ค์ œ Gmail ๋ฐœ์†ก
                success, message = email_system.send_email(subject, body, company_name, recipient)

                return message

            except Exception as e:
                return f"์ด๋ฉ”์ผ ๋ฐœ์†ก ์ฒ˜๋ฆฌ ์˜ค๋ฅ˜: {str(e)}"

        real_email_send_btn.click(
            fn=handle_real_email_send,
            inputs=[email_recipient, email_subject, email_body],
            outputs=[email_send_status]
        )

        # 6. ์ด๋ฉ”์ผ ํ˜„ํ™ฉ ์ƒˆ๋กœ๊ณ ์นจ
        refresh_email_btn.click(
            fn=lambda: email_system.get_email_history_text(),
            outputs=[email_history_display]
        )

    return demo

# ==================== ๋ฉ”์ธ ์‹คํ–‰ ====================

def main():
    """๋ฉ”์ธ ์‹คํ–‰ ํ•จ์ˆ˜"""
    print("๐Ÿš€ G-Mission ํ—ˆ๊น…ํŽ˜์ด์Šค ๋ฐฐํฌ์šฉ Agentic AI ๋Œ€์‹œ๋ณด๋“œ ์‹œ์ž‘!")
    print("โœ… Gmail SMTP ์ด๋ฉ”์ผ ์‹œ์Šคํ…œ")
    print("โœ… ํŒŒ์Šคํ…”ํ†ค ์ฐจํŠธ ์ƒ‰์ƒ")
    print("โœ… ์ƒํƒœ๊ณ„๋ณ„ ์ตœ์ ํ™”")
    print("โœ… jeongkee10@gmission.com ์ˆ˜์‹ ")

    try:
        demo = create_huggingface_dashboard()

        # ํ—ˆ๊น…ํŽ˜์ด์Šค ๋ฐฐํฌ์šฉ launch ์„ค์ •
        demo.launch(
            server_name="0.0.0.0",
            server_port=7860,
            debug=False,
            share=False
        )

        print("โœ… ํ—ˆ๊น…ํŽ˜์ด์Šค ๋ฐฐํฌ์šฉ ๋Œ€์‹œ๋ณด๋“œ ์‹คํ–‰ ์„ฑ๊ณต!")

    except Exception as e:
        print(f"โŒ ๋Œ€์‹œ๋ณด๋“œ ์‹คํ–‰ ์˜ค๋ฅ˜: {e}")
        traceback.print_exc()

if __name__ == "__main__":
    main()