Spaces:
Running

File size: 61,928 Bytes
d8546ca
 
 
99e7e16
e9e023b
b4a381f
99e7e16
 
 
e9e023b
99e7e16
 
 
 
 
 
 
 
 
 
 
e9e023b
 
 
d8546ca
e9e023b
 
 
 
 
17f9aec
 
 
 
 
 
 
 
 
 
 
 
e9e023b
 
99e7e16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12cc73b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1fbe2de
 
 
 
 
 
 
 
 
 
 
d8546ca
 
1fbe2de
d8546ca
 
 
 
 
 
 
1fbe2de
 
 
d8546ca
 
 
 
1fbe2de
 
d8546ca
e9e023b
 
d8546ca
17f9aec
 
e9e023b
 
 
17f9aec
 
 
e9e023b
 
 
17f9aec
 
 
e9e023b
 
 
d8546ca
e9e023b
d8546ca
e9e023b
 
d8546ca
17f9aec
 
d8546ca
e9e023b
 
 
99e7e16
e9e023b
 
17f9aec
 
 
 
99e7e16
 
 
d8546ca
 
 
 
e9e023b
 
d8546ca
 
 
 
 
 
 
 
 
e9e023b
 
99e7e16
d8546ca
99e7e16
 
d8546ca
99e7e16
 
 
e9e023b
17f9aec
 
 
 
 
 
 
 
 
e9e023b
 
99e7e16
 
 
 
 
 
b4a381f
d8546ca
b4a381f
 
b63d628
b4a381f
 
 
17f9aec
d8546ca
b4a381f
 
 
d8546ca
b4a381f
17f9aec
 
 
b4a381f
 
 
b63d628
b4a381f
 
17f9aec
b4a381f
b63d628
b4a381f
 
 
 
b63d628
17f9aec
b63d628
b4a381f
 
 
d8546ca
b4a381f
d8546ca
b4a381f
 
 
 
 
 
 
 
d8546ca
b4a381f
d8546ca
b4a381f
 
d8546ca
b4a381f
 
b63d628
b4a381f
 
 
b63d628
b4a381f
d8546ca
 
 
b4a381f
b63d628
b4a381f
d8546ca
 
 
b4a381f
d8546ca
b4a381f
 
 
1182948
 
 
 
 
 
 
 
 
 
 
 
 
d8546ca
b4a381f
 
d8546ca
 
b4a381f
 
d8546ca
b4a381f
 
17f9aec
5586701
b4a381f
 
d8546ca
5586701
d8546ca
b4a381f
 
ea5e7fc
 
 
 
 
 
 
 
 
 
 
 
 
f9d0d04
d8546ca
f9d0d04
 
ea5e7fc
 
 
 
 
 
 
 
 
d8546ca
17f9aec
f9d0d04
 
 
 
17f9aec
 
 
 
 
 
 
 
 
7656fb3
17f9aec
16895c1
f9d0d04
17f9aec
 
 
f9d0d04
 
17f9aec
f9d0d04
 
 
 
16895c1
17f9aec
f9d0d04
 
 
17f9aec
f9d0d04
 
16895c1
17f9aec
16895c1
 
17f9aec
 
 
 
 
 
 
 
f9d0d04
 
ea5e7fc
7656fb3
 
 
 
 
 
 
f9d0d04
 
17f9aec
 
 
f9d0d04
17f9aec
f9d0d04
17f9aec
d8546ca
 
17f9aec
16895c1
 
12cc73b
 
 
 
 
 
 
 
 
 
e9e023b
17f9aec
 
12cc73b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9e023b
 
d8546ca
 
 
 
b63d628
 
37c02f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12cc73b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e36e95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8546ca
3e36e95
12cc73b
3e36e95
 
 
37c02f2
 
12cc73b
 
d8546ca
b63d628
d8546ca
 
12cc73b
d8546ca
12cc73b
 
 
 
 
 
b63d628
d8546ca
 
12cc73b
 
 
 
 
 
b63d628
37c02f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9e023b
12cc73b
 
d8546ca
3e36e95
 
d8546ca
16895c1
3e36e95
12cc73b
3e36e95
 
 
 
 
 
 
 
 
 
12cc73b
 
 
3e36e95
 
 
 
 
 
 
 
12cc73b
3e36e95
 
 
 
 
 
 
 
 
 
 
12cc73b
 
 
 
 
3e36e95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12cc73b
 
 
 
 
3e36e95
 
 
12cc73b
 
3e36e95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12cc73b
 
f9d0d04
12cc73b
 
 
 
 
 
 
 
3e36e95
12cc73b
 
 
 
 
 
 
3e36e95
 
12cc73b
 
 
3e36e95
 
12cc73b
3e36e95
 
12cc73b
b63d628
d8546ca
99e7e16
b63d628
99e7e16
 
 
 
 
 
 
 
 
 
17f9aec
b63d628
99e7e16
d8546ca
b63d628
99e7e16
 
17f9aec
d8546ca
7656fb3
b63d628
d8546ca
99e7e16
 
d8546ca
1fbe2de
 
 
 
 
 
 
d8546ca
 
99e7e16
e9e023b
99e7e16
 
e9e023b
d8546ca
e9e023b
1fbe2de
d8546ca
1fbe2de
 
 
 
 
 
 
 
 
 
 
d8546ca
1fbe2de
d8546ca
 
 
1fbe2de
 
 
 
d8546ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99e7e16
e9e023b
d8546ca
 
 
 
 
 
 
e9e023b
b63d628
d8546ca
 
b63d628
d8546ca
e9e023b
 
16895c1
99e7e16
 
 
 
7656fb3
99e7e16
7656fb3
 
 
 
 
 
 
 
 
 
 
99e7e16
 
 
d8546ca
7656fb3
 
99e7e16
d8546ca
99e7e16
 
 
 
f9d0d04
7656fb3
99e7e16
7656fb3
 
99e7e16
7656fb3
 
 
 
d8546ca
7656fb3
 
 
e9e023b
 
d8546ca
5586701
e582d83
 
5586701
 
 
d8546ca
 
 
 
 
 
5586701
 
 
d8546ca
 
5586701
d8546ca
5586701
 
 
d8546ca
1a8f00f
 
 
 
 
 
 
5586701
18bc400
1a8f00f
18bc400
1a8f00f
18bc400
 
 
1a8f00f
18bc400
1a8f00f
18bc400
 
 
1a8f00f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea5e7fc
 
 
 
 
 
1a8f00f
 
 
18bc400
1a8f00f
 
 
 
18bc400
1a8f00f
18bc400
 
 
d8546ca
1a8f00f
 
18bc400
5586701
 
 
 
18bc400
 
1a8f00f
 
 
 
 
 
 
 
 
18bc400
5586701
 
 
1a8f00f
5586701
 
 
 
18bc400
1a8f00f
 
 
 
 
 
 
 
 
 
 
18bc400
5586701
1a8f00f
5586701
1a8f00f
 
5586701
1a8f00f
7656fb3
d8546ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e582d83
d8546ca
 
 
 
7656fb3
d8546ca
 
 
 
 
 
 
 
 
 
99e7e16
d8546ca
e9e023b
99e7e16
 
 
 
 
 
 
 
 
 
 
 
e582d83
99e7e16
 
d8546ca
 
 
 
 
f9d0d04
99e7e16
d8546ca
 
 
 
1fbe2de
 
 
 
d8546ca
 
 
 
99e7e16
7656fb3
d8546ca
5586701
d8546ca
 
 
 
1fbe2de
 
 
 
d8546ca
 
 
 
99e7e16
d8546ca
99e7e16
 
d8546ca
 
 
 
5586701
d8546ca
 
 
 
5586701
1fbe2de
 
d8546ca
 
 
1fbe2de
 
 
 
 
99e7e16
 
1fbe2de
 
d8546ca
 
 
 
 
 
 
1fbe2de
 
 
 
 
d8546ca
 
 
99e7e16
d8546ca
 
 
 
 
 
1fbe2de
 
 
 
d8546ca
 
 
99e7e16
b63d628
5586701
d8546ca
 
 
 
 
 
7656fb3
d8546ca
 
 
 
 
 
 
 
99e7e16
d8546ca
99e7e16
d8546ca
 
 
 
0e0c781
87f013a
 
0e0c781
d8546ca
99e7e16
 
 
1182948
 
e582d83
1182948
 
d8546ca
e582d83
87f013a
 
 
12cc73b
 
 
 
 
 
87f013a
12cc73b
 
 
 
d8546ca
e1e2dfe
12cc73b
 
 
 
d8546ca
e9e023b
d8546ca
 
 
 
 
b63d628
d8546ca
 
 
 
 
f9d0d04
d8546ca
 
 
 
