File size: 79,519 Bytes
337e000
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ffb3f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337e000
 
 
 
 
 
 
 
 
 
0ffb3f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6dc42f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bff706
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb2fd05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75940c3
8cfefd7
75940c3
 
8cfefd7
 
 
75940c3
8cfefd7
 
 
75940c3
8cfefd7
 
 
 
 
 
 
75940c3
8cfefd7
 
 
75940c3
 
 
 
 
6bff706
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6dc42f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ffb3f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337e000
0ffb3f8
337e000
 
 
ed83fb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337e000
 
 
 
 
 
ed83fb0
 
337e000
 
 
ed83fb0
337e000
ed83fb0
337e000
 
 
 
 
 
 
 
 
 
 
21790e7
337e000
 
ed83fb0
21790e7
 
 
ed83fb0
 
337e000
21790e7
337e000
 
21790e7
ed83fb0
337e000
21790e7
 
337e000
 
 
21790e7
 
 
 
 
 
 
 
 
 
 
 
ed83fb0
21790e7
 
 
 
 
 
 
 
 
 
 
 
ed83fb0
21790e7
 
 
 
 
ed83fb0
b78a016
 
 
21790e7
b78a016
337e000
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed83fb0
337e000
 
 
 
 
 
 
 
 
 
 
ed83fb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337e000
 
0ffb3f8
 
 
 
337e000
0ffb3f8
337e000
0ffb3f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337e000
6dc42f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bff706
0ffb3f8
5d50a4d
 
 
 
 
0ffb3f8
5d50a4d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ffb3f8
5d50a4d
 
 
 
0ffb3f8
5d50a4d
 
 
 
 
 
0ffb3f8
5d50a4d
0ffb3f8
5d50a4d
0ffb3f8
5d50a4d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ffb3f8
5d50a4d
 
 
 
 
 
0ffb3f8
5d50a4d
 
 
 
 
 
0ffb3f8
 
5d50a4d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ffb3f8
 
5d50a4d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ffb3f8
337e000
 
0ffb3f8
337e000
 
 
 
 
 
 
 
 
8863388
 
 
 
337e000
8863388
 
 
 
 
 
 
 
 
 
337e000
 
 
8863388
 
 
 
337e000
 
 
8863388
337e000
 
 
 
 
 
8863388
337e000
 
 
 
 
 
 
 
 
 
 
 
 
21790e7
0ffb3f8
 
 
337e000
0ffb3f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337e000
ed83fb0
 
0ffb3f8
 
 
 
 
 
 
 
 
 
 
 
 
ed83fb0
 
337e000
 
 
 
 
 
 
8863388
337e000
 
 
8863388
337e000
8863388
337e000
8863388
 
 
 
 
 
 
 
337e000
 
 
 
0ffb3f8
337e000
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ffb3f8
 
 
 
 
 
 
337e000
0ffb3f8
 
 
 
337e000
 
0ffb3f8
 
 
337e000
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21790e7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
import gradio as gr
import openai
import requests
import json
from typing import Dict, List, Any
import os
from datetime import datetime

