File size: 72,369 Bytes
e4fcc0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# =========================================================
# POSCO DX - MRO Composite AI - PROCESS GUIDE ENHANCED
# 업무 ν”„λ‘œμ„ΈμŠ€ κ°€μ΄λ“œ 톡합 버전 - Hugging Face Spaces 배포용
# =========================================================

import os
import json
import time
import random
import traceback
from dataclasses import dataclass
from typing import Dict, Any, List, Optional, Tuple, TypedDict
from datetime import datetime, timedelta

import numpy as np
import pandas as pd
import networkx as nx

# βœ… Plotly imports
import plotly
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots

print(f"βœ… NumPy: {np.__version__}")
print(f"βœ… Pandas: {pd.__version__}")
print(f"βœ… Plotly: {plotly.__version__}")

try:
    from pulp import LpProblem, LpMinimize, LpVariable, lpSum, LpStatus
    PULP_AVAILABLE = True
    print("βœ… PuLP available")
except ImportError:
    print("⚠️ PuLP not available")
    PULP_AVAILABLE = False

import gradio as gr
print(f"βœ… Gradio: {gr.__version__}")

try:
    from langgraph.graph import StateGraph, END
    LANGGRAPH_AVAILABLE = True
    print("βœ… LangGraph available")
except ImportError:
    print("⚠️ LangGraph not available")
    LANGGRAPH_AVAILABLE = False

try:
    from openai import OpenAI
    OPENAI_AVAILABLE = True
    print("βœ… OpenAI available")
except ImportError:
    print("⚠️ OpenAI not available")
    OPENAI_AVAILABLE = False

# =========================================================
# API Key Configuration for Hugging Face Spaces
# =========================================================
# Hugging Face Spacesμ—μ„œ ν™˜κ²½ λ³€μˆ˜λ‘œ API ν‚€ λ‘œλ“œ
OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY', '').strip()

if OPENAI_API_KEY:
    os.environ['OPENAI_API_KEY'] = OPENAI_API_KEY
    print("βœ… OpenAI API Key loaded from environment")
else:
    print("⚠️ DEMO MODE - No API Key found")
    print("πŸ’‘ To use OpenAI features, add OPENAI_API_KEY to your Hugging Face Space Secrets")

print("\n" + "=" * 60)
print("βœ… ν”„λ‘œμ„ΈμŠ€ κ°€μ΄λ“œ 톡합 버전 μ΄ˆκΈ°ν™” μ™„λ£Œ!")
print("=" * 60 + "\n")

# =========================================================
# Process Guide Configuration
# =========================================================
PROCESS_WORKFLOWS = {
    "mro": {
        "title": "πŸ”§ MRO 운영 ν”„λ‘œμ„ΈμŠ€",
        "steps": [
            {
                "id": "1",
                "name": "κ³ μž₯/μ •λΉ„ μš”μ²­ μ ‘μˆ˜",
                "description": "μ„€λΉ„ κ³ μž₯ λ˜λŠ” μ˜ˆλ°©μ •λΉ„ μš”μ²­μ„ μ ‘μˆ˜ν•©λ‹ˆλ‹€",
                "input": "μ„€λΉ„ ID, κ³ μž₯ μœ ν˜•, μš°μ„ μˆœμœ„",
                "output": "μš”μ²­ 번호, μ„€λΉ„ 상세정보",
                "owner": "ν˜„μž₯ λ‹΄λ‹Ήμž β†’ MROνŒ€",
                "duration": "5λΆ„"
            },
            {
                "id": "2",
                "name": "μ„€λΉ„ 정보 쑰회",
                "description": "Knowledge Graphμ—μ„œ μ„€λΉ„ 상세 정보λ₯Ό μ‘°νšŒν•©λ‹ˆλ‹€",
                "input": "μ„€λΉ„ ID",
                "output": "μ„€λΉ„λͺ…, μœ„μΉ˜, μ€‘μš”λ„, 정비이λ ₯",
                "owner": "MROνŒ€ (AI μžλ™)",
                "duration": "1λΆ„"
            },
            {
                "id": "3",
                "name": "ν˜Έν™˜ λΆ€ν’ˆ μžλ™ λ§€μΉ­",
                "description": "섀비와 ν˜Έν™˜λ˜λŠ” λͺ¨λ“  λΆ€ν’ˆμ„ μžλ™μœΌλ‘œ μ‘°νšŒν•©λ‹ˆλ‹€",
                "input": "μ„€λΉ„ ID, μ„€λΉ„ νƒ€μž…",
                "output": "ν˜Έν™˜ λΆ€ν’ˆ 리슀트, ν•„μˆ˜/선택 ꡬ뢄",
                "owner": "MROνŒ€ (AI μžλ™)",
                "duration": "2λΆ„"
            },
            {
                "id": "4",
                "name": "전사 재고 ν˜„ν™© 확인",
                "description": "본사 및 각 μ œμ² μ†Œμ˜ 재고 ν˜„ν™©μ„ μ‹€μ‹œκ°„ ν™•μΈν•©λ‹ˆλ‹€",
                "input": "ν’ˆλͺ© ID",
                "output": "창고별 μž¬κ³ λŸ‰, μ•ˆμ „μž¬κ³ , μ˜ˆμ•½μˆ˜λŸ‰",
                "owner": "MROνŒ€ (AI μžλ™)",
                "duration": "1λΆ„"
            },
            {
                "id": "5",
                "name": "발주 ν•„μš”μ„± νŒλ‹¨",
                "description": "재고 λΆ€μ‘± μ‹œ 발주 μš”μ²­μ„ μƒμ„±ν•©λ‹ˆλ‹€",
                "input": "ν˜„μž¬κ³ , μ•ˆμ „μž¬κ³ , μˆ˜μš”λŸ‰",
                "output": "발주 ν•„μš” μ—¬λΆ€, 발주 μˆ˜λŸ‰",
                "owner": "MROνŒ€",
                "duration": "3λΆ„"
            },
            {
                "id": "6",
                "name": "κ΅¬λ§€νŒ€ 발주 μš”μ²­",
                "description": "κ΅¬λ§€νŒ€μ— 발주 μš”μ²­μ„œλ₯Ό μ „λ‹¬ν•©λ‹ˆλ‹€",
                "input": "ν’ˆλͺ© 정보, μˆ˜λŸ‰, λ‚©κΈ° μš”κ΅¬μ‚¬ν•­",
                "output": "발주 μš”μ²­ 번호",
                "owner": "MROνŒ€ β†’ κ΅¬λ§€νŒ€",
                "duration": "2λΆ„"
            }
        ],
        "total_duration": "μ•½ 15λΆ„",
        "success_criteria": [
            "βœ“ μ„€λΉ„ 정보 μ •ν™•νžˆ 식별",
            "βœ“ ν˜Έν™˜ λΆ€ν’ˆ 100% λ§€μΉ­",
            "βœ“ 재고 ν˜„ν™© μ‹€μ‹œκ°„ 반영",
            "βœ“ 발주 μˆ˜λŸ‰ μ΅œμ ν™”"
        ]
    },
    "procurement": {
        "title": "πŸ’° ꡬ맀/쑰달 ν”„λ‘œμ„ΈμŠ€",
        "steps": [
            {
                "id": "1",
                "name": "발주 μš”μ²­ μ ‘μˆ˜",
                "description": "MROνŒ€μœΌλ‘œλΆ€ν„° 발주 μš”μ²­μ„ μ ‘μˆ˜ν•©λ‹ˆλ‹€",
                "input": "발주 μš”μ²­μ„œ, ν’ˆλͺ©, μˆ˜λŸ‰, λ‚©κΈ°",
                "output": "ꡬ맀 μž‘μ—… 번호",
                "owner": "κ΅¬λ§€νŒ€",
                "duration": "3λΆ„"
            },
            {
                "id": "2",
                "name": "곡급업체 정보 쑰회",
                "description": "ν’ˆλͺ©λ³„ λ“±λ‘λœ λͺ¨λ“  곡급업체λ₯Ό μ‘°νšŒν•©λ‹ˆλ‹€",
                "input": "ν’ˆλͺ© ID",
                "output": "곡급업체 리슀트, 단가, λ‚©κΈ°, ESGλ“±κΈ‰",
                "owner": "κ΅¬λ§€νŒ€ (AI μžλ™)",
                "duration": "2λΆ„"
            },
            {
                "id": "3",
                "name": "κ·œμ • μ€€μˆ˜ 검증",
                "description": "Neuro-Symbolic AI둜 ꡬ맀 κ·œμ •μ„ μžλ™ κ²€μ¦ν•©λ‹ˆλ‹€",
                "input": "ν’ˆλͺ© 속성, 곡급업체 정보",
                "output": "κ·œμ • μœ„λ°˜ μ—¬λΆ€, 차단/κ²½κ³  리슀트",
                "owner": "κ΅¬λ§€νŒ€ (AI μžλ™)",
                "duration": "1λΆ„"
            },
            {
                "id": "4",
                "name": "졜적 λ°°λΆ„ 계산",
                "description": "Linear Programming으둜 졜적 발주 κ³„νšμ„ μˆ˜λ¦½ν•©λ‹ˆλ‹€",
                "input": "곡급업체 였퍼, μˆ˜μš”λŸ‰, μ œμ•½μ‘°κ±΄",
                "output": "업체별 λ°œμ£ΌλŸ‰, 총 λΉ„μš©, μ˜ˆμƒ λ‚©κΈ°",
                "owner": "κ΅¬λ§€νŒ€ (AI μžλ™)",
                "duration": "2λΆ„"
            },
            {
                "id": "5",
                "name": "발주 μ „λž΅ 수립",
                "description": "LLM이 μ΅œμ ν™” κ²°κ³Όλ₯Ό λ°”νƒ•μœΌλ‘œ ꡬ맀 μ „λž΅μ„ μ œμ•ˆν•©λ‹ˆλ‹€",
                "input": "μ΅œμ ν™” κ²°κ³Ό, μ‹œμž₯ 상황",
                "output": "발주 μ „λž΅, 리슀크 뢄석, λŒ€μ•ˆ",
                "owner": "κ΅¬λ§€νŒ€ (AI 지원)",
                "duration": "5λΆ„"
            },
            {
                "id": "6",
                "name": "κ²½μ˜μ§„ 승인 μš”μ²­",
                "description": "발주 κ³„νšμ„ κ²½μ˜μ§„μ—κ²Œ 승인 μš”μ²­ν•©λ‹ˆλ‹€",
                "input": "발주 κ³„νšμ„œ, λΉ„μš© 뢄석",
                "output": "승인 μš”μ²­ 번호",
                "owner": "κ΅¬λ§€νŒ€ β†’ κ²½μ˜μ§„",
                "duration": "3λΆ„"
            },
            {
                "id": "7",
                "name": "PO λ°œν–‰ (승인 ν›„)",
                "description": "승인 ν›„ 곡급업체에 정식 λ°œμ£Όμ„œλ₯Ό λ°œν–‰ν•©λ‹ˆλ‹€",
                "input": "승인된 발주 κ³„νš",
                "output": "PO 번호, κ³„μ•½μ„œ",
                "owner": "κ΅¬λ§€νŒ€",
                "duration": "10λΆ„"
            }
        ],
        "total_duration": "μ•½ 25λΆ„ (승인 λŒ€κΈ° μ œμ™Έ)",
        "success_criteria": [
            "βœ“ κ·œμ • 100% μ€€μˆ˜",
            "βœ“ λΉ„μš© μ΅œμ ν™” 달성",
            "βœ“ λ‚©κΈ° μš”κ΅¬μ‚¬ν•­ μΆ©μ‘±",
            "βœ“ ESG λ“±κΈ‰ κΈ°μ€€ 만쑱"
        ]
    },
    "executive": {
        "title": "πŸ‘” κ²½μ˜μ§„ μ˜μ‚¬κ²°μ • ν”„λ‘œμ„ΈμŠ€",
        "steps": [
            {
                "id": "1",
                "name": "승인 μš”μ²­ μ•Œλ¦Ό",
                "description": "발주 승인 μš”μ²­ μ•Œλ¦Όμ„ μˆ˜μ‹ ν•©λ‹ˆλ‹€",
                "input": "승인 μš”μ²­ 번호, μš”μ•½ 정보",
                "output": "μ•Œλ¦Ό 확인",
                "owner": "μ‹œμŠ€ν…œ β†’ κ²½μ˜μ§„",
                "duration": "μ¦‰μ‹œ"
            },
            {
                "id": "2",
                "name": "KPI λŒ€μ‹œλ³΄λ“œ 확인",
                "description": "μ‹€μ‹œκ°„ KPI λŒ€μ‹œλ³΄λ“œλ₯Ό 톡해 μ „λ°˜μ  ν˜„ν™©μ„ νŒŒμ•…ν•©λ‹ˆλ‹€",
                "input": "μ—†μŒ",
                "output": "λΉ„μš©μ ˆκ°λ₯ , μ»΄ν”ŒλΌμ΄μ–ΈμŠ€, ESG점수 λ“±",
                "owner": "κ²½μ˜μ§„",
                "duration": "2λΆ„"
            },
            {
                "id": "3",
                "name": "Action Items κ²€ν† ",
                "description": "μš°μ„ μˆœμœ„λ³„ 쑰치 ν•­λͺ©μ„ κ²€ν† ν•©λ‹ˆλ‹€",
                "input": "Action Items 리슀트",
                "output": "κ²€ν†  의견",
                "owner": "κ²½μ˜μ§„",
                "duration": "5λΆ„"
            },
            {
                "id": "4",
                "name": "발주 상세 뢄석",
                "description": "발주 κ³„νšμ˜ 타당성을 λ©΄λ°€νžˆ κ²€ν† ν•©λ‹ˆλ‹€",
                "input": "발주 κ³„νšμ„œ, μ΅œμ ν™” κ²°κ³Ό, κ·œμ • 검증",
                "output": "뢄석 의견",
                "owner": "κ²½μ˜μ§„",
                "duration": "10λΆ„"
            },
            {
                "id": "5",
                "name": "μ˜μ‚¬κ²°μ •",
                "description": "승인/반렀/μ‘°κ±΄λΆ€μŠΉμΈμ„ κ²°μ •ν•©λ‹ˆλ‹€",
                "input": "κ²€ν†  κ²°κ³Ό",
                "output": "승인 κ²°μ •, ν”Όλ“œλ°±",
                "owner": "κ²½μ˜μ§„",
                "duration": "3λΆ„"
            },
            {
                "id": "6",
                "name": "ν”Όλ“œλ°± 제곡",
                "description": "κ°œμ„  μ œμ•ˆ λ˜λŠ” μ§€μ‹œμ‚¬ν•­μ„ μ „λ‹¬ν•©λ‹ˆλ‹€",
                "input": "μ˜μ‚¬κ²°μ • κ·Όκ±°",
                "output": "ν”Όλ“œλ°± λ©”μ‹œμ§€, κ°œμ„  λ°©ν–₯",
                "owner": "κ²½μ˜μ§„ β†’ κ΅¬λ§€νŒ€",
                "duration": "5λΆ„"
            }
        ],
        "total_duration": "μ•½ 25λΆ„",
        "success_criteria": [
            "βœ“ μ „λž΅μ  타당성 검증",
            "βœ“ 리슀크 수용 κ°€λŠ₯ μˆ˜μ€€",
            "βœ“ μ˜ˆμ‚° λ²”μœ„ λ‚΄ μ§‘ν–‰",
            "βœ“ μž₯κΈ° λͺ©ν‘œ λΆ€ν•©"
        ]
    }
}