e9e023b
1fbe2de
 
 
 
 
 
 
7656fb3
d8546ca
e1e2dfe
 
 
 
 
b4a381f
e1e2dfe
7656fb3
d8546ca
 
b4a381f
e1e2dfe
17f9aec
d8546ca
e1e2dfe
5586701
e1e2dfe
d8546ca
 
5586701
e1e2dfe
d8546ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99e7e16
d8546ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7656fb3
 
1182948
7656fb3
d8546ca
1182948
 
 
 
 
 
 
 
 
 
 
 
87f013a
1182948
d8546ca
 
 
 
12cc73b
 
 
 
 
 
 
 
 
 
 
 
7b2a6e6
12cc73b
 
7b2a6e6
12cc73b
 
 
 
99e7e16
12cc73b
 
 
 
 
d8546ca
12cc73b
 
d8546ca
12cc73b
 
 
b63d628
12cc73b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17f9aec
12cc73b
 
 
17f9aec
12cc73b
 
 
b63d628
12cc73b
 
17f9aec
12cc73b
 
 
 
 
 
 
 
 
 
 
17f9aec
d8546ca
 
 
 
12cc73b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5586701
d8546ca
 
 
 
 
 
1fbe2de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8546ca
 
 
 
 
1fbe2de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8546ca
 
 
 
5586701
d8546ca
5586701
d8546ca
7656fb3
5586701
 
d8546ca
 
5586701
d8546ca
5586701
d8546ca
 
5586701
 
d8546ca
5586701
 
d8546ca
5586701
d8546ca
5586701
 
b63d628
99e7e16
 
d8546ca
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import os
import re
import shutil
import subprocess
import tempfile
import uuid
import zipfile
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, Optional, Tuple

import pandas as pd
import streamlit as st
from rdkit import Chem
from rdkit.Chem import AllChem


SUPPORTED_PROTEIN_EXTS = {".pdb", ".pdbqt"}
SUPPORTED_LIGAND_EXTS = {".sdf", ".mol", ".mol2", ".pdb", ".pdbqt"}

APP_TMP_ROOT = Path("/tmp/batch_docking_streamlit_app")
UPLOAD_ROOT = APP_TMP_ROOT / "uploads"
EXPORT_ROOT = APP_TMP_ROOT / "exports"
UPLOAD_ROOT.mkdir(parents=True, exist_ok=True)
EXPORT_ROOT.mkdir(parents=True, exist_ok=True)

STANDARD_AA = {
    "ALA", "ARG", "ASN", "ASP", "CYS", "GLN", "GLU", "GLY", "HIS", "ILE",
    "LEU", "LYS", "MET", "PHE", "PRO", "SER", "THR", "TRP", "TYR", "VAL",
    "ASH", "GLH", "HID", "HIE", "HIP", "LYN", "CYM", "CYX", "ARN", "GLM"
}

AA_RENAMES = {
    "MSE": "MET",
    "HSD": "HIS",
    "HSE": "HIS",
    "HSP": "HIS",
}


@dataclass
class AtomRecord:
    record: str
    serial: int
    atom_name: str
    res_name: str
    chain_id: str
    res_seq: int
    x: float
    y: float
    z: float
    line: str


def ensure_command(cmd: str) -> bool:
    return shutil.which(cmd) is not None


def resolve_command(*names: str) -> Optional[str]:
    """Return the first available executable from a list of candidate names."""
    for name in names:
        resolved = shutil.which(name)
        if resolved:
            return resolved
    return None


def count_atomic_records(file_path: Path) -> int:
    """Count PDB/PDBQT ATOM and HETATM records without loading the whole file."""
    count = 0
    with open(file_path, "r", errors="ignore") as handle:
        for line in handle:
            if line.startswith(("ATOM", "HETATM")):
                count += 1
    return count


def write_command_log(log_path: Path, command: List[str], result) -> None:
    log_path.parent.mkdir(parents=True, exist_ok=True)
    log_path.write_text(
        "COMMAND:\n"
        + " ".join(command)
        + "\n\nRETURN CODE:\n"
        + str(result.returncode)
        + "\n\nSTDOUT:\n"
        + _as_text(result.stdout)
        + "\n\nSTDERR:\n"
        + _as_text(result.stderr),
        encoding="utf-8",
    )


def _as_text(value):
    """Convert subprocess output safely to text.
    This prevents Streamlit/write_text errors such as: data must be str, not bytes.
    """
    if value is None:
        return ""
    if isinstance(value, bytes):
        return value.decode("utf-8", errors="replace")
    return str(value)


def run_cmd(cmd: List[str], cwd: Optional[str] = None, timeout: int = 600):
    try:
        result = subprocess.run(
            cmd,
            cwd=cwd,
            text=True,
            capture_output=True,
            check=False,
            timeout=timeout,
        )
        result.stdout = _as_text(result.stdout)
        result.stderr = _as_text(result.stderr)
        return result
    except subprocess.TimeoutExpired as e:
        return subprocess.CompletedProcess(
            cmd,
            returncode=124,
            stdout=_as_text(e.stdout),
            stderr=f"TIMEOUT after {timeout} seconds\n" + _as_text(e.stderr)
        )


def init_state():
    st.session_state.setdefault("session_id", uuid.uuid4().hex[:12])
    st.session_state.setdefault("run_outputs", None)


def get_session_dir() -> Path:
    p = UPLOAD_ROOT / st.session_state["session_id"]
    p.mkdir(parents=True, exist_ok=True)
    return p


def get_export_dir() -> Path:
    p = EXPORT_ROOT / st.session_state["session_id"]
    p.mkdir(parents=True, exist_ok=True)
    return p


def safe_filename(name: str) -> str:
    name = Path(str(name)).name
    name = re.sub(r"[^A-Za-z0-9._-]+", "_", name)
    return name or "file"


def reset_all():
    shutil.rmtree(get_session_dir(), ignore_errors=True)
    shutil.rmtree(get_export_dir(), ignore_errors=True)
    st.session_state.clear()
    st.rerun()


def save_uploaded_file(uploaded_file, out_path: Path) -> Path:
    out_path.parent.mkdir(parents=True, exist_ok=True)
    uploaded_file.seek(0)
    with open(out_path, "wb") as f:
        f.write(uploaded_file.getbuffer())
        f.flush()
        os.fsync(f.fileno())
    return out_path


def validate_extension(name: str, allowed: set, label: str):
    suffix = Path(name).suffix.lower()
    if suffix not in allowed:
        raise ValueError(f"{label} must be one of: {', '.join(sorted(allowed))}")


def validate_input_file_content(file_path: Path, label: str):
    if not file_path.exists():
        raise ValueError(f"{label} file was not saved correctly.")
    if file_path.stat().st_size == 0:
        raise ValueError(f"{label} file is empty.")
    if file_path.suffix.lower() in {".pdb", ".pdbqt"}:
        text = file_path.read_text(errors="ignore")
        if "ATOM" not in text and "HETATM" not in text:
            raise ValueError(f"{label} file does not contain valid atomic records.")


def parse_pdb_like_atoms(file_path: Path) -> List[AtomRecord]:
    atoms = []
    with open(file_path, "r", errors="ignore") as f:
        for line in f:
            if not line.startswith(("ATOM", "HETATM")):
                continue
            try:
                atoms.append(
                    AtomRecord(
                        record=line[0:6].strip(),
                        serial=int(line[6:11].strip() or 0),
                        atom_name=line[12:16].strip(),
                        res_name=line[17:20].strip(),
                        chain_id=line[21].strip() or "A",
                        res_seq=int(line[22:26].strip() or 0),
                        x=float(line[30:38].strip()),
                        y=float(line[38:46].strip()),
                        z=float(line[46:54].strip()),
                        line=line,
                    )
                )
            except Exception:
                continue
    return atoms


def parse_residue_selection(selection_text: str) -> List[Tuple[str, int, Optional[str]]]:
    selections = []
    if not selection_text.strip():
        return selections

    blocks = [b.strip() for b in selection_text.split(";") if b.strip()]
    for block in blocks:
        if ":" not in block:
            raise ValueError(f"Invalid residue block '{block}'. Use A:45, A:LYS45, or A:45-50.")

        chain, spec = block.split(":", 1)
        chain = chain.strip()
        items = [x.strip() for x in spec.split(",") if x.strip()]

        for item in items:
            m_range = re.fullmatch(r"(\d+)\s*-\s*(\d+)", item)
            if m_range:
                start, end = int(m_range.group(1)), int(m_range.group(2))
                for rnum in range(start, end + 1):
                    selections.append((chain, rnum, None))
                continue

            m_named = re.fullmatch(r"([A-Za-z]{3})(\d+)", item)
            if m_named:
                selections.append((chain, int(m_named.group(2)), m_named.group(1).upper()))
                continue

            m_num = re.fullmatch(r"(\d+)", item)
            if m_num:
                selections.append((chain, int(m_num.group(1)), None))
                continue

            raise ValueError(f"Could not parse residue item '{item}'.")

    return selections