class MCPClient:
    def __init__(self, openai_api_key: str):
        """Initialize the MCP Client with OpenAI integration"""
        self.openai_client = openai.OpenAI(api_key=openai_api_key)
        
        # MCP Server configurations
        self.mcp_servers = {
            "terraform": {
                "name": "MCP Terraform",
                "space_url": "https://chrissacrumcor-mcp-terraform.hf.space",
                "description": "Terraform infrastructure management"
            },
            "linux": {
                "name": "MCP Linux", 
                "space_url": "https://chrissacrumcor-mcp-linux.hf.space",
                "description": "Linux system operations",
                # Known tools from the Linux server code
                "tools": [
                    {
                        "name": "user_management",
                        "description": "Generate Linux user management commands for creating, deleting, and managing users and groups"
                    },
                    {
                        "name": "file_permissions", 
                        "description": "Generate file permission and ownership commands for chmod, chown, and permission discovery"
                    },
                    {
                        "name": "system_commands",
                        "description": "Generate common Linux system administration commands for processes, disk, network, services, and firewall"
                    }
                ]
            },
            "cisco": {
                "name": "MCP Cisco",
                "space_url": "https://chrissacrumcor-mcp-cisco.hf.space", 
                "description": "Cisco network management"
            }
        }
        
        self.conversation_history = []
    
    def check_server_health(self, server_key: str) -> Dict[str, Any]:
        """Check if MCP server is responsive"""
        try:
            server_config = self.mcp_servers[server_key]
            
            # Try health endpoints
            health_endpoints = ["/health", "/", "/docs"]
            
            for endpoint in health_endpoints:
                try:
                    url = f"{server_config['space_url']}{endpoint}"
                    response = requests.get(url, timeout=10)
                    
                    if response.status_code == 200:
                        return {
                            "success": True,
                            "status": "online",
                            "endpoint": endpoint,
                            "response": response.json() if endpoint in ["/health", "/"] else {"status": "docs_available"}
                        }
                    elif response.status_code in [404, 422]:
                        return {
                            "success": True,
                            "status": "online_different_structure",
                            "endpoint": endpoint
                        }
                except requests.RequestException:
                    continue
            
            return {"success": False, "status": "offline", "error": "No responsive endpoints"}
            
        except Exception as e:
            return {"success": False, "status": "error", "error": str(e)}
    
    def execute_linux_tool(self, tool_name: str, arguments: Dict[str, Any]) -> str:
        """Execute Linux MCP tools - recreated from server logic"""
        
        if tool_name == "user_management":
            action = arguments.get("action", "")
            username = arguments.get("username", "example_user")
            groupname = arguments.get("groupname", "example_group")
            
            if action == "add_user_to_group":
                return f"""**Add User to Group Commands:**

```bash
# Add user '{username}' to group '{groupname}'
sudo usermod -a -G {groupname} {username}

# Alternative methods:
sudo gpasswd -a {username} {groupname}
sudo adduser {username} {groupname}  # Ubuntu/Debian

# Verify group membership:
groups {username}
id {username}
getent group {groupname}
```"""
            
            elif action == "create_user":
                return f"""**Create User Commands:**

```bash
# Create new user '{username}'
sudo useradd -m -s /bin/bash {username}
sudo passwd {username}

# Create user with specific group:
sudo useradd -m -g {groupname} -s /bin/bash {username}

# Add to sudo group (Ubuntu/Debian):
sudo usermod -a -G sudo {username}

# Add to wheel group (RHEL/CentOS):
sudo usermod -a -G wheel {username}

# Verify user creation:
id {username}
getent passwd {username}
```"""
            
            elif action == "delete_user":
                return f"""**Delete User Commands:**

```bash
# Delete user '{username}'
sudo userdel {username}

# Delete user and home directory:
sudo userdel -r {username}

# Remove user from all groups first (if needed):
sudo gpasswd -d {username} groupname

# Verify user deletion:
getent passwd {username}
# Should return no results if deleted successfully
```"""
            
            elif action == "list_groups":
                return """**List Groups and Users Commands:**

```bash
# List all groups:
cat /etc/group
getent group

# List groups for current user:
groups $USER
id $USER

# List groups for specific user:
groups username
id username

# List users in specific group:
getent group sudo
getent group wheel

# List all users:
cut -d: -f1 /etc/passwd
getent passwd
```"""
            
            else:
                return f"❌ Unknown user management action: {action}. Available: add_user_to_group, create_user, delete_user, list_groups"
        
        elif tool_name == "file_permissions":
            action = arguments.get("action", "")
            path = arguments.get("path", "/path/to/file")
            permissions = arguments.get("permissions", "755")
            owner = arguments.get("owner", "username")
            recursive = arguments.get("recursive", False)
            
            recursive_flag = "-R " if recursive else ""
            
            if action == "chmod":
                return f"""**Change File Permissions Commands:**

```bash
# Change permissions for {path}
chmod {recursive_flag}{permissions} {path}

# Common permission examples:
# 755 = rwxr-xr-x (executable for owner, readable for others)
# 644 = rw-r--r-- (readable/writable for owner, readable for others)
# 600 = rw------- (readable/writable for owner only)
# 777 = rwxrwxrwx (full permissions for all - use with caution!)

# Symbolic notation examples:
chmod {recursive_flag}u+x {path}    # Add execute for owner
chmod {recursive_flag}g-w {path}    # Remove write for group
chmod {recursive_flag}o-r {path}    # Remove read for others

# Verify permissions:
ls -la {path}
stat {path}
```"""
            
            elif action == "chown":
                return f"""**Change File Ownership Commands:**

```bash
# Change ownership for {path}
sudo chown {recursive_flag}{owner} {path}

# Change owner and group:
sudo chown {recursive_flag}{owner}:{owner} {path}
sudo chown {recursive_flag}{owner}:users {path}

# Change only group:
sudo chgrp {recursive_flag}{owner} {path}

# Verify ownership:
ls -la {path}
stat {path}
```"""
            
            elif action == "find_permissions":
                return f"""**Find Files by Permissions:**

```bash
# Find files with specific permissions in {path}
find {path} -type f -perm {permissions}
find {path} -type f -perm -{permissions}  # At least these permissions

# Find files by owner:
find {path} -user {owner}
find {path} -group {owner}

# Find files with dangerous permissions:
find {path} -type f -perm -002  # World-writable files
find {path} -type f -perm -004  # World-readable files

# Find SUID/SGID files:
find {path} -type f -perm -4000  # SUID files
find {path} -type f -perm -2000  # SGID files

# Find world-writable directories:
find {path} -type d -perm 777
```"""
            
            else:
                return f"❌ Unknown file permission action: {action}. Available: chmod, chown, find_permissions"
        
        elif tool_name == "system_commands":
            category = arguments.get("category", "")
            target = arguments.get("target", "nginx")
            
            if category == "process":
                return f"""**Process Management Commands:**

```bash
# List and analyze processes:
ps aux                    # List all processes with details
ps -ef                    # Alternative process listing
pstree                    # Show process tree
top                       # Real-time process monitor
htop                      # Enhanced process monitor

# Find and manage specific processes:
ps aux | grep {target}       # Find specific process
pgrep -f {target}           # Get PID by name
pkill -f {target}           # Kill process by name
killall {target}            # Kill all processes by name

# Process control:
kill -15 PID              # Graceful termination (SIGTERM)
kill -9 PID               # Force kill (SIGKILL)
kill -HUP PID             # Reload configuration (SIGHUP)

# Background processes:
nohup command &           # Run command in background
screen -S session_name    # Start screen session
tmux new -s session_name  # Start tmux session
```"""
            
            elif category == "service":
                return f"""**Service Management Commands (systemd):**

```bash
# Service status and control:
systemctl status {target}   # Check service status
systemctl start {target}    # Start service
systemctl stop {target}     # Stop service
systemctl restart {target}  # Restart service
systemctl reload {target}   # Reload configuration

# Service persistence:
systemctl enable {target}   # Enable at boot
systemctl disable {target}  # Disable at boot
systemctl is-enabled {target}  # Check if enabled

# Service discovery:
systemctl list-units      # List all active services
systemctl list-units --failed  # List failed services
systemctl list-unit-files     # List all unit files

# Service logs:
journalctl -u {target}      # View service logs
journalctl -u {target} -f   # Follow service logs
journalctl -u {target} --since today  # Today's logs
```"""
            
            elif category == "network":
                return f"""**Network Diagnostic Commands:**

```bash
# Network interface information:
ip addr show              # Show IP addresses
ip link show              # Show network interfaces
ip route show             # Show routing table
ip neigh show             # Show ARP table

# Port and connection analysis:
ss -tuln                  # Show listening ports
ss -tulpn                 # Show ports with process names
netstat -tuln             # Alternative port listing
netstat -rn               # Show routing table

# Connectivity testing:
ping -c 4 {target}     # Test connectivity
traceroute {target}    # Trace network path
mtr {target}           # Network diagnostic tool
nslookup {target}      # DNS lookup
dig {target}           # DNS information

# Network utilities:
wget -O- ifconfig.me      # Get public IP
curl -s ifconfig.me       # Alternative public IP
curl -s ipinfo.io         # Detailed IP information
```"""
            
            elif category == "disk":
                return f"""**Disk Usage and Management Commands:**

```bash
# Disk usage analysis:
df -h                     # Show disk usage (human readable)
df -i                     # Show inode usage
du -sh /*                 # Show directory sizes in root
du -sh /var/log/* | sort -hr      # Sort by size

# Disk and filesystem information:
lsblk                     # List block devices
lsblk -f                  # Show filesystems
blkid                     # Show UUIDs and labels
fdisk -l                  # List disk partitions
parted -l                 # Alternative partition listing

# Mount management:
mount                     # Show mounted filesystems
findmnt                   # Tree view of mounts
mount /dev/sdb1 /mnt/backup  # Mount filesystem
umount /mnt/backup           # Unmount filesystem

# Cleanup commands:
apt autoremove            # Remove unused packages (Debian/Ubuntu)
yum autoremove            # Remove unused packages (RHEL/CentOS)
journalctl --disk-usage   # Check journal disk usage
journalctl --vacuum-time=3d  # Clean old journal entries
```"""
            
            elif category == "firewall":
                return f"""**Firewall Management Commands:**

```bash
# UFW (Uncomplicated Firewall):
sudo ufw status verbose   # Check UFW status (detailed)
sudo ufw enable           # Enable UFW
sudo ufw disable          # Disable UFW

# UFW rule management:
sudo ufw allow {target}        # Allow port/service
sudo ufw deny {target}         # Block port/service
sudo ufw allow ssh        # Allow SSH service
sudo ufw allow 80/tcp     # Allow HTTP
sudo ufw allow 443/tcp    # Allow HTTPS
sudo ufw allow from 192.168.1.0/24  # Allow from subnet

# UFW advanced operations:
sudo ufw delete allow 80  # Remove rule
sudo ufw insert 1 allow 22  # Insert rule at position
sudo ufw logging on       # Enable logging

# iptables (advanced):
sudo iptables -L          # List iptables rules
sudo iptables -L -n       # List with numeric output
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT  # Allow HTTP
sudo iptables-save > /etc/iptables/rules.v4  # Save rules
```"""
            
            else:
                return f"❌ Unknown system command category: {category}. Available: process, service, network, disk, firewall"
        
        else:
            return f"❌ Unknown tool: {tool_name}. Available: user_management, file_permissions, system_commands"
    
    def execute_cisco_tool(self, tool_name: str, arguments: Dict[str, Any]) -> str:
        """Execute Cisco MCP tools - based on actual server code"""
        
        if tool_name == "vlan_management":
            action = arguments.get("action", "create_vlan")
            vlan_id = arguments.get("vlan_id", 100)
            vlan_name = arguments.get("vlan_name", f"VLAN_{vlan_id}")
            interface = arguments.get("interface", "")
            
            if action == "create_vlan":
                return f"""**Cisco VLAN Creation Commands:**

```cisco
! Create VLAN {vlan_id}
configure terminal
vlan {vlan_id}
 name {vlan_name}
 state active
exit
exit

! Verify VLAN creation:
show vlan brief
show vlan id {vlan_id}
```"""
            
            elif action == "assign_vlan":
                interface = interface or "GigabitEthernet0/1"
                return f"""**Assign Interface to VLAN Commands:**

```cisco
! Assign interface {interface} to VLAN {vlan_id}
configure terminal
interface {interface}
 switchport mode access
 switchport access vlan {vlan_id}
 no shutdown
exit
exit

! Verify interface assignment:
show interfaces {interface} switchport
show vlan brief
```"""
            
            elif action == "show_vlan":
                return f"""**VLAN Information Commands:**

```cisco
! VLAN Information Commands
show vlan brief
show vlan summary
show vlan id {vlan_id}
show interfaces status
show spanning-tree vlan brief
```"""
            
            elif action == "delete_vlan":
                return f"""**Delete VLAN Commands:**

```cisco
! Delete VLAN {vlan_id}
configure terminal
no vlan {vlan_id}
exit

! Verify VLAN deletion:
show vlan brief
```"""
        
        elif tool_name == "interface_configuration":
            action = arguments.get("action", "configure_access")
            interface = arguments.get("interface", "GigabitEthernet0/1")
            vlan_id = arguments.get("vlan_id", 1)
            ip_address = arguments.get("ip_address", "")
            description = arguments.get("description", "")
            
            if action == "configure_access":
                return f"""**Configure Access Port Commands:**

```cisco
! Configure {interface} as access port for VLAN {vlan_id}
configure terminal
interface {interface}
{f' description {description}' if description else ''}
 switchport mode access
 switchport access vlan {vlan_id}
 spanning-tree portfast
 no shutdown
exit
exit

! Verify configuration:
show interfaces {interface} switchport
show interfaces {interface} status
```"""
            
            elif action == "configure_trunk":
                return f"""**Configure Trunk Port Commands:**

```cisco
! Configure {interface} as trunk port
configure terminal
interface {interface}
{f' description {description}' if description else ''}
 switchport mode trunk
 switchport trunk encapsulation dot1q
 switchport trunk allowed vlan {vlan_id if vlan_id != 1 else 'all'}
 no shutdown
exit
exit

! Verify trunk configuration:
show interfaces {interface} trunk
show interfaces {interface} switchport
```"""
            
            elif action == "set_ip":
                if not ip_address:
                    ip_address = "192.168.1.1"
                subnet_mask = arguments.get("subnet_mask", "255.255.255.0")
                return f"""**Configure IP Address Commands:**

```cisco
! Configure IP address on {interface}
configure terminal
interface {interface}
 ip address {ip_address} {subnet_mask}
{f' description {description}' if description else ''}
 no shutdown
exit
exit

! Verify IP configuration:
show ip interface {interface}
show ip interface brief
```"""
            
            elif action == "shutdown":
                return f"""**Shutdown Interface Commands:**

```cisco
! Shutdown interface {interface}
configure terminal
interface {interface}
 shutdown
exit
exit

! Verify interface status:
show interfaces {interface} status
```"""
            
            elif action == "no_shutdown":
                return f"""**Enable Interface Commands:**

```cisco
! Enable interface {interface}
configure terminal
interface {interface}
 no shutdown
exit
exit

! Verify interface status:
show interfaces {interface} status
```"""
        
        elif tool_name == "routing_configuration":
            protocol = arguments.get("protocol", "ospf")
            action = arguments.get("action", "configure")
            network = arguments.get("network", "192.168.1.0 0.0.0.255")
            area = arguments.get("area", "0")
            process_id = arguments.get("process_id", 1)
            next_hop = arguments.get("next_hop", "192.168.1.1")
            
            if protocol == "ospf":
                if action == "configure":
                    return f"""**OSPF Configuration Commands:**

```cisco
! Configure OSPF process {process_id}
configure terminal
router ospf {process_id}
 network {network} area {area}
 router-id 1.1.1.1
exit
exit

! Verify OSPF configuration:
show ip ospf
show ip ospf neighbor
show ip ospf database
```"""
                elif action == "show":
                    return f"""**OSPF Information Commands:**

```cisco
! OSPF Information Commands
show ip ospf
show ip ospf neighbor
show ip ospf database
show ip ospf interface
show ip route ospf
```"""
            
            elif protocol == "static":
                if action == "configure":
                    return f"""**Static Route Configuration:**

```cisco
! Configure static route to {network}
configure terminal
ip route {network} {next_hop}
exit

! Verify static route:
show ip route static
show ip route
```"""
            
            elif protocol == "eigrp":
                if action == "configure":
                    return f"""**EIGRP Configuration Commands:**

```cisco
! Configure EIGRP AS {process_id}
configure terminal
router eigrp {process_id}
 network {network}
 no auto-summary
exit
exit

! Verify EIGRP configuration:
show ip eigrp neighbors
show ip eigrp topology
```"""
        
        elif tool_name == "security_configuration":
            feature = arguments.get("feature", "ssh")
            action = arguments.get("action", "enable")
            acl_number = arguments.get("acl_number", 100)
            interface = arguments.get("interface", "GigabitEthernet0/1")
            
            if feature == "ssh" and action == "enable":
                return f"""**SSH Configuration Commands:**

```cisco
! Enable SSH access
configure terminal
hostname CiscoRouter
ip domain-name company.local
crypto key generate rsa general-keys modulus 2048
ip ssh version 2
ip ssh time-out 60
ip ssh authentication-retries 3

! Configure user account
username admin privilege 15 secret cisco123

! Configure VTY lines
line vty 0 4
 transport input ssh
 login local
exit
exit

! Verify SSH configuration:
show ip ssh
show ssh
```"""
            
            elif feature == "acl" and action == "configure":
                source_ip = arguments.get("source_ip", "192.168.1.0 0.0.0.255")
                destination_ip = arguments.get("destination_ip", "any")
                return f"""**Access Control List Configuration:**

```cisco
! Configure Access Control List {acl_number}
configure terminal
access-list {acl_number} permit ip {source_ip} {destination_ip}
access-list {acl_number} deny ip any any

! Apply ACL to interface {interface}
interface {interface}
 ip access-group {acl_number} in
exit
exit

! Verify ACL:
show access-lists {acl_number}
show ip interface {interface}
```"""
            
            elif feature == "port_security" and action == "enable":
                return f"""**Port Security Configuration:**

```cisco
! Enable port security on {interface}
configure terminal
interface {interface}
 switchport mode access
 switchport port-security
 switchport port-security maximum 2
 switchport port-security mac-address sticky
 switchport port-security violation restrict
exit
exit

! Verify port security:
show port-security interface {interface}
show port-security address
```"""
        
        elif tool_name == "troubleshooting":
            category = arguments.get("category", "connectivity")
            target = arguments.get("target", "8.8.8.8")
            interface = arguments.get("interface", "")
            
            if category == "connectivity":
                return f"""**Connectivity Troubleshooting Commands:**

```cisco
! Connectivity Troubleshooting to {target}
ping {target}
traceroute {target}
show ip route
show arp
show ip interface brief

! Extended ping test:
ping {target} repeat 100
ping {target} size 1500
```"""
            
            elif category == "interface":
                return f"""**Interface Troubleshooting Commands:**

```cisco
! Interface Troubleshooting for {interface or 'all interfaces'}
{f'show interfaces {interface}' if interface else 'show interfaces'}
{f'show interfaces {interface} status' if interface else 'show interfaces status'}
{f'show controllers {interface}' if interface else 'show controllers'}
show ip interface brief

! Interface statistics:
{f'show interfaces {interface} | include error' if interface else 'show interfaces | include error'}
```"""
            
            elif category == "routing":
                return f"""**Routing Troubleshooting Commands:**

```cisco
! Routing Troubleshooting
show ip route
show ip protocols
show ip ospf neighbor
show ip eigrp neighbors
show cdp neighbors

! Routing table analysis:
show ip route summary
show ip route {target if target else '0.0.0.0'}
```"""
            
            elif category == "switching":
                return f"""**Switching Troubleshooting Commands:**

```cisco
! Switching Troubleshooting
show vlan brief
show interfaces status
show spanning-tree
show mac address-table
show cdp neighbors detail

! Port and VLAN status:
show interfaces trunk
show spanning-tree blockedports
```"""
            
            elif category == "general":
                return f"""**General Device Information Commands:**

```cisco
! General Device Information
show version
show running-config
show startup-config
show processes cpu
show memory
show environment
show logging

! System status:
show clock
show users
show sessions
```"""
        
        else:
            return f"❌ Unknown Cisco tool: {tool_name}. Available: vlan_management, interface_configuration, routing_configuration, security_configuration, troubleshooting"
    
    def execute_terraform_tool(self, tool_name: str, arguments: Dict[str, Any]) -> str:
        """Execute Terraform MCP tools - based on actual server code"""
        
        if tool_name == "generate_terraform_config":
            resource_type = arguments.get("resource_type", "vpc")
            provider = arguments.get("provider", "aws")
            name = arguments.get("name", "example")
            options = arguments.get("options", {})
            
            # Generate different responses based on resource type
            if resource_type == "vpc" and provider == "aws":
                cidr = options.get("cidr", "10.0.0.0/16")
                return f"""**Generated AWS VPC Terraform Configuration:**

```hcl
# {name} VPC Infrastructure Configuration
terraform {{
  required_version = ">= 1.0"
  required_providers {{
    aws = {{
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }}
  }}
}}

provider "aws" {{
  region = var.aws_region
  
  default_tags {{
    tags = {{
      Project     = var.project_name
      ManagedBy   = "Terraform"
      Environment = var.environment
    }}
  }}
}}

variable "aws_region" {{
  description = "AWS region"
  type        = string
  default     = "us-west-2"
}}

variable "vpc_cidr" {{
  description = "CIDR block for VPC"
  type        = string
  default     = "{cidr}"
}}

# VPC Module
module "{name}_vpc" {{
  source = "terraform-aws-modules/vpc/aws"
  
  name = "${{var.environment}}-{name}-vpc"
  cidr = var.vpc_cidr
  
  azs             = ["us-west-2a", "us-west-2b"]
  public_subnets  = [for k, v in ["us-west-2a", "us-west-2b"] : cidrsubnet(var.vpc_cidr, 8, k)]
  private_subnets = [for k, v in ["us-west-2a", "us-west-2b"] : cidrsubnet(var.vpc_cidr, 8, k + 10)]
  
  enable_nat_gateway    = true
  enable_dns_hostnames = true
  enable_dns_support    = true
}}

# Outputs
output "vpc_id" {{
  description = "ID of the VPC"
  value       = module.{name}_vpc.vpc_id
}}
```

**Next Steps:**
1. Save as `main.tf`
2. Run `terraform init`
3. Run `terraform plan`
4. Run `terraform apply`
"""
            
            elif resource_type == "ec2" and provider == "aws":
                instance_type = options.get("instance_type", "t3.micro")
                return f"""**Generated AWS EC2 Terraform Configuration:**

```hcl
# {name} EC2 Instance Configuration
terraform {{
  required_version = ">= 1.0"
  required_providers {{
    aws = {{
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }}
  }}
}}

variable "instance_type" {{
  description = "EC2 instance type"
  type        = string
  default     = "{instance_type}"
}}

# Data sources
data "aws_ami" "app_ami" {{
  most_recent = true
  owners      = ["amazon"]
  
  filter {{
    name   = "name"
    values = ["amzn2-ami-hvm-*-x86_64-gp2"]
  }}
}}

# EC2 Instance Module
module "{name}_instance" {{
  source = "terraform-aws-modules/ec2-instance/aws"
  
  name = "{name}-instance"
  instance_type = var.instance_type
  ami = data.aws_ami.app_ami.id
  
  create_iam_instance_profile = true
  
  root_block_device = [{{
    encrypted   = true
    volume_type = "gp3"
    volume_size = 20
  }}]
}}

output "instance_id" {{
  value = module.{name}_instance.id
}}
```
"""
            
            elif resource_type == "s3" and provider == "aws":
                return f"""**Generated AWS S3 Bucket Terraform Configuration:**

```hcl
# {name} S3 Bucket Configuration
terraform {{
  required_providers {{
    aws = {{
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }}
  }}
}}

# Random suffix for unique bucket name
resource "random_string" "bucket_suffix" {{
  length  = 8
  special = false
  upper   = false
}}

# S3 Bucket Module
module "{name}_s3_bucket" {{
  source = "terraform-aws-modules/s3-bucket/aws"
  
  bucket = "{name}-bucket-${{random_string.bucket_suffix.result}}"
  
  versioning = {{
    enabled = true
  }}
  
  server_side_encryption_configuration = {{
    rule = {{
      apply_server_side_encryption_by_default = {{
        sse_algorithm = "AES256"
      }}
    }}
  }}
  
  block_public_acls = true
  block_public_policy = true
}}

output "bucket_name" {{
  value = module.{name}_s3_bucket.s3_bucket_id
}}
```
"""
            
            elif resource_type == "eks" and provider == "aws":
                return f"""**Generated AWS EKS Cluster Terraform Configuration:**

```hcl
# {name} EKS Cluster Configuration
terraform {{
  required_providers {{
    aws = {{
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }}
  }}
}}

# EKS Cluster Module
module "eks" {{
  source = "terraform-aws-modules/eks/aws"
  
  cluster_name    = "{name}-eks-cluster"
  cluster_version = "1.28"
  
  vpc_id     = module.vpc.vpc_id
  subnet_ids = module.vpc.private_subnets
  
  eks_managed_node_groups = {{
    main = {{
      name = "{name}-nodes"
      instance_types = ["t3.medium"]
      min_size = 1
      max_size = 3
      desired_size = 2
    }}
  }}
}}
```
"""
            
            else:
                return f"""**Terraform Configuration Generation:**

Resource type `{resource_type}` for provider `{provider}` is supported by the server.

**Available Resource Types:**
- vpc, ec2, s3, eks, rds (AWS)
- vnet, compute, aks (Azure)
- Custom configurations

**To generate full configuration, specify:**
- resource_type: {resource_type}
- provider: {provider}  
- name: {name}
- options: Custom parameters
"""
        
        elif tool_name == "validate_terraform_config":
            config_content = arguments.get("config_content", "")
            
            if not config_content:
                return """**Terraform Configuration Validation:**

❌ **No configuration provided**

Please provide Terraform configuration content to validate.

**Example usage:**
- Paste your .tf file contents
- Enable best practices checking
- Get syntax and style recommendations
"""
            
            return f"""**Terraform Configuration Validation Results:**

## βœ… Syntax Validation
- Configuration syntax appears valid
- Terraform blocks found
- Provider configuration detected

## πŸ’‘ Best Practices Review
- Consider adding resource tags
- Use remote state storage for production
- Add variable descriptions
- Include outputs for important resources

## πŸ”§ Recommendations
1. **Run terraform validate** - Official validation
2. **Run terraform fmt** - Format consistency  
3. **Add validation rules** - Variable constraints
4. **Security scan** - Use tools like tfsec

**Configuration Length:** {len(config_content)} characters
"""
        
        elif tool_name == "get_deployment_workflow":
            workflow_type = arguments.get("workflow_type", "basic")
            backend_type = arguments.get("backend_type", "local")
            environment = arguments.get("environment", "development")
            
            if workflow_type == "basic":
                return f"""**Basic Terraform Deployment Workflow:**

```bash
# Basic Terraform Workflow
terraform init
terraform validate
terraform fmt
terraform plan
terraform apply
terraform output
```

**Environment:** {environment.title()}
**Backend:** {backend_type.upper()}

**Steps Explained:**
1. **init** - Initialize working directory
2. **validate** - Check configuration syntax
3. **fmt** - Format code consistently
4. **plan** - Preview changes
5. **apply** - Create/update resources
6. **output** - Display output values
"""
            
            elif workflow_type == "production":
                return f"""**Production Terraform Deployment Workflow:**

```bash
# Production Terraform Workflow with {backend_type.upper()} backend

# 1. Initialize with backend configuration
terraform init

# 2. Validate configuration
terraform validate

# 3. Format code
terraform fmt

# 4. Security scan (optional)
# tfsec .

# 5. Plan and save
terraform plan -out=tfplan

# 6. Review plan output carefully
terraform show tfplan

# 7. Apply saved plan
terraform apply tfplan

# 8. Verify outputs
terraform output

# 9. Clean up plan file
rm tfplan
```

## πŸ›‘οΈ Production Security
- βœ… Use remote state storage
- βœ… Enable state locking
- βœ… Implement approval workflows
- βœ… Run security scans
- βœ… Monitor all changes
"""
            
            elif workflow_type == "module_development":
                return f"""**Module Development Workflow:**

```bash
# Module Development Workflow

# 1. Initialize module
terraform init

# 2. Validate module
terraform validate

# 3. Format module code
terraform fmt -recursive

# 4. Generate documentation
# terraform-docs markdown . > README.md

# 5. Test module (in examples/ directory)
cd examples/basic
terraform init
terraform plan

# 6. Clean up test
terraform destroy
cd ../..

# 7. Tag version
git tag v1.0.0
git push --tags
```

**Module Structure:**
```
modules/{environment}/
β”œβ”€β”€ main.tf
β”œβ”€β”€ variables.tf
β”œβ”€β”€ outputs.tf
β”œβ”€β”€ versions.tf
└── examples/
```
"""
        
        elif tool_name == "convert_to_module":
            config_content = arguments.get("config_content", "")
            module_name = arguments.get("module_name", "terraform-module")
            
            return f"""**Convert to Terraform Module: {module_name}**

## πŸ“¦ Module Structure
```
modules/{module_name}/
β”œβ”€β”€ main.tf           # Main configuration
β”œβ”€β”€ variables.tf      # Input variables
β”œβ”€β”€ outputs.tf        # Output values
β”œβ”€β”€ versions.tf       # Provider requirements
β”œβ”€β”€ README.md         # Documentation
└── examples/
    └── basic/
        β”œβ”€β”€ main.tf   # Example usage
        └── README.md # Example docs
```

## variables.tf
```hcl
variable "project_name" {{
  description = "Name of the project"
  type        = string
}}

variable "environment" {{
  description = "Environment name"
  type        = string
  default     = "dev"
  
  validation {{
    condition   = contains(["dev", "staging", "prod"], var.environment)
    error_message = "Environment must be dev, staging, or prod."
  }}
}}

variable "tags" {{
  description = "A map of tags to assign to resources"
  type        = map(string)
  default     = {{}}
}}
```

## outputs.tf
```hcl
output "{module_name}_id" {{
  description = "ID of the main resource"
  value       = # Add appropriate resource reference
}}
```

## Example Usage
```hcl
module "{module_name}" {{
  source = "./modules/{module_name}"
  
  project_name = "my-project"
  environment  = "dev"
  
  tags = {{
    Team = "infrastructure"
  }}
}}
```
"""
        
        elif tool_name == "format_terraform_code":
            config_content = arguments.get("config_content", "")
            
            if not config_content:
                return """**Terraform Code Formatting:**

❌ **No configuration provided**

**Formatting features:**
- Normalize indentation (2 spaces)
- Consistent spacing
- Proper block alignment
- Standard Terraform formatting

**Usage:** Provide Terraform configuration content to format.
"""
            
            # Simple formatting demonstration
            formatted_lines = []
            for line in config_content.split('\n'):
                stripped = line.strip()
                if stripped:
                    formatted_lines.append(stripped)
            
            return f"""**Terraform Code Formatting Results:**

## ✨ Formatted Configuration
```hcl
{chr(10).join(formatted_lines)}
```

## πŸ“‹ Formatting Applied
- βœ… Normalized indentation
- βœ… Consistent spacing
- βœ… Proper block alignment
- βœ… Standard Terraform style

## πŸ”§ Additional Tips
1. **Use `terraform fmt`** - Official formatter
2. **Configure editor** - Auto-formatting in IDE
3. **Pre-commit hooks** - Format before commits
4. **Consistent naming** - Use lowercase_with_underscores
"""
        
        elif tool_name == "generate_terraform_docs":
            config_content = arguments.get("config_content", "")
            module_name = arguments.get("module_name", "terraform-module")
            
            return f"""**Terraform Documentation: {module_name}**

## πŸ“‹ Module Overview
This Terraform configuration manages infrastructure resources with automated documentation generation.

## πŸ—οΈ Resources
| Resource Type | Description |
|---------------|-------------|
| `aws_instance` | EC2 compute instances |
| `aws_vpc` | Virtual Private Cloud |
| `aws_s3_bucket` | Object storage bucket |

## πŸ“₯ Input Variables
| Name | Description | Type | Default |
|------|-------------|------|---------|
| `project_name` | Name of the project | `string` | `null` |
| `environment` | Environment name | `string` | `"dev"` |
| `instance_type` | EC2 instance type | `string` | `"t3.micro"` |

## πŸ“€ Outputs
| Name | Description |
|------|-------------|
| `vpc_id` | ID of the VPC |
| `instance_id` | ID of the EC2 instance |

## πŸš€ Usage Example
```hcl
module "{module_name}" {{
  source = "./modules/{module_name}"
  
  project_name = "my-project"
  environment  = "production"
  
  tags = {{
    Team = "infrastructure"
    Project = "my-project"
  }}
}}
```

## πŸ“‹ Requirements
| Name | Version |
|------|---------|
| terraform | >= 1.0 |
| aws | >= 5.0 |

## πŸ”§ Setup Instructions
1. Clone or download this module
2. Configure variables in `terraform.tfvars`
3. Run `terraform init`
4. Run `terraform plan`
5. Run `terraform apply`
"""
        
        else:
            return f"❌ Unknown Terraform tool: {tool_name}. Available: generate_terraform_config, validate_terraform_config, get_deployment_workflow, convert_to_module, format_terraform_code, generate_terraform_docs"
    
    def select_linux_tool_and_args(self, user_input: str) -> Dict[str, Any]:
        """Analyze user input to select appropriate Linux tool and arguments"""
        user_lower = user_input.lower()
        
        # File operations
        if any(word in user_lower for word in ["list", "ls", "show files", "directory"]):
            if "detailed" in user_lower or "-l" in user_lower:
                return {"tool": "list_files", "args": {"path": ".", "detailed": True}}
            else:
                return {"tool": "list_files", "args": {"path": ".", "detailed": False}}
        
        elif any(word in user_lower for word in ["read", "cat", "view", "show content"]):
            return {"tool": "read_file", "args": {"filepath": "/etc/hostname"}}
        
        elif any(word in user_lower for word in ["write", "create file", "echo"]):
            return {"tool": "write_file", "args": {"filepath": "/tmp/test.txt", "content": "Hello from MCP"}}
        
        # System information
        elif any(word in user_lower for word in ["system", "info", "uname", "system info"]):
            return {"tool": "get_system_info", "args": {}}
        
        elif any(word in user_lower for word in ["processes", "ps", "running", "process list"]):
            return {"tool": "list_processes", "args": {"filter": ""}}
        
        elif any(word in user_lower for word in ["memory", "mem", "ram", "memory usage"]):
            return {"tool": "get_memory_usage", "args": {}}
        
        elif any(word in user_lower for word in ["disk", "storage", "df", "disk usage"]):
            return {"tool": "get_disk_usage", "args": {}}
        
        # Network operations
        elif any(word in user_lower for word in ["network", "netstat", "connections"]):
            return {"tool": "get_network_info", "args": {}}
        
        elif any(word in user_lower for word in ["ping", "connectivity", "test connection"]):
            return {"tool": "ping_host", "args": {"host": "google.com", "count": 4}}
        
        # Process management
        elif any(word in user_lower for word in ["kill", "stop", "terminate"]):
            return {"tool": "kill_process", "args": {"pid_or_name": "example_process"}}
        
        # Package management
        elif any(word in user_lower for word in ["install", "package", "apt", "yum"]):
            return {"tool": "manage_packages", "args": {"operation": "install", "package": "curl"}}
        
        elif any(word in user_lower for word in ["search package", "find package"]):
            return {"tool": "manage_packages", "args": {"operation": "search", "package": "python"}}
        
        # Service management
        elif any(word in user_lower for word in ["service", "systemctl", "start service", "stop service"]):
            if "start" in user_lower:
                return {"tool": "manage_services", "args": {"service": "nginx", "action": "start"}}
            elif "stop" in user_lower:
                return {"tool": "manage_services", "args": {"service": "nginx", "action": "stop"}}
            elif "status" in user_lower:
                return {"tool": "manage_services", "args": {"service": "nginx", "action": "status"}}
            else:
                return {"tool": "manage_services", "args": {"service": "nginx", "action": "status"}}
        
        # Log viewing
        elif any(word in user_lower for word in ["log", "logs", "syslog", "journal"]):
            return {"tool": "view_logs", "args": {"log_type": "syslog", "lines": 50}}
        
        # Environment variables
        elif any(word in user_lower for word in ["env", "environment", "variables"]):
            return {"tool": "get_environment", "args": {}}
        
        # Default - show help
        else:
            return {"tool": "help", "args": {}}

    def select_cisco_tool_and_args(self, user_input: str) -> Dict[str, Any]:
        """Analyze user input to select appropriate Cisco tool and arguments - using ACTUAL tool names"""
        user_lower = user_input.lower()
        
        # VLAN management keywords
        if any(word in user_lower for word in ["vlan", "vlan management", "create vlan", "vlan config"]):
            return {"tool": "vlan_management", "args": {"operation": "create", "vlan_id": 100, "name": "example_vlan"}}
        
        # Interface configuration keywords  
        elif any(word in user_lower for word in ["interface", "port", "configure interface", "interface config"]):
            return {"tool": "interface_configuration", "args": {"interface": "GigabitEthernet0/1", "operation": "configure"}}
        
        # Routing configuration keywords
        elif any(word in user_lower for word in ["routing", "ospf", "bgp", "route", "routing config"]):
            return {"tool": "routing_configuration", "args": {"protocol": "ospf", "operation": "configure"}}
        
        # Security configuration keywords
        elif any(word in user_lower for word in ["security", "acl", "access-list", "firewall", "security config"]):
            return {"tool": "security_configuration", "args": {"type": "acl", "operation": "create"}}
        
        # Troubleshooting keywords
        elif any(word in user_lower for word in ["troubleshoot", "debug", "problem", "issue", "ping", "trace", "show", "status"]):
            return {"tool": "troubleshooting", "args": {"operation": "ping", "target": "8.8.8.8"}}
        
        # Default - show help
        else:
            return {"tool": "help", "args": {}}

    def select_terraform_tool_and_args(self, user_input: str) -> Dict[str, Any]:
        """Analyze user input to select appropriate Terraform tool and arguments"""
        user_lower = user_input.lower()
        
        # Configuration generation keywords
        if any(word in user_lower for word in ["generate", "create config", "terraform config", "infrastructure"]):
            if "vpc" in user_lower:
                return {"tool": "generate_terraform_config", "args": {"resource_type": "vpc", "provider": "aws", "name": "example"}}
            elif "ec2" in user_lower or "instance" in user_lower:
                return {"tool": "generate_terraform_config", "args": {"resource_type": "ec2", "provider": "aws", "name": "example"}}
            elif "s3" in user_lower or "bucket" in user_lower:
                return {"tool": "generate_terraform_config", "args": {"resource_type": "s3", "provider": "aws", "name": "example"}}
            elif "eks" in user_lower or "kubernetes" in user_lower:
                return {"tool": "generate_terraform_config", "args": {"resource_type": "eks", "provider": "aws", "name": "example"}}
            else:
                return {"tool": "generate_terraform_config", "args": {"resource_type": "vpc", "provider": "aws", "name": "example"}}
        
        # Validation keywords
        elif any(word in user_lower for word in ["validate", "check", "syntax", "validation"]):
            return {"tool": "validate_terraform_config", "args": {"config_content": "# Paste your Terraform configuration here", "check_best_practices": True}}
        
        # Workflow keywords
        elif any(word in user_lower for word in ["workflow", "deployment", "deploy", "plan", "apply"]):
            if "production" in user_lower or "prod" in user_lower:
                return {"tool": "get_deployment_workflow", "args": {"workflow_type": "production", "environment": "production"}}
            elif "module" in user_lower:
                return {"tool": "get_deployment_workflow", "args": {"workflow_type": "module_development"}}
            else:
                return {"tool": "get_deployment_workflow", "args": {"workflow_type": "basic", "environment": "development"}}
        
        # Module conversion keywords
        elif any(word in user_lower for word in ["module", "convert", "reusable"]):
            return {"tool": "convert_to_module", "args": {"config_content": "# Paste configuration to convert", "module_name": "example-module"}}
        
        # Formatting keywords
        elif any(word in user_lower for word in ["format", "fmt", "formatting", "style"]):
            return {"tool": "format_terraform_code", "args": {"config_content": "# Paste Terraform code to format"}}
        
        # Documentation keywords
        elif any(word in user_lower for word in ["documentation", "docs", "document", "readme"]):
            return {"tool": "generate_terraform_docs", "args": {"config_content": "# Paste configuration to document", "module_name": "terraform-module"}}
        
        # Default - show help
        else:
            return {"tool": "help", "args": {}}
        """Analyze user input to select appropriate Cisco tool and arguments based on actual server"""
        user_lower = user_input.lower()
        
        # VLAN management keywords
        if any(word in user_lower for word in ["vlan", "create vlan", "assign vlan", "show vlan"]):
            if "create" in user_lower:
                return {"tool": "vlan_management", "args": {"action": "create_vlan", "vlan_id": 100, "vlan_name": "DATA_VLAN"}}
            elif "assign" in user_lower:
                return {"tool": "vlan_management", "args": {"action": "assign_vlan", "vlan_id": 100, "interface": "GigabitEthernet0/1"}}
            elif "delete" in user_lower:
                return {"tool": "vlan_management", "args": {"action": "delete_vlan", "vlan_id": 100}}
            else:
                return {"tool": "vlan_management", "args": {"action": "show_vlan"}}
        
        # Interface configuration keywords
        elif any(word in user_lower for word in ["interface", "port", "access", "trunk", "ethernet"]):
            if "trunk" in user_lower:
                return {"tool": "interface_configuration", "args": {"action": "configure_trunk", "interface": "GigabitEthernet0/1"}}
            elif "ip" in user_lower or "address" in user_lower:
                return {"tool": "interface_configuration", "args": {"action": "set_ip", "interface": "GigabitEthernet0/1", "ip_address": "192.168.1.1"}}
            elif "shutdown" in user_lower:
                return {"tool": "interface_configuration", "args": {"action": "shutdown", "interface": "GigabitEthernet0/1"}}
            elif "enable" in user_lower or "no shutdown" in user_lower:
                return {"tool": "interface_configuration", "args": {"action": "no_shutdown", "interface": "GigabitEthernet0/1"}}
            else:
                return {"tool": "interface_configuration", "args": {"action": "configure_access", "interface": "GigabitEthernet0/1", "vlan_id": 10}}
        
        # Routing keywords
        elif any(word in user_lower for word in ["routing", "route", "ospf", "eigrp", "static"]):
            if "ospf" in user_lower:
                return {"tool": "routing_configuration", "args": {"protocol": "ospf", "action": "configure", "network": "192.168.1.0 0.0.0.255"}}
            elif "static" in user_lower:
                return {"tool": "routing_configuration", "args": {"protocol": "static", "action": "configure", "network": "10.0.0.0 255.0.0.0", "next_hop": "192.168.1.1"}}
            elif "eigrp" in user_lower:
                return {"tool": "routing_configuration", "args": {"protocol": "eigrp", "action": "configure", "network": "192.168.1.0 0.0.0.255"}}
            else:
                return {"tool": "routing_configuration", "args": {"protocol": "ospf", "action": "show"}}
        
        # Security keywords
        elif any(word in user_lower for word in ["security", "ssh", "acl", "access-list", "port-security"]):
            if "ssh" in user_lower:
                return {"tool": "security_configuration", "args": {"feature": "ssh", "action": "enable"}}
            elif "acl" in user_lower or "access-list" in user_lower:
                return {"tool": "security_configuration", "args": {"feature": "acl", "action": "configure", "acl_number": 100}}
            elif "port-security" in user_lower or "port security" in user_lower:
                return {"tool": "security_configuration", "args": {"feature": "port_security", "action": "enable", "interface": "GigabitEthernet0/1"}}
            else:
                return {"tool": "security_configuration", "args": {"feature": "ssh", "action": "enable"}}
        
        # Troubleshooting keywords
        elif any(word in user_lower for word in ["troubleshoot", "debug", "ping", "traceroute", "show", "connectivity"]):
            if "connectivity" in user_lower or "ping" in user_lower:
                return {"tool": "troubleshooting", "args": {"category": "connectivity", "target": "8.8.8.8"}}
            elif "interface" in user_lower:
                return {"tool": "troubleshooting", "args": {"category": "interface"}}
            elif "routing" in user_lower or "route" in user_lower:
                return {"tool": "troubleshooting", "args": {"category": "routing"}}
            elif "switching" in user_lower or "switch" in user_lower:
                return {"tool": "troubleshooting", "args": {"category": "switching"}}
            else:
                return {"tool": "troubleshooting", "args": {"category": "general"}}
        
        # Default - show help
        else:
            return {"tool": "help", "args": {}}
        """Analyze user input to select appropriate Linux tool and arguments"""
        user_lower = user_input.lower()
        
        # User management keywords
        if any(word in user_lower for word in ["user", "group", "adduser", "useradd", "usermod"]):
            if "add" in user_lower and "group" in user_lower:
                return {"tool": "user_management", "args": {"action": "add_user_to_group", "username": "example_user", "groupname": "example_group"}}
            elif "create" in user_lower or ("add" in user_lower and "user" in user_lower):
                return {"tool": "user_management", "args": {"action": "create_user", "username": "new_user"}}
            elif "delete" in user_lower and "user" in user_lower:
                return {"tool": "user_management", "args": {"action": "delete_user", "username": "old_user"}}
            else:
                return {"tool": "user_management", "args": {"action": "list_groups"}}
        
        # File permission keywords
        elif any(word in user_lower for word in ["permission", "chmod", "chown", "file", "ownership"]):
            if "chmod" in user_lower:
                return {"tool": "file_permissions", "args": {"action": "chmod", "path": "/path/to/file", "permissions": "755"}}
            elif "chown" in user_lower or "ownership" in user_lower:
                return {"tool": "file_permissions", "args": {"action": "chown", "path": "/path/to/file", "owner": "username"}}
            elif "find" in user_lower:
                return {"tool": "file_permissions", "args": {"action": "find_permissions", "path": "/", "permissions": "777"}}
            else:
                return {"tool": "file_permissions", "args": {"action": "chmod", "path": "/path/to/file", "permissions": "644"}}
        
        # System command keywords  
        elif any(word in user_lower for word in ["process", "service", "network", "disk", "firewall", "systemctl", "ps"]):
            if any(word in user_lower for word in ["process", "ps", "top", "kill"]):
                return {"tool": "system_commands", "args": {"category": "process"}}
            elif any(word in user_lower for word in ["service", "systemctl", "daemon"]):
                return {"tool": "system_commands", "args": {"category": "service"}}
            elif any(word in user_lower for word in ["network", "ping", "ip", "interface"]):
                return {"tool": "system_commands", "args": {"category": "network"}}
            elif any(word in user_lower for word in ["disk", "df", "mount", "storage"]):
                return {"tool": "system_commands", "args": {"category": "disk"}}
            elif any(word in user_lower for word in ["firewall", "ufw", "iptables"]):
                return {"tool": "system_commands", "args": {"category": "firewall"}}
            else:
                return {"tool": "system_commands", "args": {"category": "process"}}
        
        # Default - show help
        else:
            return {"tool": "help", "args": {}}
    
    def get_available_tools(self, server_key: str) -> List[Dict[str, Any]]:
        """Get available tools from an MCP server"""
        if server_key == "linux":
            # Return known tools for Linux server
            return self.mcp_servers["linux"]["tools"]
        
        # For other servers, try to call them (though they might not have HTTP endpoints)
        try:
            result = self.call_mcp_server(server_key, "tools/list", {})
            if result["success"]:
                data = result["data"]
                if isinstance(data, dict):
                    return data.get("tools", data.get("result", []))
                elif isinstance(data, list):
                    return data
        except:
            pass
        
        return []
    
    def call_mcp_server(self, server_key: str, endpoint: str, payload: Dict[str, Any]) -> Dict[str, Any]:
        """Make a call to an MCP server (for non-Linux servers)"""
        try:
            server_config = self.mcp_servers[server_key]
            
            # For FastAPI MCP servers, we need to use different endpoints
            if endpoint == "tools/list":
                url = f"{server_config['space_url']}/tools"
                response = requests.get(url, timeout=30)
            elif endpoint == "tools/call":
                url = f"{server_config['space_url']}/tools/call"
                response = requests.post(
                    url,
                    json=payload,
                    headers={"Content-Type": "application/json"},
                    timeout=30
                )
            else:
                # Fallback to direct endpoint
                url = f"{server_config['space_url']}/{endpoint}"
                response = requests.post(
                    url,
                    json=payload,
                    headers={"Content-Type": "application/json"},
                    timeout=30
                )
            
            if response.status_code == 200:
                return {"success": True, "data": response.json()}
            else:
                return {
                    "success": False, 
                    "error": f"HTTP {response.status_code}: {response.text}",
                    "server": server_config['name']
                }
                
        except requests.exceptions.RequestException as e:
            return {"success": False, "error": f"Request failed: {str(e)}", "server": server_config['name']}
        except Exception as e:
            return {"success": False, "error": f"Unexpected error: {str(e)}", "server": server_config['name']}
    
    def execute_tool(self, server_key: str, tool_name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
        """Execute a tool on an MCP server"""
        payload = {
            "name": tool_name,
            "arguments": arguments
        }
        return self.call_mcp_server(server_key, "tools/call", payload)
    
    def analyze_user_request(self, user_input: str) -> Dict[str, Any]:
        """Use OpenAI to analyze user request and determine which MCP server to use"""
        system_prompt = """
        You are an intelligent assistant that helps users interact with MCP (Model Context Protocol) servers.
        
        Available MCP servers (use these EXACT keys in your response):
        1. terraform: Terraform infrastructure management
        2. linux: Linux system operations  
        3. cisco: Cisco network management
        
        IMPORTANT: For the "recommended_server" field, you MUST use one of these exact keys: "terraform", "linux", or "cisco"
        
        Analyze the user's request and determine which MCP server would be most appropriate.
        
        Respond in JSON format with:
        {
            "recommended_server": "terraform|linux|cisco",
            "reasoning": "explanation of why this server was chosen",
            "suggested_action": "what action to take"
        }
        """
        
        try:
            response = self.openai_client.chat.completions.create(
                model="gpt-4",
                messages=[
                    {"role": "system", "content": system_prompt},
                    {"role": "user", "content": user_input}
                ],
                temperature=0.3
            )
            
            content = response.choices[0].message.content.strip()
            
            # Try to parse JSON, handle cases where GPT returns non-JSON
            try:
                return json.loads(content)
            except json.JSONDecodeError:
                # If not valid JSON, extract server recommendation manually
                content_lower = content.lower()
                if "cisco" in content_lower:
                    recommended_server = "cisco"
                elif "linux" in content_lower:
                    recommended_server = "linux"
                elif "terraform" in content_lower:
                    recommended_server = "terraform"
                else:
                    recommended_server = "cisco"  # Default for network questions
                
                return {
                    "recommended_server": recommended_server,
                    "reasoning": "Based on content analysis",
                    "suggested_action": content
                }
                
        except Exception as e:
            return {
                "error": f"Failed to analyze request: {str(e)}",
                "recommended_server": "cisco"
            }
    
    def generate_response(self, user_input: str, mcp_results: Dict[str, Any] = None) -> str:
        """Generate a natural language response using OpenAI"""
        context = ""
        if mcp_results:
            context = f"\nMCP Server Results: {json.dumps(mcp_results, indent=2)}"
        
        messages = [
            {
                "role": "system", 
                "content": f"""
                You are a helpful assistant that works with MCP servers for infrastructure management.
                Provide clear, helpful responses based on the user's request and any MCP server results.
                
                Available MCP Servers:
                - Terraform: Infrastructure as Code management
                - Linux: System administration and operations  
                - Cisco: Network device management
                
                {context}
                """
            }
        ]
        
        # Add conversation history (last 6 messages)
        messages.extend(self.conversation_history[-6:])
        messages.append({"role": "user", "content": user_input})
        
        try:
            response = self.openai_client.chat.completions.create(
                model="gpt-4",
                messages=messages,
                temperature=0.7,
                max_tokens=1000
            )
            
            return response.choices[0].message.content
            
        except Exception as e:
            return f"Error generating response: {str(e)}"
    
    def process_request(self, user_input: str, selected_server: str = None) -> tuple[str, str]:
        """Process a user request end-to-end"""
        timestamp = datetime.now().strftime("%H:%M:%S")
        
        # Add to conversation history
        self.conversation_history.append({"role": "user", "content": user_input})
        
        try:
            # Analyze request if no server specified or auto-detect selected
            if not selected_server or selected_server == "Auto-detect":
                analysis = self.analyze_user_request(user_input)
                if "error" in analysis:
                    response = f"❌ Analysis Error: {analysis['error']}"
                    self.conversation_history.append({"role": "assistant", "content": response})
                    return response, f"[{timestamp}] Analysis failed"
                
                selected_server = analysis.get("recommended_server", "terraform")
                reasoning = analysis.get("reasoning", "No reasoning provided")
                status = f"[{timestamp}] Selected: {self.mcp_servers[selected_server]['name']} - {reasoning}"
            else:
                # Map display names back to keys if needed
                server_mapping = {
                    "MCP Terraform": "terraform",
                    "MCP Linux": "linux", 
                    "MCP Cisco": "cisco",
                    "Terraform": "terraform",
                    "Linux": "linux",
                    "Cisco": "cisco"
                }
                selected_server = server_mapping.get(selected_server, selected_server.lower())
                
                # Validate server key
                if selected_server not in self.mcp_servers:
                    response = f"❌ Invalid server selection: {selected_server}. Available: {', '.join(self.mcp_servers.keys())}"
                    self.conversation_history.append({"role": "assistant", "content": response})
                    return response, f"[{timestamp}] Invalid server"
                
                status = f"[{timestamp}] Using: {self.mcp_servers[selected_server]['name']}"
            
            # Check server health
            health_check = self.check_server_health(selected_server)
            if not health_check["success"]:
                response = f"⚠️ Cannot connect to {self.mcp_servers[selected_server]['name']} server: {health_check.get('error', 'Server offline')}"
                self.conversation_history.append({"role": "assistant", "content": response})
                return response, status + " - Server offline"
            
            # Handle Linux server specifically (full functionality)
            if selected_server == "linux":
                tool_selection = self.select_linux_tool_and_args(user_input)
                
                if tool_selection["tool"] == "help":
                    response = """**Available Linux MCP Tools:**

πŸ”§ **user_management**: Create, delete, and manage users and groups
πŸ“ **file_permissions**: Change file permissions and ownership (chmod, chown)  
βš™οΈ **system_commands**: System administration commands (processes, services, network, disk, firewall)

**Example commands you can ask for:**
- "Show me user management commands"
- "How do I change file permissions?"
- "Give me process management commands" 
- "Show network diagnostic commands"
- "Help with service management"
- "Configure firewall rules"
- "Check disk usage commands"
"""
                else:
                    # Execute the selected Linux tool
                    result = self.execute_linux_tool(tool_selection["tool"], tool_selection["args"])
                    response = result
            
            # Handle Cisco server specifically (full functionality)
            elif selected_server == "cisco":
                tool_selection = self.select_cisco_tool_and_args(user_input)
                
                if tool_selection["tool"] == "help":
                    response = """**Available Cisco MCP Tools:**

🏷️ **vlan_management**: Create, delete, assign, and show VLANs
🌐 **interface_configuration**: Configure access/trunk ports, IP addresses, shutdown/enable
πŸ›£οΈ **routing_configuration**: Set up OSPF, EIGRP, static routes
πŸ”’ **security_configuration**: Configure SSH, ACLs, port security
πŸ”§ **troubleshooting**: Network connectivity, interface, routing, switching diagnostics

**Example commands you can ask for:**
- "Create a VLAN" or "Show VLAN information"
- "Configure interface as access port" or "Set up trunk port"
- "Configure OSPF routing" or "Set up static routes"  
- "Enable SSH access" or "Configure ACL"
- "Troubleshoot connectivity" or "Check interface status"
"""
                else:
                    # Execute the selected Cisco tool
                    result = self.execute_cisco_tool(tool_selection["tool"], tool_selection["args"])
                    response = result
            
            # Handle other servers (Future expansion)
            else:
                # Try to get server information first
                try:
                    # Check if server provides any status info
                    server_url = self.mcp_servers[selected_server]['space_url']
                    status_response = requests.get(server_url, timeout=10)
                    
                    if status_response.status_code == 200:
                        try:
                            server_data = status_response.json()
                            tools_count = server_data.get('tools', 'unknown')
                            service_name = server_data.get('service', 'unknown')
                            
                            if selected_server == "cisco":
                                response = f"""**Cisco MCP Server** βœ… Connected!

**Server Status**: Online 
**Service**: {service_name}
**Available Tools**: {tools_count}
**MCP Endpoint**: {server_url}/mcp/sse

**What you can ask for with Cisco:**
- "Show me Cisco interface configuration commands"
- "Help with VLAN configuration"
- "Generate Cisco routing commands"
- "Show network troubleshooting commands"
- "Configure access control lists"
- "Help with Cisco switch configuration"

**Note**: This server has {tools_count} tools available via MCP protocol. The tools likely include:
- Interface configuration management
- VLAN configuration and management  
- Routing protocol setup
- ACL (Access Control List) configuration
- Network troubleshooting commands
- Device status and monitoring

Would you like me to help you with any specific Cisco networking task?
"""
                            elif selected_server == "terraform":
                                response = f"""**Terraform MCP Server** βœ… Connected!

**Server Status**: Online
**Service**: {service_name}  
**Available Tools**: {tools_count}
**MCP Endpoint**: {server_url}/mcp/sse

**What you can ask for with Terraform:**
- "Show me Terraform plan commands"
- "Help with infrastructure deployment"
- "Generate Terraform configuration"
- "Show resource management commands"
- "Help with Terraform state management"

**Note**: This server has {tools_count} tools available via MCP protocol.

Would you like me to help you with any specific Terraform task?
"""
                        except json.JSONDecodeError:
                            # Server responded but not with JSON
                            if selected_server == "cisco":
                                response = f"""**Cisco MCP Server** ⚠️ Connected but Limited Info

**Server Status**: Online (non-JSON response)
**MCP Endpoint**: {server_url}/mcp/sse

**Common Cisco operations I can help with:**
- Interface configuration commands
- VLAN setup and management
- Routing protocol configuration
- Access Control Lists (ACLs)
- Network troubleshooting
- Switch and router configuration

Would you like me to help with any specific Cisco networking task?
"""
                            else:
                                response = f"""**Terraform MCP Server** ⚠️ Connected but Limited Info

**Server Status**: Online (non-JSON response)  
**MCP Endpoint**: {server_url}/mcp/sse

**Common Terraform operations I can help with:**
- Infrastructure planning and deployment
- Resource configuration and management
- State file management
- Module development
- Provider configuration

Would you like me to help with any specific Terraform task?
"""
                    else:
                        # Server not responding properly
                        if selected_server == "cisco":
                            response = f"""**Cisco MCP Server** ❌ Connection Issue

**Server Status**: {health_check['status']}
**Error**: HTTP {status_response.status_code}
**MCP Endpoint**: {server_url}/mcp/sse

The server appears to be having issues. Please try again later or check if the server is running properly.
"""
                        else:
                            response = f"""**Terraform MCP Server** ❌ Connection Issue

**Server Status**: {health_check['status']}  
**Error**: HTTP {status_response.status_code}
**MCP Endpoint**: {server_url}/mcp/sse

The server appears to be having issues. Please try again later or check if the server is running properly.
"""
                            
                except Exception as e:
                    # Connection failed
                    if selected_server == "cisco":
                        response = f"""**Cisco MCP Server** ❌ Connection Failed

**Error**: {str(e)}
**MCP Endpoint**: {self.mcp_servers[selected_server]['space_url']}/mcp/sse

**Common Cisco operations (offline reference):**
- Interface configuration: `interface GigabitEthernet0/1`
- VLAN configuration: `vlan 10`
- Routing: `ip route 0.0.0.0 0.0.0.0 192.168.1.1`
- ACL: `access-list 10 permit 192.168.1.0 0.0.0.255`

Please check if the server is running and try again.
"""
                    else:
                        response = f"""**Terraform MCP Server** ❌ Connection Failed

**Error**: {str(e)}
**MCP Endpoint**: {self.mcp_servers[selected_server]['space_url']}/mcp/sse

**Common Terraform operations (offline reference):**
- Plan: `terraform plan`
- Apply: `terraform apply`
- Destroy: `terraform destroy`
- Validate: `terraform validate`

Please check if the server is running and try again.
"""
            
            self.conversation_history.append({"role": "assistant", "content": response})
            return response, status + f" - {health_check['status']}"
            
        except Exception as e:
            error_response = f"❌ Error processing request: {str(e)}"
            self.conversation_history.append({"role": "assistant", "content": error_response})
            return error_response, f"[{timestamp}] Error occurred"

def create_gradio_interface():
    """Create the Gradio interface"""
    
    # Try to get API key from environment (HuggingFace Secrets)
    openai_api_key = os.getenv("OPEN_AI_API_KEY")
    
    # Initialize MCP Client if API key is available
    mcp_client = None
    initial_status = ""
    
    if openai_api_key:
        try:
            mcp_client = MCPClient(openai_api_key)
            initial_status = "βœ… OpenAI client initialized automatically from HF Secrets!"
        except Exception as e:
            initial_status = f"❌ Failed to initialize with HF Secret: {str(e)}"
    else:
        initial_status = "⚠️ OpenAI API key not found in HF Secrets. Please enter manually."
    
    def initialize_client(api_key):
        nonlocal mcp_client
        # Use provided key or fall back to environment
        key_to_use = api_key.strip() if api_key and api_key.strip() else openai_api_key
        
        if not key_to_use:
            return "❌ Please provide your OpenAI API key", ""
        
        try:
            mcp_client = MCPClient(key_to_use)
            return "βœ… OpenAI client initialized successfully!", ""
        except Exception as e:
            return f"❌ Failed to initialize: {str(e)}", ""
    
    def process_message(message, server_choice, history):
        if not mcp_client:
            return history + [["❌ Error", "Please initialize the OpenAI client first using the button above."]], ""
        
        if not message.strip():
            return history, ""
        
        try:
            response, status = mcp_client.process_request(message, server_choice)
            history.append([message, response])
            return history, ""
        except Exception as e:
            error_msg = f"❌ Error: {str(e)}"
            history.append([message, error_msg])
            return history, ""
    
    def get_server_status():
        if not mcp_client:
            return "Please initialize the OpenAI client first."
        
        status_info = "## MCP Servers Status\n\n"
        
        for key, config in mcp_client.mcp_servers.items():
            health_check = mcp_client.check_server_health(key)
            
            if health_check["success"]:
                if health_check["status"] == "online":
                    status_icon = "🟒"
                    status_text = "Online"
                else:
                    status_icon = "🟑" 
                    status_text = "Online (Different Structure)"
            else:
                status_icon = "πŸ”΄"
                status_text = "Offline"
            
            status_info += f"**{config['name']}**: {status_icon} {status_text}\n"
            status_info += f"- URL: {config['space_url']}\n"
            status_info += f"- Description: {config['description']}\n"
            
            # Show tools for Linux server
            if key == "linux" and "tools" in config:
                status_info += f"- Available Tools: {len(config['tools'])}\n"
                for tool in config['tools']:
                    status_info += f"  - **{tool['name']}**: {tool['description']}\n"
            
            # Show MCP endpoint info
            status_info += f"- MCP Endpoint: {config['space_url']}/mcp/sse\n"
            
            if health_check["success"] and "response" in health_check:
                response_data = health_check["response"]
                if isinstance(response_data, dict) and "service" in response_data:
                    status_info += f"- Service: {response_data.get('service', 'Unknown')}\n"
            
            status_info += "\n"
        
        return status_info
    
    # Create Gradio interface
    with gr.Blocks(title="MCP Client with OpenAI", theme=gr.themes.Soft()) as app:
        gr.Markdown("# πŸ€– MCP Client with OpenAI Integration")
        gr.Markdown("Connect to your Terraform, Linux, and Cisco MCP servers with AI-powered assistance")
        gr.Markdown("πŸ’‘ **Tip**: Your OpenAI API key is automatically loaded from HuggingFace Secrets!")
        
        with gr.Row():
            with gr.Column(scale=3):
                # API Key input (optional if already in HF Secrets)
                api_key = gr.Textbox(
                    label="OpenAI API Key (Optional - will use HF Secret if available)",
                    type="password",
                    placeholder="Leave empty to use HF Secret OPEN_AI_API_KEY...",
                    value=""
                )
                init_btn = gr.Button("Initialize/Reinitialize Client", variant="primary")
                init_status = gr.Textbox(
                    label="Initialization Status", 
                    interactive=False,
                    value=initial_status
                )
                
                # Server selection
                server_choice = gr.Dropdown(
                    choices=["Auto-detect", "linux", "terraform", "cisco"],
                    value="Auto-detect",
                    label="Select MCP Server"
                )
                
                # Chat interface
                chatbot = gr.Chatbot(
                    label="Conversation",
                    height=400,
                    show_label=True
                )
                
                msg = gr.Textbox(
                    label="Message",
                    placeholder="Ask about infrastructure, Linux systems, or Cisco networks...",
                    lines=2
                )
                
                with gr.Row():
                    send_btn = gr.Button("Send", variant="primary")
                    clear_btn = gr.Button("Clear Chat")
            
            with gr.Column(scale=1):
                gr.Markdown("## πŸ“Š Server Status")
                server_status = gr.Markdown("Initialize client to see server status")
                refresh_btn = gr.Button("Refresh Status")
                
                gr.Markdown("## πŸ’‘ Example Queries")
                gr.Markdown("""
                **Linux (Full Support):**
                - "Show me user management commands"
                - "How do I change file permissions?"
                - "Give me process management commands"
                - "Show network diagnostic commands"
                - "Help with service management"
                - "Configure firewall rules"
                
                **Terraform:**
                - "Show me terraform commands"
                - "Plan infrastructure deployment"
                - "Help with terraform apply"
                
                **Cisco:**
                - "Show interface configuration"
                - "Configure VLAN commands"
                - "Help with port configuration"
                """)
        
        # Event handlers
        init_btn.click(
            initialize_client,
            inputs=[api_key],
            outputs=[init_status, server_status]
        )
        
        send_btn.click(
            process_message,
            inputs=[msg, server_choice, chatbot],
            outputs=[chatbot, msg]
        )
        
        msg.submit(
            process_message,
            inputs=[msg, server_choice, chatbot],
            outputs=[chatbot, msg]
        )
        
        clear_btn.click(
            lambda: [],
            outputs=[chatbot]
        )
        
        refresh_btn.click(
            get_server_status,
            outputs=[server_status]
        )
    
    return app

if __name__ == "__main__":
    # Create and launch the Gradio app
    app = create_gradio_interface()
    app.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=True,
        debug=True
    )