# =========================================================
# Enhanced Configuration with Real Part Names
# =========================================================
SCENARIO_PRESETS = {
    "κΈ΄κΈ‰ κ³ μž₯ λŒ€μ‘": {
        "description": "🚨 ν¬ν•­μ œμ² μ†Œ 컨베이어 베어링 κΈ΄κΈ‰ κ³ μž₯",
        "equipment_id": "CONV-PH-007",
        "item_id": "",
        "demand_qty": 10,
        "context": "컨베이어 베어링 κ³ μž₯으둜 생산라인 쀑단. μ¦‰μ‹œ ꡐ체 ν•„μš”.",
        "priority": "κΈ΄κΈ‰",
        "guide": "λ¦¬λ“œνƒ€μž„ μ΅œμ†Œν™” μš°μ„ . κ΅­λ‚΄ 곡급업체 μš°μ„  κ³ λ €."
    },
    "μ •κΈ° 발주 κ³„νš": {
        "description": "πŸ“‹ μ›”κ°„ μ •κΈ° 발주 - μœ μ••νŽŒν”„ μ˜ˆλ°©μ •λΉ„",
        "equipment_id": "PUMP-GY-003",
        "item_id": "SEAL-A45",
        "demand_qty": 50,
        "context": "μ›”κ°„ μ˜ˆλ°©μ •λΉ„ κ³„νš. 졜적 가격 및 재고 κ· ν˜• ν•„μš”.",
        "priority": "정상",
        "guide": "λΉ„μš© μ΅œμ ν™” μš°μ„ . ESG λ“±κΈ‰ κ³ λ €."
    },
    "κ·œμ • μ€€μˆ˜ 검증": {
        "description": "βš–οΈ κ·œμ œν’ˆλͺ©(νŠΉμˆ˜ν™”ν•™λ¬Όμ§ˆ) ꡬ맀 검증",
        "equipment_id": "VALVE-PH-005",
        "item_id": "",
        "demand_qty": 20,
        "context": "특수 μ‹€λ§μž¬ ꡬ맀. 해외ꡬ맀 차단 κ·œμ • μ€€μˆ˜ ν•„μˆ˜.",
        "priority": "κ·œμ •μ€€μˆ˜",
        "guide": "μ»΄ν”ŒλΌμ΄μ–ΈμŠ€ 100% μ€€μˆ˜. κ΅­λ‚΄μ—…μ²΄λ§Œ ν—ˆμš©."
    }
}

# Real part names and categories
REAL_PART_NAMES = {
    "베어링": ["SKF 6205 볼베어링", "NSK 원톡베어링", "NTN ν…Œμ΄νΌλ² μ–΄λ§"],
    "μœ€ν™œμœ ": ["μ‰˜ 였마라 220", "λͺ¨λΉŒ DTE 25", "μ§€μ—μŠ€μΉΌν…μŠ€ ν„°λΉˆμœ "],
    "ν•„ν„°": ["ν•˜μ΄λ“œλ‘œλ½ μœ μ••ν•„ν„°", "파컀 에어필터", "λ„λ‚œλ“œμŠ¨ μ •λ°€ν•„ν„°"],
    "벨트": ["게이츠 νŒŒμ›Œκ·Έλ¦½ 벨트", "λ°˜λ„ V벨트", "μ˜΅ν‹°λ²¨νŠΈ νƒ€μ΄λ°λ²¨νŠΈ"],
    "μ„Όμ„œ": ["μ§€λ©˜μŠ€ κ·Όμ ‘μ„Όμ„œ", "μ˜€λ―€λ‘  κ΄‘μ „μ„Όμ„œ", "ν•˜λ‹ˆμ›° μ••λ ₯μ„Όμ„œ"],
    "νŒ¨ν‚Ή": ["NOK 였링", "파컀 μœ μ••μ”°", "발카 κ·Έλžœλ“œνŒ¨ν‚Ή"],
    "ν“¨μ¦ˆ": ["LSμ‚°μ „ MCCB", "μŠˆλ‚˜μ΄λ” 차단기", "ABB ν“¨μ¦ˆ"],
    "호슀": ["파컀 μœ μ••ν˜ΈμŠ€", "만리 κ³ μ••ν˜ΈμŠ€", "λΈŒλ¦¬μ§€μŠ€ν†€ μ‚°μ—…ν˜ΈμŠ€"],
    "볼트": ["SUS304 윑각볼트", "κ³ μž₯λ ₯볼트 F10T", "μ•΅μ»€λ³ΌνŠΈ M16"],
    "μ‹€λ§μž¬": ["λ‘νƒ€μ΄νŠΈ μ‹€λž€νŠΈ", "μ“°λ¦¬λ³Έλ“œ μ•‘μƒνŒ¨ν‚Ή", "ν—¨μΌˆ λ°€λ΄‰μž¬"]
}

# Enhanced supplier info
REAL_SUPPLIERS = [
    {"name": "ν¬μŠ€μ½”μΌ€λ―ΈμΉΌ", "type": "κ΅­λ‚΄", "esg": "A", "specialty": "ν™”ν•™/μœ€ν™œμœ "},
    {"name": "νš¨μ„±μ€‘κ³΅μ—…", "type": "κ΅­λ‚΄", "esg": "A", "specialty": "베어링/기계"},
    {"name": "LSμ‚°μ „", "type": "κ΅­λ‚΄", "esg": "B", "specialty": "μ „κΈ°/μ„Όμ„œ"},
    {"name": "μ‚Όν™”μ½˜λ΄μ„œ", "type": "κ΅­λ‚΄", "esg": "B", "specialty": "μ „κΈ°λΆ€ν’ˆ"},
    {"name": "νƒœκ΄‘μ‚°μ—…", "type": "κ΅­λ‚΄", "esg": "C", "specialty": "호슀/νŒ¨ν‚Ή"},
    {"name": "ν•œκ΅­νŒŒμ»€", "type": "κ΅­λ‚΄", "esg": "A", "specialty": "μœ μ••λΆ€ν’ˆ"},
    {"name": "그라코(Graco)", "type": "ν•΄μ™Έ", "esg": "B", "specialty": "μœ μ••μž₯λΉ„"},
    {"name": "μ—λ¨ΈμŠ¨(Emerson)", "type": "ν•΄μ™Έ", "esg": "C", "specialty": "밸브/μ„Όμ„œ"}
]

# =========================================================
# Utility Functions
# =========================================================
def now_ts() -> str:
    return time.strftime("%Y-%m-%d %H:%M:%S")

def safe_json(obj: Any) -> str:
    try:
        return json.dumps(obj, ensure_ascii=False, indent=2)
    except Exception:
        return str(obj)

def format_status(status_dict: Dict[str, Any]) -> str:
    lines = [
        "=" * 60,
        "πŸ“Š μ‹œμŠ€ν…œ μ‹€ν–‰ μƒνƒœ",
        "=" * 60,
        "",
        f"πŸ”Œ μ—°κ²°: {status_dict.get('mode', 'Unknown')}",
        f"🎯 μ‹œλ‚˜λ¦¬μ˜€: {status_dict.get('scenario', 'N/A')}",
        f"βš™οΈ μ„€λΉ„: {status_dict.get('equipment', 'N/A')}",
        f"πŸ“¦ ν’ˆλͺ©: {status_dict.get('item_name', 'N/A')}",
        f"πŸ“Š μˆ˜μš”: {status_dict.get('demand', 'N/A')}개",
        f"🚨 μš°μ„ μˆœμœ„: {status_dict.get('priority', 'N/A')}",
        f"\nβœ… 데이터 검증: {'톡과' if status_dict.get('tables_ok') else 'μ‹€νŒ¨'}",
        f"⏱️ μ§„ν–‰: {status_dict.get('progress', 'N/A')}",
        "\n" + "=" * 60
    ]
    return "\n".join(lines)