def get_atoms_for_selected_residues(protein_file: Path, selections):
    atoms = parse_pdb_like_atoms(protein_file)
    matched = []
    for atom in atoms:
        for chain_id, res_num, res_name in selections:
            if atom.chain_id != chain_id:
                continue
            if atom.res_seq != res_num:
                continue
            if res_name is not None and atom.res_name.upper() != res_name.upper():
                continue
            matched.append(atom)
            break
    return matched


def compute_box_from_atoms(atoms, padding=8.0, min_size=18.0):
    if not atoms:
        raise ValueError("No atoms were found for box calculation.")

    xs = [a.x for a in atoms]
    ys = [a.y for a in atoms]
    zs = [a.z for a in atoms]

    center = (
        round((min(xs) + max(xs)) / 2.0, 3),
        round((min(ys) + max(ys)) / 2.0, 3),
        round((min(zs) + max(zs)) / 2.0, 3),
    )

    size = (
        round(max((max(xs) - min(xs)) + 2 * padding, min_size), 3),
        round(max((max(ys) - min(ys)) + 2 * padding, min_size), 3),
        round(max((max(zs) - min(zs)) + 2 * padding, min_size), 3),
    )

    return center, size



def limit_box_size(size, max_size=25.0):
    """Limit Vina grid dimensions to avoid very large search spaces.

    Vina becomes slow and may timeout when the search-space volume is above
    27000 Angstrom^3. A 25 x 25 x 25 box gives 15625 Angstrom^3.
    """
    return tuple(round(min(float(x), max_size), 3) for x in size)


def box_volume(size):
    return round(float(size[0]) * float(size[1]) * float(size[2]), 3)

def compute_blind_docking_box(protein_file: Path, padding=8.0, min_size=20.0):
    atoms = parse_pdb_like_atoms(protein_file)
    if not atoms:
        raise ValueError("No protein atoms were found.")
    return compute_box_from_atoms(atoms, padding, min_size)


def compute_residue_based_box(protein_file: Path, residue_selection_text: str, padding=8.0, min_size=18.0):
    selections = parse_residue_selection(residue_selection_text)
    if not selections:
        raise ValueError("Provide at least one residue selection.")

    selected_atoms = get_atoms_for_selected_residues(protein_file, selections)
    if not selected_atoms:
        raise ValueError("None of the selected residues were found.")

    return compute_box_from_atoms(selected_atoms, padding, min_size)


def infer_element_from_atom_name(atom_name: str, is_standard_residue_atom: bool = False) -> str:
    """Infer an element symbol from a PDB atom name when the element column is blank.

    ``is_standard_residue_atom`` must be True only when the atom belongs to a
    standard amino acid ATOM record (never a HETATM/ligand/ion record). This
    matters because several two-letter ion/element symbols are also valid
    protein atom names, most importantly "CA": in a HETATM record "CA" means
    the calcium ion, but in an ATOM record for any of the 20 standard amino
    acids "CA" is always the backbone alpha-carbon and must resolve to carbon.
    Silently treating every alpha-carbon as calcium corrupts the element of
    the single most common atom in the entire structure and breaks downstream
    residue-template matching (e.g. in Meeko) for virtually every residue.
    """
    atom_name = (atom_name or "").strip()
    letters = "".join(ch for ch in atom_name if ch.isalpha()).upper()
    if not letters:
        return ""

    if is_standard_residue_atom:
        # Protein ATOM records never legitimately contain a bound metal ion
        # under a standard atom name, so two-letter ion symbols are not
        # applicable here regardless of collision. Standard backbone/side
        # chain atom names always start with the correct single-letter
        # element (C, N, O, S), so plain single-letter typing is correct.
        return letters[0].capitalize()

    two_letter = {"CL", "BR", "NA", "MG", "AL", "SI", "CA", "CR", "MN", "FE", "CO", "NI", "CU", "ZN", "SE"}
    if len(letters) >= 2 and letters[:2] in two_letter:
        return letters[:2].capitalize()
    return letters[0].capitalize()


def strict_clean_receptor_pdb(infile: Path, outfile: Path) -> Dict[str, int]:
    stats = {
        "kept_atoms": 0,
        "dropped_non_atom": 0,
        "dropped_hydrogen": 0,
        "dropped_water": 0,
        "dropped_altloc": 0,
        "dropped_nonstandard": 0,
        "renamed_residue": 0,
        "dropped_bad_element": 0,
    }

    with open(infile, "r", errors="ignore") as fin, open(outfile, "w") as fout:
        for raw_line in fin:
            if not raw_line.startswith("ATOM"):
                stats["dropped_non_atom"] += 1
                continue

            line = raw_line.rstrip("\n")
            if len(line) < 80:
                line = line.ljust(80)

            atom_name = line[12:16].strip()
            altloc = line[16].strip()
            res_name = line[17:20].strip().upper()
            element = line[76:78].strip()

            if res_name in {"HOH", "WAT"}:
                stats["dropped_water"] += 1
                continue

            if altloc not in {"", "A"}:
                stats["dropped_altloc"] += 1
                continue

            if res_name in AA_RENAMES:
                res_name = AA_RENAMES[res_name]
                line = line[:17] + f"{res_name:>3}" + line[20:]
                stats["renamed_residue"] += 1

            if res_name not in STANDARD_AA:
                stats["dropped_nonstandard"] += 1
                continue

            if not element:
                element = infer_element_from_atom_name(atom_name, is_standard_residue_atom=True)

            if not element:
                stats["dropped_bad_element"] += 1
                continue

            if element.upper() == "H" or atom_name.upper().startswith("H"):
                stats["dropped_hydrogen"] += 1
                continue

            line = line[:76] + f"{element:>2}" + line[78:]
            fout.write(line + "\n")
            stats["kept_atoms"] += 1

        fout.write("TER\nEND\n")

    if stats["kept_atoms"] == 0:
        raise ValueError("No valid protein atoms remained after cleaning.")

    return stats


def validate_receptor_pdbqt(pdbqt_path: Path, minimum_atoms: int = 20) -> Dict[str, int]:
    if not pdbqt_path.exists():
        raise RuntimeError(f"Receptor PDBQT was not created: {pdbqt_path}")

    size_bytes = pdbqt_path.stat().st_size
    if size_bytes < 200:
        raise RuntimeError(
            f"Receptor PDBQT is too small ({size_bytes} bytes), indicating failed preparation."
        )

    text = pdbqt_path.read_text(errors="ignore")
    bad_tags = [tag for tag in ("ROOT", "BRANCH", "ENDBRANCH", "TORSDOF") if tag in text]
    if bad_tags:
        raise RuntimeError(
            "Invalid receptor PDBQT: ligand-only torsion tags were found: "
            + ", ".join(bad_tags)
        )

    atom_count = sum(
        1 for line in text.splitlines() if line.startswith(("ATOM", "HETATM"))
    )
    if atom_count < minimum_atoms:
        raise RuntimeError(
            f"Receptor PDBQT contains only {atom_count} atomic records; "
            f"at least {minimum_atoms} were expected."
        )

    return {"atom_count": atom_count, "size_bytes": size_bytes}


def validate_ligand_pdbqt(pdbqt_path: Path):
    text = pdbqt_path.read_text(errors="ignore")
    if "ATOM" not in text and "HETATM" not in text:
        raise RuntimeError("Ligand PDBQT appears empty.")


def pdb_residue_key(line: str) -> Tuple[str, int, str]:
    """Return chain, residue number and insertion code for a PDB ATOM line."""
    chain_id = line[21:22].strip() or "A"
    try:
        residue_number = int(line[22:26].strip())
    except Exception as exc:
        raise ValueError(f"Invalid PDB residue number in line: {line.rstrip()}") from exc
    insertion_code = line[26:27].strip()
    return chain_id, residue_number, insertion_code


def find_interrupted_pdb_residues(pdb_path: Path) -> List[str]:
    """Find residues whose ATOM records occur in multiple separated blocks.

    Meeko requires all atoms belonging to a residue to be contiguous in the PDB.
    Some hydrogen-addition converters write all heavy atoms first and append
    hydrogens later, which makes almost every residue appear interrupted.
    """
    completed_blocks = set()
    interrupted = set()
    current_key = None

    with open(pdb_path, "r", errors="ignore") as handle:
        for line in handle:
            if not line.startswith("ATOM"):
                continue
            key = pdb_residue_key(line)
            if key != current_key:
                if key in completed_blocks:
                    interrupted.add(key)
                if current_key is not None:
                    completed_blocks.add(current_key)
                current_key = key

    return [
        f"{chain}:{number}{icode}" for chain, number, icode in sorted(interrupted)
    ]


