File size: 87,489 Bytes
c289d87
 
 
 
 
504d922
c289d87
 
 
 
 
504d922
c289d87
 
504d922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c289d87
 
 
 
 
 
504d922
c289d87
 
 
 
 
 
 
 
 
 
504d922
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
 
c289d87
 
 
 
 
 
 
 
 
504d922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c289d87
 
 
 
 
 
504d922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
504d922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
 
 
 
 
 
 
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c289d87
 
504d922
c289d87
504d922
c289d87
 
 
 
 
504d922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c289d87
 
 
 
 
 
 
 
 
504d922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c289d87
 
504d922
 
 
c289d87
504d922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c289d87
 
 
504d922
 
 
 
 
 
 
 
 
 
c289d87
 
504d922
c289d87
 
 
504d922
 
 
 
 
 
 
 
c289d87
 
 
504d922
 
 
 
 
 
 
 
 
 
 
c289d87
 
 
 
504d922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c289d87
 
504d922
 
 
 
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c289d87
504d922
 
 
 
 
c289d87
 
 
 
 
504d922
 
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
 
 
 
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
 
c289d87
504d922
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
504d922
 
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
c289d87
 
 
 
 
 
 
 
 
 
 
 
504d922
c289d87
 
504d922
 
c289d87
 
504d922
c289d87
 
 
504d922
c289d87
504d922
c289d87
 
 
504d922
 
 
 
 
 
 
c289d87
 
 
504d922
 
 
 
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
504d922
 
 
c289d87
 
 
504d922
 
 
 
 
 
 
 
c289d87
 
504d922
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
c289d87
 
504d922
 
 
 
 
 
 
 
 
 
 
 
 
 
c289d87
 
 
 
 
 
 
 
 
504d922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c289d87
504d922
 
c289d87
 
 
 
 
504d922
c289d87
504d922
 
 
c289d87
504d922
 
 
 
 
 
 
 
 
 
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
504d922
c289d87
504d922
c289d87
 
504d922
 
c289d87
 
 
 
 
 
 
 
504d922
 
 
 
 
 
 
 
 
 
 
 
c289d87
 
 
 
 
 
504d922
c289d87
504d922
 
 
 
 
 
 
 
c289d87
504d922
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
 
 
 
 
c289d87
504d922
 
 
c289d87
504d922
 
 
 
 
 
 
 
 
 
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
504d922
c289d87
 
 
 
 
 
 
 
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
from __future__ import annotations

import argparse
import csv
import json
import os
import shutil
import sys
import time
import urllib.parse
import urllib.request
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed
from pathlib import Path

try:  # pragma: no cover
    from rdkit import Chem, DataStructs
    from rdkit.Chem import rdMolDescriptors
    from rdkit.Chem import rdFingerprintGenerator
    from rdkit.Chem.Scaffolds import MurckoScaffold

    RDKIT_AVAILABLE = True
except Exception:  # pragma: no cover
    Chem = None  # type: ignore[assignment]
    DataStructs = None  # type: ignore[assignment]
    rdMolDescriptors = None  # type: ignore[assignment]
    rdFingerprintGenerator = None  # type: ignore[assignment]
    MurckoScaffold = None  # type: ignore[assignment]
    RDKIT_AVAILABLE = False

try:  # pragma: no cover
    from tqdm import tqdm
except Exception:  # pragma: no cover
    tqdm = None  # type: ignore[assignment]

ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from docking_pipeline.dataset import (
    auto_detect_reference_ligand,
    count_sdf_records,
    create_dataset_manifest,
    download_pdb_structure,
    extract_receptor_and_reference_ligand,
    list_hetero_ligands,
    list_known_good_complexes,
    prepare_dataset_target_with_rdock,
    resolve_known_good_defaults,
    validate_dataset_dir,
)
from docking_pipeline.provenance import CommandRunner, RDockPipelineError, fail_if_bad_command, probe_version, require_executable, require_file
from docking_pipeline.sdf import split_sdf_text
from docking_pipeline.validation import resolve_jobs


KNOWN_GOOD = ROOT / "configs" / "known_good_pdb_complexes.yaml"
DEFAULT_THRESHOLD_LADDER = [95, 90, 85, 80, 75, 70]
DEFAULT_BUNDLED_EXAMPLE = ROOT / "data" / "examples" / "example_smiles.smi"
DEFAULT_EXAMPLE_1000 = ROOT / "data" / "examples" / "example_smiles_1000.smi"


def _read_smiles(path: Path, n_ligands: int) -> list[tuple[str, str]]:
    rows: list[tuple[str, str]] = []
    for idx, line in enumerate(path.read_text(encoding="utf-8").splitlines()):
        text = line.strip()
        if not text or text.startswith("#"):
            continue
        parts = text.replace(",", " ").split()
        smiles = parts[0]
        ligand_id = parts[1] if len(parts) > 1 else f"lig_{idx:05d}"
        rows.append((smiles, ligand_id))
        if len(rows) >= n_ligands:
            break
    return rows


def _read_all_smiles(path: Path) -> list[tuple[str, str]]:
    rows: list[tuple[str, str]] = []
    for idx, line in enumerate(path.read_text(encoding="utf-8").splitlines()):
        text = line.strip()
        if not text or text.startswith("#"):
            continue
        parts = text.replace(",", " ").split()
        smiles = parts[0]
        ligand_id = parts[1] if len(parts) > 1 else f"lig_{idx:05d}"
        rows.append((smiles, ligand_id))
    return rows


def _default_ligand_jobs() -> int:
    cpu_total = os.cpu_count() or 8
    return max(1, cpu_total - 4)


def _mkdir_or_fail(path: Path) -> None:
    try:
        path.mkdir(parents=True, exist_ok=True)
    except PermissionError as exc:
        suggestion = Path.home() / "datasets" / path.name
        raise RDockPipelineError(
            f"Cannot create output directory {path}: permission denied. "
            f"Use a writable path such as {suggestion} or a relative path under your home/project directory."
        ) from exc


def _http_json(url: str, timeout: int, retries: int = 3, pause_seconds: float = 1.0) -> dict[str, object]:
    last_error: Exception | None = None
    for attempt in range(1, retries + 1):
        try:
            request = urllib.request.Request(url, headers={"User-Agent": "portable-rdock-pipeline/1.0"})
            with urllib.request.urlopen(request, timeout=timeout) as response:
                payload = response.read().decode("utf-8")
            return json.loads(payload)
        except Exception as exc:  # pragma: no cover - network-dependent
            last_error = exc
            if attempt < retries:
                time.sleep(pause_seconds * attempt)
    raise RDockPipelineError(f"HTTP JSON request failed after {retries} attempts for {url}: {last_error}")


def _http_post_json(
    url: str,
    data: bytes,
    content_type: str,
    timeout: int,
    retries: int = 3,
    pause_seconds: float = 1.0,
) -> dict[str, object]:
    last_error: Exception | None = None
    for attempt in range(1, retries + 1):
        try:
            request = urllib.request.Request(
                url,
                data=data,
                headers={"User-Agent": "portable-rdock-pipeline/1.0", "Content-Type": content_type},
                method="POST",
            )
            with urllib.request.urlopen(request, timeout=timeout) as response:
                payload = response.read().decode("utf-8")
            return json.loads(payload)
        except Exception as exc:  # pragma: no cover - network-dependent
            last_error = exc
            if attempt < retries:
                time.sleep(pause_seconds * attempt)
    raise RDockPipelineError(f"HTTP POST JSON request failed after {retries} attempts for {url}: {last_error}")


def _http_post_form_json(
    url: str,
    form: dict[str, str],
    timeout: int,
    retries: int = 3,
    pause_seconds: float = 1.0,
) -> dict[str, object]:
    body = urllib.parse.urlencode(form).encode("utf-8")
    return _http_post_json(url, body, "application/x-www-form-urlencoded", timeout, retries=retries, pause_seconds=pause_seconds)


def _write_smi(rows: list[tuple[str, str]], path: Path) -> Path:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text("\n".join(f"{smiles} {ligand_id}" for smiles, ligand_id in rows) + "\n", encoding="utf-8")
    return path


def _count_sdf_records_lenient(path: Path) -> int:
    if not path.exists() or path.stat().st_size <= 0:
        return 0
    text = path.read_text(encoding="utf-8", errors="ignore")
    return len(split_sdf_text(text))


def _progress_log(out: Path, message: str, payload: dict[str, object] | None = None) -> None:
    line = message
    print(line, file=sys.stderr, flush=True)
    log_path = out / "logs" / "pubchem_progress.log"
    log_path.parent.mkdir(parents=True, exist_ok=True)
    with log_path.open("a", encoding="utf-8") as handle:
        handle.write(line + "\n")
    if payload is not None:
        status_path = out / "logs" / "pubchem_progress.json"
        status_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")


def _write_partial_pubchem_hits(
    out: Path,
    rows: list[tuple[str, str]],
    metadata_rows: list[dict[str, object]],
) -> None:
    if not rows:
        return
    _write_smi(rows, out / "ligands" / "pubchem_partial_hits.smi")
    _write_csv(out / "ligands" / "pubchem_partial_metadata.csv", metadata_rows)


def _obabel_convert(runner: CommandRunner, stage: str, input_path: Path, output_path: Path, extra_args: list[str], cwd: Path) -> Path:
    obabel = require_executable("obabel")
    rec = runner.run(
        stage,
        [obabel, str(input_path.resolve()), *extra_args, "-O", str(output_path.resolve())],
        cwd,
        cwd / "logs" / f"{stage}.stdout.log",
        cwd / "logs" / f"{stage}.stderr.log",
    )
    fail_if_bad_command(rec, f"OpenBabel {stage}")
    return require_file(output_path, f"OpenBabel output {stage}")


def _merge_sdf_files(inputs: list[Path], output_path: Path) -> Path:
    output_path.parent.mkdir(parents=True, exist_ok=True)
    with output_path.open("w", encoding="utf-8") as handle:
        for path in inputs:
            if not path.exists() or path.stat().st_size <= 0:
                continue
            text = path.read_text(encoding="utf-8", errors="ignore")
            if text and not text.endswith("\n"):
                text += "\n"
            handle.write(text)
    return output_path


def _convert_single_ligand_with_obabel(
    runner: CommandRunner,
    row: tuple[str, str],
    work_dir: Path,
) -> tuple[Path | None, dict[str, object] | None]:
    smiles, ligand_id = row
    smi_path = work_dir / f"{ligand_id}.smi"
    sdf_path = work_dir / f"{ligand_id}.sdf"
    smi_path.write_text(f"{smiles} {ligand_id}\n", encoding="utf-8")
    try:
        _obabel_convert(runner, f"single_{ligand_id}_to_sdf", smi_path, sdf_path, ["--gen3d", "-h"], work_dir)
        if _count_sdf_records_lenient(sdf_path) != 1:
            raise RDockPipelineError(f"Expected 1 SDF record for ligand {ligand_id}, got {_count_sdf_records_lenient(sdf_path)}")
        return sdf_path, None
    except Exception as exc:
        return None, {"ligand_id": ligand_id, "smiles": smiles, "reason": str(exc), "stage": "single_ligand_fallback"}