def create_process_guide_html(process_key: str) -> str:
    """업무 ν”„λ‘œμ„ΈμŠ€ κ°€μ΄λ“œλ₯Ό HTML둜 생성"""
    workflow = PROCESS_WORKFLOWS.get(process_key, {})
    
    if not workflow:
        return "<p>ν”„λ‘œμ„ΈμŠ€ 정보가 μ—†μŠ΅λ‹ˆλ‹€.</p>"
    
    html = f"""
    <div style="font-family: 'Malgun Gothic', Arial, sans-serif; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 10px; color: white;">
        <h2 style="margin-top: 0;">{workflow['title']}</h2>
        <p style="font-size: 14px; opacity: 0.9;">총 μ†Œμš”μ‹œκ°„: <strong>{workflow['total_duration']}</strong></p>
    </div>
    
    <div style="margin-top: 20px;">
    """
    
    for step in workflow['steps']:
        html += f"""
        <div style="margin-bottom: 20px; padding: 15px; border-left: 4px solid #667eea; background: #f8f9fa; border-radius: 5px;">
            <div style="display: flex; align-items: center; margin-bottom: 10px;">
                <div style="background: #667eea; color: white; width: 30px; height: 30px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; margin-right: 10px;">
                    {step['id']}
                </div>
                <h3 style="margin: 0; color: #2c3e50;">{step['name']}</h3>
                <span style="margin-left: auto; background: #e3f2fd; padding: 3px 10px; border-radius: 10px; font-size: 12px; color: #1976d2;">
                    ⏱️ {step['duration']}
                </span>
            </div>
            
            <p style="margin: 10px 0; color: #555;">{step['description']}</p>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 10px;">
                <div style="background: white; padding: 10px; border-radius: 5px; border: 1px solid #e0e0e0;">
                    <strong style="color: #1976d2;">πŸ“₯ μž…λ ₯:</strong><br>
                    <span style="font-size: 13px; color: #666;">{step['input']}</span>
                </div>
                <div style="background: white; padding: 10px; border-radius: 5px; border: 1px solid #e0e0e0;">
                    <strong style="color: #388e3c;">πŸ“€ 좜λ ₯:</strong><br>
                    <span style="font-size: 13px; color: #666;">{step['output']}</span>
                </div>
            </div>
            
            <div style="margin-top: 10px; padding: 8px; background: white; border-radius: 5px; border: 1px solid #e0e0e0;">
                <strong style="color: #f57c00;">πŸ‘€ λ‹΄λ‹Ή:</strong> 
                <span style="font-size: 13px; color: #666;">{step['owner']}</span>
            </div>
        </div>
        """
    
    html += """
    </div>
    
    <div style="margin-top: 30px; padding: 20px; background: #e8f5e9; border-radius: 10px; border-left: 4px solid #4caf50;">
        <h3 style="margin-top: 0; color: #2e7d32;">βœ… 성곡 κΈ°μ€€</h3>
        <ul style="margin: 0; padding-left: 20px;">
    """
    
    for criterion in workflow['success_criteria']:
        html += f"<li style='margin: 5px 0; color: #1b5e20;'>{criterion}</li>"
    
    html += """
        </ul>
    </div>
    """
    
    return html

# =========================================================
# Enhanced Data Generator with Real Names
# =========================================================
def generate_demo_tables(seed: int = 7) -> Dict[str, pd.DataFrame]:
    """Generate realistic demo data"""
    random.seed(seed)
    np.random.seed(seed)

    plants = pd.DataFrame([
        {"plant_id": "PH", "plant_name": "ν¬ν•­μ œμ² μ†Œ", "region": "경뢁", "capacity": 1000},
        {"plant_id": "GY", "plant_name": "κ΄‘μ–‘μ œμ² μ†Œ", "region": "전남", "capacity": 1200},
        {"plant_id": "HQ", "plant_name": "본사", "region": "μ„œμšΈ", "capacity": 0},
    ])

    # Equipment with real names
    equipment = []
    eq_configs = [
        ("PUMP", "μœ μ••νŽŒν”„", ["PH", "GY"], 6),
        ("CONV", "컨베이어", ["PH", "GY"], 4),
        ("VALVE", "μ œμ–΄λ°ΈλΈŒ", ["PH", "GY"], 3),
        ("MOTOR", "ꡬ동λͺ¨ν„°", ["PH", "GY"], 5),
    ]
    
    eq_id = 1
    for eq_type, eq_name_kr, plants_list, count in eq_configs:
        for plant in plants_list:
            for i in range(1, count + 1):
                equipment.append({
                    "equipment_id": f"{eq_type}-{plant}-{eq_id:03d}",
                    "equipment_name": f"{eq_name_kr}-{plant}-{i}호기",
                    "plant_id": plant,
                    "equipment_type": eq_name_kr,
                    "criticality": random.choice(["κΈ΄κΈ‰", "κΈ΄κΈ‰", "μ€‘μš”", "보톡"]),
                    "status": "가동쀑",
                    "last_maintenance": (datetime.now() - timedelta(days=random.randint(30, 180))).strftime("%Y-%m-%d"),
                })
                eq_id += 1
    equipment = pd.DataFrame(equipment)

    # Items with real part names
    items = []
    item_id = 1
    for category, part_list in REAL_PART_NAMES.items():
        for part_name in part_list:
            items.append({
                "item_id": f"{category[:3].upper()}-{chr(65 + (item_id % 3))}{item_id:02d}",
                "item_name": part_name,
                "category": category,
                "uom": "EA",
                "risk_class": "규제" if "ν™”ν•™" in part_name or "특수" in category else "일반",
                "unit_weight": round(0.5 + random.random() * 5, 1),
                "shelf_life_days": random.choice([365, 730, 1095, None]),
            })
            item_id += 1
    items = pd.DataFrame(items)

    # Compatibility
    compat = []
    for eq_idx, eq_row in equipment.iterrows():
        eq_id = eq_row["equipment_id"]
        eq_type = eq_row["equipment_type"]
        
        # Match parts to equipment type
        if "νŽŒν”„" in eq_type:
            relevant_cats = ["베어링", "μœ€ν™œμœ ", "νŒ¨ν‚Ή"]
        elif "컨베이어" in eq_type:
            relevant_cats = ["베어링", "벨트", "μ„Όμ„œ"]
        elif "밸브" in eq_type:
            relevant_cats = ["μ‹€λ§μž¬", "νŒ¨ν‚Ή", "μœ€ν™œμœ "]
        else:
            relevant_cats = ["베어링", "μ„Όμ„œ", "ν•„ν„°"]
        
        for cat in relevant_cats:
            cat_items = items[items["category"] == cat]
            if len(cat_items) > 0:
                selected = cat_items.sample(min(2, len(cat_items)))
                for _, item in selected.iterrows():
                    compat.append({
                        "equipment_id": eq_id,
                        "item_id": item["item_id"],
                        "is_mandatory": (cat == relevant_cats[0]),
                        "annual_consumption_est": random.randint(20, 200),
                        "failure_rate": round(random.random() * 0.05, 3),
                    })
    compat = pd.DataFrame(compat).drop_duplicates(["equipment_id", "item_id"])

    # Storages
    storages = pd.DataFrame([
        {"storage_id": "WH-HQ", "plant_id": "HQ", "storage_name": "본사 쀑앙창고", "capacity": 10000},
        {"storage_id": "WH-PH", "plant_id": "PH", "storage_name": "포항 MROμ°½κ³ ", "capacity": 5000},
        {"storage_id": "WH-GY", "plant_id": "GY", "storage_name": "κ΄‘μ–‘ MROμ°½κ³ ", "capacity": 5000},
    ])

    # Inventory with realistic levels
    inventory = []
    for st_idx, st_row in storages.iterrows():
        sampled_items = items.sample(min(25, len(items)))
        for _, item in sampled_items.iterrows():
            stock_level = random.randint(10, 100)
            safety_stock = int(stock_level * 0.2)
            inventory.append({
                "storage_id": st_row["storage_id"],
                "item_id": item["item_id"],
                "on_hand": stock_level,
                "safety_stock": safety_stock,
                "reserved": random.randint(0, min(5, stock_level)),
                "last_updated": (datetime.now() - timedelta(days=random.randint(1, 30))).strftime("%Y-%m-%d"),
            })
    inventory = pd.DataFrame(inventory)

    # Suppliers with real names
    suppliers = pd.DataFrame([
        {
            "supplier_id": f"SUP-{i:03d}",
            "supplier_name": sup["name"],
            "supplier_type": sup["type"],
            "rating": round(3.5 + random.random() * 1.5, 1),
            "esg_level": sup["esg"],
            "specialty": sup["specialty"],
            "region": sup["type"],
            "payment_terms": random.choice(["NET30", "NET45", "NET60"]),
            "established_year": random.randint(1990, 2020),
        }
        for i, sup in enumerate(REAL_SUPPLIERS, 1)
    ])

    # Supplier offers with realistic pricing
    offers = []
    for _, item in items.iterrows():
        num_suppliers = random.randint(3, 4)
        selected_sups = suppliers.sample(min(num_suppliers, len(suppliers)))
        
        base_price = 10000 + random.randint(0, 90000)
        
        for rank, (_, sup) in enumerate(selected_sups.iterrows()):
            price_multiplier = 1.0 + (rank * 0.05) + random.uniform(-0.1, 0.1)
            
            offers.append({
                "item_id": item["item_id"],
                "supplier_id": sup["supplier_id"],
                "unit_price": int(base_price * price_multiplier),
                "lead_time_days": 3 + rank * 2 + random.randint(0, 5),
                "moq": [10, 20, 50, 100][rank % 4],
                "contract_type": random.choice(["단가계약", "μž₯기계약", "슀팟"]),
                "discount_rate": round(random.random() * 0.1, 2) if rank == 0 else 0,
                "quality_grade": random.choice(["A", "A", "B", "C"]),
            })
    supplier_offers = pd.DataFrame(offers)

    # Policies
    policies = pd.DataFrame([
        {
            "policy_id": "R-001",
            "rule_name": "κ·œμ œν’ˆλͺ© 해외ꡬ맀 μ œν•œ", 
            "rule_logic": "IF item.risk_class == '규제' AND supplier.region == 'ν•΄μ™Έ' THEN block",
            "severity": "차단",
            "department": "λ²•λ¬΄νŒ€"
        },
        {
            "policy_id": "R-002",
            "rule_name": "μ•ˆμ „μž¬κ³  미만 κΈ΄κΈ‰λ°œμ£Ό",
            "rule_logic": "IF (on_hand - reserved) < safety_stock THEN expedite",
            "severity": "κ²½κ³ ",
            "department": "MROνŒ€"
        },
        {
            "policy_id": "R-003",
            "rule_name": "κΈ΄κΈ‰μ„€λΉ„ μš°μ„ λ°°λΆ„",
            "rule_logic": "IF equipment.criticality == 'κΈ΄κΈ‰' THEN priority",
            "severity": "μš°μ„ μˆœμœ„",
            "department": "μƒμ‚°νŒ€"
        },
        {
            "policy_id": "R-004",
            "rule_name": "ESG Cλ“±κΈ‰ μ œν•œ",
            "rule_logic": "IF supplier.esg_level == 'C' THEN penalize",
            "severity": "νŒ¨λ„ν‹°",
            "department": "κ΅¬λ§€νŒ€"
        },
    ])

    # Purchase history
    purchase_history = []
    for i in range(200):
        item = items.sample(1).iloc[0]
        supplier = suppliers.sample(1).iloc[0]
        qty = random.randint(10, 100)
        price = random.randint(10000, 100000)
        
        purchase_history.append({
            "po_id": f"PO-2024-{10000 + i}",
            "date": (datetime.now() - timedelta(days=random.randint(1, 365))).strftime("%Y-%m-%d"),
            "item_id": item["item_id"],
            "supplier_id": supplier["supplier_id"],
            "qty": qty,
            "unit_price": price,
            "total_amount": qty * price,
            "delivery_status": random.choice(["μ™„λ£Œ", "μ™„λ£Œ", "μ™„λ£Œ", "μ§€μ—°", "진행쀑"]),
        })
    purchase_history = pd.DataFrame(purchase_history)

    return {
        "plants": plants,
        "equipment": equipment,
        "items": items,
        "compat": compat,
        "storages": storages,
        "inventory": inventory,
        "suppliers": suppliers,
        "supplier_offers": supplier_offers,
        "policies": policies,
        "purchase_history": purchase_history
    }