def rewrite_pdb_with_contiguous_residues(input_pdb: Path, output_pdb: Path) -> Dict[str, object]:
    """Group ATOM records by residue while preserving first-seen residue order."""
    header_lines = []
    residue_order = []
    residue_lines = {}

    with open(input_pdb, "r", errors="ignore") as handle:
        for line in handle:
            if line.startswith("ATOM"):
                key = pdb_residue_key(line)
                if key not in residue_lines:
                    residue_order.append(key)
                    residue_lines[key] = []
                residue_lines[key].append(line.rstrip("\n"))
            elif line.startswith(("CRYST1", "REMARK")):
                header_lines.append(line.rstrip("\n"))

    if not residue_order:
        raise RuntimeError("No ATOM records were available for residue-order repair.")

    with open(output_pdb, "w") as handle:
        for line in header_lines:
            handle.write(line + "\n")

        previous_chain = None
        atom_count = 0
        for key in residue_order:
            chain_id = key[0]
            if previous_chain is not None and chain_id != previous_chain:
                handle.write("TER\n")
            for atom_line in residue_lines[key]:
                handle.write(atom_line + "\n")
                atom_count += 1
            previous_chain = chain_id

        handle.write("TER\nEND\n")

    remaining = find_interrupted_pdb_residues(output_pdb)
    if remaining:
        raise RuntimeError(
            "Residue-order repair failed; interrupted residues remain: "
            + ", ".join(remaining[:20])
        )

    return {
        "strategy": "group_atoms_by_residue",
        "residue_count": len(residue_order),
        "atom_count": atom_count,
    }


def protonate_receptor_pdb(
    cleaned_pdb: Path,
    protonated_pdb: Path,
    work_dir: Path,
    timeout: int = 600,
) -> Tuple[Path, Dict[str, object]]:
    """Add receptor hydrogens with Open Babel when available.

    Meeko receptor preparation is most reliable when hydrogen atoms are present.
    If Open Babel protonation fails, the cleaned PDB is retained and Meeko is still
    attempted, with the complete failure log preserved for diagnosis.
    """
    obabel = resolve_command("obabel")
    if not obabel:
        return cleaned_pdb, {
            "strategy": "cleaned_pdb_without_added_hydrogens",
            "reason": "Open Babel executable was not found",
        }

    command = [
        obabel,
        str(cleaned_pdb),
        "-O",
        str(protonated_pdb),
        "-h",
        "-p",
        "7.4",
    ]
    result = run_cmd(command, cwd=str(work_dir), timeout=timeout)
    write_command_log(work_dir / "receptor_protonation.log", command, result)

    if result.returncode != 0 or not protonated_pdb.exists():
        return cleaned_pdb, {
            "strategy": "cleaned_pdb_after_protonation_failure",
            "returncode": result.returncode,
            "stderr": _as_text(result.stderr)[-2000:],
        }

    atom_count = count_atomic_records(protonated_pdb)
    if atom_count < 20:
        return cleaned_pdb, {
            "strategy": "cleaned_pdb_after_invalid_protonated_output",
            "protonated_atom_count": atom_count,
        }

    return protonated_pdb, {
        "strategy": "openbabel_pH_7.4",
        "protonated_atom_count": atom_count,
    }


def get_meeko_runtime_capabilities(
    meeko_executable: str,
    work_dir: Path,
    timeout: int = 60,
) -> Dict[str, object]:
    """Inspect the installed Meeko CLI instead of assuming release-specific flags.

    Hugging Face Docker images may contain a Meeko executable from Conda while
    the Python package is later replaced by pip. Querying ``--help`` at runtime
    prevents unsupported options such as ``--delete_bad_res`` from being passed
    to an older entry point.
    """
    help_result = run_cmd([meeko_executable, "--help"], cwd=str(work_dir), timeout=timeout)
    help_text = (_as_text(help_result.stdout) + "\n" + _as_text(help_result.stderr)).strip()
    (work_dir / "meeko_receptor_cli_help.txt").write_text(
        help_text or "No help text was returned.",
        encoding="utf-8",
    )

    version_text = "unknown"
    try:
        from importlib.metadata import version as package_version
        version_text = package_version("meeko")
    except Exception:
        pass

    def supported(option: str) -> bool:
        return option in help_text

    # Prefer long options because short options have changed meaning between
    # Meeko releases.
    if supported("--delete_bad_res"):
        bad_res_option = "--delete_bad_res"
    elif supported("--allow_bad_res"):
        bad_res_option = "--allow_bad_res"
    elif re.search(r"(^|[\s,])-a([\s,]|$)", help_text):
        bad_res_option = "-a"
    else:
        bad_res_option = None

    capabilities = {
        "python_package_version": version_text,
        "executable": meeko_executable,
        "help_returncode": help_result.returncode,
        "supports_read_pdb": supported("--read_pdb"),
        "supports_read_with_prody": supported("--read_with_prody"),
        "supports_write_pdbqt": supported("--write_pdbqt"),
        "supports_output_basename": supported("--output_basename"),
        "supports_default_altloc": supported("--default_altloc"),
        "supports_box_center": supported("--box_center"),
        "supports_box_size": supported("--box_size"),
        "bad_res_option": bad_res_option,
        "help_file": str(work_dir / "meeko_receptor_cli_help.txt"),
    }
    (work_dir / "meeko_runtime_capabilities.json").write_text(
        json.dumps(capabilities, indent=2),
        encoding="utf-8",
    )
    return capabilities


def build_meeko_receptor_command(
    meeko: str,
    receptor_input_pdb: Path,
    output_basename: Path,
    requested_pdbqt: Path,
    center,
    size,
    capabilities: Dict[str, object],
    tolerant: bool,
) -> List[str]:
    """Build a receptor command using only options reported by ``--help``."""
    command = [meeko]

    if capabilities.get("supports_read_pdb"):
        command.extend(["--read_pdb", str(receptor_input_pdb)])
    elif capabilities.get("supports_read_with_prody"):
        command.extend(["--read_with_prody", str(receptor_input_pdb)])
    else:
        # ``-i`` is the stable input form shown in the Meeko release README.
        command.extend(["-i", str(receptor_input_pdb)])

    if capabilities.get("supports_write_pdbqt"):
        command.extend(["--write_pdbqt", str(requested_pdbqt)])
    else:
        # Older and some packaged CLIs use an output basename plus the ``-p``
        # switch. Meeko then writes basename.pdbqt or basename_rigid.pdbqt.
        command.extend(["-o", str(output_basename), "-p"])

    if capabilities.get("supports_default_altloc"):
        command.extend(["--default_altloc", "A"])

    if capabilities.get("supports_box_center"):
        command.extend([
            "--box_center",
            str(center[0]),
            str(center[1]),
            str(center[2]),
        ])
    if capabilities.get("supports_box_size"):
        command.extend([
            "--box_size",
            str(size[0]),
            str(size[1]),
            str(size[2]),
        ])

    if tolerant and capabilities.get("bad_res_option"):
        command.append(str(capabilities["bad_res_option"]))

    return command


def collect_meeko_pdbqt_candidates(
    work_dir: Path,
    output_basename: Path,
    requested_pdbqt: Path,
) -> List[Path]:
    """Return possible rigid receptor outputs across Meeko CLI generations."""
    candidates = [
        requested_pdbqt,
        output_basename.with_suffix(".pdbqt"),
        output_basename.parent / f"{output_basename.name}_rigid.pdbqt",
        output_basename.parent / f"{output_basename.name}_flex.pdbqt",
    ]
    candidates.extend(sorted(work_dir.glob(f"{output_basename.name}*.pdbqt")))

    unique = []
    seen = set()
    for candidate in candidates:
        key = str(candidate.resolve()) if candidate.exists() else str(candidate)
        if key not in seen:
            seen.add(key)
            unique.append(candidate)
    return unique


