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

Main features
-------------
1. Stream-read huge JSONL auto-pick files, e.g. >40 GB.
2. Build a fast per-station / per-phase / per-second SQLite index for auto picks.
3. Match reference and automatic picks one-to-one with a configurable tolerance.
4. Normalize generic and regional phase names (P/Pg/Pn and S/Sg/Sn).
5. Report label-centred recall and optional reference-window output match fractions.
6. Separate statistics for manual labels only and all labels.
7. Count automatic picks in the SQLite index.
8. Qualify labels with exact NSLC intervals and finite HDF5 samples.
9. Optionally export residual diagnostics for workflow inspection.

Typical usage
-------------
python scripts/evaluate_picks.py \
  --auto-jsonl data/picks/phasenet.pick.jsonl \
  --label-json data/label/annotations_for_continuous_hdf5.json \
  --index-db data/picks/phasenet.pick.index.sqlite \
  --outdir eval_phasenet \
  --build-index \
  --tp-tol 1.5 \
  --err-window 5.0

If the SQLite index already exists, omit --build-index.
"""

from __future__ import annotations

import argparse
import json
import math
import os
import sqlite3
import sys
from collections import Counter, defaultdict
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple

import bisect

import numpy as np

try:
    import h5py
except Exception:  # pragma: no cover
    h5py = None

# matplotlib is only needed for --plot. Keep import lazy in plot_results().

try:
    from scipy import stats as scipy_stats
except Exception:  # pragma: no cover
    scipy_stats = None


# -----------------------------
# Time and phase normalization
# -----------------------------

def parse_utc_to_epoch_seconds(value: str) -> float:
    """Parse ISO UTC string to epoch seconds.

    Supports strings with or without trailing Z. Naive timestamps are treated as UTC.
    """
    if value is None:
        raise ValueError("time value is None")
    s = str(value).strip()
    if s.endswith("Z"):
        s = s[:-1] + "+00:00"
    dt = datetime.fromisoformat(s)
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=timezone.utc)
    else:
        dt = dt.astimezone(timezone.utc)
    return dt.timestamp()


def norm_location(loc: Optional[str]) -> str:
    if loc is None or loc == "":
        return "--"
    return str(loc)


def norm_station_id(station_id: Optional[str], network: Optional[str] = None,
                    station: Optional[str] = None, location: Optional[str] = None) -> str:
    """Normalize station id to network.station.location, using -- for empty location."""
    if station_id:
        parts = str(station_id).split(".")
        if len(parts) >= 3:
            return f"{parts[0]}.{parts[1]}.{norm_location(parts[2])}"
        return str(station_id)
    return f"{network}.{station}.{norm_location(location)}"


DEFAULT_PHASE_MAP = {
    "P": ["P", "Pg", "Pn"],
    "S": ["S", "Sg", "Sn"],
    "Pg": ["Pg"],
    "Sg": ["Sg"],
    "Pn": ["Pn"],
    "Sn": ["Sn"],
}


def parse_phase_map(text: Optional[str]) -> Dict[str, List[str]]:
    """Parse phase map string like 'P:Pg,Pn;S:Sg,Sn'."""
    if not text:
        return dict(DEFAULT_PHASE_MAP)
    phase_map: Dict[str, List[str]] = {}
    for item in text.split(";"):
        item = item.strip()
        if not item:
            continue
        left, right = item.split(":", 1)
        phase_map[left.strip()] = [x.strip() for x in right.split(",") if x.strip()]
    return phase_map


# -----------------------------
# SQLite index for huge JSONL
# -----------------------------

def connect_db(db_path: Path) -> sqlite3.Connection:
    """Open SQLite DB and automatically create its parent directory."""
    db_path = Path(db_path).expanduser().resolve()
    db_path.parent.mkdir(parents=True, exist_ok=True)
    conn = sqlite3.connect(str(db_path))
    conn.execute("PRAGMA journal_mode=WAL;")
    conn.execute("PRAGMA synchronous=NORMAL;")
    conn.execute("PRAGMA temp_store=MEMORY;")
    conn.execute("PRAGMA cache_size=-200000;")  # about 200 MB
    return conn


def init_pick_index(conn: sqlite3.Connection, drop_existing: bool = False) -> None:
    cur = conn.cursor()
    if drop_existing:
        cur.execute("DROP TABLE IF EXISTS auto_picks")
    cur.execute(
        """
        CREATE TABLE IF NOT EXISTS auto_picks (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            station_id TEXT NOT NULL,
            network TEXT,
            station TEXT,
            location TEXT,
            phase_name TEXT NOT NULL,
            time_epoch REAL NOT NULL,
            sec_key INTEGER NOT NULL,
            phase_prob REAL,
            polarity TEXT,
            polarity_prob REAL,
            snr REAL,
            amplitude REAL,
            h5_file TEXT,
            raw_json TEXT
        )
        """
    )
    cur.execute("CREATE INDEX IF NOT EXISTS idx_station_phase_sec ON auto_picks(station_id, phase_name, sec_key)")
    cur.execute("CREATE INDEX IF NOT EXISTS idx_station_sec ON auto_picks(station_id, sec_key)")
    cur.execute("CREATE INDEX IF NOT EXISTS idx_time ON auto_picks(time_epoch)")
    conn.commit()


def iter_jsonl(path: Path) -> Iterable[Dict[str, Any]]:
    with path.open("r", encoding="utf-8", errors="replace") as f:
        for line_no, line in enumerate(f, 1):
            line = line.strip()
            if not line:
                continue
            try:
                yield json.loads(line)
            except json.JSONDecodeError as exc:
                print(f"[WARN] skip bad JSONL line {line_no}: {exc}", file=sys.stderr)


def build_auto_pick_index(
    auto_jsonl: Path,
    db_path: Path,
    batch_size: int = 50000,
    drop_existing: bool = False,
    keep_raw_json: bool = False,
    progress_every: int = 200000,
) -> None:
    auto_jsonl = Path(auto_jsonl).expanduser().resolve()
    db_path = Path(db_path).expanduser().resolve()
    if not auto_jsonl.exists():
        raise FileNotFoundError(f"auto JSONL not found: {auto_jsonl}")

    conn = connect_db(db_path)
    init_pick_index(conn, drop_existing=drop_existing)
    cur = conn.cursor()

    insert_sql = (
        "INSERT INTO auto_picks "
        "(station_id, network, station, location, phase_name, time_epoch, sec_key, "
        "phase_prob, polarity, polarity_prob, snr, amplitude, h5_file, raw_json) "
        "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
    )

    batch = []
    n = 0
    skipped = 0
    for rec in iter_jsonl(auto_jsonl):
        if rec.get("record_type") != "phase_pick":
            continue
        try:
            station_info = rec.get("station_info") or {}
            station_id = norm_station_id(
                station_info.get("station_id"),
                station_info.get("network"),
                station_info.get("station"),
                station_info.get("location"),
            )
            phase_name = str(rec.get("phase_name"))
            t = parse_utc_to_epoch_seconds(rec.get("phase_time"))
            sec_key = int(math.floor(t))
            raw_json = json.dumps(rec, ensure_ascii=False) if keep_raw_json else None
            batch.append((
                station_id,
                station_info.get("network"),
                station_info.get("station"),
                norm_location(station_info.get("location")),
                phase_name,
                t,
                sec_key,
                rec.get("phase_prob"),
                rec.get("polarity"),
                rec.get("polarity_prob"),
                rec.get("snr"),
                rec.get("amplitude"),
                rec.get("h5_file"),
                raw_json,
            ))
        except Exception as exc:
            skipped += 1
            if skipped <= 10:
                print(f"[WARN] skip record: {exc}", file=sys.stderr)
            continue

        if len(batch) >= batch_size:
            cur.executemany(insert_sql, batch)
            conn.commit()
            n += len(batch)
            batch.clear()
            if n % progress_every < batch_size:
                print(f"[INDEX] inserted {n:,} picks, skipped {skipped:,}")

    if batch:
        cur.executemany(insert_sql, batch)
        conn.commit()
        n += len(batch)

    conn.execute("ANALYZE")
    conn.commit()
    conn.close()
    print(f"[INDEX] done. inserted {n:,} picks, skipped {skipped:,}. db={db_path}")


# -----------------------------
# Label loading
# -----------------------------

@dataclass
class LabelPick:
    label_phase: str
    label_time_epoch: float
    station_id: str
    status: str
    event_id: Optional[str]
    distance_km: Optional[float]
    raw: Dict[str, Any]


def iter_label_picks(label_json: Path) -> Iterable[LabelPick]:
    with label_json.open("r", encoding="utf-8") as f:
        data = json.load(f)

    years = data.get("years", {})
    for _year_id, year_obj in years.items():
        for _day_id, day_obj in (year_obj.get("days") or {}).items():
            for event_id, event_obj in (day_obj.get("events") or {}).items():
                for station_id0, sta_obj in (event_obj.get("stations") or {}).items():
                    for p in (sta_obj.get("picks") or []):
                        try:
                            station_id = norm_station_id(
                                p.get("station_id") or station_id0,
                                p.get("network"),
                                p.get("station"),
                                p.get("location"),
                            )
                            yield LabelPick(
                                label_phase=str(p.get("phase")),
                                label_time_epoch=parse_utc_to_epoch_seconds(p.get("time")),
                                station_id=station_id,
                                status=str(p.get("status", "unknown")),
                                event_id=p.get("event_id") or event_id,
                                distance_km=p.get("distance_km"),
                                raw=p,
                            )
                        except Exception as exc:
                            print(f"[WARN] skip label pick in event={event_id}, station={station_id0}: {exc}", file=sys.stderr)


def reference_coverage_key(
    event_id: Optional[str],
    station_id: str,
    phase: str,
    status: str,
    time_epoch: float,
) -> Tuple[str, str, str, str, int]:
    """Return a stable key shared by annotation JSON and reference SQLite rows."""
    return (
        "" if event_id is None else str(event_id),
        norm_station_id(station_id),
        str(phase),
        str(status),
        int(round(float(time_epoch) * 1_000_000)),
    )


REFERENCE_COVERAGE_FIELDS = {
    "C0": "c0_point_covered",
    "C1": "c1_window_covered",
    "C2": "c2_component_covered",
    "C3": "c3_processing_ready",
}


def load_reference_coverage(
    path: Path,
    coverage_level: str = "C0",
) -> Tuple[Dict[Tuple[str, str, str, str, int], bool], Dict[str, Any]]:
    """Load one declared precomputed coverage level and its configuration."""
    path = Path(path).expanduser().resolve()
    if not path.exists():
        raise FileNotFoundError(f"Reference-arrival SQLite DB not found: {path}")
    level = str(coverage_level).upper()
    if level not in REFERENCE_COVERAGE_FIELDS:
        raise ValueError(f"Unsupported coverage level: {coverage_level}")
    field = REFERENCE_COVERAGE_FIELDS[level]
    con = sqlite3.connect(str(path))
    rows = con.execute(
        f"""
        SELECT event_id, station_id, phase, status, pick_time_epoch,
               {field}
        FROM reference_arrivals
        ORDER BY arrival_id
        """
    )
    coverage: Dict[Tuple[str, str, str, str, int], bool] = {}
    for event_id, station_id, phase, status, time_epoch, covered in rows:
        key = reference_coverage_key(
            event_id, station_id, phase, status, float(time_epoch)
        )
        value = bool(covered)
        if key in coverage and coverage[key] != value:
            raise ValueError(f"Conflicting {level} flags for reference key: {key}")
        coverage[key] = value
    metadata = {
        str(key): json.loads(value_json)
        for key, value_json in con.execute("SELECT key, value_json FROM metadata")
    }
    con.close()
    metadata["selected_coverage_level"] = level
    metadata["selected_coverage_field"] = field
    return coverage, metadata


def load_reference_c0_coverage(
    path: Path,
) -> Tuple[Dict[Tuple[str, str, str, str, int], bool], Dict[str, Any]]:
    """Backward-compatible wrapper for the released C0 reporting default."""
    return load_reference_coverage(path, "C0")


def load_evaluation_reference_labels(
    path: Path,
    coverage_level: str = "C0",
) -> Tuple[List[LabelPick], Dict[int, Optional[bool]], Dict[str, Any]]:
    """Load the canonical station-phase-time evaluation-reference layer.

    Source readings remain available in ``reference_arrivals`` and
    ``evaluation_reference_members``. A canonical record is classified as
    manual when any member is manual; otherwise it retains automatic
    provenance. This prevents exact repeated readings from competing for one
    automatic pick during one-to-one evaluation.
    """
    source = Path(path).expanduser().resolve()
    level = str(coverage_level).upper()
    if level not in REFERENCE_COVERAGE_FIELDS:
        raise ValueError(f"Unsupported coverage level: {coverage_level}")
    field = REFERENCE_COVERAGE_FIELDS[level]
    con = sqlite3.connect(str(source))
    if con.execute(
        "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='evaluation_references'"
    ).fetchone()[0] != 1:
        con.close()
        raise ValueError(
            "reference database lacks the canonical evaluation_references table; "
            "regenerate it with essd_scripts/build_reference_arrivals.py"
        )
    labels: List[LabelPick] = []
    coverage_cache: Dict[int, Optional[bool]] = {}
    rows = con.execute(
        f"""
        SELECT evaluation_reference_id, station_id, phase, pick_time_epoch,
               has_manual_reference, has_automatic_reference,
               source_arrival_count, source_event_count, {field}
        FROM evaluation_references
        ORDER BY evaluation_reference_id
        """
    )
    for row in rows:
        (
            reference_id, station_id, phase, time_epoch, has_manual,
            has_automatic, source_count, event_count, covered,
        ) = row
        labels.append(
            LabelPick(
                label_phase=str(phase),
                label_time_epoch=float(time_epoch),
                station_id=str(station_id),
                status="manual" if bool(has_manual) else "automatic",
                event_id=None,
                distance_km=None,
                raw={
                    "evaluation_reference_id": int(reference_id),
                    "has_manual_reference": bool(has_manual),
                    "has_automatic_reference": bool(has_automatic),
                    "source_arrival_count": int(source_count),
                    "source_event_count": int(event_count),
                },
            )
        )
        coverage_cache[len(labels) - 1] = bool(covered)
    metadata = {
        str(key): json.loads(value_json)
        for key, value_json in con.execute("SELECT key, value_json FROM metadata")
    }
    con.close()
    metadata["selected_coverage_level"] = level
    metadata["selected_coverage_field"] = field
    metadata["reference_layer"] = "evaluation_references"
    return labels, coverage_cache, metadata


# -----------------------------
# Matching and statistics
# -----------------------------

# -----------------------------
# Waveform coverage index
# -----------------------------


@dataclass(frozen=True)
class CoverageSegment:
    start_epoch: float
    end_epoch: float
    delta: float
    sampling_rate: float
    npts: int
    dtype: str
    h5_file: Optional[Path]
    dataset_path: Optional[str]

class WaveformCoverageIndex:
    """Segment-level station, location, and channel-family coverage index.

    Intervals are merged only within the same NSLC channel. This preserves
    intra-day gaps and prevents state-of-health or low-rate channels from
    qualifying a reference arrival for a seismic picker. A ``--`` label
    location is treated as unspecified and may match one released location;
    explicit label locations are matched exactly. Floating-point HDF5 samples
    must be finite by default, so internal NaN intervals do not qualify.
    """

    def __init__(
        self,
        waveform_db: Path,
        channel_families: Sequence[str] = ("HH", "BH", "EH", "HN"),
        validate_finite_samples: bool = True,
    ) -> None:
        waveform_db = Path(waveform_db).expanduser().resolve()
        if not waveform_db.exists():
            raise FileNotFoundError(f"Waveform index DB not found: {waveform_db}")
        self.channel_families = tuple(str(x).upper() for x in channel_families)
        if not self.channel_families:
            raise ValueError("channel_families must contain at least one family")
        self._index: Dict[
            Tuple[str, str, str, str],
            Tuple[List[Tuple[float, float]], List[float]],
        ] = {}
        self._sample_rates: Dict[Tuple[str, str, str, str], List[float]] = {}
        self._segments: Dict[Tuple[str, str, str, str], List[CoverageSegment]] = {}
        self._segment_starts: Dict[Tuple[str, str, str, str], List[float]] = {}
        self._station_keys: Dict[str, List[Tuple[str, str, str, str]]] = defaultdict(list)
        self._db_path = waveform_db
        self._release_root = waveform_db.parents[2] if len(waveform_db.parents) >= 3 else waveform_db.parent
        self._validate_finite_samples_requested = bool(validate_finite_samples)
        self._validate_finite_samples = False
        self._h5_handles: Dict[Path, Any] = {}
        self._load(waveform_db)

    def _load(self, db_path: Path) -> None:
        """Load exact segment intervals and merge only overlapping NSLC rows."""
        conn = sqlite3.connect(str(db_path))
        columns = {
            str(row[1]) for row in conn.execute("PRAGMA table_info(waveform_segments)")
        }
        sample_columns = {"h5_file", "dataset_path", "sampling_rate", "npts", "dtype"}
        sample_fields_available = sample_columns.issubset(columns)
        self._validate_finite_samples = (
            self._validate_finite_samples_requested and sample_fields_available
        )
        if self._validate_finite_samples and h5py is None:
            raise RuntimeError("h5py is required for finite-sample coverage validation")
        extra_fields = (
            "h5_file, dataset_path, COALESCE(sampling_rate, 0.0), "
            "COALESCE(npts, 0), COALESCE(dtype, '')"
            if sample_fields_available
            else "NULL, NULL, 0.0, 0, ''"
        )
        sql = f"""
            SELECT network, station,
                   COALESCE(NULLIF(location, ''), '--') AS location,
                   channel, start_epoch, end_epoch,
                   COALESCE(delta, 0.0) AS delta,
                   {extra_fields}
            FROM waveform_segments
        """
        raw: Dict[Tuple[str, str, str, str], List[CoverageSegment]] = {}
        for row in conn.execute(sql):
            (
                network, station, location, channel, t0, t1, delta,
                h5_file, dataset_path, sampling_rate, npts, dtype,
            ) = row
            family = str(channel)[:2].upper()
            if family not in self.channel_families:
                continue
            station_key = f"{network}.{station}"
            key = (station_key, norm_location(location), family, str(channel).upper())
            resolved_h5: Optional[Path] = None
            if h5_file:
                candidate = Path(str(h5_file)).expanduser()
                if not candidate.is_absolute():
                    candidate = self._release_root / candidate
                resolved_h5 = candidate.resolve()
            raw.setdefault(key, []).append(
                CoverageSegment(
                    start_epoch=float(t0),
                    end_epoch=float(t1),
                    delta=float(delta or 0.0),
                    sampling_rate=float(sampling_rate or 0.0),
                    npts=int(npts or 0),
                    dtype=str(dtype or ""),
                    h5_file=resolved_h5,
                    dataset_path=str(dataset_path) if dataset_path else None,
                )
            )
        conn.close()

        # Adjacent samples from the same NSLC may be merged within one sample
        # interval. Larger gaps, including intra-day gaps, remain explicit.
        for key, segs in raw.items():
            segs.sort(key=lambda segment: (segment.start_epoch, segment.end_epoch))
            merged: List[Tuple[float, float]] = []
            for segment in segs:
                tolerance = max(1.0e-6, abs(segment.delta))
                if merged and segment.start_epoch <= merged[-1][1] + tolerance:
                    merged[-1] = (
                        merged[-1][0], max(merged[-1][1], segment.end_epoch)
                    )
                else:
                    merged.append((segment.start_epoch, segment.end_epoch))
            self._index[key] = (merged, [x[0] for x in merged])
            self._sample_rates[key] = sorted(
                {
                    segment.sampling_rate
                    if segment.sampling_rate > 0.0
                    else 1.0 / segment.delta
                    for segment in segs
                    if segment.sampling_rate > 0.0 or segment.delta > 0.0
                }
            )
            self._segments[key] = segs
            self._segment_starts[key] = [segment.start_epoch for segment in segs]
            self._station_keys[key[0]].append(key)

        n_sta = len(self._station_keys)
        n_seg = sum(len(v[0]) for v in self._index.values())
        print(
            f"[COVERAGE] loaded {n_sta} stations and {n_seg} NSLC intervals "
            f"for families {','.join(self.channel_families)} from {db_path.name}; "
            f"finite-sample validation={'on' if self._validate_finite_samples else 'off'}",
            file=sys.stderr,
        )

    def close(self) -> None:
        for handle in self._h5_handles.values():
            try:
                handle.close()
            except Exception:
                pass
        self._h5_handles.clear()

    def __del__(self) -> None:  # pragma: no cover - interpreter shutdown varies
        self.close()

    def _dataset(self, segment: CoverageSegment) -> Any:
        if segment.h5_file is None or segment.dataset_path is None:
            raise RuntimeError("waveform index row lacks HDF5 path metadata")
        handle = self._h5_handles.get(segment.h5_file)
        if handle is None:
            if not segment.h5_file.exists():
                raise FileNotFoundError(f"Indexed HDF5 file not found: {segment.h5_file}")
            handle = h5py.File(segment.h5_file, "r")
            self._h5_handles[segment.h5_file] = handle
        return handle[segment.dataset_path]

    @staticmethod
    def _floating_dtype(dtype: str) -> bool:
        try:
            return np.issubdtype(np.dtype(dtype), np.floating)
        except TypeError:
            return False

    def _covering_segments(
        self, key: Tuple[str, str, str, str], time_epoch: float
    ) -> List[CoverageSegment]:
        segments = self._segments.get(key, [])
        starts = self._segment_starts.get(key, [])
        idx = bisect.bisect_right(starts, time_epoch) - 1
        matches: List[CoverageSegment] = []
        while idx >= 0:
            segment = segments[idx]
            if segment.end_epoch + max(segment.delta, 1.0e-6) < time_epoch:
                break
            if segment.start_epoch <= time_epoch <= segment.end_epoch + max(segment.delta, 1.0e-6):
                matches.append(segment)
            idx -= 1
        return matches

    def _sample_is_finite(self, segment: CoverageSegment, time_epoch: float) -> bool:
        if not self._validate_finite_samples or not self._floating_dtype(segment.dtype):
            return True
        if segment.delta <= 0.0 or segment.npts <= 0:
            return False
        sample_offset = (time_epoch - segment.start_epoch) / segment.delta
        sample_index = int(math.floor(sample_offset + 0.5))
        if sample_index < 0 or sample_index >= segment.npts:
            return False
        value = self._dataset(segment)[sample_index]
        return bool(np.isfinite(value))

    def _key_has_point_coverage(
        self, key: Tuple[str, str, str, str], time_epoch: float
    ) -> bool:
        if not self._contains(self._index[key], time_epoch):
            return False
        return any(
            self._sample_is_finite(segment, time_epoch)
            for segment in self._covering_segments(key, time_epoch)
        )

    @staticmethod
    def _station_parts(station_id: str) -> Tuple[str, str]:
        parts = station_id.split(".")
        station_key = f"{parts[0]}.{parts[1]}" if len(parts) >= 2 else station_id
        location = norm_location(parts[2]) if len(parts) >= 3 else "--"
        return station_key, location

    @staticmethod
    def _contains(
        value: Tuple[List[Tuple[float, float]], List[float]],
        time_epoch: float,
    ) -> bool:
        intervals, starts = value
        idx = bisect.bisect_right(starts, time_epoch) - 1
        return idx >= 0 and intervals[idx][1] >= time_epoch

    @staticmethod
    def _component(channel: str) -> str:
        suffix = str(channel)[-1:].upper()
        if suffix in {"E", "1"}:
            return "H1"
        if suffix in {"N", "2"}:
            return "H2"
        if suffix in {"Z", "3"}:
            return "Z"
        return suffix

    def coverage_details(self, station_id: str, time_epoch: float) -> Dict[str, Any]:
        """Return auditable point-coverage details for one reference arrival."""
        station_key, label_location = self._station_parts(station_id)
        keys = self._station_keys.get(station_key, [])
        if label_location != "--":
            keys = [key for key in keys if key[1] == label_location]

        candidates: List[Tuple[int, int, str, str, List[str]]] = []
        for family_rank, family in enumerate(self.channel_families):
            by_location: Dict[str, List[str]] = defaultdict(list)
            for key in keys:
                _, location, key_family, channel = key
                if key_family == family and self._key_has_point_coverage(key, time_epoch):
                    by_location[location].append(channel)
            for location, channels in by_location.items():
                components = {self._component(channel) for channel in channels}
                candidates.append(
                    (-len(components), family_rank, location, family, sorted(channels))
                )

        if not candidates:
            return {
                "point_covered": False,
                "station_key": station_key,
                "label_location": label_location,
                "matched_location": None,
                "channel_family": None,
                "component_count": 0,
                "channels": [],
                "location_match_mode": "exact" if label_location != "--" else "unspecified",
            }

        _, _, location, family, channels = min(candidates)
        return {
            "point_covered": True,
            "station_key": station_key,
            "label_location": label_location,
            "matched_location": location,
            "channel_family": family,
            "component_count": len({self._component(channel) for channel in channels}),
            "channels": channels,
            "location_match_mode": "exact" if label_location != "--" else "unspecified",
        }

    def has_coverage(self, station_id: str, time_epoch: float) -> bool:
        return bool(self.coverage_details(station_id, time_epoch)["point_covered"])

    def _covered_duration(
        self,
        key: Tuple[str, str, str, str],
        start_epoch: float,
        end_epoch: float,
    ) -> float:
        value = self._index[key]
        intervals, starts = value
        if end_epoch <= start_epoch or not intervals:
            return 0.0
        if not self._validate_finite_samples:
            idx = max(0, bisect.bisect_right(starts, start_epoch) - 1)
            covered = 0.0
            while idx < len(intervals):
                t0, t1 = intervals[idx]
                if t0 >= end_epoch:
                    break
                covered += max(0.0, min(t1, end_epoch) - max(t0, start_epoch))
                idx += 1
            return min(covered, end_epoch - start_epoch)

        covered = 0.0
        for segment in self._segments.get(key, []):
            delta = segment.delta
            if delta <= 0.0:
                continue
            segment_end_exclusive = segment.end_epoch + delta
            left = max(start_epoch, segment.start_epoch)
            right = min(end_epoch, segment_end_exclusive)
            if right <= left:
                continue
            if not self._floating_dtype(segment.dtype):
                covered += right - left
                continue
            i0 = max(
                0,
                int(math.ceil((left - segment.start_epoch) / delta - 1.0e-7)),
            )
            i1 = min(
                segment.npts,
                int(math.ceil((right - segment.start_epoch) / delta - 1.0e-7)),
            )
            if i1 <= i0:
                continue
            values = np.asarray(self._dataset(segment)[i0:i1])
            covered += float(np.count_nonzero(np.isfinite(values))) * delta
        return min(covered, end_epoch - start_epoch)

    def coverage_window_details(
        self,
        station_id: str,
        time_epoch: float,
        window_before_s: float,
        window_after_s: float,
        max_gap_fraction: float = 0.0,
        required_components: Sequence[str] = ("Z",),
    ) -> Dict[str, Any]:
        """Return point, window, and observed-component coverage details.

        C1 is satisfied when at least one observed component of the selected
        family/location meets ``max_gap_fraction``. C2 additionally requires
        every component named in ``required_components``. Component names use
        ``Z``, ``H1``, and ``H2``; copied or synthetic components are never
        introduced by this calculation.
        """
        before = float(window_before_s)
        after = float(window_after_s)
        if before < 0.0 or after < 0.0 or before + after <= 0.0:
            raise ValueError("window_before_s and window_after_s must define a positive window")
        if not 0.0 <= float(max_gap_fraction) <= 1.0:
            raise ValueError("max_gap_fraction must be between 0 and 1")
        required = tuple(str(item).upper() for item in required_components)
        unknown = set(required) - {"Z", "H1", "H2"}
        if unknown:
            raise ValueError(f"Unknown required components: {sorted(unknown)}")

        point = self.coverage_details(station_id, time_epoch)
        result = dict(point)
        result.update(
            {
                "window_start_epoch": time_epoch - before,
                "window_end_epoch": time_epoch + after,
                "window_before_s": before,
                "window_after_s": after,
                "max_gap_fraction": float(max_gap_fraction),
                "required_components": list(required),
                "component_gap_fractions": {},
                "component_channels": {},
                "component_sample_rates_hz": {},
                "window_gap_fraction": 1.0,
                "required_component_gap_fraction": 1.0,
                "window_covered": False,
                "component_covered": False,
            }
        )
        if not point["point_covered"]:
            return result

        station_key = str(point["station_key"])
        location = str(point["matched_location"])
        family = str(point["channel_family"])
        start_epoch = time_epoch - before
        end_epoch = time_epoch + after
        duration = end_epoch - start_epoch

        best_by_component: Dict[str, Tuple[float, str, List[float]]] = {}
        for key in self._station_keys.get(station_key, []):
            _, key_location, key_family, channel = key
            if key_location != location or key_family != family:
                continue
            component = self._component(channel)
            if component not in {"Z", "H1", "H2"}:
                continue
            covered = self._covered_duration(key, start_epoch, end_epoch)
            gap_fraction = max(0.0, 1.0 - covered / duration)
            candidate = (gap_fraction, channel, self._sample_rates.get(key, []))
            if component not in best_by_component or candidate[:2] < best_by_component[component][:2]:
                best_by_component[component] = candidate

        gaps = {component: item[0] for component, item in best_by_component.items()}
        result["component_gap_fractions"] = gaps
        result["component_channels"] = {
            component: item[1] for component, item in best_by_component.items()
        }
        result["component_sample_rates_hz"] = {
            component: item[2] for component, item in best_by_component.items()
        }
        if gaps:
            result["window_gap_fraction"] = min(gaps.values())
            result["window_covered"] = (
                result["window_gap_fraction"] <= float(max_gap_fraction)
            )
        if required and all(component in gaps for component in required):
            required_gap = max(gaps[component] for component in required)
            result["required_component_gap_fraction"] = required_gap
            result["component_covered"] = required_gap <= float(max_gap_fraction)
        return result

    def covered_networks(self) -> List[str]:
        return sorted({key.split(".")[0] for key in self._station_keys})


@dataclass
class MatchResult:
    subset: str
    label_phase: str
    station_id: str
    event_id: Optional[str]
    label_time_epoch: float
    matched: bool
    auto_pick_id: Optional[int] = None
    auto_phase: Optional[str] = None
    auto_time_epoch: Optional[float] = None
    residual_s: Optional[float] = None  # auto - label
    phase_prob: Optional[float] = None
    snr: Optional[float] = None
    distance_km: Optional[float] = None
    has_waveform: Optional[bool] = None   # True/False when waveform_db used; None otherwise


@dataclass
class AutoPickCandidate:
    auto_pick_id: int
    phase_name: str
    time_epoch: float
    residual_s: float
    phase_prob: Optional[float]
    snr: Optional[float]


@dataclass
class _MatchingState:
    tp_count: int
    matched_count: int
    residual_cost: float
    parent: int
    label_idx: int
    auto_idx: int


def match_labels_one_to_one(
    conn: sqlite3.Connection,
    labels: Sequence[LabelPick],
    auto_phases: Sequence[str],
    search_window_s: float,
    min_prob: Optional[float] = None,
    tp_tolerance_s: Optional[float] = None,
    allowed_intervals: Optional[Sequence[Tuple[float, float]]] = None,
) -> Dict[int, AutoPickCandidate]:
    """Assign automatic picks once within one station--phase label group.

    Candidate edges form a sparse, time-ordered bipartite graph. A Fenwick-tree
    dynamic program first maximizes the number of assignments within
    ``tp_tolerance_s``, then the number within ``search_window_s``, and finally
    minimizes total absolute residual. The returned dictionary is keyed by the
    original local label index. No automatic-pick row can be assigned more than
    once.
    """
    if not labels:
        return {}
    station_ids = {label.station_id for label in labels}
    if len(station_ids) != 1:
        raise ValueError("one-to-one matching requires one station_id per group")
    station_id = next(iter(station_ids))
    t_min = min(label.label_time_epoch for label in labels) - search_window_s
    t_max = max(label.label_time_epoch for label in labels) + search_window_s
    sec0 = int(math.floor(t_min))
    sec1 = int(math.floor(t_max))
    placeholders = ",".join("?" for _ in auto_phases)
    params: List[Any] = [station_id, *auto_phases, sec0, sec1]
    prob_clause = ""
    if min_prob is not None:
        prob_clause = " AND phase_prob >= ?"
        params.append(float(min_prob))

    sql = f"""
        SELECT id, phase_name, time_epoch, phase_prob, snr
        FROM auto_picks
        WHERE station_id = ?
          AND phase_name IN ({placeholders})
          AND sec_key BETWEEN ? AND ?
          {prob_clause}
        ORDER BY time_epoch, id
    """
    rows = conn.execute(sql, params).fetchall()
    if allowed_intervals is not None:
        intervals = list(allowed_intervals)
        filtered = []
        interval_index = 0
        for row in rows:
            value = float(row[2])
            while (
                interval_index < len(intervals)
                and value > intervals[interval_index][1]
            ):
                interval_index += 1
            if interval_index >= len(intervals):
                break
            if intervals[interval_index][0] <= value <= intervals[interval_index][1]:
                filtered.append(row)
        rows = filtered
    if not rows:
        return {}

    auto_times = [float(row[2]) for row in rows]
    tp_tolerance = (
        float(search_window_s)
        if tp_tolerance_s is None else float(tp_tolerance_s)
    )
    if tp_tolerance < 0 or tp_tolerance > search_window_s:
        raise ValueError("tp_tolerance_s must be within search_window_s")

    ordered_labels = sorted(
        enumerate(labels), key=lambda item: (item[1].label_time_epoch, item[0])
    )
    states: List[_MatchingState] = [
        _MatchingState(0, 0, 0.0, -1, -1, -1)
    ]
    fenwick = [0] * (len(rows) + 1)

    def better(left_id: int, right_id: int) -> int:
        left = states[left_id]
        right = states[right_id]
        left_key = (left.tp_count, left.matched_count, -left.residual_cost)
        right_key = (right.tp_count, right.matched_count, -right.residual_cost)
        if left_key != right_key:
            return left_id if left_key > right_key else right_id
        left_tie = (left.auto_idx, left.label_idx, left_id)
        right_tie = (right.auto_idx, right.label_idx, right_id)
        return left_id if left_tie < right_tie else right_id

    def query(auto_idx_exclusive: int) -> int:
        best_id = 0
        idx = auto_idx_exclusive
        while idx > 0:
            best_id = better(best_id, fenwick[idx])
            idx -= idx & -idx
        return best_id

    def update(auto_idx: int, state_id: int) -> None:
        idx = auto_idx + 1
        while idx < len(fenwick):
            fenwick[idx] = better(fenwick[idx], state_id)
            idx += idx & -idx

    for original_label_idx, label in ordered_labels:
        left = bisect.bisect_left(auto_times, label.label_time_epoch - search_window_s)
        right = bisect.bisect_right(auto_times, label.label_time_epoch + search_window_s)
        pending: List[Tuple[int, int]] = []
        for auto_idx in range(left, right):
            residual = auto_times[auto_idx] - label.label_time_epoch
            previous_id = query(auto_idx)
            previous = states[previous_id]
            state_id = len(states)
            states.append(
                _MatchingState(
                    tp_count=previous.tp_count + int(abs(residual) <= tp_tolerance),
                    matched_count=previous.matched_count + 1,
                    residual_cost=previous.residual_cost + abs(residual),
                    parent=previous_id,
                    label_idx=original_label_idx,
                    auto_idx=auto_idx,
                )
            )
            pending.append((auto_idx, state_id))
        # Defer updates until every candidate for this label has been scored;
        # this prevents two picks from being assigned to the same label.
        for auto_idx, state_id in pending:
            update(auto_idx, state_id)

    assignments: Dict[int, AutoPickCandidate] = {}
    state_id = query(len(rows))
    while state_id != 0:
        state = states[state_id]
        label_idx = state.label_idx
        auto_idx = state.auto_idx
        row = rows[auto_idx]
        residual = float(row[2]) - labels[label_idx].label_time_epoch
        assignments[label_idx] = AutoPickCandidate(
            auto_pick_id=int(row[0]),
            phase_name=str(row[1]),
            time_epoch=float(row[2]),
            residual_s=residual,
            phase_prob=row[3],
            snr=row[4],
        )
        state_id = state.parent
    return assignments


def evaluate(
    label_json: Path,
    db_path: Path,
    outdir: Path,
    phase_map: Dict[str, List[str]],
    tp_tol: float = 1.5,
    err_window: float = 5.0,
    min_prob: Optional[float] = None,
    waveform_db: Optional[Path] = None,
    reference_db: Optional[Path] = None,
    automatic_pick_source: Optional[Path] = None,
    coverage_channel_families: Sequence[str] = ("HH", "BH", "EH", "HN"),
    validate_finite_samples: bool = True,
    coverage_level: str = "C0",
    reference_windows_s: Sequence[float] = (),
    output_eligibility_db: Optional[Path] = None,
    output_id: Optional[int] = None,
    output_name: Optional[str] = None,
) -> Tuple[List[MatchResult], Dict[str, Any]]:
    outdir = Path(outdir).expanduser().resolve()
    outdir.mkdir(parents=True, exist_ok=True)
    db_path = Path(db_path).expanduser().resolve()
    if not db_path.exists():
        raise FileNotFoundError(
            f"SQLite index DB not found: {db_path}. "
            "Run once with --build-index, or check --index-db."
        )
    conn = connect_db(db_path)

    if waveform_db is not None and reference_db is not None:
        raise ValueError("Use either waveform_db or reference_db for coverage, not both")
    coverage_level = str(coverage_level).upper()
    if coverage_level not in REFERENCE_COVERAGE_FIELDS:
        raise ValueError(f"Unsupported coverage level: {coverage_level}")
    if waveform_db is not None and coverage_level != "C0":
        raise ValueError("C1-C3 reporting requires --reference-db")
    if reference_windows_s and output_eligibility_db is None:
        raise ValueError(
            "Reference-window reporting requires --output-eligibility-db"
        )
    eligibility = None
    if reference_windows_s:
        eligibility = load_workflow_eligibility(
            Path(output_eligibility_db), output_id=output_id, output_name=output_name
        )

    # Optional waveform coverage filter
    cov_index: Optional[WaveformCoverageIndex] = None
    reference_coverage = None
    reference_metadata: Dict[str, Any] = {}
    if waveform_db is not None:
        cov_index = WaveformCoverageIndex(
            Path(waveform_db),
            channel_families=coverage_channel_families,
            validate_finite_samples=validate_finite_samples,
        )
    elif reference_db is not None:
        # Loaded with the canonical labels below; the raw source-reading table
        # remains available for provenance and inventory reporting.
        reference_coverage = None

    results: List[MatchResult] = []
    label_counter = Counter()
    label_status_counter = Counter()
    if reference_db is not None:
        loaded_labels, loaded_coverage, reference_metadata = load_evaluation_reference_labels(
            Path(reference_db), coverage_level
        )
        selected = [
            (idx, lab) for idx, lab in enumerate(loaded_labels)
            if lab.label_phase in phase_map
        ]
        labels = [lab for _, lab in selected]
        coverage_cache = {
            new_idx: loaded_coverage[old_idx]
            for new_idx, (old_idx, _) in enumerate(selected)
        }
    else:
        labels = [lab for lab in iter_label_picks(label_json) if lab.label_phase in phase_map]
        coverage_cache = {}
    for label_idx, lab in enumerate(labels):
        if lab.label_phase not in phase_map:
            continue
        label_counter[lab.label_phase] += 1
        label_status_counter[(lab.status, lab.label_phase)] += 1
        if cov_index is not None:
            coverage_cache[label_idx] = cov_index.has_coverage(
                lab.station_id, lab.label_time_epoch
            )
        elif reference_coverage is not None:
            key = reference_coverage_key(
                lab.event_id,
                lab.station_id,
                lab.label_phase,
                lab.status,
                lab.label_time_epoch,
            )
            if key not in reference_coverage:
                raise KeyError(f"Label is absent from reference-arrival DB: {key}")
            coverage_cache[label_idx] = reference_coverage[key]
        else:
            coverage_cache.setdefault(label_idx, None)

    for subset in ("all", "manual", "automatic"):
        subset_labels = [
            (idx, lab)
            for idx, lab in enumerate(labels)
            if subset == "all" or lab.status == subset
        ]
        grouped: Dict[Tuple[str, str], List[Tuple[int, LabelPick]]] = defaultdict(list)
        for global_idx, lab in subset_labels:
            grouped[(lab.station_id, lab.label_phase)].append((global_idx, lab))

        assigned: Dict[int, AutoPickCandidate] = {}
        for (_, label_phase), group in grouped.items():
            local_labels = [lab for _, lab in group]
            local_assignments = match_labels_one_to_one(
                conn,
                local_labels,
                phase_map[label_phase],
                search_window_s=err_window,
                min_prob=min_prob,
                tp_tolerance_s=tp_tol,
            )
            for local_idx, candidate in local_assignments.items():
                assigned[group[local_idx][0]] = candidate

        for global_idx, lab in subset_labels:
            candidate = assigned.get(global_idx)
            has_waveform = coverage_cache[global_idx]
            if candidate is None:
                results.append(MatchResult(
                    subset=subset, label_phase=lab.label_phase, station_id=lab.station_id,
                    event_id=lab.event_id, label_time_epoch=lab.label_time_epoch,
                    matched=False, distance_km=lab.distance_km,
                    has_waveform=has_waveform,
                ))
            else:
                results.append(MatchResult(
                    subset=subset, label_phase=lab.label_phase, station_id=lab.station_id,
                    event_id=lab.event_id, label_time_epoch=lab.label_time_epoch,
                    matched=abs(candidate.residual_s) <= tp_tol,
                    auto_pick_id=candidate.auto_pick_id,
                    auto_phase=candidate.phase_name,
                    auto_time_epoch=candidate.time_epoch,
                    residual_s=candidate.residual_s,
                    phase_prob=candidate.phase_prob,
                    snr=candidate.snr,
                    distance_km=lab.distance_km, has_waveform=has_waveform,
                ))

    if reference_windows_s and eligibility is None:
        raise RuntimeError("workflow eligibility was not initialized")
    reference_window_matches = [
        compute_reference_window_match_fraction(
            conn=conn,
            indexed_labels=list(enumerate(labels)),
            coverage_cache=coverage_cache,
            phase_map=phase_map,
            window_half_width_s=float(window_s),
            tp_tolerance_s=tp_tol,
            eligibility=eligibility,
            coverage_level=coverage_level,
            min_prob=min_prob,
        )
        for window_s in reference_windows_s
    ]

    conn.close()
    if cov_index is not None:
        cov_index.close()

    summary = summarize_results(results, label_counter, label_status_counter, tp_tol, err_window)
    summary["auto_pick_count"] = get_auto_counts(db_path, min_prob=min_prob, phase_map=phase_map)
    add_pick_centered_metrics(summary, results, summary["auto_pick_count"], phase_map)
    summary["input_sources"] = {
        "annotation_json": Path(label_json).as_posix(),
        "evaluation_reference_layer": (
            str(Path(reference_db)) if reference_db is not None else None
        ),
        "automatic_pick_jsonl": (
            Path(automatic_pick_source).as_posix()
            if automatic_pick_source is not None
            else None
        ),
    }
    summary["matching_policy"] = (
        "deterministic time-ordered one-to-one assignment that maximizes TP "
        "matches, then diagnostic-window matches, and then minimizes total "
        "absolute residual within each station, reference phase, and reported "
        "label subset"
    )
    summary["phase_map"] = phase_map
    if reference_window_matches:
        summary["reference_window_match"] = reference_window_matches
    if reference_db is not None:
        coverage_config = reference_metadata.get("coverage", {})
        summary["coverage_policy"] = {
            "source": str(Path(reference_db)),
            "reference_field": REFERENCE_COVERAGE_FIELDS[coverage_level],
            "coverage_level": coverage_level,
            "definition": coverage_config.get(
                coverage_level, f"precomputed {coverage_level} coverage"
            ),
            "channel_families": coverage_config.get(
                "channel_families", list(coverage_channel_families)
            ),
            "finite_sample_validation": coverage_config.get(
                "finite_sample_validation", True
            ),
            "unspecified_location": (
                "use the deterministic location/family selection recorded by "
                "the versioned reference-arrival table"
            ),
        }
    elif waveform_db is not None:
        summary["coverage_policy"] = {
            "source": str(Path(waveform_db)),
            "coverage_level": "C0",
            "definition": (
                "point coverage from exact NSLC segment intervals with finite-sample "
                "validation for floating-point HDF5 arrays"
                if validate_finite_samples
                else "point coverage from exact NSLC segment intervals only"
            ),
            "channel_families": list(coverage_channel_families),
            "finite_sample_validation": bool(validate_finite_samples),
            "unspecified_location": "match one released location without combining locations",
        }
    else:
        summary["coverage_policy"] = {
            "source": None,
            "definition": "coverage qualification not applied",
        }
    write_outputs(results, summary, outdir)
    return results, summary


def fit_student_t(residuals: np.ndarray) -> Dict[str, Optional[float]]:
    if residuals.size < 3 or scipy_stats is None:
        return {"df": None, "loc": None, "scale": None}
    try:
        df, loc, scale = scipy_stats.t.fit(residuals)
        return {"df": float(df), "loc": float(loc), "scale": float(scale)}
    except Exception:
        return {"df": None, "loc": None, "scale": None}


def fit_gaussian(residuals: np.ndarray) -> Dict[str, Optional[float]]:
    """Maximum-likelihood Gaussian fit for residuals."""
    if residuals.size < 2:
        return {"mean": None, "std_mle": None, "std_unbiased": None}
    return {
        "mean": float(np.mean(residuals)),
        "std_mle": float(np.std(residuals, ddof=0)),
        "std_unbiased": float(np.std(residuals, ddof=1)),
    }


def get_auto_counts(
    db_path: Path,
    min_prob: Optional[float] = None,
    phase_map: Optional[Dict[str, List[str]]] = None,
) -> Dict[str, Any]:
    """Count automatic picks in the SQLite index.

    Returns original automatic phase counts, e.g. Pg/Sg, plus optional counts
    mapped to label phases, e.g. P->Pg and S->Sg. If min_prob is set, the
    counts are computed after applying phase_prob >= min_prob.
    """
    conn = connect_db(db_path)

    where = ""
    params: List[Any] = []
    if min_prob is not None:
        where = "WHERE phase_prob >= ?"
        params.append(float(min_prob))

    rows = conn.execute(
        f"SELECT phase_name, COUNT(*) FROM auto_picks {where} GROUP BY phase_name ORDER BY phase_name",
        params,
    ).fetchall()
    by_auto_phase = {str(ph): int(c) for ph, c in rows}
    total = int(sum(by_auto_phase.values()))

    mapped: Dict[str, int] = {}
    if phase_map:
        for label_phase, auto_phases in phase_map.items():
            mapped[label_phase] = int(sum(by_auto_phase.get(ap, 0) for ap in auto_phases))

    conn.close()
    return {
        "filter": {"min_prob": min_prob},
        "total": total,
        "by_auto_phase": by_auto_phase,
        "mapped_to_label_phase": mapped,
    }


def add_pick_centered_metrics(
    summary: Dict[str, Any],
    results: Sequence[MatchResult],
    auto_counts: Dict[str, Any],
    phase_map: Dict[str, List[str]],
) -> None:
    """Add pick-centered matched fractions to label-centered summaries.

    One-to-one assignment makes the matched-pick numerator unambiguous within
    each reported subset. The denominator contains all automatic picks whose
    normalized phase is eligible for that row after the probability filter.
    """
    by_auto_phase = auto_counts.get("by_auto_phase", {})
    for subset, subset_summary in summary["subsets"].items():
        subset_results = [result for result in results if result.subset == subset]
        reported_phases = [
            phase for phase in subset_summary if phase != "P_S_combined"
        ]
        for phase in reported_phases:
            eligible_phases = set(phase_map.get(phase, []))
            n_eligible = sum(int(by_auto_phase.get(name, 0)) for name in eligible_phases)
            matched_ids = {
                result.auto_pick_id
                for result in subset_results
                if result.label_phase == phase
                and result.matched
                and result.auto_pick_id is not None
            }
            phase_summary = subset_summary[phase]
            phase_summary["n_eligible_auto_picks"] = int(n_eligible)
            phase_summary["n_unique_auto_picks_matched_within_tp_tol"] = len(matched_ids)
            phase_summary["pick_matched_fraction"] = (
                len(matched_ids) / n_eligible if n_eligible else None
            )

        combined_auto_phases = {
            auto_phase
            for phase in reported_phases
            for auto_phase in phase_map.get(phase, [])
        }
        n_eligible_combined = sum(
            int(by_auto_phase.get(name, 0)) for name in combined_auto_phases
        )
        combined_matched_ids = {
            result.auto_pick_id
            for result in subset_results
            if result.label_phase in reported_phases
            and result.matched
            and result.auto_pick_id is not None
        }
        combined = subset_summary["P_S_combined"]
        combined["n_eligible_auto_picks"] = int(n_eligible_combined)
        combined["n_unique_auto_picks_matched_within_tp_tol"] = len(
            combined_matched_ids
        )
        combined["pick_matched_fraction"] = (
            len(combined_matched_ids) / n_eligible_combined
            if n_eligible_combined
            else None
        )


def merge_reference_windows(
    reference_times: Sequence[float], window_half_width_s: float
) -> List[Tuple[float, float]]:
    """Return the disjoint union of reference-centred time windows."""
    half_width = float(window_half_width_s)
    if half_width <= 0.0:
        raise ValueError("window_half_width_s must be positive")
    intervals: List[Tuple[float, float]] = []
    for value in sorted(float(item) for item in reference_times):
        left, right = value - half_width, value + half_width
        if intervals and left <= intervals[-1][1]:
            intervals[-1] = (intervals[-1][0], max(intervals[-1][1], right))
        else:
            intervals.append((left, right))
    return intervals


def _auto_rows_in_windows(
    conn: sqlite3.Connection,
    station_id: str,
    auto_phases: Sequence[str],
    intervals: Sequence[Tuple[float, float]],
    min_prob: Optional[float],
) -> List[Tuple[int, float]]:
    if not intervals:
        return []
    placeholders = ",".join("?" for _ in auto_phases)
    params: List[Any] = [
        station_id,
        *auto_phases,
        int(math.floor(intervals[0][0])),
        int(math.floor(intervals[-1][1])),
    ]
    prob_clause = ""
    if min_prob is not None:
        prob_clause = " AND phase_prob >= ?"
        params.append(float(min_prob))
    rows = conn.execute(
        f"""
        SELECT id, time_epoch
        FROM auto_picks
        WHERE station_id = ?
          AND phase_name IN ({placeholders})
          AND sec_key BETWEEN ? AND ?
          {prob_clause}
        ORDER BY time_epoch, id
        """,
        params,
    )
    selected: List[Tuple[int, float]] = []
    interval_idx = 0
    for pick_id, time_epoch in rows:
        value = float(time_epoch)
        while interval_idx < len(intervals) and value > intervals[interval_idx][1]:
            interval_idx += 1
        if interval_idx >= len(intervals):
            break
        if intervals[interval_idx][0] <= value <= intervals[interval_idx][1]:
            selected.append((int(pick_id), value))
    return selected


@dataclass(frozen=True)
class WorkflowEligibility:
    source: str
    output_id: int
    output_name: str
    intervals: Dict[Tuple[str, str], List[Tuple[float, float]]]
    starts: Dict[Tuple[str, str], List[float]]

    def eligible_intervals(self, station_id: str, phase: str) -> List[Tuple[float, float]]:
        return self.intervals.get((norm_station_id(station_id), phase), [])

    def contains(self, station_id: str, phase: str, time_epoch: float) -> bool:
        key = (norm_station_id(station_id), phase)
        intervals = self.intervals.get(key, [])
        starts = self.starts.get(key, [])
        index = bisect.bisect_right(starts, float(time_epoch)) - 1
        return index >= 0 and intervals[index][1] >= float(time_epoch)


def _merge_intervals(
    intervals: Sequence[Tuple[float, float]],
) -> List[Tuple[float, float]]:
    merged: List[Tuple[float, float]] = []
    for left, right in sorted((float(a), float(b)) for a, b in intervals):
        if right < left:
            raise ValueError(f"invalid interval: {left} > {right}")
        if merged and left <= merged[-1][1] + 1.0e-6:
            merged[-1] = (merged[-1][0], max(merged[-1][1], right))
        else:
            merged.append((left, right))
    return merged


def intersect_intervals(
    left_intervals: Sequence[Tuple[float, float]],
    right_intervals: Sequence[Tuple[float, float]],
) -> List[Tuple[float, float]]:
    """Return the disjoint intersection of two sorted interval unions."""
    result: List[Tuple[float, float]] = []
    left_index = right_index = 0
    while left_index < len(left_intervals) and right_index < len(right_intervals):
        left = max(left_intervals[left_index][0], right_intervals[right_index][0])
        right = min(left_intervals[left_index][1], right_intervals[right_index][1])
        if left <= right:
            result.append((left, right))
        if left_intervals[left_index][1] <= right_intervals[right_index][1]:
            left_index += 1
        else:
            right_index += 1
    return _merge_intervals(result) if result else []


def load_workflow_eligibility(
    path: Path,
    output_id: Optional[int] = None,
    output_name: Optional[str] = None,
) -> WorkflowEligibility:
    """Load one workflow's valid station-time and phase processing domain."""
    if (output_id is None) == (output_name is None):
        raise ValueError("Specify exactly one of output_id or output_name")
    source = Path(path).expanduser().resolve()
    if not source.exists():
        raise FileNotFoundError(f"Output eligibility DB not found: {source}")
    con = sqlite3.connect(str(source))
    if output_id is not None:
        row = con.execute(
            "SELECT output_id, output_name FROM outputs WHERE output_id=?",
            (int(output_id),),
        ).fetchone()
    else:
        row = con.execute(
            "SELECT output_id, output_name FROM outputs WHERE output_name=?",
            (str(output_name),),
        ).fetchone()
    if row is None:
        con.close()
        raise KeyError(f"Output is absent from eligibility DB: {output_id or output_name}")
    selected_id, selected_name = int(row[0]), str(row[1])
    grouped: Dict[Tuple[str, str], List[Tuple[float, float]]] = defaultdict(list)
    rows = con.execute(
        """
        SELECT station_id, processed_start_us, processed_end_us, phase_mask
        FROM eligibility_intervals
        WHERE output_id=? AND valid_input=1
        ORDER BY station_id, processed_start_us, processed_end_us
        """,
        (selected_id,),
    )
    for station_id, start_us, end_us, phase_mask in rows:
        interval = (int(start_us) / 1_000_000, int(end_us) / 1_000_000)
        if int(phase_mask) & 1:
            grouped[(norm_station_id(str(station_id)), "P")].append(interval)
        if int(phase_mask) & 2:
            grouped[(norm_station_id(str(station_id)), "S")].append(interval)
    con.close()
    intervals = {key: _merge_intervals(values) for key, values in grouped.items()}
    starts = {key: [left for left, _ in values] for key, values in intervals.items()}
    return WorkflowEligibility(
        source=str(source),
        output_id=selected_id,
        output_name=selected_name,
        intervals=intervals,
        starts=starts,
    )