def validate_tables(tables: Dict[str, pd.DataFrame]) -> Tuple[bool, List[str]]:
    """Validate tables"""
    required = ["plants", "equipment", "items", "compat", "storages", "inventory",
                "suppliers", "supplier_offers", "policies", "purchase_history"]
    
    issues = []
    for k in required:
        if k not in tables:
            issues.append(f"Missing: {k}")
        elif not isinstance(tables[k], pd.DataFrame):
            issues.append(f"Invalid type: {k}")
        elif len(tables[k]) == 0:
            issues.append(f"Empty: {k}")
    
    return len(issues) == 0, issues

# =========================================================
# Plotly Dashboard Functions
# =========================================================
def create_mro_inventory_dashboard(inv_df: pd.DataFrame, item_name: str) -> go.Figure:
    """MRO 재고 ν˜„ν™© λŒ€μ‹œλ³΄λ“œ"""
    if len(inv_df) == 0:
        fig = go.Figure()
        fig.add_annotation(text="재고 데이터 μ—†μŒ", showarrow=False, font_size=20)
        fig.update_layout(height=700, title_text="재고 정보 μ—†μŒ")
        return fig
    
    # μ„œλΈŒν”Œλ‘― 생성
    fig = make_subplots(
        rows=2, cols=2,
        subplot_titles=('창고별 재고 ν˜„ν™©', 'μ•ˆμ „μž¬κ³  λŒ€λΉ„ ν˜„μž¬κ³ ', '재고 μƒνƒœ', '창고별 점유율'),
        specs=[[{"type": "bar"}, {"type": "indicator"}],
               [{"type": "pie"}, {"type": "table"}]]
    )
    
    # 1. 창고별 재고 λ°” 차트
    fig.add_trace(
        go.Bar(
            x=inv_df['storage_name'],
            y=inv_df['on_hand'],
            name='ν˜„μž¬κ³ ',
            marker_color='lightblue',
            text=inv_df['on_hand'],
            textposition='auto',
        ),
        row=1, col=1
    )
    
    fig.add_trace(
        go.Bar(
            x=inv_df['storage_name'],
            y=inv_df['safety_stock'],
            name='μ•ˆμ „μž¬κ³ ',
            marker_color='orange',
            text=inv_df['safety_stock'],
            textposition='auto',
        ),
        row=1, col=1
    )
    
    # 2. 총 재고 κ²Œμ΄μ§€
    total_stock = inv_df['on_hand'].sum()
    total_safety = inv_df['safety_stock'].sum()
    
    fig.add_trace(
        go.Indicator(
            mode="gauge+number+delta",
            value=total_stock,
            delta={'reference': total_safety, 'increasing': {'color': "green"}},
            title={'text': f"총 μž¬κ³ λŸ‰<br><sub>{item_name}</sub>"},
            gauge={
                'axis': {'range': [0, total_safety * 2]},
                'bar': {'color': "darkblue"},
                'steps': [
                    {'range': [0, total_safety], 'color': "lightgray"},
                    {'range': [total_safety, total_safety * 1.5], 'color': "lightgreen"}
                ],
                'threshold': {
                    'line': {'color': "red", 'width': 4},
                    'thickness': 0.75,
                    'value': total_safety
                }
            }
        ),
        row=1, col=2
    )
    
    # 3. 재고 μƒνƒœ 파이 차트
    inv_df['available'] = inv_df['on_hand'] - inv_df['reserved']
    
    fig.add_trace(
        go.Pie(
            labels=['κ°€μš©μž¬κ³ ', 'μ˜ˆμ•½λ¨', 'μ•ˆμ „μž¬κ³ '],
            values=[
                inv_df['available'].sum(),
                inv_df['reserved'].sum(),
                max(0, total_safety - inv_df['available'].sum())
            ],
            marker_colors=['green', 'orange', 'red'],
            hole=0.3,
        ),
        row=2, col=1
    )
    
    # 4. 상세 ν…Œμ΄λΈ”
    fig.add_trace(
        go.Table(
            header=dict(
                values=['μ°½κ³ ', 'ν˜„μž¬κ³ ', 'μ•ˆμ „μž¬κ³ ', 'μ˜ˆμ•½', 'κ°€μš©'],
                fill_color='paleturquoise',
                align='left'
            ),
            cells=dict(
                values=[
                    inv_df['storage_name'],
                    inv_df['on_hand'],
                    inv_df['safety_stock'],
                    inv_df['reserved'],
                    inv_df['available']
                ],
                fill_color='lavender',
                align='left'
            )
        ),
        row=2, col=2
    )
    
    fig.update_layout(
        height=700,
        showlegend=True,
        title_text=f"πŸ“¦ MRO 재고 뢄석 λŒ€μ‹œλ³΄λ“œ - {item_name}",
        title_font_size=20
    )
    
    return fig

def create_mro_workflow_status(equipment_info: Dict, compat_items: pd.DataFrame) -> go.Figure:
    """MRO μ›Œν¬ν”Œλ‘œμš° μƒνƒœ μ‹œκ°ν™”"""
    fig = go.Figure()
    
    # μ›Œν¬ν”Œλ‘œμš° 단계
    steps = [
        "μ„€λΉ„ 확인",
        "ν˜Έν™˜λΆ€ν’ˆ 쑰회",
        "재고 확인",
        "μˆ˜μš” 검증",
        "발주 μš”μ²­"
    ]
    
    statuses = ["μ™„λ£Œ", "μ™„λ£Œ", "진행쀑", "λŒ€κΈ°", "λŒ€κΈ°"]
    colors = ["green", "green", "orange", "gray", "gray"]
    
    # Funnel 차트둜 μ›Œν¬ν”Œλ‘œμš° ν‘œν˜„
    fig.add_trace(go.Funnel(
        y=steps,
        x=[100, 80, 60, 40, 20],
        textposition="inside",
        textinfo="label+percent initial",
        marker={"color": colors},
        connector={"line": {"color": "royalblue", "width": 3}}
    ))
    
    equipment_name = equipment_info.get('equipment_name', 'N/A') if equipment_info else 'N/A'
    
    fig.update_layout(
        title_text=f"πŸ”„ MRO μ›Œν¬ν”Œλ‘œμš° μ§„ν–‰ μƒνƒœ<br><sub>μ„€λΉ„: {equipment_name}</sub>",
        height=400,
        showlegend=False
    )
    
    return fig

def create_procurement_comparison_dashboard(offers_df: pd.DataFrame, rules_eval: Dict) -> go.Figure:
    """ꡬ맀 λ‹΄λ‹Ήμž - 곡급업체 비ꡐ λŒ€μ‹œλ³΄λ“œ"""
    if len(offers_df) == 0:
        fig = go.Figure()
        fig.add_annotation(text="곡급업체 데이터 μ—†μŒ", showarrow=False, font_size=20)
        fig.update_layout(height=700, title_text="곡급업체 정보 μ—†μŒ")
        return fig
    
    # μ„œλΈŒν”Œλ‘―
    fig = make_subplots(
        rows=2, cols=2,
        subplot_titles=(
            'πŸ’° 가격 비ꡐ',
            '⏱️ λ‚©κΈ° 비ꡐ',
            'πŸ“Š ESG λ“±κΈ‰ 뢄포',
            '🎯 μ’…ν•© 평가'
        ),
        specs=[
            [{"type": "bar"}, {"type": "scatter"}],
            [{"type": "pie"}, {"type": "table"}]
        ]
    )
    
    # κ·œμΉ™ 평가 κ²°κ³Ό μΆ”κ°€
    offers_df['blocked'] = offers_df['supplier_id'].apply(
        lambda x: rules_eval.get(x, {}).get('block', False)
    )
    offers_df['color'] = offers_df['blocked'].apply(lambda x: 'red' if x else 'green')
    
    # 1. 가격 비ꡐ λ°” 차트
    fig.add_trace(
        go.Bar(
            x=offers_df['supplier_name'],
            y=offers_df['unit_price'],
            marker_color=offers_df['color'],
            text=[f"{p:,}원" for p in offers_df['unit_price']],
            textposition='auto',
            name='단가',
        ),
        row=1, col=1
    )
    
    # 2. 가격-λ‚©κΈ° μŠ€μΊν„°
    fig.add_trace(
        go.Scatter(
            x=offers_df['lead_time_days'],
            y=offers_df['unit_price'],
            mode='markers+text',
            marker=dict(
                size=15,
                color=offers_df['color'],
                line=dict(width=2, color='white')
            ),
            text=offers_df['supplier_name'],
            textposition="top center",
            name='곡급업체',
        ),
        row=1, col=2
    )
    
    # 3. ESG λ“±κΈ‰ 파이
    esg_counts = offers_df['esg_level'].value_counts()
    fig.add_trace(
        go.Pie(
            labels=esg_counts.index,
            values=esg_counts.values,
            marker_colors=['lightgreen', 'lightyellow', 'lightcoral'],
            hole=0.3,
        ),
        row=2, col=1
    )
    
    # 4. μ’…ν•© 평가 ν…Œμ΄λΈ”
    evaluation = offers_df.copy()
    evaluation['μ’…ν•©μ μˆ˜'] = (
        (100 - (evaluation['unit_price'] / evaluation['unit_price'].max() * 50)) +
        (100 - (evaluation['lead_time_days'] / evaluation['lead_time_days'].max() * 30)) +
        evaluation['esg_level'].map({'A': 20, 'B': 10, 'C': 0})
    ).round(1)
    evaluation['μˆœμœ„'] = evaluation['μ’…ν•©μ μˆ˜'].rank(ascending=False).astype(int)
    
    fig.add_trace(
        go.Table(
            header=dict(
                values=['μˆœμœ„', '곡급업체', '단가', 'λ‚©κΈ°', 'ESG', '점수'],
                fill_color='paleturquoise',
                align='center'
            ),
            cells=dict(
                values=[
                    evaluation['μˆœμœ„'],
                    evaluation['supplier_name'],
                    [f"{p:,}" for p in evaluation['unit_price']],
                    [f"{d}일" for d in evaluation['lead_time_days']],
                    evaluation['esg_level'],
                    evaluation['μ’…ν•©μ μˆ˜']
                ],
                fill_color=[['white' if not b else 'lightcoral' for b in evaluation['blocked']]],
                align='center'
            )
        ),
        row=2, col=2
    )
    
    fig.update_layout(
        height=700,
        showlegend=False,
        title_text="πŸ“Š 곡급업체 μ’…ν•© 비ꡐ λŒ€μ‹œλ³΄λ“œ",
        title_font_size=20
    )
    
    fig.update_xaxes(title_text="λ‚©κΈ° (일)", row=1, col=2)
    fig.update_yaxes(title_text="단가 (원)", row=1, col=2)
    
    return fig