def prepare_receptor_once(work_dir: Path, protein_file: Path, center, size, timeout=600):
    """Prepare one rigid receptor PDBQT with runtime-compatible Meeko syntax.

    The function first performs a strict preparation. If that fails and the
    installed CLI advertises a bad-residue tolerance option, one controlled
    retry is made with that exact supported option. Open Babel is not used to
    protonate or create the receptor PDBQT because it can reorder residue atoms
    or generate empty or ligand-style receptor files.
    """
    work_dir.mkdir(parents=True, exist_ok=True)
    suffix = protein_file.suffix.lower()

    if suffix == ".pdbqt":
        receptor_pdbqt = work_dir / "prepared_receptor.pdbqt"
        receptor_source = work_dir / "receptor_source_input.pdbqt"
        shutil.copy2(protein_file, receptor_pdbqt)
        shutil.copy2(protein_file, receptor_source)
        validation = validate_receptor_pdbqt(receptor_pdbqt)
        return receptor_pdbqt, receptor_source, {
            "strategy": "validated_input_pdbqt",
            "validation": validation,
        }

    cleaned_pdb = work_dir / "receptor_cleaned.pdb"
    clean_stats = strict_clean_receptor_pdb(protein_file, cleaned_pdb)
    cleaned_atom_count = count_atomic_records(cleaned_pdb)
    if cleaned_atom_count < 20:
        raise RuntimeError(
            f"Only {cleaned_atom_count} receptor atoms remained after cleaning. "
            "Check chain selection, residue names, alternate locations and PDB formatting."
        )

    # Do not protonate the receptor with Open Babel before Meeko. Open Babel
    # commonly appends hydrogen records after the heavy-atom block, making the
    # atoms of each residue non-contiguous. Meeko then raises
    # ``ValueError: interrupted residues in PDB`` for most or all residues.
    # Meeko can add missing hydrogens internally during residue-template matching.
    interrupted_before = find_interrupted_pdb_residues(cleaned_pdb)
    if interrupted_before:
        reordered_pdb = work_dir / "receptor_cleaned_contiguous.pdb"
        residue_order_info = rewrite_pdb_with_contiguous_residues(
            cleaned_pdb, reordered_pdb
        )
        receptor_input_pdb = reordered_pdb
    else:
        receptor_input_pdb = cleaned_pdb
        residue_order_info = {
            "strategy": "original_cleaned_order_already_contiguous",
            "interrupted_residues_before": 0,
        }

    interrupted_after = find_interrupted_pdb_residues(receptor_input_pdb)
    if interrupted_after:
        raise RuntimeError(
            "The receptor still contains interrupted residues after repair: "
            + ", ".join(interrupted_after[:20])
        )

    protonation_info = {
        "strategy": "meeko_internal_missing_hydrogen_completion",
        "openbabel_receptor_protonation_used": False,
        "reason": (
            "Open Babel receptor protonation was disabled because it can reorder "
            "PDB atom records and cause Meeko interrupted-residue errors."
        ),
        "residue_order_validation": residue_order_info,
    }

    meeko = resolve_command("mk_prepare_receptor.py", "mk_prepare_receptor")
    if not meeko:
        raise RuntimeError(
            "Meeko receptor preparation executable was not found. Confirm that "
            "mk_prepare_receptor.py or mk_prepare_receptor is installed and on PATH."
        )

    capabilities = get_meeko_runtime_capabilities(meeko, work_dir)
    receptor_pdbqt = work_dir / "prepared_receptor.pdbqt"

    # Always perform a strict attempt. Add a tolerant attempt only when the
    # executable itself reports a supported option.
    attempts = [{"name": "strict", "tolerant": False}]
    if capabilities.get("bad_res_option"):
        attempts.append({
            "name": f"tolerant_{str(capabilities['bad_res_option']).lstrip('-')}",
            "tolerant": True,
        })

    attempt_reports = []

    for attempt_index, attempt in enumerate(attempts, start=1):
        attempt_base = work_dir / f"prepared_receptor_attempt_{attempt_index}"
        attempt_requested = work_dir / f"prepared_receptor_attempt_{attempt_index}.pdbqt"

        # Remove outputs belonging to this attempt so stale files can never be
        # mistaken for successful receptor preparation.
        for old_file in work_dir.glob(f"{attempt_base.name}*.pdbqt"):
            old_file.unlink(missing_ok=True)
        attempt_requested.unlink(missing_ok=True)
        receptor_pdbqt.unlink(missing_ok=True)

        command = build_meeko_receptor_command(
            meeko=meeko,
            receptor_input_pdb=receptor_input_pdb,
            output_basename=attempt_base,
            requested_pdbqt=attempt_requested,
            center=center,
            size=size,
            capabilities=capabilities,
            tolerant=bool(attempt["tolerant"]),
        )

        result = run_cmd(command, cwd=str(work_dir), timeout=timeout)
        log_path = work_dir / f"meeko_receptor_attempt_{attempt_index}_{attempt['name']}.log"
        write_command_log(log_path, command, result)

        candidate_reports = []
        valid_output = None
        if result.returncode == 0:
            for candidate in collect_meeko_pdbqt_candidates(
                work_dir=work_dir,
                output_basename=attempt_base,
                requested_pdbqt=attempt_requested,
            ):
                candidate_report = {
                    "path": str(candidate),
                    "exists": candidate.exists(),
                    "size_bytes": candidate.stat().st_size if candidate.exists() else 0,
                }
                if candidate.exists():
                    try:
                        validation = validate_receptor_pdbqt(candidate)
                        candidate_report["validation"] = validation
                        # Prefer the rigid output when both rigid and flexible
                        # receptor files were produced.
                        if valid_output is None or "_rigid" in candidate.name:
                            valid_output = candidate
                    except Exception as exc:
                        candidate_report["validation_error"] = str(exc)
                candidate_reports.append(candidate_report)

        report = {
            "attempt": attempt["name"],
            "command": command,
            "returncode": result.returncode,
            "stdout_tail": _as_text(result.stdout)[-3000:],
            "stderr_tail": _as_text(result.stderr)[-5000:],
            "candidates": candidate_reports,
        }

        if result.returncode == 0 and valid_output is not None:
            shutil.copy2(valid_output, receptor_pdbqt)
            validation = validate_receptor_pdbqt(receptor_pdbqt)
            report["selected_output"] = str(valid_output)
            report["validation"] = validation
            attempt_reports.append(report)
            return receptor_pdbqt, cleaned_pdb, {
                "strategy": "meeko_runtime_compatible_cli",
                "meeko_runtime": capabilities,
                "successful_attempt": attempt["name"],
                "cleaning_stats": clean_stats,
                "cleaned_atom_count": cleaned_atom_count,
                "protonation": protonation_info,
                "validation": validation,
                "attempts": attempt_reports,
            }

        attempt_reports.append(report)

    diagnostic_json = work_dir / "receptor_preparation_failed.json"
    diagnostic_json.write_text(
        json.dumps(
            {
                "protein_file": str(protein_file),
                "cleaning_stats": clean_stats,
                "cleaned_atom_count": cleaned_atom_count,
                "protonation": protonation_info,
                "meeko_runtime": capabilities,
                "attempts": attempt_reports,
            },
            indent=2,
        ),
        encoding="utf-8",
    )

    first_error = attempt_reports[0].get("stderr_tail", "") if attempt_reports else ""
    last_error = attempt_reports[-1].get("stderr_tail", "") if attempt_reports else ""
    raise RuntimeError(
        "Meeko receptor preparation failed, so docking was stopped before Vina. "
        f"The cleaned receptor contained {cleaned_atom_count} atoms. "
        f"Detected Meeko Python package version: {capabilities.get('python_package_version')}. "
        f"Detected bad-residue option: {capabilities.get('bad_res_option') or 'none'}. "
        f"Diagnostic files were saved in {work_dir}.\n\n"
        f"Strict-attempt error:\n{first_error}\n\n"
        f"Last-attempt error:\n{last_error}"
    )

def ligand_mol_from_input(ligand_file: Path):
    suffix = ligand_file.suffix.lower()

    if suffix == ".sdf":
        suppl = Chem.SDMolSupplier(str(ligand_file), removeHs=False)
        mol = next((m for m in suppl if m is not None), None)
    elif suffix == ".mol":
        mol = Chem.MolFromMolFile(str(ligand_file), removeHs=False)
    elif suffix == ".mol2":
        mol = Chem.MolFromMol2File(str(ligand_file), removeHs=False)
    elif suffix == ".pdb":
        mol = Chem.MolFromPDBFile(str(ligand_file), removeHs=False)
    else:
        raise ValueError("Ligand file type not supported for RDKit preparation.")

    if mol is None:
        raise ValueError("Could not parse ligand file.")

    if mol.GetNumConformers() == 0:
        mol = Chem.AddHs(mol)
        if AllChem.EmbedMolecule(mol, AllChem.ETKDGv3()) != 0:
            raise ValueError("Could not generate 3D conformer.")
        AllChem.UFFOptimizeMolecule(mol, maxIters=300)

    return mol