def compute_reference_window_match_fraction(
    conn: sqlite3.Connection,
    indexed_labels: Sequence[Tuple[int, LabelPick]],
    coverage_cache: Dict[int, Optional[bool]],
    phase_map: Dict[str, List[str]],
    window_half_width_s: float,
    tp_tolerance_s: float,
    eligibility: WorkflowEligibility,
    coverage_level: str,
    min_prob: Optional[float] = None,
) -> Dict[str, Any]:
    """Calculate a catalogue-conditioned reference-window match fraction.

    Automatic picks are counted once in the union of +/-T windows around manual
    references, intersected with the assessed workflow's valid processing domain
    for each exact station-location and normalized phase. The numerator uses
    deterministic one-to-one matches within epsilon. Catalogue-unmatched picks
    are not confirmed false detections.
    """
    window_s = float(window_half_width_s)
    epsilon_s = float(tp_tolerance_s)
    if epsilon_s <= 0.0:
        raise ValueError("tp_tolerance_s must be positive")
    if window_s < epsilon_s:
        raise ValueError("window_half_width_s must be at least tp_tolerance_s")

    coverage_applied = any(value is not None for value in coverage_cache.values())
    if not coverage_applied:
        raise ValueError(
            "Reference-window reporting requires a declared C0-C3 coverage level"
        )
    references = [
        (idx, label)
        for idx, label in indexed_labels
        if label.status == "manual"
        and label.label_phase in phase_map
        and (not coverage_applied or coverage_cache.get(idx) is True)
    ]
    grouped: Dict[Tuple[str, str], List[LabelPick]] = defaultdict(list)
    for _, label in references:
        grouped[(label.station_id, label.label_phase)].append(label)

    by_phase: Dict[str, Dict[str, Any]] = {
        phase: {
            "n_coverage_qualified_manual_references": 0,
            "n_workflow_eligible_manual_references": 0,
            "n_merged_reference_windows": 0,
            "n_effective_processed_windows": 0,
            "reference_window_union_s": 0.0,
            "effective_processed_window_s": 0.0,
            "n_reported_picks_in_effective_windows": 0,
            "n_matched_one_to_one": 0,
        }
        for phase in phase_map
    }
    for (station_id, phase), group in sorted(grouped.items()):
        group = sorted(group, key=lambda item: item.label_time_epoch)
        target = by_phase[phase]
        target["n_coverage_qualified_manual_references"] += len(group)
        eligible_group = [
            label
            for label in group
            if eligibility.contains(station_id, phase, label.label_time_epoch)
        ]
        target["n_workflow_eligible_manual_references"] += len(eligible_group)
        if not eligible_group:
            continue
        reference_intervals = merge_reference_windows(
            [label.label_time_epoch for label in eligible_group], window_s
        )
        effective_intervals = intersect_intervals(
            reference_intervals,
            eligibility.eligible_intervals(station_id, phase),
        )
        if not effective_intervals:
            continue
        auto_rows = _auto_rows_in_windows(
            conn, station_id, phase_map[phase], effective_intervals, min_prob
        )
        assignments = match_labels_one_to_one(
            conn,
            eligible_group,
            phase_map[phase],
            search_window_s=window_s,
            min_prob=min_prob,
            tp_tolerance_s=epsilon_s,
            allowed_intervals=effective_intervals,
        )
        matched_ids = {
            candidate.auto_pick_id
            for candidate in assignments.values()
            if abs(candidate.residual_s) <= epsilon_s
        }
        selected_ids = {pick_id for pick_id, _ in auto_rows}
        if not matched_ids.issubset(selected_ids):
            raise RuntimeError("matched automatic pick lies outside merged windows")
        target["n_merged_reference_windows"] += len(reference_intervals)
        target["n_effective_processed_windows"] += len(effective_intervals)
        target["reference_window_union_s"] += sum(
            right - left for left, right in reference_intervals
        )
        target["effective_processed_window_s"] += sum(
            right - left for left, right in effective_intervals
        )
        target["n_reported_picks_in_effective_windows"] += len(auto_rows)
        target["n_matched_one_to_one"] += len(matched_ids)

    for values in by_phase.values():
        reported = int(values["n_reported_picks_in_effective_windows"])
        matched = int(values["n_matched_one_to_one"])
        references_count = int(values["n_workflow_eligible_manual_references"])
        values["reference_window_union_s"] = round(
            float(values["reference_window_union_s"]), 6
        )
        values["effective_processed_window_s"] = round(
            float(values["effective_processed_window_s"]), 6
        )
        values["n_catalogue_unmatched_in_effective_windows"] = reported - matched
        values["reference_window_match_fraction"] = (
            matched / reported if reported else None
        )
        values["reference_recovery_fraction"] = (
            matched / references_count if references_count else None
        )

    auto_phase_owners: Dict[str, List[str]] = defaultdict(list)
    for phase, auto_phases in phase_map.items():
        for auto_phase in auto_phases:
            auto_phase_owners[auto_phase].append(phase)
    overlaps = {
        phase: owners
        for phase, owners in auto_phase_owners.items()
        if len(owners) > 1
    }
    combined = None
    if not overlaps:
        combined = {}
        for field in (
            "n_coverage_qualified_manual_references",
            "n_workflow_eligible_manual_references",
            "n_merged_reference_windows",
            "n_effective_processed_windows",
            "reference_window_union_s",
            "effective_processed_window_s",
            "n_reported_picks_in_effective_windows",
            "n_matched_one_to_one",
            "n_catalogue_unmatched_in_effective_windows",
        ):
            combined[field] = sum(values[field] for values in by_phase.values())
        reported = int(combined["n_reported_picks_in_effective_windows"])
        matched = int(combined["n_matched_one_to_one"])
        references_count = int(combined["n_workflow_eligible_manual_references"])
        combined["reference_window_match_fraction"] = (
            matched / reported if reported else None
        )
        combined["reference_recovery_fraction"] = (
            matched / references_count if references_count else None
        )

    return {
        "window_half_width_s": window_s,
        "matching_tolerance_epsilon_s": epsilon_s,
        "reference_subset": f"{coverage_level}-covered manual arrivals",
        "coverage_level": str(coverage_level).upper(),
        "workflow_eligibility": {
            "source": eligibility.source,
            "output_id": eligibility.output_id,
            "output_name": eligibility.output_name,
            "valid_input_required": True,
        },
        "probability_filter": {"min_prob": min_prob},
        "window_definition": (
            "union of closed +/-T windows around workflow-eligible, coverage-"
            "qualified manual references by exact station-location and normalized "
            "phase; overlaps are merged and intersected with the workflow's "
            "valid processing intervals"
        ),
        "interpretation": (
            "catalogue-conditioned reference-window output match fraction; a "
            "precision-oriented diagnostic, not an estimator of conventional "
            "full-stream precision; catalogue-unmatched picks are not confirmed "
            "false detections"
        ),
        "by_phase": by_phase,
        "combined": combined,
        "combined_omitted_for_overlapping_phase_map": overlaps,
    }