def create_procurement_workflow(opt_result: Dict) -> go.Figure:
    """ꡬ맀 μ›Œν¬ν”Œλ‘œμš° μ§„ν–‰ μƒνƒœ"""
    fig = go.Figure()
    
    # μ›Œν¬ν”Œλ‘œμš° 단계와 μƒνƒœ
    workflow_steps = [
        {"step": "1. μˆ˜μš” μ ‘μˆ˜", "status": "μ™„λ£Œ", "time": "10λΆ„"},
        {"step": "2. 곡급업체 쑰회", "status": "μ™„λ£Œ", "time": "5λΆ„"},
        {"step": "3. κ·œμ • 검증", "status": "μ™„λ£Œ", "time": "2λΆ„"},
        {"step": "4. μ΅œμ ν™” 뢄석", "status": "μ™„λ£Œ", "time": "3λΆ„"},
        {"step": "5. 발주 승인", "status": "λŒ€κΈ°μ€‘", "time": "-"},
        {"step": "6. PO λ°œν–‰", "status": "λŒ€κΈ°μ€‘", "time": "-"},
    ]
    
    # Progress Bar μŠ€νƒ€μΌ
    y_pos = list(range(len(workflow_steps)))
    colors = []
    for step_info in workflow_steps:
        if step_info["status"] == "μ™„λ£Œ":
            colors.append("lightgreen")
        elif step_info["status"] == "진행쀑":
            colors.append("lightyellow")
        else:
            colors.append("lightgray")
    
    fig.add_trace(go.Bar(
        y=[s["step"] for s in workflow_steps],
        x=[100 if s["status"] == "μ™„λ£Œ" else 50 if s["status"] == "진행쀑" else 0 
           for s in workflow_steps],
        orientation='h',
        marker=dict(color=colors),
        text=[f"{s['status']} ({s['time']})" for s in workflow_steps],
        textposition='auto',
    ))
    
    fig.update_layout(
        title_text="πŸ”„ ꡬ맀 μ›Œν¬ν”Œλ‘œμš° μ§„ν–‰ ν˜„ν™©",
        xaxis_title="μ§„ν–‰λ₯  (%)",
        height=400,
        showlegend=False
    )
    
    return fig

def create_executive_kpi_dashboard(
    opt_result: Dict,
    offers_df: pd.DataFrame,
    purchase_history: pd.DataFrame
) -> go.Figure:
    """κ²½μ˜μ§„ KPI λŒ€μ‹œλ³΄λ“œ"""
    
    fig = make_subplots(
        rows=2, cols=3,
        subplot_titles=(
            'πŸ’° λΉ„μš© 절감',
            'βš–οΈ μ»΄ν”ŒλΌμ΄μ–ΈμŠ€',
            'πŸ“ˆ ESG 점수',
            '⏱️ 처리 μ‹œκ°„',
            '🎯 λͺ©ν‘œ 달성λ₯ ',
            'πŸ“Š μ›”κ°„ νŠΈλ Œλ“œ'
        ),
        specs=[
            [{"type": "indicator"}, {"type": "indicator"}, {"type": "indicator"}],
            [{"type": "indicator"}, {"type": "indicator"}, {"type": "scatter"}]
        ]
    )
    
    # 1. λΉ„μš© 절감
    if len(offers_df) > 0:
        min_price = offers_df['unit_price'].min()
        max_price = offers_df['unit_price'].max()
        savings = ((max_price - min_price) / max_price * 100) if max_price > 0 else 0
    else:
        savings = 0
    
    fig.add_trace(
        go.Indicator(
            mode="gauge+number+delta",
            value=savings,
            title={'text': "λΉ„μš© 절감λ₯  (%)"},
            delta={'reference': 10},
            gauge={
                'axis': {'range': [0, 50]},
                'bar': {'color': "darkblue"},
                'steps': [
                    {'range': [0, 10], 'color': "lightgray"},
                    {'range': [10, 25], 'color': "lightgreen"},
                    {'range': [25, 50], 'color': "green"}
                ],
                'threshold': {
                    'line': {'color': "red", 'width': 4},
                    'thickness': 0.75,
                    'value': 15
                }
            }
        ),
        row=1, col=1
    )
    
    # 2. μ»΄ν”ŒλΌμ΄μ–ΈμŠ€ μ€€μˆ˜μœ¨
    fig.add_trace(
        go.Indicator(
            mode="gauge+number",
            value=100,
            title={'text': "κ·œμ • μ€€μˆ˜μœ¨ (%)"},
            gauge={
                'axis': {'range': [0, 100]},
                'bar': {'color': "green"},
                'steps': [
                    {'range': [0, 80], 'color': "lightcoral"},
                    {'range': [80, 95], 'color': "lightyellow"},
                    {'range': [95, 100], 'color': "lightgreen"}
                ]
            }
        ),
        row=1, col=2
    )
    
    # 3. ESG 평균 점수
    if len(offers_df) > 0:
        esg_score = offers_df['esg_level'].map({'A': 100, 'B': 70, 'C': 40}).mean()
    else:
        esg_score = 0
    
    fig.add_trace(
        go.Indicator(
            mode="gauge+number",
            value=esg_score,
            title={'text': "ESG 평균 점수"},
            gauge={
                'axis': {'range': [0, 100]},
                'bar': {'color': "darkgreen"},
                'steps': [
                    {'range': [0, 50], 'color': "lightcoral"},
                    {'range': [50, 80], 'color': "lightyellow"},
                    {'range': [80, 100], 'color': "lightgreen"}
                ]
            }
        ),
        row=1, col=3
    )
    
    # 4. 평균 처리 μ‹œκ°„
    fig.add_trace(
        go.Indicator(
            mode="number+delta",
            value=20,
            title={'text': "처리 μ‹œκ°„ (λΆ„)"},
            delta={'reference': 30, 'increasing': {'color': "red"}, 'decreasing': {'color': "green"}},
            number={'suffix': "λΆ„"}
        ),
        row=2, col=1
    )
    
    # 5. λͺ©ν‘œ 달성λ₯ 
    fig.add_trace(
        go.Indicator(
            mode="gauge+number",
            value=85,
            title={'text': "μ›”κ°„ λͺ©ν‘œ 달성λ₯  (%)"},
            gauge={
                'axis': {'range': [0, 100]},
                'bar': {'color': "royalblue"},
                'threshold': {
                    'line': {'color': "red", 'width': 4},
                    'thickness': 0.75,
                    'value': 80
                }
            }
        ),
        row=2, col=2
    )
    
    # 6. μ›”κ°„ νŠΈλ Œλ“œ
    months = ['1μ›”', '2μ›”', '3μ›”', '4μ›”', '5μ›”', '6μ›”']
    values = [75, 78, 82, 85, 88, 90]
    
    fig.add_trace(
        go.Scatter(
            x=months,
            y=values,
            mode='lines+markers',
            name='발주 효율',
            line=dict(color='royalblue', width=3),
            marker=dict(size=10)
        ),
        row=2, col=3
    )
    
    fig.update_layout(
        height=700,
        showlegend=False,
        title_text="πŸ“Š κ²½μ˜μ§„ KPI λŒ€μ‹œλ³΄λ“œ",
        title_font_size=22
    )
    
    return fig

def create_action_items_table(opt_result: Dict, offers_df: pd.DataFrame) -> pd.DataFrame:
    """κ²½μ˜μ§„ Action Items 생성"""
    
    action_items = []
    
    # 1. μ¦‰μ‹œ 발주 승인 ν•­λͺ©
    alloc = opt_result.get('allocation', {})
    if alloc:
        for supplier_id, details in alloc.items():
            if isinstance(details, dict):
                action_items.append({
                    "μš°μ„ μˆœμœ„": "πŸ”΄ κΈ΄κΈ‰",
                    "Action Item": f"{details.get('supplier_name')} 발주 승인",
                    "μˆ˜λŸ‰": f"{details.get('qty')}개",
                    "μ˜ˆμƒ λΉ„μš©": f"{details.get('qty', 0) * details.get('unit_price', 0):,}원",
                    "λ‹΄λ‹Ή": "κ΅¬λ§€νŒ€",
                    "κΈ°ν•œ": "μ¦‰μ‹œ",
                    "μƒνƒœ": "승인 λŒ€κΈ°"
                })
    
    # 2. 재고 보좩 ꢌ고
    action_items.append({
        "μš°μ„ μˆœμœ„": "🟑 μ€‘μš”",
        "Action Item": "μ•ˆμ „μž¬κ³  미달 ν’ˆλͺ© 보좩",
        "μˆ˜λŸ‰": "3개 ν’ˆλͺ©",
        "μ˜ˆμƒ λΉ„μš©": "κ²€ν†  ν•„μš”",
        "λ‹΄λ‹Ή": "MROνŒ€",
        "κΈ°ν•œ": "1주일 λ‚΄",
        "μƒνƒœ": "κ²€ν†  쀑"
    })
    
    # 3. ESG κ°œμ„ 
    if len(offers_df) > 0:
        c_grade_count = len(offers_df[offers_df['esg_level'] == 'C'])
        if c_grade_count > 0:
            action_items.append({
                "μš°μ„ μˆœμœ„": "🟒 보톡",
                "Action Item": "ESG Cλ“±κΈ‰ 곡급업체 λŒ€μ²΄ κ²€ν† ",
                "μˆ˜λŸ‰": f"{c_grade_count}κ°œμ‚¬",
                "μ˜ˆμƒ λΉ„μš©": "영ν–₯도 뢄석 ν•„μš”",
                "λ‹΄λ‹Ή": "κ΅¬λ§€νŒ€",
                "κΈ°ν•œ": "1κ°œμ›” λ‚΄",
                "μƒνƒœ": "κ³„νš 단계"
            })
    
    # 4. μž₯κΈ° 계약 ν˜‘μƒ
    action_items.append({
        "μš°μ„ μˆœμœ„": "🟒 보톡",
        "Action Item": "μ£Όμš” 곡급업체 μž₯기계약 ν˜‘μƒ",
        "μˆ˜λŸ‰": "2-3κ°œμ‚¬",
        "μ˜ˆμƒ λΉ„μš©": "5-10% 절감 μ˜ˆμƒ",
        "λ‹΄λ‹Ή": "κ΅¬λ§€νŒ€",
        "κΈ°ν•œ": "λΆ„κΈ° λ‚΄",
        "μƒνƒœ": "κ³„νš 단계"
    })
    
    return pd.DataFrame(action_items)

# =========================================================
# Core Components
# =========================================================
@dataclass
class ToolCallLog:
    ts: str
    actor: str
    tool: str
    input: Dict[str, Any]
    output_preview: str