def prepare_ligand_pdbqt(work_dir: Path, ligand_file: Path, timeout=300):
    """Prepare ligand PDBQT using Open Babel directly.

    This is faster and more reliable for COCONUT/PubChem PDB ligands because many
    downloaded ligand PDB files contain HETATM records but no CONECT/bond table.
    RDKit may fail or guess wrong bonds in such files. Open Babel handles these
    ligand formats better for docking preparation.
    """
    if ligand_file.suffix.lower() == ".pdbqt":
        dst = work_dir / "ligand.pdbqt"
        shutil.copy2(ligand_file, dst)
        validate_ligand_pdbqt(dst)
        return dst

    if not ensure_command("obabel"):
        raise RuntimeError("obabel is required for ligand preparation.")

    out_pdbqt = work_dir / "ligand.pdbqt"

    # Direct conversion is preferred for SDF/MOL/MOL2/PDB files.
    # -h adds hydrogens; --partialcharge gasteiger assigns charges for Vina.
    cmd = [
        "obabel",
        str(ligand_file),
        "-O",
        str(out_pdbqt),
        "-h",
        "--partialcharge",
        "gasteiger",
    ]

    result = run_cmd(cmd, cwd=str(work_dir), timeout=timeout)

    if result.returncode != 0 or not out_pdbqt.exists():
        raise RuntimeError(
            "Ligand preparation failed with Open Babel.\n"
            f"Command: {' '.join(cmd)}\n"
            f"STDOUT:\n{_as_text(result.stdout)}\n"
            f"STDERR:\n{_as_text(result.stderr)}"
        )

    validate_ligand_pdbqt(out_pdbqt)
    return out_pdbqt


def prepare_smiles_ligand_pdbqt(work_dir: Path, smiles: str, ligand_name: str, timeout=300):
    mol = Chem.MolFromSmiles(smiles.strip())
    if mol is None:
        raise ValueError("Invalid SMILES.")

    mol = Chem.AddHs(mol)

    if AllChem.EmbedMolecule(mol, AllChem.ETKDGv3()) != 0:
        raise ValueError("RDKit could not build 3D conformer.")

    AllChem.UFFOptimizeMolecule(mol, maxIters=300)

    sdf_path = work_dir / f"{safe_filename(ligand_name)}.sdf"
    writer = Chem.SDWriter(str(sdf_path))
    writer.write(mol)
    writer.close()

    out_pdbqt = work_dir / "ligand.pdbqt"

    result = run_cmd(
        ["obabel", str(sdf_path), "-O", str(out_pdbqt), "-xh"],
        cwd=str(work_dir),
        timeout=timeout,
    )

    if result.returncode != 0 or not out_pdbqt.exists():
        raise RuntimeError(
            "SMILES ligand preparation failed.\n"
            f"STDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}"
        )

    validate_ligand_pdbqt(out_pdbqt)
    return out_pdbqt


VINA_TABLE_RE = re.compile(r"^\s*(\d+)\s+(-?\d+\.\d+)\s+([0-9.]+)\s+([0-9.]+)\s*$")


def parse_vina_stdout(stdout_text: str) -> pd.DataFrame:
    rows = []
    for line in stdout_text.splitlines():
        m = VINA_TABLE_RE.match(line.strip())
        if m:
            rows.append(
                {
                    "mode": int(m.group(1)),
                    "affinity_kcal_per_mol": float(m.group(2)),
                    "rmsd_lb": float(m.group(3)),
                    "rmsd_ub": float(m.group(4)),
                }
            )
    return pd.DataFrame(rows)


def split_first_model_pdbqt(pdbqt_path: Path, out_path: Path):
    lines = []
    in_first_model = False
    saw_model = False

    with open(pdbqt_path, "r", errors="ignore") as f:
        for line in f:
            if line.startswith("MODEL"):
                saw_model = True
                parts = line.split()
                in_first_model = len(parts) > 1 and parts[1] == "1"
                continue
            if line.startswith("ENDMDL") and in_first_model:
                break
            if saw_model:
                if in_first_model:
                    lines.append(line)
            else:
                lines.append(line)

    with open(out_path, "w") as out:
        out.writelines(lines)
        out.write("END\n")


def convert_structure_to_pdb(input_path: Path, output_path: Path, timeout=300):
    if input_path.suffix.lower() == ".pdb":
        if input_path.resolve() != output_path.resolve():
            shutil.copy2(input_path, output_path)
        return output_path

    if not ensure_command("obabel"):
        raise RuntimeError("obabel is required to convert structure to PDB.")

    result = run_cmd(
        ["obabel", str(input_path), "-O", str(output_path)],
        timeout=timeout,
    )

    if result.returncode != 0 or not output_path.exists():
        raise RuntimeError(
            f"Failed to convert {input_path.name} to PDB.\n"
            f"STDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}"
        )

    return output_path


def combine_protein_and_ligand_pdb(receptor_pdb: Path, ligand_pdb: Path, complex_pdb: Path):
    """
    Combine receptor and docked ligand into one PDB complex.

    This revised version preserves ligand atom names and element columns as much
    as possible so LigPlot/LigPlus can keep its normal default coloring.
    The ligand is still written as HETATM with residue name LIG and chain Z.
    """
    serial = 1

    def safe_int(field, default=1):
        try:
            return int(str(field).strip())
        except Exception:
            return default

    def safe_float(field, default=0.0):
        try:
            return float(str(field).strip())
        except Exception:
            return default

    def normalize_atom_line(line, record, atom_serial, force_resname=None, force_chain=None, force_resseq=None):
        line = line.rstrip("\n")
        if len(line) < 80:
            line = line.ljust(80)

        atom_name = line[12:16]
        altloc = " "
        res_name = force_resname if force_resname is not None else (line[17:20].strip() or "UNK")
        chain_id = force_chain if force_chain is not None else (line[21].strip() or "A")
        res_seq = force_resseq if force_resseq is not None else safe_int(line[22:26], 1)

        x = safe_float(line[30:38])
        y = safe_float(line[38:46])
        z = safe_float(line[46:54])

        occ = safe_float(line[54:60], 1.00)
        bfac = safe_float(line[60:66], 0.00)

        element = line[76:78].strip()
        if not element:
            # record is "ATOM" for the receptor and "HETATM" for the docked
            # ligand; only the receptor side is guaranteed to be a standard
            # amino acid, so only there can "CA" safely be forced to carbon.
            element = infer_element_from_atom_name(
                atom_name.strip(), is_standard_residue_atom=(record == "ATOM")
            ) or "C"

        charge = line[78:80].strip()

        return (
            f"{record:<6}"
            f"{atom_serial:5d} "
            f"{atom_name:<4}"
            f"{altloc}"
            f"{res_name[:3].upper():>3} "
            f"{chain_id[:1]}"
            f"{res_seq:4d}"
            f"    "
            f"{x:8.3f}{y:8.3f}{z:8.3f}"
            f"{occ:6.2f}{bfac:6.2f}"
            f"          "
            f"{element:>2}{charge:>2}"
        )

    with open(complex_pdb, "w") as out:
        with open(receptor_pdb, "r", errors="ignore") as fin:
            for line in fin:
                if not line.startswith("ATOM"):
                    continue

                out.write(
                    normalize_atom_line(
                        line=line,
                        record="ATOM",
                        atom_serial=serial,
                    )
                    + "\n"
                )
                serial += 1

        out.write("TER\n")

        ligand_atom_count = 0
        with open(ligand_pdb, "r", errors="ignore") as fin:
            for line in fin:
                if not line.startswith(("ATOM", "HETATM")):
                    continue

                out.write(
                    normalize_atom_line(
                        line=line,
                        record="HETATM",
                        atom_serial=serial,
                        force_resname="LIG",
                        force_chain="Z",
                        force_resseq=1,
                    )
                    + "\n"
                )

                serial += 1
                ligand_atom_count += 1

        if ligand_atom_count == 0:
            raise RuntimeError("No ligand atoms were found while generating the complex PDB.")

        out.write("END\n")

def make_zip(zip_path: Path, folder: Path):
    with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
        for fp in folder.rglob("*"):
            if fp.is_file():
                zf.write(fp, arcname=fp.relative_to(folder))