def summarize_results(
    results: List[MatchResult],
    label_counter: Counter,
    label_status_counter: Counter,
    tp_tol: float,
    err_window: float,
) -> Dict[str, Any]:
    summary: Dict[str, Any] = {
        "tp_tolerance_s": tp_tol,
        "residual_window_s": err_window,
        "label_phase_count_all_status": dict(label_counter),
        "label_phase_count_by_status": {f"{k[0]}:{k[1]}": v for k, v in label_status_counter.items()},
        "subsets": {},
    }

    for subset in sorted({r.subset for r in results}):
        subset_results = [r for r in results if r.subset == subset]
        phases = sorted({r.label_phase for r in subset_results})
        subset_summary: Dict[str, Any] = {}
        for ph in phases:
            ph_results = [r for r in subset_results if r.label_phase == ph]
            n_label = len(ph_results)
            n_tp = sum(1 for r in ph_results if r.matched)
            residuals = np.array([r.residual_s for r in ph_results if r.residual_s is not None and abs(r.residual_s) <= err_window], dtype=float)
            tp_residuals = np.array([r.residual_s for r in ph_results if r.matched and r.residual_s is not None], dtype=float)

            # Waveform-coverage-corrected recall: denominator is only labels that
            # have waveform data available (has_waveform=True). Labels where
            # has_waveform is None (waveform_db not supplied) are excluded from
            # the covered subset so the field stays None rather than 0/1.
            cov_results = [r for r in ph_results if r.has_waveform is True]
            n_label_cov = len(cov_results)
            n_tp_cov = sum(1 for r in cov_results if r.matched)
            # Distinguish "waveform_db not used" (all None) from "used but 0 covered"
            use_cov = any(r.has_waveform is not None for r in ph_results)

            phase_summary = {
                "n_label": int(n_label),
                "n_matched_within_tp_tol": int(n_tp),
                "recall": float(n_tp / n_label) if n_label else None,
                # Coverage-corrected metrics (only present when --waveform-db is used)
                "n_label_with_waveform": int(n_label_cov) if use_cov else None,
                "n_tp_with_waveform": int(n_tp_cov) if use_cov else None,
                "recall_covered": float(n_tp_cov / n_label_cov) if (use_cov and n_label_cov) else None,
                "n_residual_within_err_window": int(residuals.size),
                "residual_mean_s": float(np.mean(residuals)) if residuals.size else None,
                "residual_std_s": float(np.std(residuals, ddof=1)) if residuals.size > 1 else None,
                "residual_median_s": float(np.median(residuals)) if residuals.size else None,
                "residual_abs_p90_s": float(np.percentile(np.abs(residuals), 90)) if residuals.size else None,
                "residual_abs_p95_s": float(np.percentile(np.abs(residuals), 95)) if residuals.size else None,
                "tp_residual_std_s": float(np.std(tp_residuals, ddof=1)) if tp_residuals.size > 1 else None,
                "gaussian_fit_all_within_err_window": fit_gaussian(residuals),
                "student_t_fit_all_within_err_window": fit_student_t(residuals),
            }
            subset_summary[ph] = phase_summary

        # Combined P+S / Pg+Sg style summary
        n_label_all = len(subset_results)
        n_tp_all = sum(1 for r in subset_results if r.matched)
        cov_all = [r for r in subset_results if r.has_waveform is True]
        n_label_cov_all = len(cov_all)
        n_tp_cov_all = sum(1 for r in cov_all if r.matched)
        use_cov_all = any(r.has_waveform is not None for r in subset_results)
        subset_summary["P_S_combined"] = {
            "n_label": int(n_label_all),
            "n_matched_within_tp_tol": int(n_tp_all),
            "recall": float(n_tp_all / n_label_all) if n_label_all else None,
            "n_label_with_waveform": int(n_label_cov_all) if use_cov_all else None,
            "n_tp_with_waveform": int(n_tp_cov_all) if use_cov_all else None,
            "recall_covered": float(n_tp_cov_all / n_label_cov_all) if (use_cov_all and n_label_cov_all) else None,
        }
        summary["subsets"][subset] = subset_summary
    return summary