class MCPToolRegistry:
    def __init__(self, tables: Dict[str, pd.DataFrame]):
        self.tables = tables
        self.logs: List[ToolCallLog] = []

    def _log(self, actor: str, tool: str, inp: Dict[str, Any], out: Any):
        self.logs.append(ToolCallLog(
            ts=now_ts(),
            actor=actor,
            tool=tool,
            input=inp,
            output_preview=str(out)[:500]
        ))

    def query_inventory(self, actor: str, item_id: str) -> pd.DataFrame:
        inv = self.tables["inventory"]
        stor = self.tables["storages"]
        df = inv[inv["item_id"] == item_id].copy()
        if len(df) > 0:
            df = df.merge(stor, on="storage_id", how="left")
        self._log(actor, "query_inventory", {"item_id": item_id}, f"{len(df)} rows")
        return df

    def query_offers(self, actor: str, item_id: str) -> pd.DataFrame:
        offers = self.tables["supplier_offers"]
        suppliers = self.tables["suppliers"]
        df = offers[offers["item_id"] == item_id].copy()
        if len(df) > 0:
            df = df.merge(suppliers, on="supplier_id", how="left")
        self._log(actor, "query_offers", {"item_id": item_id}, f"{len(df)} rows")
        return df

    def query_compat_items(self, actor: str, equipment_id: str) -> pd.DataFrame:
        compat = self.tables["compat"]
        items = self.tables["items"]
        df = compat[compat["equipment_id"] == equipment_id].copy()
        if len(df) > 0:
            df = df.merge(items, on="item_id", how="left")
        self._log(actor, "query_compat_items", {"equipment_id": equipment_id}, f"{len(df)} rows")
        return df

    def get_equipment_info(self, actor: str, equipment_id: str) -> Dict[str, Any]:
        eq = self.tables["equipment"]
        match = eq[eq["equipment_id"] == equipment_id]
        if len(match) == 0:
            return {}
        info = match.iloc[0].to_dict()
        self._log(actor, "get_equipment_info", {"equipment_id": equipment_id}, safe_json(info))
        return info

    def audit_log_df(self) -> pd.DataFrame:
        if not self.logs:
            return pd.DataFrame({"λ©”μ‹œμ§€": ["둜그 μ—†μŒ"]})
        return pd.DataFrame([{
            "μ‹œκ°„": l.ts[:19],
            "μ—μ΄μ „νŠΈ": l.actor,
            "도ꡬ": l.tool,
            "μž…λ ₯": str(l.input)[:50],
        } for l in self.logs])

def apply_rules(tables: Dict[str, pd.DataFrame], item_id: str, 
                supplier_row: Dict[str, Any]) -> Dict[str, Any]:
    """Apply rules"""
    items = tables["items"]
    item_match = items[items["item_id"] == item_id]
    
    if len(item_match) == 0:
        return {"block": False, "alerts": [], "explanations": [], "rules_fired": []}
    
    item = item_match.iloc[0].to_dict()
    
    decision = {
        "block": False,
        "alerts": [],
        "explanations": [],
        "rules_fired": []
    }
    
    if item.get("risk_class") == "규제" and supplier_row.get("region") == "ν•΄μ™Έ":
        decision["block"] = True
        decision["rules_fired"].append("R-001")
        decision["explanations"].append(
            f"🚫 R-001: κ·œμ œν’ˆλͺ©({item.get('item_name')}) 해외업체({supplier_row.get('supplier_name')}) ꡬ맀 차단"
        )
    
    if supplier_row.get("esg_level") == "C":
        decision["rules_fired"].append("R-004")
        decision["explanations"].append(
            f"πŸ“Š R-004: ESG Cλ“±κΈ‰({supplier_row.get('supplier_name')}) νŒ¨λ„ν‹°"
        )
    
    return decision

def optimize_order_allocation(demand_qty: int, offers_df: pd.DataFrame, 
                              rules_eval: Dict[str, Dict[str, Any]]) -> Dict[str, Any]:
    """Optimize allocation"""
    if not PULP_AVAILABLE:
        return {
            "status": "UNAVAILABLE",
            "reason": "PuLP not installed",
            "allocation": {},
            "demand": demand_qty
        }
    
    feasible = []
    blocked = []
    
    for _, r in offers_df.iterrows():
        sid = r["supplier_id"]
        if rules_eval.get(sid, {}).get("block"):
            blocked.append({
                "supplier_id": sid,
                "supplier_name": r.get("supplier_name", sid),
                "reason": "κ·œμΉ™ μœ„λ°˜"
            })
        else:
            feasible.append(r)
    
    if len(feasible) == 0:
        return {
            "status": "INFEASIBLE",
            "reason": "λͺ¨λ“  곡급업체 차단",
            "allocation": {},
            "blocked_suppliers": blocked,
            "demand": demand_qty
        }
    
    fdf = pd.DataFrame(feasible)
    prob = LpProblem("MRO_Allocation", LpMinimize)
    
    x = {}
    for _, r in fdf.iterrows():
        sid = r["supplier_id"]
        x[sid] = LpVariable(f"x_{sid}", lowBound=0, cat="Integer")
    
    prob += lpSum(list(x.values())) >= demand_qty, "DemandConstraint"
    
    obj_terms = []
    for _, r in fdf.iterrows():
        sid = r["supplier_id"]
        price = float(r["unit_price"])
        obj_terms.append(x[sid] * price)
    
    prob += lpSum(obj_terms), "TotalCost"
    prob.solve()
    
    alloc = {}
    total_cost = 0.0
    for _, r in fdf.iterrows():
        sid = r["supplier_id"]
        val = x[sid].value()
        if val is not None and val > 0:
            qty = int(val)
            alloc[sid] = {
                "qty": qty,
                "unit_price": float(r["unit_price"]),
                "supplier_name": r.get("supplier_name", sid),
                "lead_time": int(r.get("lead_time_days", 0))
            }
            total_cost += qty * float(r["unit_price"])
    
    return {
        "status": LpStatus.get(prob.status, "Unknown"),
        "allocation": alloc,
        "demand": demand_qty,
        "blocked_suppliers": blocked,
        "total_cost": round(total_cost, 2)
    }

class LLMOrchestrator:
    def __init__(self):
        self.api_key = os.environ.get("OPENAI_API_KEY", "").strip()
        self.demo_mode = (not self.api_key or not OPENAI_AVAILABLE)
        
        if not self.demo_mode:
            try:
                self.client = OpenAI(api_key=self.api_key)
                test_resp = self.client.chat.completions.create(
                    model="gpt-4o-mini",
                    messages=[{"role": "user", "content": "test"}],
                    max_tokens=5
                )
                print("βœ… OpenAI API μ—°κ²° 성곡!")
            except Exception:
                self.demo_mode = True
                self.client = None
        else:
            self.client = None

    def chat(self, role: str, system: str, user: str) -> str:
        if self.demo_mode:
            return self._demo_response(role)
        try:
            resp = self.client.chat.completions.create(
                model="gpt-4o-mini",
                temperature=0.2,
                messages=[
                    {"role": "system", "content": system},
                    {"role": "user", "content": user}
                ]
            )
            return resp.choices[0].message.content
        except Exception as e:
            return f"[ERROR: {e}]\n" + self._demo_response(role)

    def _demo_response(self, role: str) -> str:
        return f"[DEMO MODE - {role}] AI 뢄석 μ™„λ£Œ"

# =========================================================
# LangGraph Workflow
# =========================================================
class DemoState(TypedDict, total=False):
    tables: Dict[str, pd.DataFrame]
    mcp: MCPToolRegistry
    llm: LLMOrchestrator
    scenario: str
    equipment_id: str
    item_id: str
    demand_qty: int
    priority: str
    tables_ok: bool
    validation_issues: List[str]
    progress: str
    inventory_view: pd.DataFrame
    offers_view: pd.DataFrame
    rules_eval: Dict[str, Any]
    optimization: Dict[str, Any]
    narrative: Dict[str, str]
    audit_log: pd.DataFrame
    selected_item_name: str
    equipment_info: Dict[str, Any]
    compat_items: pd.DataFrame

def node_validate(state: DemoState) -> DemoState:
    ok, issues = validate_tables(state["tables"])
    state["tables_ok"] = ok
    state["validation_issues"] = issues
    state["progress"] = "1/4 검증 μ™„λ£Œ"
    return state

def node_mro_agent(state: DemoState) -> DemoState:
    mcp: MCPToolRegistry = state["mcp"]
    equipment_id = state.get("equipment_id", "")
    item_id = state.get("item_id", "")
    
    # Get equipment info
    equipment_info = mcp.get_equipment_info("MRO_AGENT", equipment_id)
    state["equipment_info"] = equipment_info
    
    # Get compatible items
    compat_df = pd.DataFrame()
    if equipment_id:
        compat_df = mcp.query_compat_items("MRO_AGENT", equipment_id)
        state["compat_items"] = compat_df
    
    if not item_id and len(compat_df) > 0:
        mandatory = compat_df[compat_df["is_mandatory"] == True]
        if len(mandatory) > 0:
            selected = mandatory.iloc[0]
        else:
            selected = compat_df.iloc[0]
        item_id = selected["item_id"]
        state["item_id"] = item_id
        state["selected_item_name"] = selected.get("item_name", item_id)
    
    inv_df = pd.DataFrame()
    if item_id:
        inv_df = mcp.query_inventory("MRO_AGENT", item_id)
    state["inventory_view"] = inv_df
    
    llm: LLMOrchestrator = state["llm"]
    if "narrative" not in state:
        state["narrative"] = {}
    state["narrative"]["mro"] = llm.chat("MRO", "MRO 뢄석", "μ„€λΉ„/재고")
    state["progress"] = "2/4 MRO μ™„λ£Œ"
    return state

def node_procurement_agent(state: DemoState) -> DemoState:
    mcp: MCPToolRegistry = state["mcp"]
    item_id = state.get("item_id", "")
    demand_qty = int(state.get("demand_qty", 10))
    
    offers_df = pd.DataFrame()
    if item_id:
        offers_df = mcp.query_offers("PROC_AGENT", item_id)
    state["offers_view"] = offers_df
    
    rules_eval = {}
    if len(offers_df) > 0:
        for _, r in offers_df.iterrows():
            sid = r["supplier_id"]
            supplier_row = {
                "supplier_id": sid,
                "supplier_name": r.get("supplier_name", sid),
                "region": r.get("region", ""),
                "esg_level": r.get("esg_level", ""),
            }
            rules_eval[sid] = apply_rules(state["tables"], item_id, supplier_row)
    state["rules_eval"] = rules_eval
    
    opt_result = {}
    if len(offers_df) > 0:
        opt_result = optimize_order_allocation(demand_qty, offers_df, rules_eval)
    else:
        opt_result = {
            "status": "NO_DATA",
            "reason": "곡급업체 정보 μ—†μŒ",
            "allocation": {},
            "demand": demand_qty
        }
    state["optimization"] = opt_result
    
    llm: LLMOrchestrator = state["llm"]
    state["narrative"]["proc"] = llm.chat("PROC", "ꡬ맀 μ „λž΅", "μ΅œμ ν™”")
    state["narrative"]["exec"] = llm.chat("EXEC", "μž„μ› μš”μ•½", "μ’…ν•©")
    state["progress"] = "3/4 ꡬ맀 μ™„λ£Œ"
    return state

def node_collect_audit(state: DemoState) -> DemoState:
    mcp: MCPToolRegistry = state["mcp"]
    state["audit_log"] = mcp.audit_log_df()
    state["progress"] = "4/4 μ™„λ£Œ βœ“"
    return state

def build_workflow():
    if not LANGGRAPH_AVAILABLE:
        return None
    try:
        graph = StateGraph(DemoState)
        graph.add_node("validate", node_validate)
        graph.add_node("mro_agent", node_mro_agent)
        graph.add_node("procurement_agent", node_procurement_agent)
        graph.add_node("collect_audit", node_collect_audit)
        graph.set_entry_point("validate")
        graph.add_edge("validate", "mro_agent")
        graph.add_edge("mro_agent", "procurement_agent")
        graph.add_edge("procurement_agent", "collect_audit")
        graph.add_edge("collect_audit", END)
        return graph.compile()
    except Exception as e:
        print(f"⚠️ LangGraph failed: {e}")
        return None