def dock_single_ligand(
    ligand_source,
    ligand_kind,
    receptor_pdbqt: Path,
    receptor_source: Path,
    batch_dir: Path,
    center,
    size,
    exhaustiveness,
    num_modes,
    vina_timeout,
    prep_timeout,
    cpu_threads,
):
    ligand_name = ligand_source.name if ligand_kind == "file" else ligand_source["name"]
    ligand_dir = batch_dir / safe_filename(Path(ligand_name).stem)
    ligand_dir.mkdir(parents=True, exist_ok=True)

    try:
        if ligand_kind == "file":
            ligand_pdbqt = prepare_ligand_pdbqt(ligand_dir, ligand_source, timeout=prep_timeout)
        else:
            ligand_pdbqt = prepare_smiles_ligand_pdbqt(
                ligand_dir,
                ligand_source["smiles"],
                ligand_source["name"],
                timeout=prep_timeout,
            )

        docked_pdbqt = ligand_dir / "docked_out.pdbqt"

        cmd = [
            "vina",
            "--receptor", str(receptor_pdbqt),
            "--ligand", str(ligand_pdbqt),
            "--center_x", str(center[0]),
            "--center_y", str(center[1]),
            "--center_z", str(center[2]),
            "--size_x", str(size[0]),
            "--size_y", str(size[1]),
            "--size_z", str(size[2]),
            "--exhaustiveness", str(exhaustiveness),
            "--num_modes", str(num_modes),
            "--cpu", str(cpu_threads),
            "--out", str(docked_pdbqt),
        ]

        result = run_cmd(cmd, cwd=str(ligand_dir), timeout=vina_timeout)

        (ligand_dir / "vina_stdout.txt").write_text(result.stdout or "")
        (ligand_dir / "vina_stderr.txt").write_text(result.stderr or "")

        if result.returncode != 0 or not docked_pdbqt.exists():
            return {
                "ligand": ligand_name,
                "status": "FAILED",
                "best_affinity_kcal_per_mol": "",
                "best_mode": "",
                "rmsd_lb": "",
                "rmsd_ub": "",
                "num_modes_generated": "",
                "error": f"Vina failed or timed out. STDERR: {result.stderr[-500:]}",
                "complex_pdb": "",
                "scores_csv": "",
            }

        scores_df = parse_vina_stdout((result.stdout or "") + "\n" + (result.stderr or ""))

        if scores_df.empty:
            return {
                "ligand": ligand_name,
                "status": "FAILED",
                "best_affinity_kcal_per_mol": "",
                "best_mode": "",
                "rmsd_lb": "",
                "rmsd_ub": "",
                "num_modes_generated": "",
                "error": "Docking completed but score table was not parsed.",
                "complex_pdb": "",
                "scores_csv": "",
            }

        scores_csv = ligand_dir / "docking_scores.csv"
        scores_df.to_csv(scores_csv, index=False)

        best_pose_pdbqt = ligand_dir / "best_pose_model1.pdbqt"
        best_pose_pdb = ligand_dir / "best_ligand_pose.pdb"
        receptor_pdb = ligand_dir / "receptor_for_complex.pdb"
        complex_pdb = ligand_dir / "best_protein_ligand_complex.pdb"

        split_first_model_pdbqt(docked_pdbqt, best_pose_pdbqt)
        convert_structure_to_pdb(receptor_source, receptor_pdb, timeout=prep_timeout)
        convert_structure_to_pdb(best_pose_pdbqt, best_pose_pdb, timeout=prep_timeout)
        combine_protein_and_ligand_pdb(receptor_pdb, best_pose_pdb, complex_pdb)

        best_row = scores_df.iloc[0]

        summary = {
            "ligand": ligand_name,
            "status": "SUCCESS",
            "best_mode": int(best_row["mode"]),
            "best_affinity_kcal_per_mol": float(best_row["affinity_kcal_per_mol"]),
            "rmsd_lb": float(best_row["rmsd_lb"]),
            "rmsd_ub": float(best_row["rmsd_ub"]),
            "num_modes_generated": int(len(scores_df)),
            "grid_center": {"x": center[0], "y": center[1], "z": center[2]},
            "grid_size": {"x": size[0], "y": size[1], "z": size[2]},
            "complex_pdb": str(complex_pdb),
            "scores_csv": str(scores_csv),
        }

        (ligand_dir / "summary.json").write_text(json.dumps(summary, indent=2))

        return {
            "ligand": ligand_name,
            "status": "SUCCESS",
            "best_mode": int(best_row["mode"]),
            "best_affinity_kcal_per_mol": float(best_row["affinity_kcal_per_mol"]),
            "rmsd_lb": float(best_row["rmsd_lb"]),
            "rmsd_ub": float(best_row["rmsd_ub"]),
            "num_modes_generated": int(len(scores_df)),
            "error": "",
            "complex_pdb": str(complex_pdb),
            "scores_csv": str(scores_csv),
        }

    except Exception as e:
        return {
            "ligand": ligand_name,
            "status": "FAILED",
            "best_affinity_kcal_per_mol": "",
            "best_mode": "",
            "rmsd_lb": "",
            "rmsd_ub": "",
            "num_modes_generated": "",
            "error": str(e),
            "complex_pdb": "",
            "scores_csv": "",
        }


def parse_smiles_table(smiles_text: str):
    ligands = []
    for i, line in enumerate(smiles_text.splitlines(), start=1):
        line = line.strip()
        if not line:
            continue

        if "," in line:
            parts = [p.strip() for p in line.split(",", 1)]
            name, smiles = parts[0], parts[1]
        elif "\t" in line:
            parts = [p.strip() for p in line.split("\t", 1)]
            name, smiles = parts[0], parts[1]
        else:
            name, smiles = f"SMILES_{i}", line

        ligands.append({"name": safe_filename(name), "smiles": smiles})

    return ligands