def write_outputs(results: List[MatchResult], summary: Dict[str, Any], outdir: Path) -> None:
    with (outdir / "summary.json").open("w", encoding="utf-8") as f:
        json.dump(summary, f, ensure_ascii=False, indent=2)

    with (outdir / "matches.jsonl").open("w", encoding="utf-8") as f:
        for r in results:
            f.write(json.dumps(r.__dict__, ensure_ascii=False) + "\n")

    with (outdir / "summary.tsv").open("w", encoding="utf-8") as f:
        f.write("subset\tphase\tn_label\tn_tp\trecall\tn_label_with_waveform\tn_tp_with_waveform\trecall_covered\tn_eligible_auto_picks\tn_unique_auto_picks_matched\tpick_matched_fraction\tn_residual\tmean_s\tstd_s\tmedian_s\tabs_p90_s\tabs_p95_s\tgauss_mean\tgauss_std_mle\tgauss_std_unbiased\tt_df\tt_loc\tt_scale\n")
        for subset, ss in summary["subsets"].items():
            for phase, d in ss.items():
                if phase == "P_S_combined":
                    continue
                gfit = d.get("gaussian_fit_all_within_err_window", {}) or {}
                tfit = d.get("student_t_fit_all_within_err_window", {}) or {}
                f.write("\t".join([
                    subset, phase,
                    str(d.get("n_label")), str(d.get("n_matched_within_tp_tol")), str(d.get("recall")),
                    str(d.get("n_label_with_waveform")), str(d.get("n_tp_with_waveform")), str(d.get("recall_covered")),
                    str(d.get("n_eligible_auto_picks")),
                    str(d.get("n_unique_auto_picks_matched_within_tp_tol")),
                    str(d.get("pick_matched_fraction")),
                    str(d.get("n_residual_within_err_window")), str(d.get("residual_mean_s")),
                    str(d.get("residual_std_s")), str(d.get("residual_median_s")),
                    str(d.get("residual_abs_p90_s")), str(d.get("residual_abs_p95_s")),
                    str(gfit.get("mean")), str(gfit.get("std_mle")), str(gfit.get("std_unbiased")),
                    str(tfit.get("df")), str(tfit.get("loc")), str(tfit.get("scale")),
                ]) + "\n")