def _convert_batch_with_obabel(
    runner: CommandRunner,
    batch_rows: list[tuple[str, str]],
    batch_dir: Path,
    batch_name: str,
    single_fallback_workers: int,
) -> tuple[Path, list[dict[str, object]]]:
    batch_dir.mkdir(parents=True, exist_ok=True)
    batch_smi = _write_smi(batch_rows, batch_dir / f"{batch_name}.smi")
    batch_sdf = batch_dir / f"{batch_name}.sdf"
    invalid_rows: list[dict[str, object]] = []
    try:
        _obabel_convert(runner, f"{batch_name}_to_sdf", batch_smi, batch_sdf, ["--gen3d", "-h"], batch_dir)
        if _count_sdf_records_lenient(batch_sdf) == len(batch_rows):
            return batch_sdf, invalid_rows
    except Exception as exc:
        invalid_rows.append({"ligand_id": batch_name, "smiles": "", "reason": str(exc), "stage": "batch_conversion"})

    single_dir = batch_dir / f"{batch_name}_single"
    single_dir.mkdir(parents=True, exist_ok=True)
    single_outputs: dict[str, Path] = {}
    with ThreadPoolExecutor(max_workers=min(max(1, single_fallback_workers), len(batch_rows))) as pool:
        futures = {
            pool.submit(_convert_single_ligand_with_obabel, runner, row, single_dir): row
            for row in batch_rows
        }
        for future in as_completed(futures):
            row = futures[future]
            output_path, invalid = future.result()
            if output_path is not None:
                single_outputs[row[1]] = output_path
            if invalid is not None:
                invalid_rows.append(invalid)
    ordered_outputs = [single_outputs[ligand_id] for _, ligand_id in batch_rows if ligand_id in single_outputs]
    _merge_sdf_files(ordered_outputs, batch_sdf)
    return batch_sdf, invalid_rows


def _convert_batch_with_obabel_worker(
    batch_rows: list[tuple[str, str]],
    batch_dir: str,
    batch_name: str,
    single_fallback_workers: int,
) -> tuple[str, list[dict[str, object]]]:
    batch_path = Path(batch_dir)
    runner = CommandRunner(batch_path / "logs" / "commands.log")
    sdf_path, invalid_rows = _convert_batch_with_obabel(
        runner,
        batch_rows,
        batch_path,
        batch_name,
        single_fallback_workers,
    )
    return str(sdf_path), invalid_rows


def _prepare_ligands_from_existing_smi(
    out: Path,
    runner: CommandRunner,
    batch_size: int,
    jobs: int | str,
    cpu_fraction: float,
    force_rebuild: bool = False,
    metadata_rows: list[dict[str, object]] | None = None,
) -> dict[str, object]:
    lig_root = out / "ligands"
    smi_path = require_file(lig_root / "all_ligands.smi", "all_ligands.smi for ligand preparation")
    rows = _read_all_smiles(smi_path)
    if not rows:
        raise RDockPipelineError(f"No usable SMILES rows found in {smi_path}")
    expected_total = len(rows)
    final_sdf = lig_root / "all_ligands.sdf"
    existing_final = _count_sdf_records_lenient(final_sdf)
    if existing_final > expected_total:
        raise RDockPipelineError(
            f"Existing {final_sdf} contains {existing_final} records but {smi_path} contains only {expected_total} ligands. "
            "Refuse to resume from an inconsistent dataset."
        )
    if not force_rebuild and existing_final == expected_total:
        metadata_path = lig_root / "ligand_metadata.csv"
        if not metadata_path.exists():
            _write_csv(metadata_path, [{"ligand_id": ligand_id, "smiles": smiles, "source": "smiles_file"} for smiles, ligand_id in rows])
        invalid_path = lig_root / "invalid_ligands.csv"
        if not invalid_path.exists():
            _write_csv(invalid_path, [])
        return {
            "mode": "prepare_ligands_only",
            "status": "already_complete",
            "expected_ligands": expected_total,
            "prepared_ligands": existing_final,
            "batch_size": batch_size,
            "jobs": _default_ligand_jobs() if str(jobs).strip().lower() == "auto" else resolve_jobs(jobs, cpu_fraction),
            "final_sdf": str(final_sdf),
        }

    batch_root = lig_root / "obabel_batches"
    batch_root.mkdir(parents=True, exist_ok=True)
    progress_path = lig_root / "ligand_preparation_progress.json"
    resume_prefix_count = 0
    recovered_prefix_sdf: Path | None = None
    if not force_rebuild and existing_final > 0:
        existing_batch_files = list(batch_root.glob("batch_*/*.sdf"))
        if not existing_batch_files:
            resume_prefix_count = existing_final
            recovered_prefix_sdf = batch_root / "recovered_prefix.sdf"
            shutil.copy2(final_sdf, recovered_prefix_sdf)
    batches: list[tuple[str, list[tuple[str, str]]]] = []
    for batch_index, start in enumerate(range(0, expected_total, batch_size), start=1):
        batches.append((f"batch_{batch_index:05d}", rows[start : start + batch_size]))

    resolved_jobs = _default_ligand_jobs() if str(jobs).strip().lower() == "auto" else resolve_jobs(jobs, cpu_fraction)
    invalid_rows: list[dict[str, object]] = []
    completed_batch_outputs: dict[str, Path] = {}
    if recovered_prefix_sdf is not None:
        completed_batch_outputs["__recovered_prefix__"] = recovered_prefix_sdf
    pending_batches: list[tuple[str, list[tuple[str, str]]]] = []
    ligands_skipped_by_prefix = 0
    for batch_number, (batch_name, batch_rows) in enumerate(batches, start=1):
        batch_start = (batch_number - 1) * batch_size
        batch_end = batch_start + len(batch_rows)
        if resume_prefix_count and batch_end <= resume_prefix_count:
            ligands_skipped_by_prefix += len(batch_rows)
            continue
        if resume_prefix_count and batch_start < resume_prefix_count < batch_end:
            prefix_skip = resume_prefix_count - batch_start
            ligands_skipped_by_prefix += prefix_skip
            batch_rows = batch_rows[prefix_skip:]
            if not batch_rows:
                continue
        batch_dir = batch_root / batch_name
        batch_sdf = batch_dir / f"{batch_name}.sdf"
        if (not force_rebuild) and _count_sdf_records_lenient(batch_sdf) == len(batch_rows):
            completed_batch_outputs[batch_name] = batch_sdf
            continue
        pending_batches.append((batch_name, batch_rows))

    progress_path.write_text(
        json.dumps(
            {
                "expected_ligands": expected_total,
                "prepared_batches": len(completed_batch_outputs),
                "total_batches": len(batches),
                "pending_batches": [name for name, _ in pending_batches[:1000]],
                "resumed_from_existing_final_sdf_records": resume_prefix_count,
                "ligands_skipped_by_prefix_resume": ligands_skipped_by_prefix,
                "jobs": resolved_jobs,
                "batch_size": batch_size,
            },
            indent=2,
        ),
        encoding="utf-8",
    )

    if pending_batches:
        progress = tqdm(total=len(pending_batches), desc="Ligand 3D batches", unit="batch") if tqdm is not None else None
        ligand_progress = tqdm(total=expected_total, desc="Ligands prepared", unit="lig") if tqdm is not None else None
        if ligand_progress is not None:
            ligand_progress.update(sum(_count_sdf_records_lenient(path) for path in completed_batch_outputs.values()))
        max_workers = min(resolved_jobs, len(pending_batches))
        executor_cls = ProcessPoolExecutor
        pool = None
        try:
            pool = executor_cls(max_workers=max_workers)
        except Exception:
            executor_cls = ThreadPoolExecutor
            pool = executor_cls(max_workers=max_workers)
        with pool:
            futures = {
                pool.submit(
                    _convert_batch_with_obabel_worker,
                    batch_rows,
                    str(batch_root / batch_name),
                    batch_name,
                    max(1, min(4, resolved_jobs)),
                ): batch_name
                for batch_name, batch_rows in pending_batches
            }
            for future in as_completed(futures):
                batch_name = futures[future]
                batch_sdf, batch_invalid = future.result()
                completed_batch_outputs[batch_name] = Path(batch_sdf)
                invalid_rows.extend(batch_invalid)
                batch_prepared = _count_sdf_records_lenient(Path(batch_sdf))
                if progress is not None:
                    progress.update(1)
                    progress.set_postfix(last_batch=batch_name, invalid=len(invalid_rows), worker=executor_cls.__name__)
                if ligand_progress is not None:
                    ligand_progress.update(batch_prepared)
                    ligand_progress.set_postfix(last_batch=batch_name, invalid=len(invalid_rows), worker=executor_cls.__name__)
                prepared_count = sum(_count_sdf_records_lenient(path) for path in completed_batch_outputs.values())
                progress_path.write_text(
                    json.dumps(
                        {
                            "expected_ligands": expected_total,
                            "prepared_batches": len(completed_batch_outputs),
                            "total_batches": len(batches),
                            "prepared_ligands_estimate": prepared_count,
                            "resumed_from_existing_final_sdf_records": resume_prefix_count,
                            "ligands_skipped_by_prefix_resume": ligands_skipped_by_prefix,
                            "jobs": resolved_jobs,
                            "batch_size": batch_size,
                            "worker_backend": executor_cls.__name__,
                            "last_completed_batch": batch_name,
                            "invalid_count": len(invalid_rows),
                        },
                        indent=2,
                    ),
                    encoding="utf-8",
                )
        if progress is not None:
            progress.close()
        if ligand_progress is not None:
            ligand_progress.close()

    ordered_outputs: list[Path] = []
    if "__recovered_prefix__" in completed_batch_outputs:
        ordered_outputs.append(completed_batch_outputs["__recovered_prefix__"])
    ordered_outputs.extend(completed_batch_outputs[batch_name] for batch_name, _ in batches if batch_name in completed_batch_outputs)
    _merge_sdf_files(ordered_outputs, final_sdf)
    prepared_count = _count_sdf_records_lenient(final_sdf)
    metadata_payload = metadata_rows or _existing_ligand_metadata_payload(lig_root, expected_total)
    if metadata_payload is None:
        metadata_payload = [{"ligand_id": ligand_id, "smiles": smiles, "source": "smiles_file"} for smiles, ligand_id in rows]
    _write_csv(lig_root / "ligand_metadata.csv", metadata_payload)
    _write_csv(lig_root / "invalid_ligands.csv", invalid_rows)
    progress_path.write_text(
        json.dumps(
            {
                "expected_ligands": expected_total,
                "prepared_ligands": prepared_count,
                "invalid_ligands": len(invalid_rows),
                "prepared_batches": len(ordered_outputs),
                "total_batches": len(batches),
                "resumed_from_existing_final_sdf_records": resume_prefix_count,
                "ligands_skipped_by_prefix_resume": ligands_skipped_by_prefix,
                "jobs": resolved_jobs,
                "batch_size": batch_size,
                "final_sdf": str(final_sdf),
                "status": "complete" if prepared_count > 0 else "empty",
            },
            indent=2,
        ),
        encoding="utf-8",
    )
    return {
        "mode": "prepare_ligands_only",
        "status": "complete" if prepared_count > 0 else "empty",
        "expected_ligands": expected_total,
        "prepared_ligands": prepared_count,
        "invalid_ligands": len(invalid_rows),
        "batch_size": batch_size,
        "jobs": resolved_jobs,
        "resumed_from_existing_final_sdf_records": resume_prefix_count,
        "ligands_skipped_by_prefix_resume": ligands_skipped_by_prefix,
        "final_sdf": str(final_sdf),
        "progress_json": str(progress_path),
    }