def main():
    st.set_page_config(page_title="Bulamarwa Batch Protein-Ligand Docking Tool", layout="wide")
    init_state()

    st.title("Bulamarwa Batch Protein-Ligand Docking Tool")
    st.caption("Prepared receptor is reused once; multiple ligands are docked with timeout, failure skipping, CSV summary, and ZIP export.")

    with st.sidebar:
        st.header("Run settings")
        exhaustiveness = st.slider("Exhaustiveness", 1, 24, 1, 1)
        num_modes = st.slider("Number of poses", 1, 10, 1, 1)
        prep_timeout = st.number_input("Preparation timeout per step (seconds)", min_value=60, max_value=1800, value=240, step=60)
        vina_timeout = st.number_input("Vina timeout per ligand (seconds)", min_value=60, max_value=7200, value=180, step=60)
        cpu_threads = st.slider("CPU threads for Vina", 1, 8, 1, 1)

        st.warning("Fast/stable default: exhaustiveness 4, poses 3. For poor network, dock fewer ligands per run and download ZIP immediately.")
        if st.button("Clear all inputs and results"):
            reset_all()

    required_commands = {
        "AutoDock Vina": resolve_command("vina"),
        "Open Babel": resolve_command("obabel"),
        "Meeko receptor preparation": resolve_command("mk_prepare_receptor.py", "mk_prepare_receptor"),
    }
    missing_cmds = [label for label, executable in required_commands.items() if not executable]
    if missing_cmds:
        st.error(
            "Missing required docking component(s): " + ", ".join(missing_cmds)
            + ". Rebuild the Hugging Face Docker Space using the supplied Dockerfile and requirements.txt."
        )
        st.stop()

    with st.expander("Installed docking components", expanded=False):
        for label, executable in required_commands.items():
            st.code(f"{label}: {executable}")

    st.subheader("Step 1: Upload receptor and ligands")

    protein_upload = st.file_uploader(
        "Upload protein receptor (PDB or PDBQT)",
        type=["pdb", "pdbqt"],
        accept_multiple_files=False,
    )

    ligand_uploads = st.file_uploader(
        "Upload one or more ligands (SDF, MOL, MOL2, PDB, or PDBQT)",
        type=["sdf", "mol", "mol2", "pdb", "pdbqt"],
        accept_multiple_files=True,
    )

    smiles_text = st.text_area(
        "Optional: paste SMILES, one ligand per line. Format: Name,SMILES or only SMILES",
        height=120,
    )

    docking_run_mode = st.radio(
        "Ligand running option",
        ["Run only one ligand", "Run all uploaded/pasted ligands"],
        index=0,
        help="Use 'Run only one ligand' when network is unstable or when testing one compound at a time."
    )

    st.subheader("Step 2: Docking box definition")

    docking_mode = st.radio(
        "Choose docking mode",
        ["Residue-based docking", "Blind docking", "Manual box coordinates"],
        index=0,
    )

    residue_selection_text = ""
    padding = 8.0
    center = (0.0, 0.0, 0.0)
    size = (20.0, 20.0, 20.0)

    if docking_mode == "Residue-based docking":
        st.code("Examples:\nA:LYS45,ASP46\nA:45-50\nA:LYS45;B:TYR120")
        residue_selection_text = st.text_area("Residues and chains")
        padding = st.number_input("Padding around selected residues (Å)", min_value=2.0, value=8.0, step=1.0)

    elif docking_mode == "Blind docking":
        padding = st.number_input("Padding around whole protein (Å)", min_value=2.0, value=6.0, step=1.0)
        st.warning("Blind docking can be slow. Use residue-based docking when possible.")

    else:
        c1, c2, c3 = st.columns(3)
        center_x = c1.number_input("Center X", value=0.0, format="%.3f")
        center_y = c2.number_input("Center Y", value=0.0, format="%.3f")
        center_z = c3.number_input("Center Z", value=0.0, format="%.3f")

        s1, s2, s3 = st.columns(3)
        size_x = s1.number_input("Size X", value=20.0, min_value=5.0, format="%.3f")
        size_y = s2.number_input("Size Y", value=20.0, min_value=5.0, format="%.3f")
        size_z = s3.number_input("Size Z", value=20.0, min_value=5.0, format="%.3f")

        center = (center_x, center_y, center_z)
        size = (size_x, size_y, size_z)

    run_disabled = protein_upload is None or (not ligand_uploads and not smiles_text.strip())

    if st.button("Run batch docking", type="primary", disabled=run_disabled):
        try:
            session_dir = get_session_dir()
            export_dir = get_export_dir()
            shutil.rmtree(export_dir, ignore_errors=True)
            export_dir.mkdir(parents=True, exist_ok=True)

            protein_name = safe_filename(protein_upload.name)
            protein_path = session_dir / f"protein_{protein_name}"
            save_uploaded_file(protein_upload, protein_path)
            validate_extension(protein_upload.name, SUPPORTED_PROTEIN_EXTS, "Protein")
            validate_input_file_content(protein_path, "Protein")

            ligand_paths = []

            for lig in ligand_uploads or []:
                validate_extension(lig.name, SUPPORTED_LIGAND_EXTS, "Ligand")
                lig_path = session_dir / f"ligand_{safe_filename(lig.name)}"
                save_uploaded_file(lig, lig_path)
                validate_input_file_content(lig_path, "Ligand")
                ligand_paths.append(lig_path)

            smiles_ligands = parse_smiles_table(smiles_text)

            if docking_mode == "Blind docking":
                center, size = compute_blind_docking_box(protein_path, padding=padding, min_size=20.0)
                size = limit_box_size(size, max_size=25.0)
            elif docking_mode == "Residue-based docking":
                center, size = compute_residue_based_box(protein_path, residue_selection_text, padding=padding, min_size=18.0)
                size = limit_box_size(size, max_size=25.0)
            else:
                size = limit_box_size(size, max_size=25.0)

            current_volume = box_volume(size)

            if current_volume > 27000:
                st.error(
                    f"Docking box is still too large: {current_volume} Angstrom^3. "
                    "Reduce Size X/Y/Z below 30 Angstrom."
                )
                st.stop()

            st.info(f"Docking box center: {center}; size: {size}; volume: {current_volume} Angstrom^3")

            batch_dir = export_dir / "batch_docking_results"
            batch_dir.mkdir(parents=True, exist_ok=True)

            receptor_work = batch_dir / "_receptor_preparation"
            shutil.rmtree(receptor_work, ignore_errors=True)
            receptor_work.mkdir(parents=True, exist_ok=True)

            with st.spinner("Preparing receptor once with Meeko..."):
                receptor_pdbqt, receptor_source, receptor_info = prepare_receptor_once(
                    receptor_work,
                    protein_path,
                    center,
                    size,
                    timeout=prep_timeout,
                )

                fixed_receptor_pdbqt = batch_dir / "prepared_receptor.pdbqt"
                fixed_receptor_source = batch_dir / "receptor_source.pdb"

                if receptor_pdbqt.resolve() != fixed_receptor_pdbqt.resolve():
                    shutil.copy2(receptor_pdbqt, fixed_receptor_pdbqt)
                else:
                    fixed_receptor_pdbqt = receptor_pdbqt

                if receptor_source.resolve() != fixed_receptor_source.resolve():
                    convert_structure_to_pdb(
                        receptor_source,
                        fixed_receptor_source,
                        timeout=prep_timeout,
                    )
                else:
                    fixed_receptor_source = receptor_source

                (batch_dir / "receptor_preparation_summary.json").write_text(
                    json.dumps(receptor_info, indent=2)
                )

            all_ligands = [("file", p) for p in ligand_paths]
            all_ligands.extend([("smiles", s) for s in smiles_ligands])

            if docking_run_mode == "Run only one ligand":
                all_ligands = all_ligands[:1]
                st.info("Single-ligand mode selected. Only the first uploaded/pasted ligand will be docked.")

            progress = st.progress(0)
            status_box = st.empty()
            records = []

            for i, (kind, source) in enumerate(all_ligands, start=1):
                lig_name = source.name if kind == "file" else source["name"]
                status_box.info(f"Docking ligand {i}/{len(all_ligands)}: {lig_name}")

                record = dock_single_ligand(
                    ligand_source=source,
                    ligand_kind=kind,
                    receptor_pdbqt=fixed_receptor_pdbqt,
                    receptor_source=fixed_receptor_source,
                    batch_dir=batch_dir,
                    center=center,
                    size=size,
                    exhaustiveness=exhaustiveness,
                    num_modes=num_modes,
                    vina_timeout=vina_timeout,
                    prep_timeout=prep_timeout,
                    cpu_threads=cpu_threads,
                )

                records.append(record)
                pd.DataFrame(records).to_csv(batch_dir / "batch_docking_summary.csv", index=False)
                progress.progress(i / len(all_ligands))

            summary_df = pd.DataFrame(records)
            summary_csv = batch_dir / "batch_docking_summary.csv"
            summary_xlsx = batch_dir / "batch_docking_summary.xlsx"

            summary_df.to_csv(summary_csv, index=False)
            summary_df.to_excel(summary_xlsx, index=False)

            zip_path = export_dir / "batch_docking_results.zip"
            make_zip(zip_path, batch_dir)

            st.session_state["run_outputs"] = {
                "summary_csv": str(summary_csv),
                "summary_xlsx": str(summary_xlsx),
                "zip": str(zip_path),
                "summary_df": records,
                "center": center,
                "size": size,
            }

            st.success("Batch docking completed. Failed ligands, if any, were skipped and recorded.")

        except Exception as e:
            st.error(str(e))
            try:
                export_dir = get_export_dir()
                batch_dir = export_dir / "batch_docking_results"
                if batch_dir.exists():
                    diagnostic_zip = export_dir / "docking_failure_diagnostics.zip"
                    make_zip(diagnostic_zip, batch_dir)
                    with open(diagnostic_zip, "rb") as diagnostic_file:
                        st.download_button(
                            "Download failure diagnostics",
                            diagnostic_file.read(),
                            file_name="docking_failure_diagnostics.zip",
                            mime="application/zip",
                        )
            except Exception:
                pass

    outputs = st.session_state.get("run_outputs")

    if outputs:
        st.subheader("Batch docking summary")

        df = pd.DataFrame(outputs["summary_df"])

        preferred_columns = [
            "ligand",
            "status",
            "best_mode",
            "best_affinity_kcal_per_mol",
            "rmsd_lb",
            "rmsd_ub",
            "num_modes_generated",
            "complex_pdb",
            "scores_csv",
            "error",
        ]

        existing_columns = [col for col in preferred_columns if col in df.columns]
        remaining_columns = [col for col in df.columns if col not in existing_columns]
        df = df[existing_columns + remaining_columns]

        st.dataframe(df, use_container_width=True)

        st.metric("Successful ligands", int((df["status"] == "SUCCESS").sum()))
        st.metric("Failed ligands", int((df["status"] == "FAILED").sum()))

        successful_df = df[df["status"] == "SUCCESS"].copy()

        if not successful_df.empty:
            st.subheader("Download individual best protein-ligand complexes")

            for idx, row in successful_df.iterrows():
                complex_path = Path(str(row.get("complex_pdb", "")))

                if complex_path.exists():
                    ligand_label = safe_filename(str(row.get("ligand", f"ligand_{idx}")))

                    with open(complex_path, "rb") as complex_file:
                        st.download_button(
                            label=f"Download best complex: {ligand_label}",
                            data=complex_file.read(),
                            file_name=f"{ligand_label}_best_protein_ligand_complex.pdb",
                            mime="chemical/x-pdb",
                            key=f"download_complex_{idx}",
                        )

        c1, c2, c3 = st.columns(3)

        with c1:
            with open(outputs["summary_csv"], "rb") as f:
                st.download_button(
                    "Download summary CSV",
                    f.read(),
                    file_name="batch_docking_summary.csv",
                    mime="text/csv",
                )

        with c2:
            with open(outputs["summary_xlsx"], "rb") as f:
                st.download_button(
                    "Download summary Excel",
                    f.read(),
                    file_name="batch_docking_summary.xlsx",
                    mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                )

        with c3:
            with open(outputs["zip"], "rb") as f:
                st.download_button(
                    "Download all results ZIP",
                    f.read(),
                    file_name="batch_docking_results.zip",
                    mime="application/zip",
                )


if __name__ == "__main__":
    main()