APP = build_workflow()

# =========================================================
# Main Execution - Enhanced with Dashboards
# =========================================================
def run_demo(scenario: str, seed: int, equipment_id: str, item_id: str, 
             demand_qty: int) -> Tuple:
    """Main execution - returns 12 outputs (enhanced)"""
    try:
        seed_int = int(seed)
        demand_int = int(demand_qty)
        
        tables = generate_demo_tables(seed=seed_int)
        mcp = MCPToolRegistry(tables)
        llm = LLMOrchestrator()
        
        preset = SCENARIO_PRESETS.get(scenario, SCENARIO_PRESETS["κΈ΄κΈ‰ κ³ μž₯ λŒ€μ‘"])
        
        state: DemoState = {
            "tables": tables,
            "mcp": mcp,
            "llm": llm,
            "scenario": scenario,
            "equipment_id": equipment_id.strip(),
            "item_id": item_id.strip(),
            "demand_qty": demand_int,
            "priority": preset.get("priority", "정상"),
        }
        
        if APP is not None:
            out = APP.invoke(state)
        else:
            out = node_validate(state)
            out = node_mro_agent(out)
            out = node_procurement_agent(out)
            out = node_collect_audit(out)
        
        status = {
            "mode": "⚠️ DEMO" if llm.demo_mode else "βœ… LLM",
            "scenario": scenario,
            "tables_ok": out.get("tables_ok", False),
            "equipment": out.get("equipment_id", ""),
            "item_name": out.get("selected_item_name", ""),
            "demand": out.get("demand_qty", 0),
            "priority": out.get("priority", "정상"),
            "progress": out.get("progress", "μ™„λ£Œ"),
        }
        
        status_text = format_status(status)
        
        # Data extraction
        inv_df = out.get("inventory_view", pd.DataFrame())
        offers_df = out.get("offers_view", pd.DataFrame())
        audit_df = out.get("audit_log", pd.DataFrame())
        equipment_info = out.get("equipment_info", {})
        compat_items = out.get("compat_items", pd.DataFrame())
        rules_eval = out.get("rules_eval", {})
        opt_result = out.get("optimization", {})
        purchase_history = tables.get("purchase_history", pd.DataFrame())
        
        item_name = out.get("selected_item_name", "λΆ€ν’ˆ")
        
        # Create dashboards
        mro_dashboard = create_mro_inventory_dashboard(inv_df, item_name)
        mro_workflow = create_mro_workflow_status(equipment_info, compat_items)
        proc_dashboard = create_procurement_comparison_dashboard(offers_df, rules_eval)
        proc_workflow = create_procurement_workflow(opt_result)
        exec_dashboard = create_executive_kpi_dashboard(opt_result, offers_df, purchase_history)
        action_items = create_action_items_table(opt_result, offers_df)
        
        # Fallback for empty dataframes
        if len(audit_df) == 0:
            audit_df = pd.DataFrame({"λ©”μ‹œμ§€": ["κ°μ‚¬λ‘œκ·Έ μ—†μŒ"]})
        
        print("βœ… λŒ€μ‹œλ³΄λ“œ 생성 μ™„λ£Œ\n")
        
        # Return 12 outputs
        return (
            status_text,        # 1
            mro_dashboard,      # 2 - MRO 재고 λŒ€μ‹œλ³΄λ“œ
            mro_workflow,       # 3 - MRO μ›Œν¬ν”Œλ‘œμš°
            proc_dashboard,     # 4 - ꡬ맀 비ꡐ λŒ€μ‹œλ³΄λ“œ
            proc_workflow,      # 5 - ꡬ맀 μ›Œν¬ν”Œλ‘œμš°
            exec_dashboard,     # 6 - κ²½μ˜μ§„ KPI
            action_items,       # 7 - Action Items
            offers_df,          # 8 - 곡급업체 원본 데이터
            inv_df,             # 9 - 재고 원본 데이터
            opt_result,         # 10 - μ΅œμ ν™” κ²°κ³Ό (dictλ₯Ό text둜)
            audit_df,           # 11 - 감사 둜그
            out.get("selected_item_name", "N/A")  # 12 - ν’ˆλͺ©λͺ…
        )
    
    except Exception as e:
        print(f"❌ 였λ₯˜: {e}\n{traceback.format_exc()}")
        error_msg = f"❌ 였λ₯˜\n\n{str(e)}"
        empty_fig = go.Figure()
        empty_fig.add_annotation(text="였λ₯˜ λ°œμƒ", showarrow=False)
        empty_df = pd.DataFrame({"였λ₯˜": [str(e)[:100]]})
        
        return (
            error_msg, empty_fig, empty_fig, empty_fig, empty_fig,
            empty_fig, empty_df, empty_df, empty_df, {}, empty_df, "N/A"
        )

def update_scenario(scenario: str) -> Tuple[str, str, int, str]:
    preset = SCENARIO_PRESETS.get(scenario, SCENARIO_PRESETS["κΈ΄κΈ‰ κ³ μž₯ λŒ€μ‘"])
    guide_text = f"""**πŸ“Œ {preset['description']}**

**λ°°κ²½**: {preset['context']}
**μš°μ„ μˆœμœ„**: {preset.get('priority', '정상')}
**κ°€μ΄λ“œ**: {preset.get('guide', '')}
"""
    
    return (
        preset["equipment_id"],
        preset["item_id"],
        preset["demand_qty"],
        guide_text
    )

# =========================================================
# Enhanced Gradio UI with Process Guides
# =========================================================
print("🎨 ν”„λ‘œμ„ΈμŠ€ κ°€μ΄λ“œ 톡합 UI ꡬ성 쀑...\n")