def _reference_ligand_to_smiles(runner: CommandRunner, reference_sdf: Path, cwd: Path) -> str:
    obabel = require_executable("obabel")
    stdout_log = cwd / "logs" / "reference_ligand_to_smiles.stdout.log"
    stderr_log = cwd / "logs" / "reference_ligand_to_smiles.stderr.log"
    rec = runner.run(
        "reference_ligand_to_smiles",
        [obabel, str(reference_sdf.resolve()), "-osmi"],
        cwd,
        stdout_log,
        stderr_log,
    )
    fail_if_bad_command(rec, "OpenBabel reference ligand to SMILES")
    text = stdout_log.read_text(encoding="utf-8", errors="ignore").strip()
    if not text:
        raise RDockPipelineError(f"OpenBabel did not produce SMILES for reference ligand {reference_sdf}")
    first = text.splitlines()[0].strip()
    parts = first.split()
    if not parts:
        raise RDockPipelineError(f"Could not parse OpenBabel SMILES output for {reference_sdf}: {first!r}")
    return parts[0]


def _reference_ligand_sdf_block(reference_sdf: Path) -> str:
    text = reference_sdf.read_text(encoding="utf-8", errors="ignore")
    first = text.split("$$$$", 1)[0].strip()
    if not first:
        raise RDockPipelineError(f"Reference ligand SDF is empty or unreadable: {reference_sdf}")
    return first + "\n$$$$\n"


def _canonicalize_smiles_for_filter(smiles: str) -> str:
    return smiles.strip()


def _looks_organic_smiles(smiles: str) -> bool:
    text = _canonicalize_smiles_for_filter(smiles)
    if not text or "." in text:
        return False
    return "C" in text or "c" in text


def _parse_threshold_ladder(text: str) -> list[int]:
    try:
        values = [int(part.strip()) for part in text.split(",") if part.strip()]
    except Exception as exc:
        raise RDockPipelineError(f"Invalid --pubchem-threshold-ladder value {text!r}: {exc}") from exc
    if not values:
        raise RDockPipelineError("Empty --pubchem-threshold-ladder")
    return values


def _resolve_threshold_ladder(args: argparse.Namespace) -> list[int]:
    ladder_override = str(getattr(args, "similarity_thresholds", "") or "").strip()
    if ladder_override:
        return _parse_threshold_ladder(ladder_override)
    start = getattr(args, "pubchem_threshold_start", None)
    stop = getattr(args, "pubchem_threshold_stop", None)
    step = int(getattr(args, "pubchem_threshold_step", 1) or 1)
    if start is not None or stop is not None:
        start_value = int(99 if start is None else start)
        stop_value = int(70 if stop is None else stop)
        if step <= 0:
            raise RDockPipelineError("--pubchem-threshold-step must be a positive integer")
        if start_value < stop_value:
            raise RDockPipelineError(
                f"Invalid PubChem threshold range: start {start_value} is lower than stop {stop_value}. "
                "Use a descending range such as --pubchem-threshold-start 99 --pubchem-threshold-stop 80."
            )
        return list(range(start_value, stop_value - 1, -step))
    return _parse_threshold_ladder(args.pubchem_threshold_ladder)


def _pubchem_similarity_cids_from_sdf(reference_sdf_block: str, threshold: int, max_records: int, timeout: int) -> list[int]:
    url = (
        "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/"
        f"sdf/cids/JSON?Threshold={int(threshold)}&MaxRecords={int(max_records)}&MaxSeconds={int(timeout)}"
    )
    payload = _http_post_form_json(url, {"sdf": reference_sdf_block}, timeout)
    info = payload.get("IdentifierList", {}) if isinstance(payload, dict) else {}
    cids = info.get("CID", []) if isinstance(info, dict) else []
    return [int(cid) for cid in cids]


def _pubchem_identity_cids_from_sdf(reference_sdf_block: str, timeout: int) -> list[int]:
    url = (
        "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastidentity/"
        f"sdf/cids/JSON?identity_type=same_connectivity&MaxRecords=10&MaxSeconds={int(timeout)}"
    )
    payload = _http_post_form_json(url, {"sdf": reference_sdf_block}, timeout)
    info = payload.get("IdentifierList", {}) if isinstance(payload, dict) else {}
    cids = info.get("CID", []) if isinstance(info, dict) else []
    return [int(cid) for cid in cids]


def _pubchem_identity_cids_from_smiles(reference_smiles: str, timeout: int) -> list[int]:
    encoded = urllib.parse.quote(reference_smiles, safe="")
    identity_url = (
        "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastidentity/"
        f"smiles/{encoded}/cids/JSON?identity_type=same_connectivity&MaxRecords=10&MaxSeconds={int(timeout)}"
    )
    identity_payload = _http_json(identity_url, timeout)
    identity_info = identity_payload.get("IdentifierList", {}) if isinstance(identity_payload, dict) else {}
    identity_cids = identity_info.get("CID", []) if isinstance(identity_info, dict) else []
    return [int(cid) for cid in identity_cids]


def _pubchem_reference_cid(
    reference_smiles: str,
    timeout: int,
    reference_sdf_block: str | None = None,
) -> int | None:
    try:
        identity_cids = _pubchem_identity_cids_from_smiles(reference_smiles, timeout)
        if identity_cids:
            return int(identity_cids[0])
    except Exception:  # pragma: no cover - network-dependent
        pass
    if reference_sdf_block:
        try:
            identity_cids = _pubchem_identity_cids_from_sdf(reference_sdf_block, timeout)
            if identity_cids:
                return int(identity_cids[0])
        except Exception:  # pragma: no cover - network-dependent
            pass
    return None


def _pubchem_similarity_cids_from_cid(reference_cid: int, threshold: int, max_records: int, timeout: int) -> list[int]:
    cid_url = (
        "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/"
        f"cid/{int(reference_cid)}/cids/JSON?Threshold={int(threshold)}&MaxRecords={int(max_records)}&MaxSeconds={int(timeout)}"
    )
    cid_payload = _http_json(cid_url, timeout)
    cid_info = cid_payload.get("IdentifierList", {}) if isinstance(cid_payload, dict) else {}
    cid_hits = cid_info.get("CID", []) if isinstance(cid_info, dict) else []
    return [int(cid) for cid in cid_hits]


def _pubchem_similarity_cids(
    reference_smiles: str,
    threshold: int,
    max_records: int,
    timeout: int,
    reference_sdf_block: str | None = None,
    reference_cid: int | None = None,
) -> list[int]:
    errors: list[str] = []
    if reference_cid is not None:
        try:
            parsed = _pubchem_similarity_cids_from_cid(reference_cid, threshold, max_records, timeout)
            if parsed:
                return parsed
        except Exception as exc:  # pragma: no cover - network-dependent
            errors.append(f"cid_fastsim:{exc}")
    if reference_sdf_block:
        try:
            parsed = _pubchem_similarity_cids_from_sdf(reference_sdf_block, threshold, max_records, timeout)
            if parsed:
                return parsed
        except Exception as exc:  # pragma: no cover - network-dependent
            errors.append(f"sdf_fastsim:{exc}")
        try:
            identity_cids = _pubchem_identity_cids_from_sdf(reference_sdf_block, timeout)
        except Exception as exc:  # pragma: no cover - network-dependent
            identity_cids = []
            errors.append(f"sdf_identity:{exc}")
        if identity_cids:
            ref_cid = int(identity_cids[0])
            cid_url = (
                "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/"
                f"cid/{ref_cid}/cids/JSON?Threshold={int(threshold)}&MaxRecords={int(max_records)}&MaxSeconds={int(timeout)}"
            )
            try:
                cid_payload = _http_json(cid_url, timeout)
                cid_info = cid_payload.get("IdentifierList", {}) if isinstance(cid_payload, dict) else {}
                cid_hits = cid_info.get("CID", []) if isinstance(cid_info, dict) else []
                parsed = [int(cid) for cid in cid_hits]
                if parsed:
                    return parsed
            except Exception as exc:  # pragma: no cover - network-dependent
                errors.append(f"cid_fastsim_from_sdf:{exc}")
    encoded = urllib.parse.quote(reference_smiles, safe="")
    url = (
        "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/"
        f"smiles/{encoded}/cids/JSON?Threshold={int(threshold)}&MaxRecords={int(max_records)}&MaxSeconds={int(timeout)}"
    )
    try:
        payload = _http_json(url, timeout)
        info = payload.get("IdentifierList", {}) if isinstance(payload, dict) else {}
        cids = info.get("CID", []) if isinstance(info, dict) else []
        parsed = [int(cid) for cid in cids]
        if parsed:
            return parsed
    except Exception as exc:  # pragma: no cover - network-dependent
        errors.append(f"smiles_fastsim:{exc}")
    identity_url = (
        "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastidentity/"
        f"smiles/{encoded}/cids/JSON?identity_type=same_connectivity&MaxRecords=10&MaxSeconds={int(timeout)}"
    )
    try:
        identity_payload = _http_json(identity_url, timeout)
        identity_info = identity_payload.get("IdentifierList", {}) if isinstance(identity_payload, dict) else {}
        identity_cids = identity_info.get("CID", []) if isinstance(identity_info, dict) else []
    except Exception as exc:  # pragma: no cover - network-dependent
        identity_cids = []
        errors.append(f"smiles_identity:{exc}")
    if not identity_cids:
        return []
    try:
        return _pubchem_similarity_cids_from_cid(int(identity_cids[0]), threshold, max_records, timeout)
    except Exception:  # pragma: no cover - network-dependent
        return []


def _pubchem_name_search_cids(query: str, max_records: int, timeout: int) -> list[int]:
    encoded = urllib.parse.quote(query.strip(), safe="")
    url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/{encoded}/cids/JSON?MaxRecords={int(max_records)}"
    payload = _http_json(url, timeout)
    info = payload.get("IdentifierList", {}) if isinstance(payload, dict) else {}
    cids = info.get("CID", []) if isinstance(info, dict) else []
    return [int(cid) for cid in cids]