def load_matches(path: Path) -> List[Dict[str, Any]]:
    rows = []
    with path.open("r", encoding="utf-8") as f:
        for line in f:
            if line.strip():
                rows.append(json.loads(line))
    return rows


def plot_results(outdir: Path) -> None:
    import matplotlib.pyplot as plt

    matches_path = outdir / "matches.jsonl"
    if not matches_path.exists():
        print(f"[PLOT] missing {matches_path}", file=sys.stderr)
        return
    rows = load_matches(matches_path)
    plot_dir = outdir / "figures"
    plot_dir.mkdir(parents=True, exist_ok=True)

    # Residual distribution by subset and phase
    for subset in sorted({r["subset"] for r in rows}):
        for phase in sorted({r["label_phase"] for r in rows if r["subset"] == subset}):
            vals = np.array([
                r["residual_s"] for r in rows
                if r["subset"] == subset and r["label_phase"] == phase and r.get("residual_s") is not None
            ], dtype=float)
            if vals.size == 0:
                continue
            vals = vals[np.isfinite(vals)]
            if vals.size == 0:
                continue

            fig = plt.figure(figsize=(7.5, 4.8))
            plt.hist(vals, bins=100, density=True, alpha=0.55, label=f"Residuals (n={vals.size:,})")

            x_min, x_max = float(np.min(vals)), float(np.max(vals))
            if x_min == x_max:
                x_min -= 1.0
                x_max += 1.0
            x = np.linspace(x_min, x_max, 800)

            mu = float(np.mean(vals))
            sigma = float(np.std(vals, ddof=0)) if vals.size > 1 else 0.0
            if scipy_stats is not None and sigma > 0:
                gauss_pdf = scipy_stats.norm.pdf(x, loc=mu, scale=sigma)
                plt.plot(x, gauss_pdf, linewidth=2, label=f"Gaussian μ={mu:.3f}, σ={sigma:.3f}")

                if vals.size >= 3:
                    try:
                        df, loc, scale = scipy_stats.t.fit(vals)
                        if scale > 0:
                            t_pdf = scipy_stats.t.pdf(x, df, loc=loc, scale=scale)
                            plt.plot(x, t_pdf, linewidth=2, label=f"Student-t df={df:.2f}, loc={loc:.3f}, scale={scale:.3f}")
                    except Exception as exc:
                        print(f"[PLOT] Student-t fit failed for {subset}/{phase}: {exc}", file=sys.stderr)
            else:
                plt.text(
                    0.02, 0.95,
                    "Install scipy to overlay Gaussian/Student-t PDFs",
                    transform=plt.gca().transAxes,
                    va="top",
                )

            plt.axvline(0.0, linestyle="--", linewidth=1)
            plt.xlabel("Residual time: automatic - label (s)")
            plt.ylabel("Probability density")
            plt.title(f"Residual distribution with fits: {subset}, {phase}")
            plt.legend(fontsize=8)
            plt.tight_layout()
            fig.savefig(plot_dir / f"residual_fit_{subset}_{phase}.png", dpi=220)
            plt.close(fig)

    # Recall bar chart
    summary = json.loads((outdir / "summary.json").read_text(encoding="utf-8"))
    labels, vals = [], []
    for subset, ss in summary["subsets"].items():
        for phase, d in ss.items():
            if phase == "P_S_combined":
                continue
            if d.get("recall") is not None:
                labels.append(f"{subset}-{phase}")
                vals.append(d["recall"])
    if labels:
        fig = plt.figure(figsize=(max(7, 0.8 * len(labels)), 4.5))
        plt.bar(labels, vals)
        plt.ylim(0, 1)
        plt.ylabel("Recall")
        plt.title("Phase-pick recall")
        plt.xticks(rotation=45, ha="right")
        plt.tight_layout()
        fig.savefig(plot_dir / "recall_bar.png", dpi=200)
        plt.close(fig)


    # Automatic pick counts by original automatic phase
    auto_counts = summary.get("auto_pick_count", {}).get("by_auto_phase", {})
    if auto_counts:
        phases = list(auto_counts.keys())
        counts = [auto_counts[p] for p in phases]
        fig = plt.figure(figsize=(max(7, 0.8 * len(phases)), 4.5))
        plt.bar(phases, counts)
        plt.ylabel("Number of automatic picks")
        plt.title("Automatic pick counts by phase")
        plt.xticks(rotation=45, ha="right")
        plt.tight_layout()
        fig.savefig(plot_dir / "auto_pick_count_bar.png", dpi=220)
        plt.close(fig)
    print(f"[PLOT] saved figures to {plot_dir}")