with gr.Blocks(title="POSCO DX MRO Composite AI", theme=gr.themes.Soft()) as demo:
    
    gr.Markdown("""
# 🏭 POSCO DX - MRO Composite AI ν”„λ‘œμ„ΈμŠ€ κ°€μ΄λ“œ 톡합 버전

## 🎯 업무 ν”„λ‘œμ„ΈμŠ€ μžλ™ν™” + AI μ˜μ‚¬κ²°μ • 지원 μ‹œμŠ€ν…œ

**3-Agent Collaboration**: MRO 운영 β†’ ꡬ맀/쑰달 β†’ κ²½μ˜μ§„ 승인
""")
    
    # Process Overview Section
    with gr.Accordion("πŸ“– 전체 업무 ν”„λ‘œμ„ΈμŠ€ κ°œμš”", open=False):
        gr.Markdown("""
### πŸ”„ End-to-End μ›Œν¬ν”Œλ‘œμš°

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  1️⃣ MRO 운영    β”‚ ───> β”‚  2️⃣ ꡬ맀/쑰달     β”‚ ───> β”‚  3️⃣ κ²½μ˜μ§„ 승인  β”‚
β”‚                 β”‚      β”‚                  β”‚      β”‚                 β”‚
β”‚ β€’ κ³ μž₯ μ ‘μˆ˜     β”‚      β”‚ β€’ 곡급업체 쑰회  β”‚      β”‚ β€’ KPI 확인      β”‚
β”‚ β€’ λΆ€ν’ˆ 확인     β”‚      β”‚ β€’ κ·œμ • 검증      β”‚      β”‚ β€’ μ˜μ‚¬κ²°μ •      β”‚
β”‚ β€’ 재고 확인     β”‚      β”‚ β€’ μ΅œμ ν™” 뢄석    β”‚      β”‚ β€’ ν”Όλ“œλ°±        β”‚
β”‚ β€’ 발주 μš”μ²­     β”‚      β”‚ β€’ 승인 μš”μ²­      β”‚      β”‚                 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
     ⏱️ 15λΆ„                   ⏱️ 25λΆ„                   ⏱️ 25λΆ„
```

### πŸ’‘ 핡심 κ°€μΉ˜

1. **μžλ™ν™”**: μ„€λΉ„-λΆ€ν’ˆ λ§€μΉ­, 재고 쑰회, κ·œμ • 검증 λ“± 반볡 업무 μžλ™ν™”
2. **μ΅œμ ν™”**: AI 기반 λΉ„μš© μ΅œμ ν™” 및 곡급업체 μ„ μ •
3. **검증**: Neuro-Symbolic AI둜 100% κ·œμ • μ€€μˆ˜ 보μž₯
4. **κ°€μ‹œμ„±**: μ‹€μ‹œκ°„ λŒ€μ‹œλ³΄λ“œλ‘œ μ „ κ³Όμ • λͺ¨λ‹ˆν„°λ§
5. **좔적성**: λͺ¨λ“  μ˜μ‚¬κ²°μ • κ³Όμ • μžλ™ 기둝

### πŸ“Š κΈ°λŒ€ 효과

- ⏱️ **처리 μ‹œκ°„**: κΈ°μ‘΄ 3-5일 β†’ **1μ‹œκ°„ 이내**
- πŸ’° **λΉ„μš© 절감**: 평균 **15-25%** ꡬ맀 λΉ„μš© 절감
- βš–οΈ **μ»΄ν”ŒλΌμ΄μ–ΈμŠ€**: **100%** κ·œμ • μ€€μˆ˜
- πŸ“ˆ **νš¨μœ¨μ„±**: λ‹΄λ‹Ήμž 업무 μ‹œκ°„ **60%** 단좕
""")
    
    with gr.Row():
        with gr.Column():
            gr.Markdown("### 🎯 μ‹œλ‚˜λ¦¬μ˜€")
            scenario_radio = gr.Radio(
                choices=list(SCENARIO_PRESETS.keys()),
                value="κΈ΄κΈ‰ κ³ μž₯ λŒ€μ‘",
                label="뢄석 μ‹œλ‚˜λ¦¬μ˜€"
            )
            scenario_info = gr.Markdown(
                value=f"""**πŸ“Œ {SCENARIO_PRESETS['κΈ΄κΈ‰ κ³ μž₯ λŒ€μ‘']['description']}**

**λ°°κ²½**: {SCENARIO_PRESETS['κΈ΄κΈ‰ κ³ μž₯ λŒ€μ‘']['context']}
**κ°€μ΄λ“œ**: {SCENARIO_PRESETS['κΈ΄κΈ‰ κ³ μž₯ λŒ€μ‘']['guide']}
"""
            )
        
        with gr.Column():
            gr.Markdown("### βš™οΈ νŒŒλΌλ―Έν„°")
            seed_number = gr.Number(value=7, label="데이터 μ‹œλ“œ", precision=0)
            equipment_text = gr.Textbox(value="CONV-PH-007", label="μ„€λΉ„ ID")
            item_text = gr.Textbox(value="", label="ν’ˆλͺ© ID (선택)")
            demand_number = gr.Number(value=10, label="μˆ˜λŸ‰", precision=0)
    
    run_button = gr.Button("πŸš€ Composite AI 뢄석 μ‹€ν–‰", variant="primary", size="lg")
    
    gr.Markdown("---")
    
    status_output = gr.Textbox(label="πŸ“Š μ‹€ν–‰ μƒνƒœ", lines=10)
    selected_item_display = gr.Textbox(label="πŸ“¦ μ„ νƒλœ ν’ˆλͺ©", interactive=False)
    
    with gr.Tabs():
        with gr.Tab("πŸ”§ MRO λ‹΄λ‹Ήμž"):
            # Process Guide for MRO
            with gr.Accordion("πŸ“‹ MRO 운영 ν”„λ‘œμ„ΈμŠ€ κ°€μ΄λ“œ", open=True):
                mro_process_html = gr.HTML(create_process_guide_html("mro"))
            
            gr.Markdown("---")
            gr.Markdown("### πŸ“Š λŒ€μ‹œλ³΄λ“œ 및 뢄석 κ²°κ³Ό")
            
            mro_inventory_plot = gr.Plot(label="πŸ“¦ 재고 뢄석 λŒ€μ‹œλ³΄λ“œ")
            mro_workflow_plot = gr.Plot(label="πŸ”„ MRO μ›Œν¬ν”Œλ‘œμš° μ§„ν–‰")
            mro_inventory_table = gr.Dataframe(label="πŸ“‹ 상세 재고 데이터")
        
        with gr.Tab("πŸ’° ꡬ맀 λ‹΄λ‹Ήμž"):
            # Process Guide for Procurement
            with gr.Accordion("πŸ“‹ ꡬ맀/쑰달 ν”„λ‘œμ„ΈμŠ€ κ°€μ΄λ“œ", open=True):
                proc_process_html = gr.HTML(create_process_guide_html("procurement"))
            
            gr.Markdown("---")
            gr.Markdown("### πŸ“Š λŒ€μ‹œλ³΄λ“œ 및 뢄석 κ²°κ³Ό")
            
            proc_comparison_plot = gr.Plot(label="πŸ“Š 곡급업체 비ꡐ λŒ€μ‹œλ³΄λ“œ")
            proc_workflow_plot = gr.Plot(label="πŸ”„ ꡬ맀 μ›Œν¬ν”Œλ‘œμš°")
            proc_offers_table = gr.Dataframe(label="πŸ“‹ 곡급업체 상세 정보")
        
        with gr.Tab("πŸ‘” κ²½μ˜μ§„"):
            # Process Guide for Executive
            with gr.Accordion("πŸ“‹ κ²½μ˜μ§„ μ˜μ‚¬κ²°μ • ν”„λ‘œμ„ΈμŠ€ κ°€μ΄λ“œ", open=True):
                exec_process_html = gr.HTML(create_process_guide_html("executive"))
            
            gr.Markdown("---")
            gr.Markdown("### πŸ“Š λŒ€μ‹œλ³΄λ“œ 및 뢄석 κ²°κ³Ό")
            
            exec_kpi_plot = gr.Plot(label="πŸ“Š κ²½μ˜μ§„ KPI λŒ€μ‹œλ³΄λ“œ")
            exec_action_table = gr.Dataframe(label="πŸ“‹ Action Items")
            
            gr.Markdown("### πŸ’¬ κ²½μ˜μ§„ ν”Όλ“œλ°±")
            with gr.Row():
                feedback_text = gr.Textbox(
                    label="κ°œμ„  μ œμ•ˆ / ν”Όλ“œλ°±",
                    placeholder="예: ESG Cλ“±κΈ‰ 업체 비쀑을 20% μ΄ν•˜λ‘œ μ œν•œν•˜μ‹œκΈ° λ°”λžλ‹ˆλ‹€.",
                    lines=3
                )
            with gr.Row():
                approve_btn = gr.Button("βœ… 승인", variant="primary")
                reject_btn = gr.Button("❌ 반렀", variant="stop")
                suggest_btn = gr.Button("πŸ’‘ κ°œμ„  μ œμ•ˆ", variant="secondary")
            
            feedback_output = gr.Textbox(label="ν”Όλ“œλ°± 처리 κ²°κ³Ό", lines=2)
        
        with gr.Tab("πŸ“ 감사 둜그"):
            gr.Markdown("""
### 감사 좔적 (Audit Trail)

**λͺ©μ **: λͺ¨λ“  μ˜μ‚¬κ²°μ • κ³Όμ • 좔적 및 μ»΄ν”ŒλΌμ΄μ–ΈμŠ€ 확보

**기둝 ν•­λͺ©**:
- πŸ• μ‹œκ°„: μž‘μ—… μˆ˜ν–‰ μ‹œκ°
- πŸ‘€ μ—μ΄μ „νŠΈ: MRO/ꡬ맀/κ²½μ˜μ§„
- πŸ”§ 도ꡬ: μ‚¬μš©ν•œ κΈ°λŠ₯
- πŸ“₯ μž…λ ₯: νŒŒλΌλ―Έν„°
- πŸ“€ 좜λ ₯: κ²°κ³Ό μš”μ•½

**ν™œμš©**:
- κ·œμ • μ€€μˆ˜ 감사
- ν”„λ‘œμ„ΈμŠ€ κ°œμ„ 
- μ±…μž„ 좔적성
""")
            audit_table = gr.Dataframe(label="πŸ“ 전체 감사 둜그")
            
            # Hidden outputs for optimization result
            opt_result_json = gr.JSON(label="μ΅œμ ν™” 상세 κ²°κ³Ό", visible=False)
    
    gr.Markdown("""
---
## πŸ’‘ μ‹œμŠ€ν…œ μ‚¬μš© κ°€μ΄λ“œ

### πŸ“‹ 단계별 μ‚¬μš©λ²•

#### 1️⃣ μ‹œλ‚˜λ¦¬μ˜€ 선택
- **κΈ΄κΈ‰ κ³ μž₯ λŒ€μ‘**: μ„€λΉ„ κ³ μž₯으둜 μ¦‰μ‹œ ꡐ체가 ν•„μš”ν•œ 경우
- **μ •κΈ° 발주 κ³„νš**: μ›”κ°„/λΆ„κΈ° μ •κΈ° 발주 μ΅œμ ν™”
- **κ·œμ • μ€€μˆ˜ 검증**: 특수 ν’ˆλͺ© ꡬ맀 μ‹œ μ»΄ν”ŒλΌμ΄μ–ΈμŠ€ 확인

#### 2️⃣ νŒŒλΌλ―Έν„° μž…λ ₯
- **μ„€λΉ„ ID**: κ³ μž₯/μ •λΉ„ λŒ€μƒ μ„€λΉ„ (μžλ™ μž…λ ₯)
- **ν’ˆλͺ© ID**: νŠΉμ • ν’ˆλͺ© μ§€μ • (선택사항, λΉ„μš°λ©΄ μžλ™ 선택)
- **μˆ˜λŸ‰**: 발주 ν•„μš” μˆ˜λŸ‰

#### 3️⃣ 뢄석 μ‹€ν–‰
- "πŸš€ Composite AI 뢄석 μ‹€ν–‰" λ²„νŠΌ 클릭
- μ•½ 5-10초 λ‚΄ κ²°κ³Ό 확인

#### 4️⃣ κ²°κ³Ό κ²€ν† 
- **MRO νƒ­**: 재고 ν˜„ν™© 및 발주 ν•„μš”μ„± 확인
- **ꡬ맀 νƒ­**: 곡급업체 비ꡐ 및 졜적 선택
- **κ²½μ˜μ§„ νƒ­**: KPI 확인 및 μ˜μ‚¬κ²°μ •

#### 5️⃣ 승인/ν”Όλ“œλ°±
- Action Items κ²€ν†  ν›„ 승인/반렀 κ²°μ •
- κ°œμ„  μ œμ•ˆ μž…λ ₯ μ‹œ μžλ™μœΌλ‘œ λ‹΄λ‹Ή λΆ€μ„œμ— 전달

### πŸŽ“ ν”„λ‘œμ„ΈμŠ€ 이해

각 νƒ­μ˜ "πŸ“‹ ν”„λ‘œμ„ΈμŠ€ κ°€μ΄λ“œ"λ₯Ό 펼치면:
- 단계별 상세 절차
- μž…λ ₯/좜λ ₯ λͺ…μ„Έ
- λ‹΄λ‹Ήμž 및 μ†Œμš” μ‹œκ°„
- 성곡 κΈ°μ€€

을 확인할 수 μžˆμŠ΅λ‹ˆλ‹€.

### πŸ” μ£Όμš” κΈ°λŠ₯

1. **μžλ™ λΆ€ν’ˆ λ§€μΉ­**: μ„€λΉ„ ID만으둜 ν˜Έν™˜ λΆ€ν’ˆ μžλ™ 검색
2. **전사 재고 톡합**: 본사, 포항, κ΄‘μ–‘ 전체 μ°½κ³  μ‹€μ‹œκ°„ 쑰회
3. **AI κ·œμ • 검증**: κ·œμ œν’ˆλͺ©, ESG λ“±κΈ‰ λ“± μžλ™ 검증
4. **μ΅œμ ν™” μ—”μ§„**: Linear Programming으둜 λΉ„μš© μ΅œμ†Œν™”
5. **μΈν„°λž™ν‹°λΈŒ λŒ€μ‹œλ³΄λ“œ**: Plotly 차트둜 λ“œλ¦΄λ‹€μš΄ 뢄석 κ°€λŠ₯

### πŸ”‘ API Key μ„€μ • (Hugging Face Spaces)

OpenAI κΈ°λŠ₯을 μ‚¬μš©ν•˜λ €λ©΄:
1. Space Settings β†’ Secrets으둜 이동
2. μƒˆ Secret μΆ”κ°€: 
   - Name: `OPENAI_API_KEY`
   - Value: `your-openai-api-key`
3. Space μž¬μ‹œμž‘

API ν‚€ 없이도 데λͺ¨ λͺ¨λ“œλ‘œ κΈ°λ³Έ κΈ°λŠ₯ μ‚¬μš© κ°€λŠ₯ν•©λ‹ˆλ‹€.
""")
    
    # Event Handlers
    scenario_radio.change(
        fn=update_scenario,
        inputs=[scenario_radio],
        outputs=[equipment_text, item_text, demand_number, scenario_info]
    )
    
    run_button.click(
        fn=run_demo,
        inputs=[scenario_radio, seed_number, equipment_text, item_text, demand_number],
        outputs=[
            status_output,           # 1
            mro_inventory_plot,      # 2
            mro_workflow_plot,       # 3
            proc_comparison_plot,    # 4
            proc_workflow_plot,      # 5
            exec_kpi_plot,          # 6
            exec_action_table,      # 7
            proc_offers_table,      # 8
            mro_inventory_table,    # 9
            opt_result_json,        # 10
            audit_table,            # 11
            selected_item_display   # 12
        ]
    )
    
    # Feedback handlers
    def handle_approve(feedback):
        return f"βœ… 승인 μ™„λ£Œ: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\nν”Όλ“œλ°±: {feedback}"
    
    def handle_reject(feedback):
        return f"❌ 반렀됨: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\nμ‚¬μœ : {feedback}"
    
    def handle_suggest(feedback):
        return f"πŸ’‘ κ°œμ„  μ œμ•ˆ μ ‘μˆ˜: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\nλ‚΄μš©: {feedback}"
    
    approve_btn.click(fn=handle_approve, inputs=[feedback_text], outputs=[feedback_output])
    reject_btn.click(fn=handle_reject, inputs=[feedback_text], outputs=[feedback_output])
    suggest_btn.click(fn=handle_suggest, inputs=[feedback_text], outputs=[feedback_output])

print("=" * 60)
print("βœ… ν”„λ‘œμ„ΈμŠ€ κ°€μ΄λ“œ 톡합 UI μ™„λ£Œ!")
print("=" * 60)

if __name__ == "__main__":
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        show_error=True
    )

print("\nπŸŽ‰ ν”„λ‘œμ„ΈμŠ€ κ°€μ΄λ“œ 톡합 버전 μ‹€ν–‰ 쀑!\n")