def _default_pubchem_workers() -> int:
    cpu_count = os.cpu_count() or 4
    return max(2, min(8, cpu_count // 2 or 1))


def _pubchem_fetch_properties_chunk(chunk: list[int], timeout: int) -> list[dict[str, object]]:
    cid_text = ",".join(str(cid) for cid in chunk)
    url = (
        "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/"
        f"{cid_text}/property/SMILES,ConnectivitySMILES,IUPACName,Title,MolecularFormula,MolecularWeight,"
        "XLogP,TPSA,HBondDonorCount,HBondAcceptorCount,RotatableBondCount,HeavyAtomCount/JSON"
    )
    payload = _http_json(url, timeout)
    table = payload.get("PropertyTable", {}) if isinstance(payload, dict) else {}
    props = table.get("Properties", []) if isinstance(table, dict) else []
    return [item for item in props if isinstance(item, dict)]


def _pubchem_fetch_properties_chunk_resilient(
    chunk: list[int],
    timeout: int,
    out: Path | None = None,
    progress_prefix: str = "",
    chunk_label: str = "",
) -> list[dict[str, object]]:
    if not chunk:
        return []
    try:
        return _pubchem_fetch_properties_chunk(chunk, timeout)
    except Exception as exc:  # pragma: no cover - network-dependent
        if len(chunk) <= 1:
            if out is not None:
                _progress_log(
                    out,
                    f"{progress_prefix} property fetch failed for single CID chunk {chunk_label}: {exc}",
                )
            return []
        mid = max(1, len(chunk) // 2)
        left = chunk[:mid]
        right = chunk[mid:]
        if out is not None:
            _progress_log(
                out,
                f"{progress_prefix} property chunk {chunk_label} failed ({exc}); splitting {len(chunk)} CIDs into {len(left)} + {len(right)}",
            )
        left_rows = _pubchem_fetch_properties_chunk_resilient(
            left,
            timeout,
            out=out,
            progress_prefix=progress_prefix,
            chunk_label=f"{chunk_label}.L",
        )
        right_rows = _pubchem_fetch_properties_chunk_resilient(
            right,
            timeout,
            out=out,
            progress_prefix=progress_prefix,
            chunk_label=f"{chunk_label}.R",
        )
        return left_rows + right_rows


def _pubchem_fetch_properties(
    cids: list[int],
    timeout: int,
    out: Path | None = None,
    progress_prefix: str = "",
    workers: int = 1,
    chunk_size: int = 200,
) -> list[dict[str, object]]:
    if not cids:
        return []
    chunk_size = max(1, int(chunk_size))
    workers = max(1, int(workers))
    chunks = [cids[start : start + chunk_size] for start in range(0, len(cids), chunk_size)]
    rows: list[dict[str, object]] = []
    if workers == 1 or len(chunks) == 1:
        for index, chunk in enumerate(chunks, start=1):
            if out is not None:
                _progress_log(
                    out,
                    f"{progress_prefix} fetching properties chunk {index}/{len(chunks)} ({len(chunk)} CIDs)",
                )
            rows.extend(
                _pubchem_fetch_properties_chunk_resilient(
                    chunk,
                    timeout,
                    out=out,
                    progress_prefix=progress_prefix,
                    chunk_label=f"{index}/{len(chunks)}",
                )
            )
        return rows

    with ThreadPoolExecutor(max_workers=min(workers, len(chunks))) as pool:
        futures = {
            pool.submit(_pubchem_fetch_properties_chunk, chunk, timeout): (index, chunk)
            for index, chunk in enumerate(chunks, start=1)
        }
        for future in as_completed(futures):
            index, chunk = futures[future]
            if out is not None:
                _progress_log(
                    out,
                    f"{progress_prefix} fetching properties chunk {index}/{len(chunks)} ({len(chunk)} CIDs)",
                )
            try:
                rows.extend(future.result())
            except Exception as exc:  # pragma: no cover - network-dependent
                if out is not None:
                    _progress_log(
                        out,
                        f"{progress_prefix} property chunk {index}/{len(chunks)} failed asynchronously ({exc}); retrying with recursive split",
                    )
                rows.extend(
                    _pubchem_fetch_properties_chunk_resilient(
                        chunk,
                        timeout,
                        out=out,
                        progress_prefix=progress_prefix,
                        chunk_label=f"{index}/{len(chunks)}",
                    )
                )
    return rows


def _resolve_pubchem_max_records(
    needed: int,
    record_multiplier: int,
    min_records_per_threshold: int,
    max_records_per_threshold: int,
) -> int:
    candidate = max(int(needed) * int(record_multiplier), int(min_records_per_threshold))
    return max(1, min(candidate, int(max_records_per_threshold)))


def _pubchem_similarity_rows(
    reference_smiles: str,
    reference_sdf_block: str,
    n_ligands: int,
    threshold_ladder: list[int],
    timeout: int,
    allow_partial: bool = False,
    out: Path | None = None,
    property_workers: int = 1,
    property_chunk_size: int = 200,
    record_multiplier: int = 8,
    min_records_per_threshold: int = 1000,
    max_records_per_threshold: int = 5000,
) -> tuple[list[tuple[str, str]], list[dict[str, object]], list[dict[str, object]], str | None]:
    collected_smiles: dict[str, tuple[str, str]] = {}
    metadata: list[dict[str, object]] = []
    diagnostics: list[dict[str, object]] = []
    reference_cid = _pubchem_reference_cid(reference_smiles, timeout, reference_sdf_block=reference_sdf_block)
    if out is not None:
        _progress_log(
            out,
            f"PubChem reference CID resolution: {'resolved to CID ' + str(reference_cid) if reference_cid is not None else 'not resolved; using direct similarity fallbacks'}",
            {
                "mode": "pubchem_similarity",
                "reference_cid": reference_cid,
                "reference_cid_resolved": reference_cid is not None,
            },
        )
    for threshold in threshold_ladder:
        needed = max(0, n_ligands - len(collected_smiles))
        if needed <= 0:
            break
        max_records = _resolve_pubchem_max_records(
            needed,
            record_multiplier=record_multiplier,
            min_records_per_threshold=min_records_per_threshold,
            max_records_per_threshold=max_records_per_threshold,
        )
        if out is not None:
            _progress_log(
                out,
                f"PubChem similarity threshold {threshold}: requesting up to {max_records} records; collected so far {len(collected_smiles)}/{n_ligands}",
                {
                    "mode": "pubchem_similarity",
                    "threshold": threshold,
                    "requested_ligands": n_ligands,
                    "collected_ligands": len(collected_smiles),
                    "needed_ligands": needed,
                    "max_records": max_records,
                },
            )
        similarity_kwargs: dict[str, object] = {
            "max_records": max_records,
            "timeout": timeout,
            "reference_sdf_block": reference_sdf_block,
        }
        if reference_cid is not None:
            similarity_kwargs["reference_cid"] = reference_cid
        try:
            cids = _pubchem_similarity_cids(
                reference_smiles,
                threshold,
                **similarity_kwargs,
            )
        except Exception as exc:  # pragma: no cover - network-dependent
            diagnostics.append(
                {
                    "threshold": threshold,
                    "returned_cids": 0,
                    "accepted_new_smiles": 0,
                    "collected_total": len(collected_smiles),
                    "error": str(exc),
                }
            )
            if out is not None:
                _progress_log(
                    out,
                    f"PubChem similarity threshold {threshold}: failed ({exc}); continuing to next threshold",
                )
            continue
        if out is not None:
            _progress_log(out, f"PubChem similarity threshold {threshold}: received {len(cids)} CIDs")
        try:
            props = _pubchem_fetch_properties(
                cids,
                timeout,
                out=out,
                progress_prefix=f"PubChem threshold {threshold}:",
                workers=property_workers,
                chunk_size=property_chunk_size,
            )
        except Exception as exc:  # pragma: no cover - network-dependent
            diagnostics.append(
                {
                    "threshold": threshold,
                    "returned_cids": len(cids),
                    "accepted_new_smiles": 0,
                    "collected_total": len(collected_smiles),
                    "error": f"property_fetch_failed: {exc}",
                }
            )
            if out is not None:
                _progress_log(
                    out,
                    f"PubChem similarity threshold {threshold}: property fetch failed ({exc}); continuing to next threshold",
                )
            continue
        accepted = 0
        for item in props:
            smiles = str(
                item.get("SMILES")
                or item.get("ConnectivitySMILES")
                or item.get("CanonicalSMILES", "")
            ).strip()
            cid = int(item.get("CID", 0) or 0)
            if not smiles or cid <= 0 or not _looks_organic_smiles(smiles):
                continue
            ligand_id = f"pubchem_cid_{cid}"
            if ligand_id in collected_smiles:
                continue
            collected_smiles[ligand_id] = (smiles, ligand_id)
            metadata.append(
                {
                    "ligand_id": ligand_id,
                    "smiles": smiles,
                    "source": "pubchem_similarity",
                    "pubchem_cid": cid,
                    "pubchem_threshold": threshold,
                    "pubchem_title": item.get("Title", ""),
                    "iupac_name": item.get("IUPACName", ""),
                    "molecular_formula": item.get("MolecularFormula", ""),
                    "molecular_weight": item.get("MolecularWeight", ""),
                    "xlogp": item.get("XLogP", ""),
                    "tpsa": item.get("TPSA", ""),
                    "hbd": item.get("HBondDonorCount", ""),
                    "hba": item.get("HBondAcceptorCount", ""),
                    "rotatable_bonds": item.get("RotatableBondCount", ""),
                    "heavy_atom_count": item.get("HeavyAtomCount", ""),
                }
            )
            accepted += 1
            if len(collected_smiles) >= n_ligands:
                break
        diagnostics.append(
            {
                "threshold": threshold,
                "returned_cids": len(cids),
                "accepted_new_smiles": accepted,
                "collected_total": len(collected_smiles),
            }
        )
        if out is not None:
            _write_partial_pubchem_hits(out, list(collected_smiles.values()), metadata)
            _progress_log(
                out,
                f"PubChem similarity threshold {threshold}: accepted {accepted} new ligands; total {len(collected_smiles)}/{n_ligands}",
                {
                    "mode": "pubchem_similarity",
                    "threshold": threshold,
                    "requested_ligands": n_ligands,
                    "collected_ligands": len(collected_smiles),
                    "accepted_new_smiles": accepted,
                    "returned_cids": len(cids),
                },
            )
            if len(collected_smiles) >= n_ligands:
                _progress_log(
                    out,
                    f"PubChem similarity target reached: collected {len(collected_smiles)}/{n_ligands} ligands",
                    {
                        "mode": "pubchem_similarity",
                        "threshold": threshold,
                        "requested_ligands": n_ligands,
                        "collected_ligands": len(collected_smiles),
                        "target_reached": True,
                    },
                )
    warning: str | None = None
    if len(collected_smiles) < n_ligands:
        warning = (
            f"PubChem similarity search collected {len(collected_smiles)} ligands after thresholds {threshold_ladder}. "
            f"Requested {n_ligands}."
        )
    if len(collected_smiles) < n_ligands and not allow_partial:
        raise RDockPipelineError(
            f"PubChem similarity search collected only {len(collected_smiles)} ligands for reference SMILES after thresholds "
            f"{threshold_ladder}. Requested {n_ligands}. Lower the threshold ladder, request fewer ligands, or provide --smiles-file."
        )
    rows = list(collected_smiles.values())[:n_ligands]
    if out is not None:
        _write_partial_pubchem_hits(out, rows, metadata[:n_ligands])
    return rows, metadata[:n_ligands], diagnostics, warning


def _pubchem_name_rows(
    queries: list[str],
    n_ligands: int,
    timeout: int,
) -> tuple[list[tuple[str, str]], list[dict[str, object]], list[dict[str, object]]]:
    collected_smiles: dict[str, tuple[str, str]] = {}
    metadata: list[dict[str, object]] = []
    diagnostics: list[dict[str, object]] = []
    for query in [item.strip() for item in queries if item.strip()]:
        needed = max(0, n_ligands - len(collected_smiles))
        if needed <= 0:
            break
        cids = _pubchem_name_search_cids(query, max_records=max(needed * 4, needed), timeout=timeout)
        props = _pubchem_fetch_properties(cids, timeout)
        accepted = 0
        for item in props:
            smiles = str(
                item.get("SMILES")
                or item.get("ConnectivitySMILES")
                or item.get("CanonicalSMILES", "")
            ).strip()
            cid = int(item.get("CID", 0) or 0)
            if not smiles or cid <= 0 or not _looks_organic_smiles(smiles):
                continue
            ligand_id = f"pubchem_cid_{cid}"
            if ligand_id in collected_smiles:
                continue
            collected_smiles[ligand_id] = (smiles, ligand_id)
            metadata.append(
                {
                    "ligand_id": ligand_id,
                    "smiles": smiles,
                    "source": "pubchem_compound_search",
                    "pubchem_cid": cid,
                    "pubchem_query": query,
                    "pubchem_title": item.get("Title", ""),
                    "iupac_name": item.get("IUPACName", ""),
                    "molecular_formula": item.get("MolecularFormula", ""),
                    "molecular_weight": item.get("MolecularWeight", ""),
                    "xlogp": item.get("XLogP", ""),
                    "tpsa": item.get("TPSA", ""),
                    "hbd": item.get("HBondDonorCount", ""),
                    "hba": item.get("HBondAcceptorCount", ""),
                    "rotatable_bonds": item.get("RotatableBondCount", ""),
                    "heavy_atom_count": item.get("HeavyAtomCount", ""),
                }
            )
            accepted += 1
            if len(collected_smiles) >= n_ligands:
                break
        diagnostics.append(
            {
                "query": query,
                "returned_cids": len(cids),
                "accepted_new_smiles": accepted,
                "collected_total": len(collected_smiles),
            }
        )
    return list(collected_smiles.values())[:n_ligands], metadata[:n_ligands], diagnostics


def _known_good_entry(pdb_id: str) -> dict[str, object] | None:
    for item in list_known_good_complexes(KNOWN_GOOD):
        if str(item.get("pdb_id", "")).upper() == pdb_id.upper():
            return item
    return None


def _pubchem_diagnostics_payload(
    source_name: str,
    reference_smiles: str,
    threshold_ladder: list[int],
    diagnostics: list[dict[str, object]],
    errors: list[str],
) -> dict[str, object]:
    return {
        "source": source_name,
        "reference_smiles": reference_smiles,
        "thresholds_tried": threshold_ladder,
        "requested_ligands": None,
        "collected_ligands": None,
        "endpoints_tried": [
            "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/sdf/cids/JSON (POST form field: sdf=...)",
            "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastidentity/sdf/cids/JSON (POST form field: sdf=...)",
            "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{smiles}/cids/JSON",
            "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/{query}/cids/JSON",
            "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{cids}/property/.../JSON",
        ],
        "diagnostics": diagnostics,
        "errors": errors,
    }


def _write_pubchem_diagnostics(out: Path, payload: dict[str, object]) -> Path:
    target = out / "logs" / "pubchem_diagnostics.json"
    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_text(json.dumps(payload, indent=2), encoding="utf-8")
    qc_target = out / "qc" / "similarity_collection_diagnostics.json"
    qc_target.parent.mkdir(parents=True, exist_ok=True)
    qc_target.write_text(json.dumps(payload, indent=2), encoding="utf-8")
    return target


def _resolve_smiles_source(args: argparse.Namespace) -> Path | None:
    if args.smiles_file:
        return Path(args.smiles_file)
    if args.ligand_source == "bundled_example":
        return DEFAULT_BUNDLED_EXAMPLE
    return None


def _write_csv(path: Path, rows: list[dict[str, object]]) -> Path:
    path.parent.mkdir(parents=True, exist_ok=True)
    fields: list[str] = []
    for row in rows:
        for key in row:
            if key not in fields:
                fields.append(key)
    with path.open("w", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=fields)
        writer.writeheader()
        writer.writerows(rows)
    return path


def _mol_from_smiles(smiles: str):
    if not RDKIT_AVAILABLE:
        return None
    try:
        return Chem.MolFromSmiles(str(smiles))
    except Exception:
        return None


def _canonical_smiles(smiles: str) -> str:
    mol = _mol_from_smiles(smiles)
    if mol is None:
        return str(smiles).strip()
    try:
        return str(Chem.MolToSmiles(mol, canonical=True))
    except Exception:
        return str(smiles).strip()


def _scaffold_smiles(mol) -> str:
    if not RDKIT_AVAILABLE or mol is None:
        return ""
    try:
        return str(MurckoScaffold.MurckoScaffoldSmiles(mol=mol) or "")
    except Exception:
        return ""


def _morgan_fp(mol):
    if not RDKIT_AVAILABLE or mol is None:
        return None
    try:
        generator = rdFingerprintGenerator.GetMorganGenerator(radius=2, fpSize=1024)
        return generator.GetFingerprint(mol)
    except Exception:
        try:
            return rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, 2, nBits=1024)
        except Exception:
            return None


def _existing_ligand_metadata_payload(lig_root: Path, expected_total: int) -> list[dict[str, object]] | None:
    metadata_path = lig_root / "ligand_metadata.csv"
    if not metadata_path.exists():
        return None
    try:
        with metadata_path.open(newline="", encoding="utf-8") as handle:
            rows = list(csv.DictReader(handle))
    except Exception:
        return None
    return rows if len(rows) == expected_total else None


def _annotate_near_duplicate_analogs(
    metadata_rows: list[dict[str, object]],
    *,
    tanimoto_threshold: float = 0.55,
    max_heavy_atom_delta: int = 3,
) -> tuple[list[dict[str, object]], dict[str, object]]:
    if not metadata_rows:
        return metadata_rows, {"analog_group_count": 0, "analog_grouped_ligands": 0, "analog_grouping_available": bool(RDKIT_AVAILABLE)}
    enriched: list[dict[str, object]] = []
    representatives_by_scaffold: dict[str, list[int]] = {}
    groups: dict[str, list[int]] = {}
    group_parent: dict[str, str] = {}
    for idx, row in enumerate(metadata_rows):
        item = dict(row)
        ligand_id = str(item.get("ligand_id", f"lig_{idx:05d}"))
        smiles = str(item.get("smiles", "")).strip()
        mol = _mol_from_smiles(smiles)
        canonical = _canonical_smiles(smiles)
        scaffold = _scaffold_smiles(mol) or canonical
        heavy = int(mol.GetNumHeavyAtoms()) if mol is not None else 0
        fp = _morgan_fp(mol)
        group_id = ""
        rule = "singleton"
        for rep_idx in representatives_by_scaffold.get(scaffold, []):
            rep = enriched[rep_idx]
            if canonical and canonical == str(rep.get("canonical_smiles", "")):
                group_id = str(rep["analog_group_id"])
                rule = "canonical_duplicate"
                break
            rep_heavy = int(rep.get("heavy_atom_count_for_grouping", 0) or 0)
            rep_fp = rep.get("_analog_fp")
            if fp is None or rep_fp is None:
                continue
            if abs(heavy - rep_heavy) > max_heavy_atom_delta:
                continue
            try:
                sim = float(DataStructs.TanimotoSimilarity(fp, rep_fp))
            except Exception:
                sim = 0.0
            if sim >= tanimoto_threshold:
                group_id = str(rep["analog_group_id"])
                rule = f"same_scaffold_tanimoto_{sim:.3f}"
                break
        if not group_id:
            group_id = f"analog_group_{len(groups) + 1:06d}"
            representatives_by_scaffold.setdefault(scaffold, []).append(idx)
            group_parent[group_id] = ligand_id
        item["canonical_smiles"] = canonical
        item["scaffold_core"] = scaffold
        item["heavy_atom_count_for_grouping"] = heavy
        item["analog_group_id"] = group_id
        item["analog_parent_id"] = group_parent.get(group_id, ligand_id)
        item["analog_group_rule"] = rule
        item["_analog_fp"] = fp
        groups.setdefault(group_id, []).append(idx)
        enriched.append(item)
    for group_id, indices in groups.items():
        size = len(indices)
        parent_id = str(enriched[indices[0]].get("analog_parent_id", enriched[indices[0]].get("ligand_id", "")))
        for variant_idx, row_idx in enumerate(indices, start=1):
            enriched[row_idx]["analog_group_size"] = size
            enriched[row_idx]["analog_variant_index"] = variant_idx
            enriched[row_idx]["analog_group_weight"] = 1.0 / max(1, size)
            enriched[row_idx]["analog_parent_id"] = parent_id
            enriched[row_idx].pop("_analog_fp", None)
    summary = {
        "analog_grouping_available": bool(RDKIT_AVAILABLE),
        "analog_group_count": len(groups),
        "analog_grouped_ligands": sum(len(indices) for indices in groups.values() if len(indices) > 1),
        "analog_largest_group_size": max((len(indices) for indices in groups.values()), default=0),
        "analog_tanimoto_threshold": float(tanimoto_threshold),
        "analog_max_heavy_atom_delta": int(max_heavy_atom_delta),
    }
    return enriched, summary


def _dataset_uniqueness_summary(metadata_rows: list[dict[str, object]]) -> dict[str, object]:
    seen_smiles: set[str] = set()
    total = 0
    for row in metadata_rows:
        smiles = str(row.get("smiles", "")).strip()
        if not smiles:
            continue
        total += 1
        seen_smiles.add(smiles)
    duplicate_count = max(0, total - len(seen_smiles))
    duplicate_fraction = (duplicate_count / total) if total else 0.0
    warnings: list[str] = []
    if duplicate_fraction > 0.01:
        warnings.append(
            f"duplicate parent fraction is {duplicate_fraction:.4f} (>1%); inspect ligand source and deduplication settings before scientific benchmarking"
        )
    return {
        "n_input_smiles": total,
        "n_unique_parent_ligands": len(seen_smiles),
        "duplicate_parent_count": duplicate_count,
        "duplicate_parent_fraction": duplicate_fraction,
        "warnings": warnings,
        "deduplication_method": "exact_smiles",
    }


def _infer_existing_dataset_manifest(out: Path, prepared_ligands: int, warnings: list[str] | None = None) -> dict[str, object]:
    warnings = list(warnings or [])
    raw_dir = out / "raw"
    pdb_candidates = sorted(list(raw_dir.glob("*.pdb")) + list(raw_dir.glob("*.cif")) + list(raw_dir.glob("*.mmcif")))
    pdb_id = pdb_candidates[0].stem[:4].upper() if pdb_candidates else ""
    resolved = resolve_known_good_defaults(KNOWN_GOOD, pdb_id or "UNKN", None, None, None)
    ligand_source = "smiles_file"
    reference_smiles = ""
    pubchem_payload: dict[str, object] = {}
    pubchem_path = out / "logs" / "pubchem_diagnostics.json"
    if pubchem_path.exists():
        try:
            pubchem_payload = json.loads(pubchem_path.read_text(encoding="utf-8"))
        except Exception:
            pubchem_payload = {}
        ligand_source = str(pubchem_payload.get("source") or "pubchem_similarity")
        reference_smiles = str(pubchem_payload.get("reference_smiles") or "")
    else:
        ref_smiles_log = out / "logs" / "reference_ligand_to_smiles.stdout.log"
        if ref_smiles_log.exists():
            first = ref_smiles_log.read_text(encoding="utf-8", errors="ignore").splitlines()
            if first:
                reference_smiles = first[0].split()[0].strip()
    manifest = {
        "pdb_id": resolved["pdb_id"] or pdb_id,
        "receptor_chain": resolved["receptor_chain"],
        "reference_ligand_resname": resolved["reference_ligand_resname"],
        "reference_ligand_chain": resolved["reference_ligand_chain"],
        "n_ligands_requested": len(_read_all_smiles(require_file(out / "ligands" / "all_ligands.smi", "all_ligands.smi"))),
        "ligands_prepared": int(prepared_ligands),
        "paths": {
            "target_mol2": str(out / "target" / "target.mol2"),
            "reference_ligand_sdf": str(out / "target" / "reference_ligand.sdf"),
            "all_ligands_sdf": str(out / "ligands" / "all_ligands.sdf"),
            "all_ligands_smi": str(out / "ligands" / "all_ligands.smi"),
            "rdock_prm_dir": str(out / "target" / "rdock_prm"),
            "target_config_yaml": str(out / "target" / "rdock_prm" / "target_config.yaml"),
        },
        "versions": {
            "obabel": probe_version(require_executable("obabel")) if shutil.which("obabel") else "",
            "rbdock": probe_version(require_executable("rbdock")) if shutil.which("rbdock") else "",
            "rbcavity": probe_version(require_executable("rbcavity")) if shutil.which("rbcavity") else "",
        },
        "ligand_source": ligand_source,
        "reference_ligand_smiles": reference_smiles,
        "pubchem_threshold_ladder": pubchem_payload.get("thresholds_tried", []) if pubchem_payload else [],
        "pubchem_diagnostics": pubchem_payload,
        "rbcavity_status": "success" if (out / "target" / "rdock_prm").exists() else "unknown",
        "warnings": warnings,
        "available_hetero_ligands": [],
        "auto_reference_ligand": False,
        "auto_reference_candidates": [],
        "auto_reference_selected": {},
    }
    return manifest


def _ensure_dataset_metadata_files(out: Path, prepared_ligands: int, warnings: list[str] | None = None) -> None:
    manifest_path = out / "dataset_manifest.json"
    if manifest_path.exists():
        manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
        manifest["ligands_prepared"] = int(prepared_ligands)
        manifest.setdefault("paths", {})
        manifest["paths"]["all_ligands_sdf"] = str(out / "ligands" / "all_ligands.sdf")
        manifest["paths"]["all_ligands_smi"] = str(out / "ligands" / "all_ligands.smi")
        if warnings:
            manifest["warnings"] = list(dict.fromkeys(list(manifest.get("warnings", [])) + list(warnings)))
        create_dataset_manifest(out, manifest)
    else:
        synth_warnings = ["dataset_manifest.json was missing and was reconstructed from existing dataset files"]
        if warnings:
            synth_warnings.extend(warnings)
        create_dataset_manifest(out, _infer_existing_dataset_manifest(out, prepared_ligands, warnings=synth_warnings))

    report_path = out / "qc" / "preparation_report.md"
    if not report_path.exists():
        report_lines = [
            f"# Dataset Preparation Report: {out.name}",
            "",
            "- report_status: `reconstructed`",
            f"- ligands_prepared: `{prepared_ligands}`",
            f"- target_mol2: `{out / 'target' / 'target.mol2'}`",
            f"- reference_ligand_sdf: `{out / 'target' / 'reference_ligand.sdf'}`",
            f"- all_ligands_sdf: `{out / 'ligands' / 'all_ligands.sdf'}`",
            f"- all_ligands_smi: `{out / 'ligands' / 'all_ligands.smi'}`",
        ]
        if warnings:
            report_lines.extend(["", "## Warnings", *[f"- {item}" for item in warnings]])
        report_path.parent.mkdir(parents=True, exist_ok=True)
        report_path.write_text("\n".join(report_lines) + "\n", encoding="utf-8")


def _list_known_good() -> int:
    complexes = list_known_good_complexes(KNOWN_GOOD)
    print(json.dumps(complexes, indent=2))
    return 0


def _list_hetero_for_pdb(args: argparse.Namespace) -> int:
    temp_root = Path(args.out) if args.out else ROOT / ".tmp_list_hetero"
    _mkdir_or_fail(temp_root)
    pdb_path = download_pdb_structure(str(args.pdb_id), temp_root / "raw", force=False)
    payload = {
        "pdb_id": str(args.pdb_id).upper(),
        "hetero_ligands": list_hetero_ligands(pdb_path, min_reference_ligand_atoms=args.min_reference_ligand_atoms),
    }
    print(json.dumps(payload, indent=2))
    return 0


def _validate_only(dataset_dir: Path) -> int:
    print(json.dumps(validate_dataset_dir(dataset_dir, check_rdock_tools=False), indent=2))
    return 0


def _plan(args: argparse.Namespace, resolved: dict[str, str], smiles_file: Path | None) -> dict[str, object]:
    if smiles_file is None:
        ligand_count = None
        smiles_repr = ""
    elif not smiles_file.exists():
        ligand_count = 0
        smiles_repr = str(smiles_file)
    else:
        ligand_count = len(_read_smiles(smiles_file, args.n_ligands))
        smiles_repr = str(smiles_file)
    missing_tools = [tool for tool in ("obabel", "rbcavity", "rbdock") if shutil.which(tool) is None]
    return {
        "pdb_id": resolved["pdb_id"],
        "receptor_chain": resolved["receptor_chain"],
        "reference_ligand_resname": resolved["reference_ligand_resname"],
        "reference_ligand_chain": resolved["reference_ligand_chain"],
        "n_ligands_requested": args.n_ligands,
        "ligand_source": args.ligand_source,
        "auto_reference_ligand": bool(args.auto_reference_ligand),
        "min_reference_ligand_atoms": int(args.min_reference_ligand_atoms),
        "smiles_file": smiles_repr,
        "detected_smiles_rows": ligand_count,
        "out": str(args.out),
        "missing_dependencies": missing_tools,
        "commands": [
            "download PDB structure if absent",
            "extract receptor chain and reference ligand from PDB",
            "convert reference ligand and receptor with OpenBabel",
            "resolve ligand source via smiles file or PubChem when --smiles-file is not provided",
            "prepare target with rbcavity",
            "convert SMILES to 3D SDF",
            "write dataset_manifest.json and qc/preparation_report.md",
        ],
    }


def _reference_selection_error(
    exc: RDockPipelineError,
    pdb_id: str,
    receptor_chain: str,
    out: Path,
) -> RDockPipelineError:
    known = _known_good_entry(pdb_id)
    lines = [str(exc)]
    if known:
        lines.append(
            "Known-good suggestion: "
            f"--receptor-chain {known.get('receptor_chain')} "
            f"--reference-ligand-resname {known.get('reference_ligand_resname')} "
            f"--reference-ligand-chain {known.get('reference_ligand_chain')}"
        )
    lines.append(
        "Recommended correction: "
        f"python scripts/prepare_pdb_ligand_dataset.py --pdb-id {pdb_id} --receptor-chain {receptor_chain} "
        f"--auto-reference-ligand --n-ligands 1000 --ligand-source smiles_file "
        f"--smiles-file data/examples/example_smiles_1000.smi --out {out} --force"
    )
    lines.append(
        "You can inspect candidate hetero ligands with: "
        f"python scripts/prepare_pdb_ligand_dataset.py --list-hetero --pdb-id {pdb_id}"
    )
    return RDockPipelineError("\n".join(lines))


def _select_reference_ligand(args: argparse.Namespace, resolved: dict[str, str], pdb_path: Path) -> tuple[dict[str, str], list[dict[str, object]], dict[str, object] | None]:
    if args.auto_reference_ligand or not resolved["reference_ligand_resname"]:
        selected, candidates = auto_detect_reference_ligand(
            pdb_path,
            resolved["receptor_chain"],
            min_reference_ligand_atoms=args.min_reference_ligand_atoms,
        )
        resolved = dict(resolved)
        resolved["reference_ligand_resname"] = str(selected["resname"])
        resolved["reference_ligand_chain"] = str(selected["chain"])
        return resolved, candidates, selected
    return resolved, [], None


def _resolve_ligand_rows(
    args: argparse.Namespace,
    resolved: dict[str, str],
    runner: CommandRunner,
    reference_sdf: Path,
    out: Path,
) -> tuple[list[tuple[str, str]], list[dict[str, object]], str, dict[str, object] | None, str, list[str]]:
    smiles_file = _resolve_smiles_source(args)
    source = args.ligand_source
    if args.smiles_file:
        source = "smiles_file"
    if source == "smiles_file" and smiles_file is None:
        raise RDockPipelineError("`--ligand-source smiles_file` requires --smiles-file /path/to/library.smi.")
    if source in {"pubchem_random_compounds", "zinc_file"}:
        raise RDockPipelineError(
            f"Ligand source `{source}` is not enabled in this portable bundle. "
            "Use --ligand-source smiles_file --smiles-file /path/to/real_library.smi."
        )
    if source == "bundled_example":
        if args.n_ligands > 50:
            raise RDockPipelineError(
                f"`bundled_example` contains only 50 ligands. Requested {args.n_ligands}. "
                f"Use --ligand-source smiles_file --smiles-file data/examples/example_smiles_1000.smi or a larger real library."
            )
    if args.n_ligands > 5000 and source not in {"smiles_file", "pubchem_similarity"}:
        raise RDockPipelineError(
            f"Requested {args.n_ligands} ligands with source `{source}`. For libraries larger than 5000 ligands, "
            "provide a real large library via --ligand-source smiles_file --smiles-file /path/to/library.smi."
        )
    if smiles_file is not None:
        rows = _read_smiles(smiles_file, args.n_ligands)
        if len(rows) < args.n_ligands:
            raise RDockPipelineError(
                f"Requested {args.n_ligands} ligands but {smiles_file} contains only {len(rows)} usable rows. "
                f"Provide a larger --smiles-file. Example: --smiles-file /data/libraries/real_50k_library.smi"
            )
        metadata_rows = [{"ligand_id": ligand_id, "smiles": smiles, "source": "smiles_file"} for smiles, ligand_id in rows]
        return rows, metadata_rows, "", None, source, []

    reference_smiles = _reference_ligand_to_smiles(runner, reference_sdf, out)
    reference_sdf_block = _reference_ligand_sdf_block(reference_sdf)
    threshold_ladder = _resolve_threshold_ladder(args)
    diagnostics_errors: list[str] = []
    combined_diagnostics: list[dict[str, object]] = []
    warnings: list[str] = []

    if source in {"auto", "pubchem_similarity"}:
        try:
            rows, metadata_rows, diagnostics, warning = _pubchem_similarity_rows(
                reference_smiles,
                reference_sdf_block,
                args.n_ligands,
                threshold_ladder,
                timeout=args.pubchem_timeout,
                allow_partial=bool(getattr(args, "allow_partial_ligand_set", False)),
                out=out,
                property_workers=int(getattr(args, "pubchem_property_workers", _default_pubchem_workers())),
                property_chunk_size=int(getattr(args, "pubchem_property_chunk_size", 200)),
                record_multiplier=int(getattr(args, "pubchem_record_multiplier", 8)),
                min_records_per_threshold=int(getattr(args, "pubchem_min_records_per_threshold", 1000)),
                max_records_per_threshold=int(getattr(args, "pubchem_max_records_per_threshold", 5000)),
            )
            combined_diagnostics.extend(diagnostics)
            payload = _pubchem_diagnostics_payload("pubchem_similarity", reference_smiles, threshold_ladder, combined_diagnostics, diagnostics_errors)
            payload["requested_ligands"] = args.n_ligands
            payload["collected_ligands"] = len(rows)
            if warning:
                warnings.append(warning)
            return rows, metadata_rows, reference_smiles, payload, "pubchem_similarity", warnings
        except RDockPipelineError as exc:
            diagnostics_errors.append(str(exc))

    if source in {"auto", "pubchem_compound_search"}:
        queries = [
            resolved["reference_ligand_resname"],
            f"{resolved['pdb_id']} {resolved['reference_ligand_resname']}",
            str((_known_good_entry(resolved["pdb_id"]) or {}).get("target_name", "")),
        ]
        rows, metadata_rows, diagnostics = _pubchem_name_rows(queries, args.n_ligands, timeout=args.pubchem_timeout)
        combined_diagnostics.extend(diagnostics)
        if len(rows) >= args.n_ligands:
            payload = _pubchem_diagnostics_payload("pubchem_compound_search", reference_smiles, threshold_ladder, combined_diagnostics, diagnostics_errors)
            payload["requested_ligands"] = args.n_ligands
            payload["collected_ligands"] = len(rows)
            return rows, metadata_rows, reference_smiles, payload, "pubchem_compound_search", warnings
        diagnostics_errors.append(
            f"PubChem compound search collected only {len(rows)} ligands for queries {queries}. Requested {args.n_ligands}."
        )
        if rows and bool(getattr(args, "allow_partial_ligand_set", False)):
            payload = _pubchem_diagnostics_payload("pubchem_compound_search", reference_smiles, threshold_ladder, combined_diagnostics, diagnostics_errors)
            payload["requested_ligands"] = args.n_ligands
            payload["collected_ligands"] = len(rows)
            warnings.append(
                f"PubChem compound search collected {len(rows)} ligands for queries {queries}. Requested {args.n_ligands}."
            )
            return rows, metadata_rows, reference_smiles, payload, "pubchem_compound_search", warnings

    payload = _pubchem_diagnostics_payload(source, reference_smiles, threshold_ladder, combined_diagnostics, diagnostics_errors)
    payload["requested_ligands"] = args.n_ligands
    payload["collected_ligands"] = 0
    _write_pubchem_diagnostics(out, payload)
    raise RDockPipelineError(
        f"Could not collect {args.n_ligands} ligands from source `{source}` for {resolved['pdb_id']}. "
        f"Diagnostics were written to {out / 'logs' / 'pubchem_diagnostics.json'}. "
        "Use --ligand-source smiles_file --smiles-file /path/to/real_library.smi for a stable large-library workflow."
    )


def run(args: argparse.Namespace) -> int:
    if args.list_known_good:
        return _list_known_good()
    if args.list_hetero:
        return _list_hetero_for_pdb(args)
    if args.validate_only:
        return _validate_only(Path(args.out))
    if args.prepare_ligands_only:
        out = Path(args.out)
        _mkdir_or_fail(out)
        for name in ("ligands", "logs", "qc"):
            _mkdir_or_fail(out / name)
        runner = CommandRunner(out / "logs" / "commands.log")
        result = _prepare_ligands_from_existing_smi(
            out,
            runner,
            batch_size=int(args.ligand_batch_size),
            jobs=args.ligand_jobs,
            cpu_fraction=float(args.ligand_cpu_fraction),
            force_rebuild=bool(args.force),
        )
        metadata_warnings: list[str] = []
        if not (out / "dataset_manifest.json").exists():
            metadata_warnings.append("dataset_manifest.json was missing before ligand resume")
        if not (out / "qc" / "preparation_report.md").exists():
            metadata_warnings.append("qc/preparation_report.md was missing before ligand resume")
        _ensure_dataset_metadata_files(out, int(result["prepared_ligands"]), warnings=metadata_warnings)
        print(json.dumps(result, indent=2))
        return 0

    resolved = resolve_known_good_defaults(
        KNOWN_GOOD,
        args.pdb_id,
        args.receptor_chain,
        args.reference_ligand_resname,
        args.reference_ligand_chain,
    )
    if not resolved["receptor_chain"] or (not resolved["reference_ligand_resname"] and not args.auto_reference_ligand):
        raise RDockPipelineError(
            "Missing receptor chain or reference ligand resname. Provide them explicitly, use --auto-reference-ligand, or use a known-good PDB entry."
        )
    smiles_file = _resolve_smiles_source(args)
    plan = _plan(args, resolved, smiles_file)
    plan["ligand_source"] = args.ligand_source
    plan["pubchem_threshold_ladder"] = _resolve_threshold_ladder(args)
    plan["uses_pubchem_similarity"] = smiles_file is None
    out = Path(args.out)
    _mkdir_or_fail(out)
    if args.dry_run:
        (out / "dataset_plan.json").write_text(json.dumps(plan, indent=2), encoding="utf-8")
        print(json.dumps(plan, indent=2))
        return 0

    if out.exists() and args.force:
        shutil.rmtree(out)
        _mkdir_or_fail(out)
    for name in ("raw", "target", "ligands", "logs", "qc"):
        _mkdir_or_fail(out / name)
    runner = CommandRunner(out / "logs" / "commands.log")
    pdb_path = download_pdb_structure(resolved["pdb_id"], out / "raw", force=args.force)
    resolved, auto_candidates, auto_selected = _select_reference_ligand(args, resolved, pdb_path)
    (out / "raw" / "download_metadata.json").write_text(
        json.dumps({"pdb_id": resolved["pdb_id"], "source": str(pdb_path), "status": "downloaded_or_reused"}, indent=2),
        encoding="utf-8",
    )
    try:
        receptor_pdb, ligand_pdb, hetero = extract_receptor_and_reference_ligand(
            pdb_path,
            resolved["receptor_chain"],
            resolved["reference_ligand_resname"],
            resolved["reference_ligand_chain"],
            out / "target",
            min_reference_ligand_atoms=args.min_reference_ligand_atoms,
        )
    except RDockPipelineError as exc:
        raise _reference_selection_error(exc, resolved["pdb_id"], resolved["receptor_chain"], out) from exc
    reference_raw_sdf = out / "target" / "reference_ligand_raw.sdf"
    reference_sdf = out / "target" / "reference_ligand.sdf"
    _obabel_convert(runner, "reference_ligand_raw_to_sdf", ligand_pdb, reference_raw_sdf, [], out)
    shutil.copy2(reference_raw_sdf, reference_sdf)
    rows, metadata_rows, reference_smiles, pubchem_payload, ligand_source_used, ligand_warnings = _resolve_ligand_rows(args, resolved, runner, reference_sdf, out)
    if pubchem_payload is not None:
        _write_pubchem_diagnostics(out, pubchem_payload)
    if ligand_warnings:
        for warning in ligand_warnings:
            print(f"WARNING: {warning}", file=sys.stderr)
    if not rows:
        diagnostics_path = out / "logs" / "pubchem_diagnostics.json"
        raise RDockPipelineError(
            f"PubChem returned zero usable ligands for {resolved['pdb_id']} with source `{ligand_source_used}` and thresholds "
            f"{_resolve_threshold_ladder(args)}. No docking dataset can be created from zero ligands. "
            f"See diagnostics: {diagnostics_path}. "
            "Lower --identity-threshold-stop, try a different reference complex, or provide --smiles-file with a real library."
        )
    metadata_rows, analog_summary = _annotate_near_duplicate_analogs(metadata_rows)
    metadata_by_id = {str(row.get("ligand_id", "")): row for row in metadata_rows}
    rows = [(smiles, ligand_id) for smiles, ligand_id in rows if str(ligand_id) in metadata_by_id]

    target_prm_dir = out / "target" / "rdock_prm"
    prep = prepare_dataset_target_with_rdock(receptor_pdb, reference_sdf, target_prm_dir, jobs="auto", cpu_fraction=0.85)
    target_mol2 = require_file(target_prm_dir / "receptor.mol2", "prepared receptor mol2")
    shutil.copy2(target_mol2, out / "target" / "target.mol2")

    smi_path = _write_smi(rows, out / "ligands" / "all_ligands.smi")
    _write_csv(out / "ligands" / "ligand_metadata.csv", metadata_rows)
    _write_csv(out / "ligands" / "invalid_ligands.csv", [])
    if args.stop_after_ligand_collection:
        collection_summary = {
            "status": "ligand_collection_complete",
            "pdb_id": resolved["pdb_id"],
            "ligands_requested": args.n_ligands,
            "ligands_collected": len(rows),
            "reference_ligand_smiles": reference_smiles,
            "ligand_source": ligand_source_used,
            "all_ligands_smi": str(smi_path),
            "ligand_metadata_csv": str(out / "ligands" / "ligand_metadata.csv"),
            "analog_grouping": analog_summary,
            "pubchem_diagnostics_json": str(out / "logs" / "pubchem_diagnostics.json"),
            "next_stage": "openbabel_ligand_preparation",
        }
        (out / "qc" / "collection_summary.json").write_text(json.dumps(collection_summary, indent=2), encoding="utf-8")
        print(
            f"Collected {len(rows)}/{args.n_ligands} ligands and wrote {smi_path}. "
            "Stopping before OpenBabel ligand preparation as requested.",
            file=sys.stderr,
        )
        print(json.dumps(collection_summary, indent=2))
        return 0
    ligand_prep = _prepare_ligands_from_existing_smi(
        out,
        runner,
        batch_size=int(args.ligand_batch_size),
        jobs=args.ligand_jobs,
        cpu_fraction=float(args.ligand_cpu_fraction),
        force_rebuild=bool(args.force),
        metadata_rows=metadata_rows,
    )
    ligands_sdf = require_file(Path(str(ligand_prep["final_sdf"])), "prepared ligand sdf")

    uniqueness = _dataset_uniqueness_summary(metadata_rows)
    manifest_warnings = list(ligand_warnings) + [str(item) for item in uniqueness.get("warnings", [])]
    manifest = {
        "pdb_id": resolved["pdb_id"],
        "receptor_chain": resolved["receptor_chain"],
        "reference_ligand_resname": resolved["reference_ligand_resname"],
        "reference_ligand_chain": resolved["reference_ligand_chain"],
        "reference_ligand_pubchem_cid": (pubchem_payload or {}).get("reference_pubchem_cid", ""),
        "n_ligands_requested": args.n_ligands,
        "n_collected_raw": len(rows),
        "n_input_smiles": int(uniqueness["n_input_smiles"]),
        "n_unique_parent_ligands": int(uniqueness["n_unique_parent_ligands"]),
        "ligands_prepared": len(rows),
        "n_prepared_ligands": len(rows),
        "n_invalid": 0,
        "deduplication_method": str(uniqueness["deduplication_method"]),
        "source": ligand_source_used,
        "synthetic_expansion": False,
        "synthetic_stress_test_only": False,
        "similarity_thresholds": _resolve_threshold_ladder(args) if pubchem_payload is not None else [],
        "min_similarity": float(getattr(args, "min_similarity", 0.70)),
        "max_similarity": float(getattr(args, "max_similarity", 0.99)),
        "deduplicate_canonical_smiles": _bool_arg(getattr(args, "deduplicate_canonical_smiles", "true"), True),
        "deduplicate_inchikey": _bool_arg(getattr(args, "deduplicate_inchikey", "true"), True),
        "paths": {
            "target_mol2": str(out / "target" / "target.mol2"),
            "reference_ligand_sdf": str(reference_sdf),
            "all_ligands_sdf": str(ligands_sdf),
            "rdock_prm_dir": str(target_prm_dir),
            "target_config_yaml": str(target_prm_dir / "target_config.yaml"),
        },
        "versions": {
            "obabel": probe_version(require_executable("obabel")),
            "rbdock": probe_version(require_executable("rbdock")),
            "rbcavity": probe_version(require_executable("rbcavity")),
        },
        "ligand_source": ligand_source_used,
        "analog_grouping": analog_summary,
        "reference_ligand_smiles": reference_smiles,
        "pubchem_threshold_ladder": _resolve_threshold_ladder(args) if pubchem_payload is not None else [],
        "pubchem_diagnostics": pubchem_payload or {},
        "rbcavity_status": "success",
        "warnings": manifest_warnings,
        "ligand_preparation": ligand_prep,
        "available_hetero_ligands": hetero[:50],
        "auto_reference_ligand": bool(args.auto_reference_ligand),
        "auto_reference_candidates": auto_candidates[:50],
        "auto_reference_selected": auto_selected or {},
        "prepared_target": prep,
        "copied_target_bundle": {path.name: str(path) for path in target_prm_dir.iterdir() if path.is_file()},
    }
    create_dataset_manifest(out, manifest)
    _write_csv(
        out / "qc" / "deduplication_report.tsv",
        [
            {
                "n_input_smiles": int(uniqueness["n_input_smiles"]),
                "n_unique_parent_ligands": int(uniqueness["n_unique_parent_ligands"]),
                "duplicate_parent_fraction": float(uniqueness["duplicate_parent_fraction"]),
                "deduplication_method": str(uniqueness["deduplication_method"]),
                "synthetic_expansion": "false",
            }
        ],
    )
    qc_report = [
        f"# Dataset Preparation Report: {resolved['pdb_id']}",
        "",
        f"- receptor_chain: `{resolved['receptor_chain']}`",
        f"- reference_ligand: `{resolved['reference_ligand_resname']}` chain `{resolved['reference_ligand_chain']}`",
        f"- ligands_prepared: `{len(rows)}`",
        f"- ligands_requested: `{args.n_ligands}`",
        f"- ligand_source: `{ligand_source_used}`",
        f"- n_input_smiles: `{uniqueness['n_input_smiles']}`",
        f"- n_unique_parent_ligands: `{uniqueness['n_unique_parent_ligands']}`",
        f"- duplicate_parent_fraction: `{float(uniqueness['duplicate_parent_fraction']):.4f}`",
        f"- analog_group_count: `{analog_summary['analog_group_count']}`",
        f"- analog_grouped_ligands: `{analog_summary['analog_grouped_ligands']}`",
        f"- analog_largest_group_size: `{analog_summary['analog_largest_group_size']}`",
        f"- deduplication_method: `{uniqueness['deduplication_method']}`",
        "- synthetic_expansion: `false`",
        f"- reference_ligand_smiles: `{reference_smiles}`",
        f"- pubchem_threshold_ladder: `{_resolve_threshold_ladder(args) if pubchem_payload is not None else []}`",
        f"- target_mol2: `{out / 'target' / 'target.mol2'}`",
        f"- reference_ligand_sdf: `{reference_sdf}`",
        f"- all_ligands_sdf: `{ligands_sdf}`",
        f"- target_config_yaml: `{target_prm_dir / 'target_config.yaml'}`",
    ]
    if auto_selected:
        qc_report.extend(
            [
                "",
                "## Auto reference ligand selection",
                f"- selected_resname: `{auto_selected.get('resname', '')}`",
                f"- selected_chain: `{auto_selected.get('chain', '')}`",
                f"- selected_residue_id: `{auto_selected.get('residue_id', '')}`",
                f"- heavy_atom_count: `{auto_selected.get('heavy_atom_count', '')}`",
                f"- min_distance_to_receptor: `{auto_selected.get('min_distance_to_receptor', '')}`",
            ]
        )
    if manifest_warnings:
        qc_report.extend(["", "## Ligand Collection Warnings", *[f"- {warning}" for warning in manifest_warnings]])
    (out / "qc" / "preparation_report.md").write_text("\n".join(qc_report) + "\n", encoding="utf-8")
    print(json.dumps(validate_dataset_dir(out, check_rdock_tools=False), indent=2))
    return 0


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="Prepare a portable PDB + ligand dataset for rDock production runs.")
    parser.add_argument("--pdb-id")
    parser.add_argument("--receptor-chain")
    parser.add_argument("--reference-ligand-resname")
    parser.add_argument("--reference-ligand-chain")
    parser.add_argument("--auto-reference-ligand", action="store_true")
    parser.add_argument("--min-reference-ligand-atoms", type=int, default=8)
    parser.add_argument("--n-ligands", type=int, default=1000)
    parser.add_argument(
        "--ligand-source",
        default="auto",
        choices=[
            "auto",
            "smiles_file",
            "pubchem_similarity",
            "pubchem_compound_search",
            "pubchem_random_compounds",
            "zinc_file",
            "bundled_example",
        ],
    )
    parser.add_argument("--source", dest="ligand_source")
    parser.add_argument("--smiles-file")
    parser.add_argument("--similarity-thresholds", default="")
    parser.add_argument("--min-similarity", type=float, default=0.70)
    parser.add_argument("--max-similarity", type=float, default=0.99)
    parser.add_argument("--deduplicate-canonical-smiles", default="true")
    parser.add_argument("--deduplicate-inchikey", default="true")
    parser.add_argument("--pubchem-threshold-ladder", default="95,90,85,80,75,70")
    parser.add_argument("--pubchem-threshold-start", "--identity-threshold-start", dest="pubchem_threshold_start", type=int, default=None)
    parser.add_argument("--pubchem-threshold-stop", "--identity-threshold-stop", dest="pubchem_threshold_stop", type=int, default=None)
    parser.add_argument("--pubchem-threshold-step", type=int, default=1)
    parser.add_argument("--pubchem-timeout", type=int, default=60)
    parser.add_argument("--pubchem-property-workers", type=int, default=_default_pubchem_workers())
    parser.add_argument("--pubchem-property-chunk-size", type=int, default=200)
    parser.add_argument("--pubchem-record-multiplier", type=int, default=8)
    parser.add_argument("--pubchem-min-records-per-threshold", type=int, default=1000)
    parser.add_argument("--pubchem-max-records-per-threshold", type=int, default=5000)
    parser.add_argument("--allow-partial-ligand-set", action="store_true")
    parser.add_argument("--prepare-ligands-only", action="store_true")
    parser.add_argument("--stop-after-ligand-collection", action="store_true")
    parser.add_argument("--ligand-batch-size", type=int, default=250)
    parser.add_argument("--ligand-jobs", default=str(_default_ligand_jobs()))
    parser.add_argument("--ligand-cpu-fraction", type=float, default=0.85)
    parser.add_argument("--out")
    parser.add_argument("--ph", type=float, default=7.4)
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--force", action="store_true")
    parser.add_argument("--dry-run", action="store_true")
    parser.add_argument("--list-known-good", action="store_true")
    parser.add_argument("--list-hetero", action="store_true")
    parser.add_argument("--validate-only", action="store_true")
    return parser


def main() -> int:
    parser = build_parser()
    args = parser.parse_args()
    if not args.list_known_good and not args.validate_only and not args.list_hetero and not args.prepare_ligands_only and not args.pdb_id:
        parser.error("--pdb-id is required unless --list-known-good, --list-hetero, or --validate-only is used")
    if not args.list_known_good and not args.list_hetero and not args.out:
        parser.error("--out is required unless --list-known-good or --list-hetero is used")
    return run(args)


if __name__ == "__main__":
    raise SystemExit(main())