# -----------------------------
# Optional utilities
# -----------------------------

def print_db_info(db_path: Path) -> None:
    db_path = Path(db_path).expanduser().resolve()
    if not db_path.exists():
        raise FileNotFoundError(f"SQLite index DB not found: {db_path}")
    conn = connect_db(db_path)
    n = conn.execute("SELECT COUNT(*) FROM auto_picks").fetchone()[0]
    print(f"auto_picks: {n:,}")
    print("phase counts:")
    for ph, c in conn.execute("SELECT phase_name, COUNT(*) FROM auto_picks GROUP BY phase_name ORDER BY COUNT(*) DESC"):
        print(f"  {ph}: {c:,}")
    conn.close()


# -----------------------------
# CLI
# -----------------------------

def main() -> None:
    parser = argparse.ArgumentParser(description="Evaluate automatic phase picks against continuous-HDF5 annotation JSON.")
    parser.add_argument("--auto-jsonl", type=Path, default=Path("data/picks/skynet.phase.jsonl"))
    parser.add_argument("--label-json", type=Path, default=Path("data/label/annotations_for_continuous_hdf5.json"))
    parser.add_argument("--index-db", type=Path, default=Path("~/skynet.pick.index.sqlite"))
    parser.add_argument("--outdir", type=Path, default=Path("eval_skynet"))
    parser.add_argument("--build-index", action="store_true", help="Build or update SQLite index from auto JSONL.")
    parser.add_argument("--drop-existing", action="store_true", help="Drop existing index table before rebuilding.")
    parser.add_argument("--keep-raw-json", action="store_true", help="Store raw JSON in SQLite. Not recommended for 40GB files.")
    parser.add_argument("--batch-size", type=int, default=50000)
    parser.add_argument("--tp-tol", type=float, default=1.5, help="TP tolerance in seconds.")
    parser.add_argument("--err-window", type=float, default=5.0, help="Window for residual distribution in seconds.")
    parser.add_argument(
        "--reference-window-s",
        type=float,
        action="append",
        default=[],
        help=(
            "Half-width T for a catalogue-conditioned reference-window output "
            "match fraction. Repeat for sensitivity analysis; each T must be "
            ">= --tp-tol and workflow eligibility must be supplied."
        ),
    )
    parser.add_argument("--min-prob", type=float, default=None, help="Optional minimum automatic pick probability.")
    parser.add_argument(
        "--phase-map", type=str, default=None,
        help="Override the default normalization 'P:P,Pg,Pn;S:S,Sg,Sn'.",
    )
    parser.add_argument("--waveform-db", type=Path, default=None,
                        help="Waveform coverage SQLite index (built by hdf5_waveform_index.py). "
                             "When supplied, each label is checked against exact NSLC segment intervals.")
    parser.add_argument(
        "--reference-db",
        type=Path,
        default=None,
        help=(
            "Versioned reference-arrival SQLite table containing precomputed "
            "C0-C3 flags. This avoids reopening HDF5 files and is mutually "
            "exclusive with --waveform-db."
        ),
    )
    parser.add_argument(
        "--coverage-level",
        choices=tuple(REFERENCE_COVERAGE_FIELDS),
        default="C0",
        help="Coverage configuration used for recall and reference-window reporting.",
    )
    parser.add_argument(
        "--output-eligibility-db",
        type=Path,
        default=None,
        help="SQLite station-time processing domain for the assessed workflow.",
    )
    output_selector = parser.add_mutually_exclusive_group()
    output_selector.add_argument("--output-id", type=int, default=None)
    output_selector.add_argument("--output-name", default=None)
    parser.add_argument(
        "--coverage-channel-families",
        default="HH,BH,EH,HN",
        help="Comma-separated seismic channel families used for point coverage.",
    )
    parser.add_argument(
        "--skip-finite-sample-check",
        action="store_true",
        help=(
            "Use indexed NSLC intervals without opening HDF5 samples. This is "
            "appropriate for download planning only, not coverage-qualified reporting."
        ),
    )
    parser.add_argument("--plot", action="store_true", help="Generate figures after evaluation.")
    parser.add_argument("--db-info", action="store_true", help="Only print index database info.")
    args = parser.parse_args()
    if any(value < args.tp_tol for value in args.reference_window_s):
        parser.error("every --reference-window-s value must be >= --tp-tol")
    if args.reference_window_s:
        if args.reference_db is None:
            parser.error("--reference-window-s requires --reference-db")
        if args.output_eligibility_db is None:
            parser.error("--reference-window-s requires --output-eligibility-db")
        if (args.output_id is None) == (args.output_name is None):
            parser.error(
                "--reference-window-s requires exactly one of --output-id or --output-name"
            )
    if not args.label_json.exists():
        mini_label = Path("data/label/annotations_mini_two_hours.json")
        if mini_label.exists():
            args.label_json = mini_label
    if not args.auto_jsonl.exists():
        mini_auto = Path("data/picks/pnsn_v3_diff.mini.phase.jsonl")
        if mini_auto.exists():
            args.auto_jsonl = mini_auto

    if args.build_index:
        build_auto_pick_index(
            args.auto_jsonl, args.index_db,
            batch_size=args.batch_size,
            drop_existing=args.drop_existing,
            keep_raw_json=args.keep_raw_json,
        )

    if args.db_info:
        print_db_info(args.index_db)
        return

    phase_map = parse_phase_map(args.phase_map)
    coverage_channel_families = tuple(
        value.strip().upper()
        for value in args.coverage_channel_families.split(",")
        if value.strip()
    )
    results, summary = evaluate(
        label_json=args.label_json,
        db_path=args.index_db,
        outdir=args.outdir,
        phase_map=phase_map,
        tp_tol=args.tp_tol,
        err_window=args.err_window,
        min_prob=args.min_prob,
        waveform_db=args.waveform_db,
        reference_db=args.reference_db,
        automatic_pick_source=args.auto_jsonl,
        coverage_channel_families=coverage_channel_families,
        validate_finite_samples=not args.skip_finite_sample_check,
        coverage_level=args.coverage_level,
        reference_windows_s=args.reference_window_s,
        output_eligibility_db=args.output_eligibility_db,
        output_id=args.output_id,
        output_name=args.output_name,
    )
    print(json.dumps(summary, ensure_ascii=False, indent=2))

    if args.plot:
        plot_results(args.outdir)


if __name__ == "__main__":
    main()