File size: 133,677 Bytes
a8e0542
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
"""Run dataset layer modules over the latband5km-v1 grid and upload them to the Hub as they finish.

Usage (from the repository root):

    python -m pipeline.layers.driver <slug>[,<slug>...] --planet mars|earth [--bands START-END]
        [--resume] [--workers N] [--cache-max-gb G] [--retries R] [--dry-run] [--no-upload] [--out DIR]
    python -m pipeline.layers.driver <slug> --planet mars|earth --publish [--dry-run]

Layer module interface (``pipeline/layers/<slug>.py``)
------------------------------------------------------

``SOURCE``      dict: ``product``, ``version``, ``url``, ``licence``, ``planet`` (``mars`` | ``earth`` |
                ``both``) and optionally ``aux``, a list of further source dicts.
``COLUMNS``     dict: feature column -> ``{'dtype', 'unit', 'description', 'comparison', 'fill'}``.
                ``dtype`` defaults to ``float32``; ``comparison`` is one of :data:`COMPARISON_MODES`;
                ``fill`` is the value given to cells with no data (default NaN / null), for example
                ``0.0`` for a ``valid_frac`` column. The driver needs it to write rows for cells the
                layer has no data for, and ``--publish`` needs units and comparison modes.
``plan(band_group, ctx)``    -> list of source items. An item is an :class:`Item`, a dict of
                :class:`Item` fields, or a URL string. ``[]`` means "no source data": every cell gets
                the fill values and the missing flag, and ``reduce`` is not called.
``reduce(band_group, items, ctx)`` -> ``pyarrow.Table`` keyed by ``region_id`` holding feature
                columns (and optionally ``quality_flags``) only. ``items`` is an :class:`Items`
                view: iterate it to stream items through the cache (each item is fetched when
                reached and deleted when the loop moves on), or use ``items.get(key)`` /
                ``items.release(key)`` / ``items.all()`` for random access. Cells missing from the
                table get the fill values and the missing flag.

Asset catalog (optional, see ``docs/asset_catalog.md`` and ``pipeline/catalog/``):

* An item from ``plan()`` may carry ``asset={...}`` (uri, footprint, geotransform, time range, ...).
  The driver turns those into ``assets`` rows.
* ``reduce()`` may return ``(feature_table, coverage_table)``, the second holding ``region_id``,
  ``asset_id``, ``coverage_frac``. Without it the driver computes ``coverage_frac`` from the item
  footprints and the grid, vectorised per band group (items with ``link_regions=False`` or
  ``covers_planet=True`` get no ``region_assets`` rows).
* Per band group the same commit carries ``catalog/region_assets/planet=<p>/layer=<slug>/band_group=NNN.parquet``
  and ``catalog/assets_staging/...`` (that group's assets rows); ``--publish`` merges the staging files
  into ``catalog/assets/planet=<p>/layer=<slug>.parquet`` (deduplicated by ``asset_id``).

Optional:

``prepare(ctx)``     one-time work before band groups run: small downloads into ``ctx.raw_dir``
                     (``data/raw/<planet>/<slug>/``, see ``ctx.download``) or streaming global
                     sources into ``ctx.interim_dir`` (``data/interim/<planet>/<slug>/``, capped by
                     ``--interim-max-gb``, never uploaded, deleted after a successful publish).
``finalize(ctx)``    whole-planet post-pass. Reads band groups with ``ctx.read_layer(g, columns)``
                     over ``ctx.band_groups`` and writes extra column sets with
                     ``ctx.write_extra(name, g, table)``; each name must be declared in
                     ``EXTRA_COLUMNS = {name: COLUMNS-style dict}``.
``PASS_GROUP``       name shared by layers that read the same expensive source. Layers named
                     together on the command line with the same PASS_GROUP run in one pass: each
                     item is fetched once and handed to every layer that planned it.
``MISSING_FLAG``     quality flag for cells with no data: a string (default ``no_source``) or
                     ``callable(band_group, missing_cells_table, ctx) -> list[str]`` (e.g. to say
                     ``ocean`` using :func:`earth_land_frac`).
``VERSION``          default ``v0.1``; the layer version is ``<slug>-<VERSION>``.
``CROSSWALKS``       file names (next to the module) hashed into code_version and uploaded on publish.
``LIMITATIONS``      list of strings for the manifest and the dataset card.
``validate(summary, ctx)`` -> list of ``(name, ok, detail)``: layer-specific publish checks.

What the driver guarantees
--------------------------

* One file per band group of 100 bands, holding exactly one row per grid cell of the group, in grid
  order, with the standard metadata columns (:data:`LEADING_COLUMNS`, :data:`TRAILING_COLUMNS`).
* The cache never holds more than ``--cache-max-gb``: every byte is charged before it is written,
  and the cache is wiped after each band group.
* A failed download is never turned into NaNs. Transient errors are retried with exponential
  backoff; after ``--retries`` attempts the band group stops and nothing is written for it. Only an
  item planned with ``required=False`` may be *absent* (HTTP 404), and the reduce sees that.
* Uploads are one Hub commit per band group per layer, holding the Parquet file and the updated
  progress file together, so a crash leaves either both or neither. The local file is deleted only
  after the remote copy is re-listed and its size and hash match.
* ``--resume`` skips a band group only when the progress file records it with the current
  code_version and the remote file matches the recorded size and hash.
"""
from __future__ import annotations

import argparse
import hashlib
import importlib
import importlib.util
import io
import json
import math
import os
import random
import re
import shutil
import socket
import sys
import tempfile
import threading
import time
import traceback
import urllib.error
import urllib.parse
import urllib.request
import http.client
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field, replace
from datetime import datetime, timezone
from functools import lru_cache
from pathlib import Path
from typing import Any, Callable

import numpy as np
import pyarrow as pa
import pyarrow.compute as pc
import pyarrow.parquet as pq

LAYERS_DIR = Path(__file__).resolve().parent
PIPELINE_DIR = LAYERS_DIR.parent
ROOT = PIPELINE_DIR.parent
DRIVER_PATH = Path(__file__).resolve()
if str(PIPELINE_DIR) not in sys.path:
    sys.path.insert(0, str(PIPELINE_DIR))

import terrain_features as tf  # noqa: E402
from catalog import assets as catalog_assets  # noqa: E402
from catalog import coverage as catalog_coverage  # noqa: E402
from catalog import schema as catalog_schema  # noqa: E402
from planetary_grid import PLANETS, VERSION as GRID_VERSION, PlanetBandGrid  # noqa: E402

REPO_ID = 'enzeeoai/starman'
REPO_TYPE = 'dataset'
BANDS_PER_GROUP = tf.BANDS_PER_GROUP
DEFAULT_VERSION = 'v0.1'
GB = 10 ** 9

TERRAIN_FEATURE_VERSION = 'terrain-v0.2'
# the terrain-v0.2 releases (docs/contracts.md); pinned so a layer reads the values it was built on
TERRAIN_REVISION = {'mars': 'terrain-mars-v0.3.0', 'earth': 'terrain-earth-v0.2.0'}
TERRAIN_LOCAL = {p: ROOT / 'data' / 'processed' / p / 'terrain' / TERRAIN_FEATURE_VERSION for p in PLANETS}

DEFAULT_OUT = ROOT / 'data' / 'processed' / 'layers'
DEFAULT_LOG_DIR = ROOT / 'logs' / 'layers'
RAW_ROOT = ROOT / 'data' / 'raw'
INTERIM_ROOT = ROOT / 'data' / 'interim'

LEADING_COLUMNS = ('grid_version', 'region_id', 'planet', 'band', 'column')
FLAGS_COLUMN = 'quality_flags'
TRAILING_COLUMNS = ('source_product', 'source_version', 'source_checksum', 'layer', 'layer_version',
                    'code_version', 'computed_at')
RESERVED_COLUMNS = frozenset(LEADING_COLUMNS) | frozenset(TRAILING_COLUMNS)
DEFAULT_MISSING_FLAG = 'no_source'

COMPARISON_MODES = {
    'absolute': 'same quantity and unit on both planets; compare values directly',
    'within_planet': 'only meaningful against the same planet (percentiles, ranks, z-scores)',
    'categorical': 'class codes; compare through a crosswalk, never numerically',
    'planet_specific': 'defined for one planet only; no cross-planet comparison',
}

METHODS = {'http', 'cog', 'earthaccess', 'api', 'local', 'none'}
METHOD_ALIASES = {'range': 'http', 'vsicurl': 'http', 'vsis3': 'http', 's3': 'http', 'https': 'http',
                  'provider': 'api'}

HTTP_TIMEOUT = 60
CHUNK = 1 << 20
BACKOFF_BASE = 2.0
BACKOFF_MAX = 60.0
WAIT_POLL = 0.5
CONFLICT_RETRIES = 8
EXTRA_FILES_PER_COMMIT = 20
USER_AGENT = 'starman-layers/0.1'
SLEEP = time.sleep          # tests replace this to make backoff instant


# --------------------------------------------------------------------------
# errors
# --------------------------------------------------------------------------

class LayerError(Exception):
    """A layer module broke the interface (bad plan, bad table, undeclared column...)."""


class FetchFailed(Exception):
    """An item could not be fetched. The band group stops; nothing is written for it."""


class ItemAbsent(Exception):
    """The source says the item does not exist (HTTP 404/410, missing file).

    Raise it from an ``api`` fetcher to report absence. Only ``required=False`` items may be absent.
    """


class CacheCapExceeded(Exception):
    """The fetch cache cannot hold what the layer needs at once under --cache-max-gb."""


class TransientError(Exception):
    """A retryable failure the driver detected itself (truncated body, checksum mismatch)."""


class UploadError(Exception):
    """The Hub copy does not match the local file after a commit."""


class _Aborted(Exception):
    """A speculative prefetch gave way because the cache had no room; not an error."""


# --------------------------------------------------------------------------
# small helpers
# --------------------------------------------------------------------------

def _now() -> str:
    return datetime.now(timezone.utc).isoformat(timespec='seconds')


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with open(path, 'rb') as f:
        for chunk in iter(lambda: f.read(CHUNK), b''):
            digest.update(chunk)
    return digest.hexdigest()


def git_blob_id(data: bytes) -> str:
    """The id git (and the Hub, for non-LFS files) gives a blob."""
    return hashlib.sha1(f'blob {len(data)}\0'.encode() + data).hexdigest()


def git_blob_id_file(path: Path) -> str:
    digest = hashlib.sha1(f'blob {Path(path).stat().st_size}\0'.encode())
    with open(path, 'rb') as f:
        for chunk in iter(lambda: f.read(CHUNK), b''):
            digest.update(chunk)
    return digest.hexdigest()


def du(path: Path) -> int:
    path = Path(path)
    if not path.exists():
        return 0
    if path.is_file():
        return path.stat().st_size
    total = 0
    for p in path.rglob('*'):
        try:
            if p.is_file():
                total += p.stat().st_size
        except FileNotFoundError:      # deleted while we walked
            pass
    return total


def human(n: float | None) -> str:
    if n is None:
        return 'n/a'
    for unit in ('B', 'KiB', 'MiB', 'GiB', 'TiB'):
        if abs(n) < 1024 or unit == 'TiB':
            return f'{n:.0f} {unit}' if unit == 'B' else f'{n:.1f} {unit}'
        n /= 1024
    return f'{n:.1f} TiB'


def _json_default(value):
    if isinstance(value, (np.integer,)):
        return int(value)
    if isinstance(value, (np.floating,)):
        return None if not math.isfinite(float(value)) else float(value)
    if isinstance(value, np.bool_):
        return bool(value)
    if isinstance(value, Path):
        return str(value)
    if isinstance(value, (set, frozenset, tuple)):
        return list(value)
    return str(value)


def _sanitize(obj):
    """JSON has no NaN: non-finite floats become null, recursively."""
    if isinstance(obj, float):
        return obj if math.isfinite(obj) else None
    if isinstance(obj, dict):
        return {k: _sanitize(v) for k, v in obj.items()}
    if isinstance(obj, (list, tuple)):
        return [_sanitize(v) for v in obj]
    return obj


def dumps(obj) -> str:
    return json.dumps(_sanitize(obj), indent=2, sort_keys=True, default=_json_default, allow_nan=False)


def _status_code(exc: BaseException) -> int | None:
    if isinstance(exc, urllib.error.HTTPError):
        return exc.code
    for holder in (exc, getattr(exc, 'response', None)):
        code = getattr(holder, 'status_code', None)
        if isinstance(code, int):
            return code
    return None


@lru_cache(maxsize=1)
def _transport_error_types() -> tuple:
    found = []
    for module_name in ('httpx2', 'httpx', 'requests'):
        try:
            module = importlib.import_module(module_name)
        except ImportError:
            continue
        for name in ('TransportError', 'ConnectionError', 'Timeout', 'TimeoutException'):
            cls = getattr(module, name, None)
            if isinstance(cls, type) and issubclass(cls, BaseException):
                found.append(cls)
    return tuple(found)


def is_transient(exc: BaseException) -> bool:
    """Network-shaped failures worth another attempt. 404s, 4xx and layer bugs are not."""
    if isinstance(exc, (ItemAbsent, LayerError, CacheCapExceeded, _Aborted, FetchFailed)):
        return False
    if isinstance(exc, TransientError):
        return True
    code = _status_code(exc)
    if code is not None:
        return code in (408, 425, 429) or code >= 500
    if isinstance(exc, (urllib.error.URLError, ConnectionError, TimeoutError, socket.timeout,
                        http.client.HTTPException)):
        return True
    return bool(_transport_error_types()) and isinstance(exc, _transport_error_types())


def with_retries(fn: Callable[[], Any], attempts: int, what: str,
                 on_retry: Callable[[int, BaseException, float], None] | None = None):
    """Call ``fn``; retry transient errors with exponential backoff, ``attempts`` tries in all."""
    attempts = max(1, int(attempts))
    for attempt in range(1, attempts + 1):
        try:
            return fn()
        except Exception as exc:
            if attempt >= attempts or not is_transient(exc):
                raise
            delay = min(BACKOFF_MAX, BACKOFF_BASE * 2 ** (attempt - 1)) * (1 + 0.25 * random.random())
            print(f'  retry {attempt}/{attempts - 1} {what}: {type(exc).__name__}: {exc} '
                  f'(waiting {delay:.1f}s)', file=sys.stderr, flush=True)
            if on_retry is not None:
                on_retry(attempt, exc, delay)
            SLEEP(delay)
    raise AssertionError('unreachable')


# --------------------------------------------------------------------------
# items
# --------------------------------------------------------------------------

@dataclass
class Item:
    """One source item a band group needs: a tile, granule, file, byte range or raster window.

    ``key``       unique id, also the dedupe key across layers of one PASS_GROUP.
    ``url``       http(s)://, file://, s3://bucket/key, /vsis3/bucket/key, /vsicurl/<url>, or a local
                  path. ``None`` with method ``none`` for a purely virtual item (data in ``meta``).
    ``method``    inferred from the URL; set ``cog`` for a raster window (``meta['window'] =
                  (col_off, row_off, width, height)``, optional ``meta['band']``), ``earthaccess``
                  for a NASA Earthdata granule, ``api`` with ``fetch`` for a provider API.
    ``size``      expected bytes. Known sizes let items download in parallel inside the cap.
    ``range``     inclusive byte range (start, end) for an HTTP range request.
    ``required``  False only when the item may legitimately not exist (404 -> absent). A failed
                  download stops the band group either way.
    ``checksum``  expected SHA-256 (hex, optionally ``sha256:`` prefixed), verified after download.
    ``fetch``     ``fetch(item, out)`` for method ``api``: write bytes with ``out.write`` (each byte is
                  charged to the cache cap) or save files into ``out.dir`` and call
                  ``out.adopt(path)``; raise :class:`ItemAbsent` for a missing item.
    ``asset``     optional catalog metadata (uri, footprint, geotransform, time range, ...; see
                  ``catalog/assets.py``). Items that carry it become ``assets`` rows.
    """
    key: str
    url: str | None = None
    method: str | None = None
    size: int | None = None
    range: tuple[int, int] | None = None
    required: bool = True
    checksum: str | None = None
    headers: dict = field(default_factory=dict)
    fetch: Callable | None = None
    meta: dict = field(default_factory=dict)
    asset: dict | None = None

    def resolved_method(self) -> str:
        if self.method:
            return METHOD_ALIASES.get(self.method, self.method)
        if self.fetch is not None:
            return 'api'
        if self.url is None:
            return 'none'
        if self.url.startswith(('http://', 'https://', 'file://', 's3://', '/vsis3/', '/vsicurl/')):
            return 'http'
        return 'local'

    def expected_size(self) -> int | None:
        if self.size is not None:
            return int(self.size)
        if self.range is not None:
            return int(self.range[1]) - int(self.range[0]) + 1
        return None

    def source_id(self) -> tuple:
        return (self.resolved_method(), self.url, tuple(self.range) if self.range else None)

    def describe(self) -> dict:
        out = {'key': self.key, 'url': self.url, 'method': self.resolved_method(),
               'size': self.size, 'range': list(self.range) if self.range else None,
               'checksum': self.checksum}
        for name in ('etag', 'version', 'modified'):
            if name in self.meta:
                out[name] = str(self.meta[name])
        return out


@dataclass
class Fetched:
    """An item as the reduce sees it. ``path`` is None for absent and virtual items."""
    item: Item
    path: Path | None
    absent: bool = False
    nbytes: int = 0

    @property
    def key(self) -> str:
        return self.item.key

    @property
    def meta(self) -> dict:
        return self.item.meta

    def array(self) -> np.ndarray:
        """The window a ``cog`` item read, as saved by the driver."""
        if self.path is None:
            raise LayerError(f'{self.key}: no data (absent or virtual item)')
        return np.load(self.path, allow_pickle=False)

    def read_bytes(self) -> bytes:
        if self.path is None:
            raise LayerError(f'{self.key}: no data (absent or virtual item)')
        return Path(self.path).read_bytes()


def normalize_items(planned, slug: str) -> list[Item]:
    if planned is None:
        raise LayerError(f'{slug}.plan returned None; return [] for "no source data"')
    items = []
    for raw in planned:
        if isinstance(raw, Item):
            item = raw
        elif isinstance(raw, dict):
            try:
                item = Item(**raw)
            except TypeError as exc:
                raise LayerError(f'{slug}.plan: bad item {raw!r}: {exc}') from exc
        elif isinstance(raw, str):
            item = Item(key=raw, url=raw)
        else:
            raise LayerError(f'{slug}.plan: items must be Item, dict or URL string, got {type(raw).__name__}')
        method = item.resolved_method()
        if method not in METHODS:
            raise LayerError(f'{slug}.plan: item {item.key!r} has unknown method {item.method!r}')
        if item.asset is not None and not isinstance(item.asset, dict):
            raise LayerError(f'{slug}.plan: item {item.key!r}: asset must be a dict')
        if method == 'api' and not callable(item.fetch):
            raise LayerError(f'{slug}.plan: api item {item.key!r} needs a fetch callable')
        if method == 'cog' and 'window' not in item.meta:
            raise LayerError(f"{slug}.plan: cog item {item.key!r} needs meta['window']")
        if item.range is not None:
            start, end = (int(v) for v in item.range)
            if start < 0 or end < start:
                raise LayerError(f'{slug}.plan: item {item.key!r} has bad range {item.range!r}')
        items.append(item)
    keys = [i.key for i in items]
    if len(set(keys)) != len(keys):
        dupes = sorted({k for k in keys if keys.count(k) > 1})
        raise LayerError(f'{slug}.plan: duplicate item keys {dupes[:5]}')
    return items


def items_checksum(items: list[Item]) -> str:
    blob = json.dumps(sorted((i.describe() for i in items), key=lambda d: d['key']), sort_keys=True)
    return 'items-sha256:' + hashlib.sha256(blob.encode()).hexdigest()


# --------------------------------------------------------------------------
# transports: each writes through a _CacheWriter so the cap is enforced per byte
# --------------------------------------------------------------------------

def http_url(url: str) -> str:
    """Map GDAL-style and s3:// paths to a plain URL (anonymous S3 over HTTPS)."""
    for prefix in ('/vsis3/', 's3://'):
        if url.startswith(prefix):
            bucket, _, key = url[len(prefix):].partition('/')
            return f'https://{bucket}.s3.amazonaws.com/{urllib.parse.quote(key)}'
    if url.startswith('/vsicurl/'):
        return url[len('/vsicurl/'):]
    return url


def gdal_path(url: str) -> str:
    if url.startswith(('http://', 'https://')):
        return '/vsicurl/' + url
    if url.startswith('s3://'):
        return '/vsis3/' + url[len('s3://'):]
    if url.startswith('file://'):
        return urllib.request.url2pathname(urllib.parse.urlparse(url).path)
    return url


def fetch_http(item: Item, out: '_CacheWriter') -> None:
    url = http_url(item.url)
    if url.startswith('file://'):
        path = Path(urllib.request.url2pathname(urllib.parse.urlparse(url).path))
        if not path.exists():
            raise ItemAbsent(f'{url}: no such file')
        with open(path, 'rb') as f:
            if item.range:
                f.seek(int(item.range[0]))
                remaining = int(item.range[1]) - int(item.range[0]) + 1
            else:
                remaining = None
            while remaining is None or remaining > 0:
                chunk = f.read(CHUNK if remaining is None else min(CHUNK, remaining))
                if not chunk:
                    break
                out.write(chunk)
                if remaining is not None:
                    remaining -= len(chunk)
        return
    headers = {'User-Agent': USER_AGENT, **item.headers}
    if item.range:
        headers['Range'] = f'bytes={int(item.range[0])}-{int(item.range[1])}'
    request = urllib.request.Request(url, headers=headers)
    try:
        response = urllib.request.urlopen(request, timeout=HTTP_TIMEOUT)
    except urllib.error.HTTPError as exc:
        if exc.code in (404, 410):
            raise ItemAbsent(f'{url}: HTTP {exc.code}') from exc
        raise
    with response:
        status = getattr(response, 'status', None)
        if item.range and status != 206:
            raise FetchFailed(f'{url}: server answered {status} to a Range request')
        expected = response.headers.get('Content-Length')
        received = 0
        while True:
            chunk = response.read(CHUNK)
            if not chunk:
                break
            out.write(chunk)
            received += len(chunk)
    if expected is not None and int(expected) != received:
        raise TransientError(f'{url}: received {received} of {expected} bytes')


def fetch_cog(item: Item, out: '_CacheWriter') -> None:
    """Read one window of a (cloud-optimized) raster and store it as .npy."""
    try:
        import rasterio
        from rasterio.errors import RasterioIOError
        from rasterio.windows import Window
    except ImportError as exc:  # pragma: no cover - rasterio is in the venv
        raise FetchFailed('method "cog" needs rasterio') from exc
    window = Window(*item.meta['window'])
    band = int(item.meta.get('band', 1))
    try:
        with rasterio.Env(**item.meta.get('gdal_env', {})):
            with rasterio.open(gdal_path(item.url)) as src:
                array = src.read(band, window=window, boundless=bool(item.meta.get('boundless', False)))
    except RasterioIOError as exc:
        text = str(exc)
        if any(s in text for s in ('No such file', 'does not exist', 'HTTP response code: 404', '404')):
            raise ItemAbsent(f'{item.url}: {text}') from exc
        raise TransientError(f'{item.url}: {text}') from exc
    buffer = io.BytesIO()
    np.save(buffer, array, allow_pickle=False)
    out.name = 'window.npy'
    out.write(buffer.getvalue())


_EARTHACCESS_LOCK = threading.Lock()
_EARTHACCESS_READY = False


def fetch_earthaccess(item: Item, out: '_CacheWriter') -> None:
    """Download one Earthdata granule (``meta['granule']`` or the URL) into the item's cache folder."""
    global _EARTHACCESS_READY
    try:
        import earthaccess
    except ImportError as exc:
        raise FetchFailed('method "earthaccess" needs `pip install earthaccess`') from exc
    with _EARTHACCESS_LOCK:
        if not _EARTHACCESS_READY:
            for strategy in ('environment', 'netrc'):
                try:
                    if earthaccess.login(strategy=strategy):
                        _EARTHACCESS_READY = True
                        break
                except Exception:
                    continue
            if not _EARTHACCESS_READY:
                raise FetchFailed('earthaccess login failed: set EARTHDATA_USERNAME/PASSWORD or ~/.netrc')
    if item.size is None:
        print(f'  note: earthaccess item {item.key} has no size; the cap is checked after it lands',
              file=sys.stderr, flush=True)
    files = earthaccess.download([item.meta.get('granule') or item.url], str(out.dir))
    if not files:
        raise TransientError(f'{item.key}: earthaccess downloaded nothing')
    for name in files:
        out.adopt(Path(name))


# --------------------------------------------------------------------------
# the per-band-group cache
# --------------------------------------------------------------------------

class _Entry:
    __slots__ = ('item', 'seq', 'state', 'path', 'dir', 'nbytes', 'reserved', 'refs', 'claimed',
                 'error', 'fetcher_consumer', 'fetch_count', 'was_absent')

    def __init__(self, item: Item, seq: int):
        self.item = item
        self.seq = seq
        self.state = 'pending'       # pending | fetching | ready | absent | failed | done
        self.path: Path | None = None
        self.dir: Path | None = None
        self.nbytes = 0              # bytes on disk, charged to cache.used
        self.reserved = 0            # bytes reserved up front for an item of known size
        self.refs: set[str] = set()  # consumers (layers) still needing it
        self.claimed = False         # a consumer has acquired it (otherwise speculative)
        self.error: BaseException | None = None
        self.fetcher_consumer = False
        self.fetch_count = 0
        self.was_absent = False


class _CacheWriter:
    """The sink a fetcher writes into. Every byte is charged to the cap before it reaches disk."""

    def __init__(self, cache: 'GroupCache', entry: _Entry, blocking: bool):
        self._cache = cache
        self._entry = entry
        self._blocking = blocking
        self.dir: Path = entry.dir
        self.name = self._default_name(entry.item)
        self._fh = None
        self._hash = hashlib.sha256()
        self.nbytes = 0
        self._adopted: list[Path] = []

    @staticmethod
    def _default_name(item: Item) -> str:
        if 'filename' in item.meta:
            return str(item.meta['filename'])
        if item.url:
            base = Path(urllib.parse.urlparse(http_url(item.url)).path).name
            if base:
                return base
        return re.sub(r'[^A-Za-z0-9._-]+', '_', item.key)[:120] or 'data'

    def write(self, data: bytes) -> int:
        if not data:
            return 0
        self._cache._charge(self._entry, len(data), self._blocking)
        if self._fh is None:
            self._fh = open(self.dir / self.name, 'wb')
        self._fh.write(data)
        self._hash.update(data)
        self.nbytes += len(data)
        return len(data)

    def adopt(self, path: Path) -> None:
        """Account for a file the fetcher saved into ``self.dir`` itself."""
        path = Path(path)
        size = path.stat().st_size
        try:
            self._cache._charge(self._entry, size, self._blocking)
        except BaseException:
            path.unlink(missing_ok=True)
            raise
        self._adopted.append(path)

    def close(self) -> None:
        if self._fh is not None:
            self._fh.close()
            self._fh = None

    def verify(self, expected: str | None) -> None:
        if not expected:
            return
        want = expected.split(':', 1)[1] if expected.startswith('sha256:') else expected
        if self._adopted:
            got = sha256_file(self._adopted[0]) if len(self._adopted) == 1 else None
        else:
            got = self._hash.hexdigest()
        if got is not None and got != want.lower():
            raise TransientError(f'{self._entry.item.key}: SHA-256 {got} != expected {want}')

    def result(self) -> Path:
        if self._adopted:
            return self._adopted[0] if len(self._adopted) == 1 else self.dir
        path = self.dir / self.name
        if not path.exists():
            path.touch()
        return path


class GroupCache:
    """Items of one band group, on disk under ``root``, never more than ``cap`` bytes in total.

    Several consumers (the layers of one PASS_GROUP) may need the same item; it is fetched once and
    deleted when the last of them releases it. A consumer that needs room waits while another
    consumer can still free some, and fails with :class:`CacheCapExceeded` when nobody can.
    Prefetches (``workers - 1`` threads) only use room that is free and never wait for it; an
    unclaimed prefetched item is evicted first when a consumer needs the space.
    """

    def __init__(self, root: Path, cap_bytes: int, *, retries: int, workers: int = 1):
        self.root = Path(root)
        self.root.mkdir(parents=True, exist_ok=True)
        self.cap = int(cap_bytes)
        self.retries = max(1, int(retries))
        self.cond = threading.Condition()
        self.entries: dict[str, _Entry] = {}
        self.used = 0
        self.reserved = 0
        self.peak = 0
        self.bytes_read = 0
        self.retried = 0
        self.alive = 0
        self.blocked = 0
        self.prefetching = 0
        self.depth = max(0, int(workers) - 1)
        self.pool = (ThreadPoolExecutor(max_workers=self.depth, thread_name_prefix='layer-prefetch')
                     if self.depth else None)

    # -- registration ------------------------------------------------------
    def register(self, consumer: str, items: list[Item]) -> None:
        with self.cond:
            for item in items:
                entry = self.entries.get(item.key)
                if entry is None:
                    entry = self.entries[item.key] = _Entry(item, len(self.entries))
                elif entry.item.source_id() != item.source_id():
                    raise LayerError(f'item {item.key!r} is planned with two different sources: '
                                     f'{entry.item.source_id()} and {item.source_id()}')
                elif item.required and not entry.item.required:
                    entry.item = replace(entry.item, required=True)
                entry.refs.add(consumer)

    def add_consumers(self, n: int) -> None:
        with self.cond:
            self.alive += n

    def finish(self, consumer: str) -> None:
        """A consumer is done: drop its claim on everything it planned."""
        with self.cond:
            self.alive -= 1
            for entry in self.entries.values():
                if consumer in entry.refs:
                    entry.refs.discard(consumer)
                    if not entry.refs:
                        self._drop(entry)
            self.cond.notify_all()

    # -- consumer API ------------------------------------------------------
    def acquire(self, consumer: str, key: str) -> Fetched:
        with self.cond:
            entry = self.entries.get(key)
            if entry is None:
                raise LayerError(f'item {key!r} was not in the plan')
            entry.refs.add(consumer)
        while True:
            with self.cond:
                while True:
                    if entry.state in ('ready', 'absent'):
                        entry.claimed = True
                        return Fetched(entry.item, entry.path, absent=entry.state == 'absent',
                                       nbytes=entry.nbytes)
                    if entry.state == 'failed':
                        raise entry.error
                    if entry.state == 'fetching':
                        counted = entry.fetcher_consumer
                        if counted:
                            self.blocked += 1
                        self.cond.wait(WAIT_POLL)
                        if counted:
                            self.blocked -= 1
                        continue
                    # pending, or done and wanted again: fetch it in this thread
                    entry.state = 'fetching'
                    entry.fetcher_consumer = True
                    break
            self._fetch(entry, blocking=True)

    def release(self, consumer: str, key: str) -> None:
        with self.cond:
            entry = self.entries.get(key)
            if entry is None:
                return
            entry.refs.discard(consumer)
            if not entry.refs:
                self._drop(entry)
            self.cond.notify_all()

    def prefetch(self, keys: list[str]) -> None:
        if self.pool is None:
            return
        with self.cond:
            for key in keys:
                if self.prefetching >= self.depth:
                    break
                entry = self.entries.get(key)
                if entry is None or entry.state != 'pending' or not entry.refs:
                    continue
                entry.state = 'fetching'
                entry.fetcher_consumer = False
                self.prefetching += 1
                self.pool.submit(self._prefetch_task, entry)

    def _prefetch_task(self, entry: _Entry) -> None:
        try:
            self._fetch(entry, blocking=False)
        finally:
            with self.cond:
                self.prefetching -= 1
                self.cond.notify_all()

    # -- accounting (lock held) ------------------------------------------
    def _make_room(self, n: int, blocking: bool, entry: _Entry) -> None:
        while self.used + self.reserved + n > self.cap:
            if self._evict_one(exclude=entry):
                continue
            if not blocking:
                raise _Aborted()
            if entry.nbytes + entry.reserved + n > self.cap:
                raise CacheCapExceeded(
                    f'item {entry.item.key!r} needs more than the whole cache cap '
                    f'({human(self.cap)}); raise --cache-max-gb or split the item')
            others = self.alive - self.blocked - 1
            if others <= 0 and self.prefetching == 0:
                raise CacheCapExceeded(
                    f'cache cap {human(self.cap)} is full ({human(self.used)} held by items still '
                    f'in use) and {entry.item.key!r} needs {human(n)} more; the layer keeps too much '
                    f'at once (stream items instead of items.all()) or --cache-max-gb is too small')
            self.blocked += 1
            self.cond.wait(WAIT_POLL)
            self.blocked -= 1

    def _charge(self, entry: _Entry, n: int, blocking: bool) -> None:
        with self.cond:
            take = min(n, entry.reserved)
            entry.reserved -= take
            self.reserved -= take
            self.used += take
            entry.nbytes += take
            rest = n - take
            if rest:
                self._make_room(rest, blocking, entry)
                self.used += rest
                entry.nbytes += rest
            self.bytes_read += n
            self.peak = max(self.peak, self.used)

    def _evict_one(self, exclude: _Entry) -> bool:
        candidates = [e for e in self.entries.values()
                      if e is not exclude and e.state == 'ready' and not e.claimed]
        if not candidates:
            return False
        victim = max(candidates, key=lambda e: e.seq)   # the one needed last
        self._delete_files(victim)
        victim.state = 'pending'
        return True

    def _delete_files(self, entry: _Entry) -> None:
        if entry.dir is not None:
            shutil.rmtree(entry.dir, ignore_errors=True)
        self.used -= entry.nbytes
        entry.nbytes = 0
        entry.dir = None
        if entry.path is not None and entry.item.resolved_method() != 'local':
            entry.path = None

    def _free_reservation(self, entry: _Entry) -> None:
        self.reserved -= entry.reserved
        entry.reserved = 0

    def _drop(self, entry: _Entry) -> None:
        if entry.state in ('ready', 'absent', 'pending'):
            self._delete_files(entry)
            entry.path = None
            entry.claimed = False
            entry.state = 'done'
        # 'fetching': the fetcher drops it when it finishes; 'failed' keeps its error

    # -- fetching ----------------------------------------------------------
    def _fetch(self, entry: _Entry, blocking: bool) -> None:
        item = entry.item
        try:
            size = item.expected_size()
            if size:
                with self.cond:
                    self._make_room(size, blocking, entry)
                    self.reserved += size
                    entry.reserved = size
            path = with_retries(lambda: self._fetch_once(entry, blocking), self.retries,
                                f'fetch {item.key}', on_retry=self._on_retry)
        except _Aborted:
            with self.cond:
                self._delete_files(entry)
                self._free_reservation(entry)
                entry.state = 'pending'
                self.cond.notify_all()
            return
        except ItemAbsent as exc:
            with self.cond:
                self._delete_files(entry)
                self._free_reservation(entry)
                entry.fetch_count += 1
                if item.required:
                    entry.state = 'failed'
                    entry.error = FetchFailed(f'required item {item.key!r} does not exist at its '
                                              f'source ({exc}); mark it required=False if absence '
                                              f'is legitimate')
                else:
                    entry.state = 'absent'
                    entry.was_absent = True
                    if blocking:
                        entry.claimed = True
                self.cond.notify_all()
            return
        except Exception as exc:
            with self.cond:
                self._delete_files(entry)
                self._free_reservation(entry)
                entry.state = 'failed'
                if isinstance(exc, (FetchFailed, CacheCapExceeded, LayerError)):
                    entry.error = exc
                else:
                    entry.error = FetchFailed(f'item {item.key!r} failed after {self.retries} '
                                              f'attempt(s): {type(exc).__name__}: {exc}')
                    entry.error.__cause__ = exc
                self.cond.notify_all()
            return
        with self.cond:
            self._free_reservation(entry)
            entry.path = path
            entry.state = 'ready'
            entry.fetch_count += 1
            if blocking:
                entry.claimed = True
            if not entry.refs:
                self._drop(entry)
            self.cond.notify_all()

    def _on_retry(self, attempt, exc, delay) -> None:
        with self.cond:
            self.retried += 1

    def _fetch_once(self, entry: _Entry, blocking: bool) -> Path | None:
        item = entry.item
        method = item.resolved_method()
        if method == 'none':
            return None
        if method == 'local':
            path = Path(item.url)
            if not path.exists():
                raise ItemAbsent(f'{path}: no such file')
            return path
        with self.cond:
            self._delete_files(entry)          # a previous attempt's partial download
            entry.dir = self.root / f'{entry.seq:06d}'
        entry.dir.mkdir(parents=True, exist_ok=True)
        out = _CacheWriter(self, entry, blocking)
        try:
            if method == 'http':
                fetch_http(item, out)
            elif method == 'cog':
                fetch_cog(item, out)
            elif method == 'earthaccess':
                fetch_earthaccess(item, out)
            elif method == 'api':
                item.fetch(item, out)
            else:  # pragma: no cover - normalize_items rejects it
                raise LayerError(f'unknown method {method!r}')
        finally:
            out.close()
        out.verify(item.checksum)
        return out.result()

    # -- teardown ----------------------------------------------------------
    def stats(self) -> dict:
        with self.cond:
            entries = list(self.entries.values())
            return {
                'items': len(entries),
                'items_fetched': sum(1 for e in entries if e.fetch_count and e.state != 'failed'),
                'items_absent': sum(1 for e in entries if e.was_absent),
                'items_failed': sum(1 for e in entries if e.state == 'failed'),
                'fetches': sum(e.fetch_count for e in entries),
                'refetches': sum(max(0, e.fetch_count - 1) for e in entries),
                'bytes_read': self.bytes_read,
                'peak_cache_bytes': self.peak,
                'cache_cap_bytes': self.cap,
                'retried': self.retried,
            }

    def close(self) -> int:
        """Stop prefetching and wipe the folder. Returns the bytes that were still on disk."""
        if self.pool is not None:
            self.pool.shutdown(wait=True, cancel_futures=True)
        left = du(self.root)
        shutil.rmtree(self.root, ignore_errors=True)
        return left


class Items:
    """What ``reduce`` receives: the planned items of one band group, fetched on demand.

    Iterating fetches each item when the loop reaches it (with up to ``--workers - 1`` of the next
    ones downloading meanwhile) and deletes it when the loop asks for the next one, so a reduce that
    streams never holds more than a few items. ``get(key)`` fetches one item and keeps it until
    ``release(key)``; ``all()`` keeps every item and fails when they do not fit under the cap.
    """

    def __init__(self, cache: GroupCache, consumer: str, planned: list[Item]):
        self._cache = cache
        self._consumer = consumer
        self.planned = list(planned)
        self._keys = [i.key for i in self.planned]
        self._kept: set[str] = set()
        self.failed: list[str] = []
        self.absent: list[str] = []

    def __len__(self) -> int:
        return len(self.planned)

    def keys(self) -> list[str]:
        return list(self._keys)

    def _acquire(self, key: str) -> Fetched:
        try:
            fetched = self._cache.acquire(self._consumer, key)
        except Exception:
            self.failed.append(key)
            raise
        if fetched.absent:
            self.absent.append(key)
        return fetched

    def __iter__(self):
        depth = self._cache.depth
        self._cache.prefetch(self._keys[:depth])
        previous = None
        for i, key in enumerate(self._keys):
            if previous is not None and previous not in self._kept:
                self._cache.release(self._consumer, previous)
            fetched = self._acquire(key)
            self._cache.prefetch(self._keys[i + 1:i + 1 + depth])
            previous = key
            yield fetched
        if previous is not None and previous not in self._kept:
            self._cache.release(self._consumer, previous)

    def get(self, key: str) -> Fetched:
        fetched = self._acquire(key)
        self._kept.add(key)
        return fetched

    def release(self, key: str) -> None:
        self._kept.discard(key)
        self._cache.release(self._consumer, key)

    def all(self) -> list[Fetched]:
        self._cache.prefetch(self._keys)
        return [self.get(key) for key in self._keys]


# --------------------------------------------------------------------------
# grid helpers
# --------------------------------------------------------------------------

@lru_cache(maxsize=None)
def _build_grid(planet: str) -> PlanetBandGrid:
    return PlanetBandGrid.build(planet)


def planet_grid(planet: str) -> PlanetBandGrid:
    """The latband5km-v1 grid for a planet (tests replace this with a small grid)."""
    return _build_grid(planet)


def n_groups(grid: PlanetBandGrid) -> int:
    return math.ceil(len(grid.column_counts) / BANDS_PER_GROUP)


def group_bands(grid: PlanetBandGrid, group: int) -> list[int]:
    n_bands = len(grid.column_counts)
    if not 0 <= group < n_groups(grid):
        raise ValueError(f'band group {group} outside 0-{n_groups(grid) - 1}')
    return list(range(group * BANDS_PER_GROUP, min((group + 1) * BANDS_PER_GROUP, n_bands)))


def group_cell_count(grid: PlanetBandGrid, group: int) -> int:
    bands = group_bands(grid, group)
    return int(np.sum(grid.column_counts[bands[0]:bands[-1] + 1], dtype=np.int64))


_CELLS_CACHE: dict = {}
_CELLS_LOCK = threading.Lock()


def cells_table(planet: str, group: int) -> pa.Table:
    """Every cell of a band group in grid order, with the same values ``PlanetBandGrid.cell`` gives."""
    grid = planet_grid(planet)
    key = (planet, group, len(grid.column_counts), grid.number_of_cells, float(grid.edges_deg[1]))
    with _CELLS_LOCK:
        if key in _CELLS_CACHE:
            return _CELLS_CACHE[key]
    bands = np.asarray(group_bands(grid, group), dtype=np.int64)
    counts = grid.column_counts[bands].astype(np.int64)
    band = np.repeat(bands, counts)
    column = np.concatenate([np.arange(c, dtype=np.int64) for c in counts])
    width = np.repeat(360.0 / counts, counts)
    lat_min = grid.edges_deg[band]
    lat_max = grid.edges_deg[band + 1]
    lon_min = -180 + width * column
    lon_max = -180 + width * (column + 1)
    area = np.repeat(grid.strip_area_m2()[bands] / counts / 1e6, counts)
    prefix = PLANETS[planet]['prefix']
    region_id = [f'{prefix}_{b:04d}_{c:05d}' for b, c in zip(band.tolist(), column.tolist())]
    table = pa.table({
        'region_id': pa.array(region_id, type=pa.string()),
        'band': pa.array(band.astype(np.int32)),
        'column': pa.array(column.astype(np.int32)),
        'lat_min': lat_min, 'lat_max': lat_max, 'lon_min': lon_min, 'lon_max': lon_max,
        'center_lat': (lat_min + lat_max) / 2, 'center_lon': (lon_min + lon_max) / 2,
        'area_km2': area,
    })
    with _CELLS_LOCK:
        if len(_CELLS_CACHE) > 8:
            _CELLS_CACHE.clear()
        _CELLS_CACHE[key] = table
    return table


def groups_for_bands(grid: PlanetBandGrid, bands: list[int] | None) -> list[int]:
    if bands is None:
        return list(range(n_groups(grid)))
    groups = sorted({b // BANDS_PER_GROUP for b in bands})
    wanted = set(bands)
    partial = [g for g in groups if not set(group_bands(grid, g)) <= wanted]
    if partial:
        print(f'note: --bands covers only part of band group(s) {partial}; a band-group file always '
              f'holds the whole group, so those groups run in full', flush=True)
    return groups


# --------------------------------------------------------------------------
# the Hub
# --------------------------------------------------------------------------

@dataclass
class RemoteFile:
    path: str
    size: int
    sha256: str | None      # LFS files
    blob_id: str | None     # git blob id; the content hash for non-LFS files

    def matches(self, size: int, sha256: str, blob_id: str | None) -> bool:
        if self.size != size:
            return False
        if self.sha256:
            return self.sha256 == sha256
        return blob_id is not None and self.blob_id == blob_id


def _not_found(exc: BaseException) -> bool:
    try:
        from huggingface_hub.errors import EntryNotFoundError
        if isinstance(exc, EntryNotFoundError):
            return True
    except ImportError:  # pragma: no cover
        pass
    return isinstance(exc, FileNotFoundError) or _status_code(exc) == 404


def _is_conflict(exc: BaseException) -> bool:
    return _status_code(exc) in (409, 412)


class HubStore:
    """The few Hub operations the driver uses, each retried on transient errors."""

    def __init__(self, api=None, repo_id: str = REPO_ID, repo_type: str = REPO_TYPE, retries: int = 4):
        if api is None:
            from huggingface_hub import HfApi
            api = HfApi()
        self.api = api
        self.repo_id = repo_id
        self.repo_type = repo_type
        self.retries = max(1, int(retries))

    def _call(self, fn, what):
        return with_retries(fn, self.retries, f'hub {what}')

    def head(self) -> str:
        return self._call(lambda: self.api.repo_info(self.repo_id, repo_type=self.repo_type).sha,
                          'repo_info')

    @staticmethod
    def _remote(entry) -> RemoteFile | None:
        size = getattr(entry, 'size', None)
        blob = getattr(entry, 'blob_id', None)
        if size is None or blob is None:
            return None                       # a folder
        lfs = getattr(entry, 'lfs', None)
        return RemoteFile(entry.path, int(size), getattr(lfs, 'sha256', None) if lfs else None, blob)

    def list(self, prefix: str, revision: str | None = None) -> dict[str, RemoteFile]:
        try:
            entries = self._call(lambda: list(self.api.list_repo_tree(
                self.repo_id, path_in_repo=prefix, recursive=True, repo_type=self.repo_type,
                revision=revision)), f'list {prefix}')
        except Exception as exc:
            if _not_found(exc):
                return {}
            raise
        out = {}
        for entry in entries:
            remote = self._remote(entry)
            if remote is not None:
                out[remote.path] = remote
        return out

    def info(self, paths: list[str], revision: str | None = None) -> dict[str, RemoteFile]:
        try:
            entries = self._call(lambda: self.api.get_paths_info(
                self.repo_id, list(paths), repo_type=self.repo_type, revision=revision),
                'paths_info')
        except Exception as exc:
            if _not_found(exc):
                return {}
            raise
        out = {}
        for entry in entries:
            remote = self._remote(entry)
            if remote is not None:
                out[remote.path] = remote
        return out

    def read_bytes(self, path: str, revision: str | None = None) -> bytes | None:
        with tempfile.TemporaryDirectory(prefix='layer-hub-') as tmp:
            try:
                local = self._call(lambda: self.api.hf_hub_download(
                    self.repo_id, path, repo_type=self.repo_type, revision=revision, local_dir=tmp),
                    f'download {path}')
            except Exception as exc:
                if _not_found(exc):
                    return None
                raise
            return Path(local).read_bytes()

    def read_json(self, path: str, revision: str | None = None) -> dict | None:
        data = self.read_bytes(path, revision)
        return None if data is None else json.loads(data)

    def read_parquet(self, path: str, columns=None, revision: str | None = None) -> pa.Table | None:
        with tempfile.TemporaryDirectory(prefix='layer-hub-') as tmp:
            try:
                local = self._call(lambda: self.api.hf_hub_download(
                    self.repo_id, path, repo_type=self.repo_type, revision=revision, local_dir=tmp),
                    f'download {path}')
            except Exception as exc:
                if _not_found(exc):
                    return None
                raise
            return pq.read_table(local, columns=columns)

    def cached_download(self, path: str, revision: str) -> Path:
        """Download into the normal Hub cache (for pinned, reused files like the terrain tables)."""
        return Path(self._call(lambda: self.api.hf_hub_download(
            self.repo_id, path, repo_type=self.repo_type, revision=revision), f'download {path}'))

    def commit(self, files: dict[str, Path | bytes], message: str, parent_commit: str | None) -> str:
        from huggingface_hub import CommitOperationAdd

        def attempt():
            operations = [CommitOperationAdd(path_in_repo=p,
                                              path_or_fileobj=str(v) if isinstance(v, Path) else v)
                          for p, v in files.items()]
            return self.api.create_commit(self.repo_id, operations=operations, commit_message=message,
                                          repo_type=self.repo_type, parent_commit=parent_commit)
        return self._call(attempt, 'create_commit').oid

    def commit_update(self, files: dict[str, Path | bytes], message: str, progress_path: str,
                      mutate: Callable[[dict | None], dict],
                      already_done: Callable[[dict | None, str], bool] | None = None) -> tuple[str, dict]:
        """Commit ``files`` plus a read-modify-write of the progress JSON, atomically.

        The commit names its parent, so a concurrent commit makes it fail instead of overwriting
        someone else's progress; it is then redone on the new head. ``already_done`` lets a retry
        recognise that an earlier attempt landed after all (e.g. a timeout after the server acted).
        """
        for _ in range(CONFLICT_RETRIES):
            head = self.head()
            progress = self.read_json(progress_path, revision=head)
            if already_done is not None and already_done(progress, head):
                return head, progress
            progress = mutate(progress)
            payload = dict(files)
            payload[progress_path] = (dumps(progress) + '\n').encode()
            try:
                return self.commit(payload, message, parent_commit=head), progress
            except Exception as exc:
                if _is_conflict(exc):
                    continue
                raise
        raise UploadError(f'gave up after {CONFLICT_RETRIES} commit conflicts on {self.repo_id}')

    def tags(self) -> set[str]:
        refs = self._call(lambda: self.api.list_repo_refs(self.repo_id, repo_type=self.repo_type),
                          'list_repo_refs')
        return {t.name for t in refs.tags}

    def create_tag(self, tag: str, revision: str, message: str) -> None:
        # never retried: a retry after a lost response must not turn into "tag already exists" noise,
        # and exist_ok=False means a tag is never moved
        self.api.create_tag(self.repo_id, tag=tag, revision=revision, repo_type=self.repo_type,
                            exist_ok=False, tag_message=message)


_DEFAULT_HUB: HubStore | None = None


def default_hub() -> HubStore:
    global _DEFAULT_HUB
    if _DEFAULT_HUB is None:
        _DEFAULT_HUB = HubStore()
    return _DEFAULT_HUB


# --------------------------------------------------------------------------
# shared inputs for layers: terrain values and the Earth land mask
# --------------------------------------------------------------------------

def terrain_remote_path(planet: str, band_group: int) -> str:
    return (f'terrain/planet={planet}/feature_version={TERRAIN_FEATURE_VERSION}/'
            f'band_group={band_group:03d}.parquet')


def read_terrain(planet: str, band_group: int, columns) -> pa.Table:
    """terrain-v0.2 columns (plus ``region_id``) for one band group, in grid order.

    Reads ``data/processed/<planet>/terrain/terrain-v0.2/band_group=NNN.parquet`` when it is on
    disk, otherwise the Hub copy at the pinned terrain release tag (kept in the Hub cache).
    """
    wanted = list(dict.fromkeys(['region_id', *columns]))
    local = TERRAIN_LOCAL[planet] / f'band_group={band_group:03d}.parquet'
    if local.exists():
        return pq.read_table(local, columns=wanted)
    path = default_hub().cached_download(terrain_remote_path(planet, band_group),
                                         revision=TERRAIN_REVISION[planet])
    return pq.read_table(path, columns=wanted)


_LAND_CACHE: dict = {}
_LAND_LOCK = threading.Lock()


def earth_land_frac(band_group: int) -> pa.Table:
    """The shared Earth land mask: ``region_id``, ``land_frac`` (0-1) for one band group.

    It is the Earth terrain ``valid_frac_200m``: the share of 200 m samples with Copernicus GLO-30
    data. Cells with no tile (open ocean) and cells with no samples are 0. Inland water and the sea
    pixels inside a coastal GLO-30 tile carry elevation, so they count as land here; layers that need
    a water-aware mask should say so in LIMITATIONS rather than build their own.
    """
    with _LAND_LOCK:
        if band_group in _LAND_CACHE:
            return _LAND_CACHE[band_group]
    terrain = read_terrain('earth', band_group, ['valid_frac_200m'])
    frac = terrain['valid_frac_200m'].to_numpy(zero_copy_only=False).astype(np.float32)
    frac = np.where(np.isfinite(frac), frac, np.float32(0))
    table = pa.table({'region_id': terrain['region_id'], 'land_frac': pa.array(frac)})
    with _LAND_LOCK:
        if len(_LAND_CACHE) > 4:
            _LAND_CACHE.clear()
        _LAND_CACHE[band_group] = table
    return table


# --------------------------------------------------------------------------
# layers
# --------------------------------------------------------------------------

def _normalize_columns(spec, where: str) -> dict[str, dict]:
    if not isinstance(spec, dict) or not spec:
        raise LayerError(f'{where} must be a non-empty dict of column -> definition')
    out = {}
    for name, definition in spec.items():
        if name in RESERVED_COLUMNS or name == FLAGS_COLUMN:
            raise LayerError(f'{where}: {name!r} is a driver column and cannot be a feature')
        definition = dict(definition or {})
        dtype = definition.setdefault('dtype', 'float32')
        try:
            definition['_type'] = pa.type_for_alias(dtype)
        except (ValueError, KeyError) as exc:
            raise LayerError(f'{where}: column {name!r} has unknown dtype {dtype!r}') from exc
        out[name] = definition
    return out


class Layer:
    """A loaded layer module plus everything derived from it."""

    def __init__(self, module, slug: str):
        self.module = module
        self.slug = slug
        source = getattr(module, 'SOURCE', None)
        if not isinstance(source, dict):
            raise LayerError(f'{slug}: SOURCE dict is missing')
        missing = [k for k in ('product', 'version', 'url', 'licence', 'planet') if k not in source]
        if missing:
            raise LayerError(f'{slug}: SOURCE lacks {missing}')
        if source['planet'] not in ('mars', 'earth', 'both'):
            raise LayerError(f"{slug}: SOURCE['planet'] must be mars, earth or both")
        self.source = source
        self.planets = ('mars', 'earth') if source['planet'] == 'both' else (source['planet'],)
        for name in ('plan', 'reduce'):
            if not callable(getattr(module, name, None)):
                raise LayerError(f'{slug}: {name}() is missing')
        self.columns = _normalize_columns(getattr(module, 'COLUMNS', None), f'{slug}.COLUMNS')
        extras = getattr(module, 'EXTRA_COLUMNS', None) or {}
        self.extra_columns = {name: _normalize_columns(spec, f'{slug}.EXTRA_COLUMNS[{name!r}]')
                              for name, spec in extras.items()}
        self.has_finalize = callable(getattr(module, 'finalize', None))
        if self.has_finalize and not self.extra_columns:
            raise LayerError(f'{slug}: finalize() needs EXTRA_COLUMNS naming the sets it writes')
        self.pass_group = getattr(module, 'PASS_GROUP', None)
        self.version = getattr(module, 'VERSION', DEFAULT_VERSION)
        self.layer_version = f'{slug}-{self.version}'
        self.path = Path(module.__file__).resolve()
        self.crosswalks = [self.path.parent / name for name in getattr(module, 'CROSSWALKS', [])]
        for path in self.crosswalks:
            if not path.exists():
                raise LayerError(f'{slug}: crosswalk {path} does not exist')
        # the module, then the driver, then crosswalks: any change to what makes the rows moves it
        self.code_version = tf.code_version(self.path, DRIVER_PATH, *self.crosswalks)

    def tag(self, planet: str) -> str:
        return f'{self.slug}-{planet}-{self.version}.0'

    def remote_prefix(self, planet: str) -> str:
        return f'layers/planet={planet}/layer={self.slug}/version={self.layer_version}'

    def relative_group_path(self, planet: str, group: int, extra: str | None = None) -> str:
        middle = f'/extra={extra}' if extra else ''
        return f'{self.remote_prefix(planet)}{middle}/band_group={group:03d}.parquet'

    def progress_path(self, planet: str) -> str:
        return f'manifests/progress/{self.slug}_{planet}.json'

    def manifest_path(self, planet: str) -> str:
        return f'manifests/{self.slug}_{planet}_{self.version}.json'

    def missing_flag(self):
        return getattr(self.module, 'MISSING_FLAG', DEFAULT_MISSING_FLAG)


def load_module(slug: str, layers_dir: Path = LAYERS_DIR):
    if not re.fullmatch(r'[a-z0-9_]+', slug):
        raise LayerError(f'bad layer slug {slug!r} (lowercase letters, digits, underscores)')
    if Path(layers_dir).resolve() == LAYERS_DIR and __package__:
        return importlib.import_module(f'{__package__}.{slug}')
    path = Path(layers_dir) / f'{slug}.py'
    if not path.exists():
        raise LayerError(f'no layer module {path}')
    spec = importlib.util.spec_from_file_location(f'layer_{slug}', path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


# --------------------------------------------------------------------------
# table assembly: one row per cell, metadata columns, validation summary
# --------------------------------------------------------------------------

def _constant(value: str, length: int) -> pa.Array:
    return pa.DictionaryArray.from_arrays(pa.array(np.zeros(length, dtype=np.int32)),
                                          pa.array([value], type=pa.string()))


def _column_stats(values) -> dict:
    out = {'dtype': str(values.type), 'n_null': int(values.null_count)}
    if pa.types.is_floating(values.type):
        array = values.to_numpy(zero_copy_only=False).astype(np.float64)
        finite = np.isfinite(array)
        out['n_nan'] = int((~finite).sum())
        out['n_finite'] = int(finite.sum())
        if finite.any():
            out.update(min=float(array[finite].min()), max=float(array[finite].max()),
                       sum=float(array[finite].sum()))
    elif pa.types.is_integer(values.type) and len(values) > values.null_count:
        minmax = pc.min_max(values)
        out.update(min=minmax['min'].as_py(), max=minmax['max'].as_py())
    return out


def _flag_counts(flags) -> dict[str, int]:
    counts: dict[str, int] = {}
    for row in pc.value_counts(flags).to_pylist():
        value, n = row['values'], int(row['counts'])
        parts = [p for p in (value or '').split(';') if p]
        if not parts:
            counts['(clean)'] = counts.get('(clean)', 0) + n
        for part in parts:
            counts[part] = counts.get(part, 0) + n
    return dict(sorted(counts.items()))


def assemble_table(layer: Layer, ctx: 'LayerContext', group: int, reduced, columns: dict[str, dict],
                   *, source_checksum: str, computed_at: str, extra: str | None = None
                   ) -> tuple[pa.Table, dict]:
    """Expand a reduce result to exactly one row per cell of the band group, plus metadata."""
    planet = ctx.planet
    where = f'{layer.slug} band group {group:03d}' + (f' extra {extra!r}' if extra else '')
    cells = cells_table(planet, group)
    n = len(cells)
    if reduced is None:
        reduced = pa.table({'region_id': pa.array([], type=pa.string())})
    elif not isinstance(reduced, pa.Table):
        if hasattr(reduced, 'to_dict') and hasattr(reduced, 'columns'):
            reduced = pa.Table.from_pandas(reduced, preserve_index=False)
        else:
            raise LayerError(f'{where}: reduce must return a pyarrow.Table, got {type(reduced).__name__}')
    names = set(reduced.column_names)
    if 'region_id' not in names:
        raise LayerError(f'{where}: the table has no region_id column')
    reserved = sorted((names & RESERVED_COLUMNS) - {'region_id'})
    if reserved:
        raise LayerError(f'{where}: the table must hold feature columns only, not {reserved}')
    features = names - {'region_id', FLAGS_COLUMN}
    if len(reduced):
        missing = sorted(set(columns) - features)
        if missing:
            raise LayerError(f'{where}: declared columns missing from the table: {missing}')
    undeclared = sorted(features - set(columns))
    if undeclared:
        raise LayerError(f'{where}: columns not declared in COLUMNS: {undeclared}')

    m = len(reduced)
    present = np.zeros(n, dtype=bool)
    take = np.full(n, -1, dtype=np.int64)
    if m:
        ids = reduced['region_id'].cast(pa.string())
        position = pc.index_in(ids, value_set=cells['region_id'])
        if position.null_count:
            bad = pc.filter(ids, pc.is_null(position)).to_pylist()[:5]
            raise LayerError(f'{where}: {position.null_count} region_id(s) are not cells of this band '
                             f'group, e.g. {bad}')
        position = position.to_numpy(zero_copy_only=False).astype(np.int64)
        if len(np.unique(position)) != m:
            raise LayerError(f'{where}: duplicate region_id rows ({m - len(np.unique(position))})')
        take[position] = np.arange(m)
        present[position] = True
    present_arr = pa.array(present)
    index = pa.array(take, mask=~present)

    data: dict[str, Any] = {
        'grid_version': _constant(GRID_VERSION, n),
        'region_id': cells['region_id'],
        'planet': _constant(planet, n),
        'band': cells['band'],
        'column': cells['column'],
    }
    for name, spec in columns.items():
        typ = spec['_type']
        if m and name in names:
            try:
                values = reduced[name].cast(typ, safe=False).take(index)
            except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as exc:
                raise LayerError(f'{where}: column {name!r} cannot be {spec["dtype"]}: {exc}') from exc
        else:
            values = pa.nulls(n, type=typ)
        if pa.types.is_floating(typ):
            values = pc.fill_null(values, pa.scalar(float('nan'), type=typ))
        fill = spec.get('fill')
        if fill is None and pa.types.is_floating(typ):
            fill = float('nan')
        values = pc.if_else(present_arr, values, pa.scalar(fill, type=typ))
        data[name] = values

    missing_rows = int(n - present.sum())
    if m and FLAGS_COLUMN in names:
        flags = pc.fill_null(reduced[FLAGS_COLUMN].cast(pa.string()).take(index), '')
    else:
        flags = pa.array([''] * n, type=pa.string())
    if missing_rows:
        rule = layer.missing_flag()
        if callable(rule):
            missing_cells = cells.filter(pa.array(~present))
            values = list(rule(group, missing_cells, ctx))
            if len(values) != missing_rows:
                raise LayerError(f'{where}: MISSING_FLAG returned {len(values)} flags for '
                                 f'{missing_rows} cells')
            filler = np.full(n, '', dtype=object)
            filler[~present] = values
            flags = pc.if_else(present_arr, flags, pa.array(filler, type=pa.string()))
        else:
            flags = pc.if_else(present_arr, flags, pa.scalar(str(rule), type=pa.string()))
    data[FLAGS_COLUMN] = flags

    source = layer.source
    data['source_product'] = _constant(str(source['product']), n)
    data['source_version'] = _constant(str(source['version']), n)
    data['source_checksum'] = _constant(source_checksum, n)
    data['layer'] = _constant(layer.slug, n)
    data['layer_version'] = _constant(layer.layer_version, n)
    data['code_version'] = _constant(layer.code_version, n)
    data['computed_at'] = _constant(computed_at, n)
    table = pa.table(data)

    unique = pc.count_distinct(table['region_id']).as_py() == n
    summary = {
        'rows': n,
        'expected_rows': group_cell_count(planet_grid(planet), group),
        'rows_with_data': int(present.sum()),
        'rows_without_data': missing_rows,
        'columns': {name: _column_stats(table[name]) for name in columns},
        'flags': _flag_counts(table[FLAGS_COLUMN]),
        'checks': {'one_row_per_cell': n == group_cell_count(planet_grid(planet), group),
                   'region_ids_unique': bool(unique),
                   'region_ids_match_grid': table['region_id'].equals(cells['region_id'])},
        'schema_sha256': hashlib.sha256(json.dumps(
            [(f.name, str(f.type)) for f in table.schema]).encode()).hexdigest(),
        'source_checksum': source_checksum,
        'computed_at': computed_at,
    }
    if not all(summary['checks'].values()):
        raise LayerError(f'{where}: row checks failed: {summary["checks"]}')
    bands = group_bands(planet_grid(planet), group)
    metadata = {
        'layer': layer.slug, 'layer_version': layer.layer_version, 'planet': planet,
        'grid_version': GRID_VERSION, 'band_group': str(group), 'extra': extra or '',
        'bands': json.dumps([bands[0], bands[-1]]), 'code_version': layer.code_version,
        'source': json.dumps(layer.source, sort_keys=True, default=_json_default),
    }
    return table.replace_schema_metadata(metadata), summary


def write_group_file(table: pa.Table, summary: dict, path: Path) -> None:
    metadata = dict(table.schema.metadata or {})
    metadata[b'layer_summary'] = dumps(summary).encode()
    tf.write_atomic(table.replace_schema_metadata(metadata), path)


def read_local_summary(path: Path, layer: Layer, planet: str, group: int, extra: str | None = None
                       ) -> dict | None:
    """The recorded summary of a finished local file written by this code, else None."""
    path = Path(path)
    if not path.exists():
        return None
    try:
        metadata = pq.read_schema(path).metadata or {}
        get = lambda k: metadata.get(k.encode(), b'').decode()  # noqa: E731
        if (get('layer') != layer.slug or get('planet') != planet or get('band_group') != str(group)
                or get('code_version') != layer.code_version or get('extra') != (extra or '')):
            return None
        summary = json.loads(get('layer_summary'))
        rows = pq.read_metadata(path).num_rows
    except Exception:
        return None
    if rows != group_cell_count(planet_grid(planet), group) or summary.get('rows') != rows:
        return None
    return summary


# --------------------------------------------------------------------------
# logging
# --------------------------------------------------------------------------

class JsonlLog:
    def __init__(self, path: Path | None, **base):
        self.path = path
        self.base = base

    def write(self, event: str, **fields) -> None:
        if self.path is None:
            return
        record = {'ts': _now(), 'event': event, **self.base, **fields}
        self.path.parent.mkdir(parents=True, exist_ok=True)
        with self.path.open('a', encoding='utf8') as f:
            f.write(json.dumps(record, default=_json_default) + '\n')


# --------------------------------------------------------------------------
# context handed to layer functions
# --------------------------------------------------------------------------

@dataclass
class Options:
    planet: str
    bands: list[int] | None = None
    resume: bool = False
    workers: int = 4
    cache_max_bytes: int = 10 * GB
    retries: int = 4
    dry_run: bool = False
    upload: bool = True
    out: Path = DEFAULT_OUT
    cache_dir: Path | None = None
    log_dir: Path | None = DEFAULT_LOG_DIR
    raw_root: Path | None = None        # None: RAW_ROOT, looked up when used
    interim_root: Path | None = None    # None: INTERIM_ROOT
    interim_max_bytes: int = 50 * GB


class LayerContext:
    """What ``prepare``/``plan``/``reduce``/``finalize`` receive as ``ctx``."""

    def __init__(self, run: 'LayerRun'):
        self._run = run
        layer, opts = run.layer, run.opts
        self.slug = layer.slug
        self.planet = run.planet
        self.layer_version = layer.layer_version
        self.code_version = layer.code_version
        self.source = layer.source
        self.grid = planet_grid(run.planet)
        self.retries = opts.retries
        self.workers = opts.workers
        self.dry_run = opts.dry_run
        self.raw_dir = Path(opts.raw_root or RAW_ROOT) / run.planet / layer.slug
        self.interim_dir = Path(opts.interim_root or INTERIM_ROOT) / run.planet / layer.slug
        self.interim_cap_bytes = opts.interim_max_bytes
        self.band_group: int | None = None
        self.bands: list[int] = []
        self.cache_dir: Path | None = None
        self.state: dict = {}                  # free for the layer, kept across calls in one run
        self.source_checksum: str | None = None  # set in prepare() to pin e.g. a file's SHA-256
        self.source_files: dict[str, dict] = {}
        self._finalizing = False
        self._staged: list[tuple[str, int, Path, dict]] = []
        self._finalize_checksum: str | None = None
        self._read_cache: dict[str, Path] = {}

    # -- grid and shared inputs --------------------------------------------
    @property
    def band_groups(self) -> list[int]:
        return list(range(n_groups(self.grid)))

    def cells(self, band_group: int | None = None) -> pa.Table:
        return cells_table(self.planet, self._group(band_group))

    def read_terrain(self, columns, band_group: int | None = None) -> pa.Table:
        return read_terrain(self.planet, self._group(band_group), columns)

    def land_frac(self, band_group: int | None = None) -> pa.Table:
        if self.planet != 'earth':
            raise LayerError('the land mask is Earth-only')
        return earth_land_frac(self._group(band_group))

    def _group(self, band_group):
        group = self.band_group if band_group is None else band_group
        if group is None:
            raise LayerError('no current band group; pass band_group')
        return group

    # -- prepare helpers ---------------------------------------------------
    def download(self, url: str, dest: Path | str | None = None, *, headers: dict | None = None,
                 sha256: str | None = None) -> Path:
        """Fetch a small file into ``raw_dir`` (default) with retries; skip it if already there."""
        dest = Path(dest) if dest else self.raw_dir / (Path(urllib.parse.urlparse(http_url(url)).path).name
                                                         or 'download')
        dest.parent.mkdir(parents=True, exist_ok=True)
        if dest.exists() and (sha256 is None or sha256_file(dest) == sha256):
            return dest
        partial = dest.with_name(f'.{dest.name}.part')

        class _File:
            def __init__(self, fh):
                self.fh, self.hash = fh, hashlib.sha256()

            def write(self, data):
                self.fh.write(data)
                self.hash.update(data)
                return len(data)

        def attempt():
            with open(partial, 'wb') as fh:
                sink = _File(fh)
                fetch_http(Item(key=url, url=url, headers=headers or {}), sink)
            if sha256 and sink.hash.hexdigest() != sha256:
                raise TransientError(f'{url}: SHA-256 mismatch')
            os.replace(partial, dest)
        try:
            with_retries(attempt, self.retries, f'download {url}')
        finally:
            partial.unlink(missing_ok=True)
        return dest

    def record_source_file(self, path: Path | str, name: str | None = None) -> str:
        """Hash a source file and record it in the progress file and the manifest."""
        path = Path(path)
        digest = sha256_file(path)
        self.source_files[name or path.name] = {'sha256': digest, 'size': path.stat().st_size}
        return digest

    def interim_bytes(self) -> int:
        return du(self.interim_dir)

    def check_interim(self) -> int:
        """Raise when the interim folder is over --interim-max-gb; call it while streaming."""
        size = self.interim_bytes()
        if size > self.interim_cap_bytes:
            raise CacheCapExceeded(f'{self.interim_dir} holds {human(size)}, over the interim cap of '
                                   f'{human(self.interim_cap_bytes)}')
        return size

    def log(self, **fields) -> None:
        self._run.log.write('layer_note', band_group=self.band_group, **fields)

    # -- finalize helpers --------------------------------------------------
    def read_layer(self, band_group: int, columns=None, extra: str | None = None) -> pa.Table:
        """One already-written band group of this layer (local copy if present, else the Hub)."""
        run = self._run
        local = run.local_path(band_group, extra)
        if local.exists():
            return pq.read_table(local, columns=columns)
        if not run.opts.upload:
            raise LayerError(f'{local} does not exist (and --no-upload means there is no Hub copy)')
        remote = run.layer.relative_group_path(run.planet, band_group, extra)
        table = run.hub.read_parquet(remote, columns=columns)
        if table is None:
            raise LayerError(f'{remote} is not on the Hub')
        return table

    def write_extra(self, name: str, band_group: int, table) -> None:
        """Stage an extra column set for one band group (finalize only). Uploaded after finalize."""
        if not self._finalizing:
            raise LayerError('write_extra is only available inside finalize()')
        run = self._run
        if name not in run.layer.extra_columns:
            raise LayerError(f'{run.slug}: extra set {name!r} is not declared in EXTRA_COLUMNS')
        if any(n == name and g == band_group for n, g, _, _ in self._staged):
            raise LayerError(f'{run.slug}: extra {name!r} band group {band_group} written twice')
        full, summary = assemble_table(run.layer, self, band_group, table, run.layer.extra_columns[name],
                                       source_checksum=self._finalize_checksum, computed_at=_now(),
                                       extra=name)
        path = run.local_path(band_group, name)
        write_group_file(full, summary, path)
        self._staged.append((name, band_group, path, summary))


# --------------------------------------------------------------------------
# running layers
# --------------------------------------------------------------------------

@dataclass
class Outcome:
    table: Any = None
    error: BaseException | None = None
    trace: str = ''
    empty_plan: bool = False
    items: list[Item] = field(default_factory=list)
    absent: list[str] = field(default_factory=list)
    coverage: Any = None        # optional (region_id, asset_id, coverage_frac) table from reduce()


def _new_progress(layer: Layer, planet: str) -> dict:
    return {'layer': layer.slug, 'planet': planet, 'layer_version': layer.layer_version,
            'grid_version': GRID_VERSION, 'groups': {}, 'extras': {}, 'source_files': {},
            'updated_at': None}


def _entry_on_remote(entry: dict | None, listing: dict[str, RemoteFile], code_version: str) -> bool:
    if not entry or entry.get('code_version') != code_version:
        return False
    remote = listing.get(entry['path'])
    return remote is not None and remote.matches(entry['size'], entry['sha256'], entry.get('git_blob_id'))


class LayerRun:
    """One layer on one planet for one invocation."""

    def __init__(self, layer: Layer, planet: str, opts: Options, hub: HubStore | None):
        self.layer = layer
        self.slug = layer.slug
        self.planet = planet
        self.opts = opts
        self.hub = hub
        log_path = (None if opts.dry_run or opts.log_dir is None
                    else Path(opts.log_dir) / f'{layer.slug}_{planet}.jsonl')
        self.log = JsonlLog(log_path, layer=layer.slug, planet=planet,
                            layer_version=layer.layer_version)
        self.ctx = LayerContext(self)
        self.broken: str | None = None
        self.progress: dict | None = None
        self.listing: dict[str, RemoteFile] = {}

    def local_path(self, group: int, extra: str | None = None) -> Path:
        relative = self.layer.relative_group_path(self.planet, group, extra).removeprefix('layers/')
        return Path(self.opts.out) / relative

    def catalog_files(self, group: int) -> dict[str, Path]:
        """remote path -> local path of the catalog files that travel with one band group."""
        remote = [catalog_schema.staging_path(self.planet, self.slug, group),
                  catalog_schema.region_assets_path(self.planet, self.slug, group)]
        return {r: Path(self.opts.out) / r for r in remote}

    def _build_catalog(self, group: int, outcome: 'Outcome') -> dict:
        """Write this band group's assets rows and region_assets rows beside its feature file.

        Returns a small summary (empty when no item carried asset metadata).
        """
        staging, region = self.catalog_files(group).values()
        for path in (staging, region):
            path.unlink(missing_ok=True)
        rows, linked = catalog_assets.rows_from_items(
            outcome.items, planet=self.planet, layer=self.slug, source=self.layer.source,
            raw_root=Path(self.opts.raw_root or RAW_ROOT))
        if not rows:
            if outcome.coverage is not None:
                raise LayerError(f'{self.slug} band group {group:03d}: reduce returned a coverage '
                                 f'table but no item carries asset metadata')
            return {}
        info = {'assets_rows': len(rows)}
        tf.write_atomic(catalog_schema.assets_table(rows), staging)
        cells = cells_table(self.planet, group)
        if outcome.coverage is not None:
            table = _check_coverage(outcome.coverage, cells, {r['asset_id'] for r in rows},
                                    f'{self.slug} band group {group:03d}')
        elif linked:
            table = catalog_coverage.coverage_table(
                cells, [(r['asset_id'], r['footprint']) for r in rows if r['asset_id'] in linked])
        else:
            return info
        tf.write_atomic(table, region)
        info['region_assets_rows'] = table.num_rows
        return info

    # -- status --------------------------------------------------------------
    def refresh(self) -> None:
        if self.opts.upload:
            self.progress = (self.hub.read_json(self.layer.progress_path(self.planet))
                             or _new_progress(self.layer, self.planet))
            self.listing = self.hub.list(self.layer.remote_prefix(self.planet))
        else:
            self.progress, self.listing = None, {}

    def group_done(self, group: int, extra: str | None = None) -> bool:
        if not self.opts.upload:
            return read_local_summary(self.local_path(group, extra), self.layer, self.planet, group,
                                      extra) is not None
        key = f'{group:03d}'
        entry = (self.progress['groups'].get(key) if extra is None
                 else self.progress.get('extras', {}).get(extra, {}).get(key))
        return _entry_on_remote(entry, self.listing, self.layer.code_version)

    # -- prepare -------------------------------------------------------------
    def prepare(self) -> None:
        prepare = getattr(self.layer.module, 'prepare', None)
        if not callable(prepare):
            return
        started = time.monotonic()
        prepare(self.ctx)
        size = self.ctx.check_interim()
        print(f'{self.slug} {self.planet}: prepare done in {time.monotonic() - started:.1f}s, '
              f'interim folder {human(size)} ({self.ctx.interim_dir})', flush=True)
        self.log.write('prepare', seconds=time.monotonic() - started, interim_bytes=size,
                       interim_dir=self.ctx.interim_dir, raw_bytes=du(self.ctx.raw_dir),
                       source_files=self.ctx.source_files)

    # -- per band group ------------------------------------------------------
    def finish_group(self, group: int, outcome: Outcome, stats: dict, shared_with: list[str]) -> bool:
        base = {'band_group': group, **stats, 'code_version': self.layer.code_version}
        if shared_with:
            base['pass_group'] = self.layer.pass_group
            base['shared_with'] = shared_with
        base['items_planned'] = len(outcome.items)
        base['items_absent'] = len(outcome.absent)
        if outcome.error is not None:
            return self._failed(group, outcome.error, outcome.trace, base)
        try:
            checksum = self.ctx.source_checksum or items_checksum(outcome.items)
            table, summary = assemble_table(self.layer, self.ctx, group, outcome.table,
                                            self.layer.columns, source_checksum=checksum,
                                            computed_at=_now())
            summary['run'] = {k: base[k] for k in ('seconds', 'items_planned', 'items_absent',
                                                   'bytes_read', 'peak_cache_bytes', 'fetches',
                                                   'refetches', 'retried') if k in base}
            summary['items_absent'] = outcome.absent[:50]
            catalog_info = self._build_catalog(group, outcome)
            if catalog_info:
                summary['catalog'] = catalog_info
            path = self.local_path(group)
            if self.planet == 'earth' and self.layer.pass_group == 'copdem_glo30':
                print(f'{_now()} Copernicus group {group:03d} writing Parquet {self.slug}', flush=True)
            write_group_file(table, summary, path)
        except Exception as exc:
            return self._failed(group, exc, traceback.format_exc(), base)
        base['rows'] = summary['rows']
        base['rows_without_data'] = summary['rows_without_data']
        if not self.opts.upload:
            self.log.write('band_group', status='written', path=path, **base)
            print(self._line(group, base, f'written {path}'), flush=True)
            return True
        return self.upload_group(group, path, summary, base)

    def _failed(self, group, exc, trace, base) -> bool:
        message = f'{type(exc).__name__}: {exc}'
        print(f'{self.slug} {self.planet} group {group:03d}: FAILED, nothing written: {message}',
              file=sys.stderr, flush=True)
        self.log.write('band_group', status='failed', error=message, traceback=trace[-4000:], **base)
        return False

    def _line(self, group, base, tail) -> str:
        return (f"{self.slug} {self.planet} group {group:03d}: {base.get('items_planned', 0)} items "
                f"({base.get('items_absent', 0)} absent), {human(base.get('bytes_read'))} read, "
                f"peak cache {human(base.get('peak_cache_bytes'))}, {base.get('rows', 0)} rows, "
                f"{base.get('seconds', 0):.1f}s -> {tail}")

    def upload_group(self, group: int, path: Path, summary: dict, base: dict) -> bool:
        remote_path = self.layer.relative_group_path(self.planet, group)
        key = f'{group:03d}'
        size, sha, blob = path.stat().st_size, sha256_file(path), git_blob_id_file(path)
        bands = group_bands(planet_grid(self.planet), group)
        entry = {'path': remote_path, 'size': size, 'sha256': sha, 'git_blob_id': blob,
                 'code_version': self.layer.code_version, 'bands': [bands[0], bands[-1]],
                 **{k: summary[k] for k in ('rows', 'expected_rows', 'rows_with_data',
                                            'rows_without_data', 'columns', 'flags', 'checks',
                                            'schema_sha256', 'source_checksum', 'computed_at')},
                 'run': summary.get('run', {})}
        catalog = {r: p for r, p in self.catalog_files(group).items() if p.exists()}
        if summary.get('catalog'):
            entry['catalog'] = {**summary['catalog'], 'files': sorted(catalog)}
        started = time.monotonic()

        def mutate(progress):
            progress = progress or _new_progress(self.layer, self.planet)
            progress.setdefault('groups', {})[key] = entry
            progress.setdefault('source_files', {}).update(self.ctx.source_files)
            progress['interim_bytes'] = self.ctx.interim_bytes()
            progress['updated_at'] = _now()
            return progress

        def already(progress, head):
            done = (progress or {}).get('groups', {}).get(key)
            if not done or done.get('sha256') != sha:
                return False
            remote = self.hub.info([remote_path], revision=head).get(remote_path)
            return remote is not None and remote.matches(size, sha, blob)

        try:
            oid, progress = self.hub.commit_update(
                {remote_path: path, **catalog},
                f'layer {self.layer.layer_version} {self.planet} band_group={key} '
                f'(code {self.layer.code_version[:12]})',
                self.layer.progress_path(self.planet), mutate, already)
            remote = self.hub.info([remote_path], revision=oid).get(remote_path)
            if remote is None or not remote.matches(size, sha, blob):
                raise UploadError(f'{remote_path} on the Hub does not match the local file '
                                  f'(remote {remote}, local size {size} sha256 {sha})')
            if catalog:
                info = self.hub.info(list(catalog), revision=oid)
                for rpath, lpath in catalog.items():
                    got = info.get(rpath)
                    if got is None or not got.matches(lpath.stat().st_size, sha256_file(lpath),
                                                      git_blob_id_file(lpath)):
                        raise UploadError(f'{rpath} on the Hub does not match the local file')
        except Exception as exc:
            base['upload_seconds'] = time.monotonic() - started
            message = f'{type(exc).__name__}: {exc}'
            print(f'{self.slug} {self.planet} group {key}: UPLOAD FAILED, local file kept at {path}: '
                  f'{message}', file=sys.stderr, flush=True)
            self.log.write('band_group', status='upload_failed', error=message, path=path, **base)
            return False
        path.unlink()
        for lpath in catalog.values():
            lpath.unlink(missing_ok=True)
        self.progress = progress
        self.listing[remote_path] = remote
        base['upload_seconds'] = time.monotonic() - started
        base['commit'] = oid
        self.log.write('band_group', status='uploaded', remote_path=remote_path, size=size,
                       sha256=sha, **base)
        print(self._line(group, base, f'{remote_path} ({human(size)}, upload '
                                      f'{base["upload_seconds"]:.1f}s)'), flush=True)
        return True

    def reuse_local(self, group: int) -> bool | None:
        """Upload a finished local file left by an interrupted run instead of recomputing it."""
        path = self.local_path(group)
        summary = read_local_summary(path, self.layer, self.planet, group)
        if summary is None:
            return None
        print(f'{self.slug} {self.planet} group {group:03d}: uploading the finished local file '
              f'from an earlier run ({path})', flush=True)
        base = {'band_group': group, 'reused_local': True, 'rows': summary['rows'],
                'code_version': self.layer.code_version, **summary.get('run', {})}
        return self.upload_group(group, path, summary, base)

    # -- finalize -------------------------------------------------------------
    def finalize(self) -> bool:
        groups = list(range(n_groups(planet_grid(self.planet))))
        self.refresh()
        missing = [g for g in groups if not self.group_done(g)]
        if missing:
            print(f'{self.slug} {self.planet}: finalize waits for {len(missing)} band group(s) '
                  f'(first {missing[:5]})', flush=True)
            self.log.write('finalize', status='waiting', missing_groups=missing)
            return True
        names = list(self.layer.extra_columns)
        if self.opts.resume and all(self.group_done(g, n) for n in names for g in groups):
            print(f'{self.slug} {self.planet}: finalize already complete, skipped', flush=True)
            self.log.write('finalize', status='skipped')
            return True
        if self.opts.upload:
            shas = [self.progress['groups'][f'{g:03d}']['sha256'] for g in groups]
        else:
            shas = [sha256_file(self.local_path(g)) for g in groups]
        ctx = self.ctx
        ctx._finalize_checksum = 'groups-sha256:' + hashlib.sha256(''.join(shas).encode()).hexdigest()
        ctx._finalizing, ctx._staged, ctx.band_group = True, [], None
        started = time.monotonic()
        try:
            self.layer.module.finalize(ctx)
            for name in names:
                written = {g for n, g, _, _ in ctx._staged if n == name}
                if written != set(groups):
                    raise LayerError(f'finalize wrote extra {name!r} for {len(written)} of '
                                     f'{len(groups)} band groups')
        except Exception as exc:
            for _, _, path, _ in ctx._staged:
                path.unlink(missing_ok=True)
            message = f'{type(exc).__name__}: {exc}'
            print(f'{self.slug} {self.planet}: finalize FAILED, nothing uploaded: {message}',
                  file=sys.stderr, flush=True)
            self.log.write('finalize', status='failed', error=message,
                           traceback=traceback.format_exc()[-4000:])
            return False
        finally:
            ctx._finalizing = False
        seconds = time.monotonic() - started
        staged = sorted(ctx._staged, key=lambda s: (s[0], s[1]))
        if not self.opts.upload:
            self.log.write('finalize', status='written', seconds=seconds, files=len(staged))
            print(f'{self.slug} {self.planet}: finalize wrote {len(staged)} extra files locally '
                  f'in {seconds:.1f}s', flush=True)
            return True
        return self._upload_extras(staged, seconds)

    def _upload_extras(self, staged, seconds) -> bool:
        started = time.monotonic()
        for i in range(0, len(staged), EXTRA_FILES_PER_COMMIT):
            batch = staged[i:i + EXTRA_FILES_PER_COMMIT]
            files, entries = {}, {}
            for name, group, path, summary in batch:
                remote_path = self.layer.relative_group_path(self.planet, group, name)
                files[remote_path] = path
                entries[(name, f'{group:03d}')] = {
                    'path': remote_path, 'size': path.stat().st_size, 'sha256': sha256_file(path),
                    'git_blob_id': git_blob_id_file(path), 'code_version': self.layer.code_version,
                    **{k: summary[k] for k in ('rows', 'expected_rows', 'columns', 'flags', 'checks',
                                               'schema_sha256', 'source_checksum', 'computed_at')}}

            def mutate(progress, entries=entries):
                progress = progress or _new_progress(self.layer, self.planet)
                for (name, key), entry in entries.items():
                    progress.setdefault('extras', {}).setdefault(name, {})[key] = entry
                progress.setdefault('finalize', {})['seconds'] = seconds
                progress['updated_at'] = _now()
                return progress

            def already(progress, head, entries=entries):
                extras = (progress or {}).get('extras', {})
                if not all(extras.get(n, {}).get(k, {}).get('sha256') == e['sha256']
                           for (n, k), e in entries.items()):
                    return False
                info = self.hub.info([e['path'] for e in entries.values()], revision=head)
                return all(info.get(e['path']) and info[e['path']].matches(
                    e['size'], e['sha256'], e['git_blob_id']) for e in entries.values())
            try:
                oid, progress = self.hub.commit_update(
                    files, f'layer {self.layer.layer_version} {self.planet} finalize '
                           f'{i // EXTRA_FILES_PER_COMMIT + 1} (code {self.layer.code_version[:12]})',
                    self.layer.progress_path(self.planet), mutate, already)
                info = self.hub.info(list(files), revision=oid)
                for e in entries.values():
                    if not (info.get(e['path']) and info[e['path']].matches(
                            e['size'], e['sha256'], e['git_blob_id'])):
                        raise UploadError(f'{e["path"]} on the Hub does not match the local file')
            except Exception as exc:
                message = f'{type(exc).__name__}: {exc}'
                print(f'{self.slug} {self.planet}: finalize UPLOAD FAILED (local files kept): '
                      f'{message}', file=sys.stderr, flush=True)
                self.log.write('finalize', status='upload_failed', error=message)
                return False
            for path in files.values():
                path.unlink()
            self.progress = progress
        self.log.write('finalize', status='uploaded', seconds=seconds, files=len(staged),
                       upload_seconds=time.monotonic() - started)
        print(f'{self.slug} {self.planet}: finalize uploaded {len(staged)} extra files '
              f'({seconds:.1f}s compute, {time.monotonic() - started:.1f}s upload)', flush=True)
        return True


def run_band_group(runs: list[LayerRun], group: int, opts: Options, cache_root: Path
                   ) -> tuple[dict[str, Outcome], dict]:
    """Plan, fetch and reduce one band group for the layers of one pass. Wipes the cache after."""
    grid = planet_grid(opts.planet)
    bands = group_bands(grid, group)
    outcomes: dict[str, Outcome] = {}
    plans: dict[str, list[Item]] = {}
    started = time.monotonic()
    for run in runs:
        run.ctx.band_group, run.ctx.bands = group, bands
        try:
            plans[run.slug] = normalize_items(run.layer.module.plan(group, run.ctx), run.slug)
        except Exception as exc:
            outcomes[run.slug] = Outcome(error=exc, trace=traceback.format_exc())
    cache = GroupCache(cache_root / f'group_{group:03d}', opts.cache_max_bytes,
                       retries=opts.retries, workers=opts.workers)
    try:
        for slug, items in list(plans.items()):
            try:
                cache.register(slug, items)
            except LayerError as exc:
                outcomes[slug] = Outcome(error=exc, trace=traceback.format_exc(), items=items)
                del plans[slug]
        active = [r for r in runs if plans.get(r.slug)]
        for run in runs:
            if run.slug in plans and not plans[run.slug]:
                outcomes[run.slug] = Outcome(empty_plan=True)
        cache.add_consumers(len(active))

        def work(run: LayerRun) -> None:
            run.ctx.cache_dir = cache.root
            items = Items(cache, run.slug, plans[run.slug])
            try:
                table = run.layer.module.reduce(group, items, run.ctx)
                coverage = None
                if isinstance(table, tuple):
                    if len(table) != 2:
                        raise LayerError(f'{run.slug}.reduce returned a {len(table)}-tuple; return a '
                                         f'table or (feature table, coverage table)')
                    table, coverage = table
                if items.failed:
                    raise FetchFailed(f'{len(items.failed)} item(s) failed to fetch, so the band group '
                                      f'stops instead of writing NaNs: {items.failed[:5]}')
                if table is None:
                    raise LayerError(f'{run.slug}.reduce returned None; return a pyarrow.Table')
                outcomes[run.slug] = Outcome(table=table, items=plans[run.slug], absent=items.absent,
                                             coverage=coverage)
            except Exception as exc:
                outcomes[run.slug] = Outcome(error=exc, trace=traceback.format_exc(),
                                             items=plans[run.slug], absent=items.absent)
            finally:
                cache.finish(run.slug)

        if len(active) == 1:
            work(active[0])
        elif active:
            threads = [threading.Thread(target=work, args=(r,), name=f'reduce-{r.slug}') for r in active]
            for thread in threads:
                thread.start()
            for thread in threads:
                thread.join()
    finally:
        stats = cache.stats()
        stats['cache_bytes_left'] = cache.close()
        for run in runs:
            run.ctx.cache_dir = None
    stats['seconds'] = time.monotonic() - started
    stats['cache_files_after_wipe'] = sum(1 for p in cache.root.rglob('*')) if cache.root.exists() else 0
    return outcomes, stats


def _pass_groups(runs: list[LayerRun]) -> list[list[LayerRun]]:
    groups: dict[str, list[LayerRun]] = {}
    for run in runs:
        groups.setdefault(run.layer.pass_group or f'__{run.slug}', []).append(run)
    return list(groups.values())


def _dry_run_plan(runs: list[LayerRun], todo: dict[int, list[LayerRun]], opts: Options) -> None:
    print(f'DRY RUN: planning only; nothing is fetched, written or uploaded '
          f'(prepare() is not run, so a plan that needs it reports an error)')
    for group, need in todo.items():
        seen: dict[str, Item] = {}
        for run in need:
            run.ctx.band_group, run.ctx.bands = group, group_bands(planet_grid(opts.planet), group)
            try:
                items = normalize_items(run.layer.module.plan(group, run.ctx), run.slug)
            except Exception as exc:
                print(f'  group {group:03d} {run.slug}: plan failed: {type(exc).__name__}: {exc}')
                continue
            sizes = [i.expected_size() for i in items]
            known = [s for s in sizes if s is not None]
            fits = all(s <= opts.cache_max_bytes for s in known)
            print(f'  group {group:03d} {run.slug}: {len(items)} items, {human(sum(known))} of known '
                  f'size (+{len(sizes) - len(known)} unknown), largest {human(max(known, default=0))}'
                  f'{"" if fits else "  ** an item is larger than --cache-max-gb **"}'
                  f'{"  (no source data: rows get fill values)" if not items else ""}')
            for item in items:
                seen.setdefault(item.key, item)
        if len(need) > 1:
            print(f'  group {group:03d} pass total: {len(seen)} distinct items')


def run_layers(layers: list[Layer], opts: Options, hub: HubStore | None) -> int:
    planet = opts.planet
    grid = planet_grid(planet)
    groups = groups_for_bands(grid, opts.bands)
    runs = []
    for layer in layers:
        if planet not in layer.planets:
            only = layer.planets[0]
            print(f'{layer.slug}: {only.capitalize()}-only layer; it writes no {planet.capitalize()} '
                  f'rows (recorded in its manifest feature dictionary). Nothing to do.', flush=True)
            if not opts.dry_run and opts.log_dir is not None:
                JsonlLog(Path(opts.log_dir) / f'{layer.slug}_{planet}.jsonl', layer=layer.slug,
                         planet=planet).write('not_applicable', layer_planets=list(layer.planets))
            continue
        runs.append(LayerRun(layer, planet, opts, hub))
    if not runs:
        return 0
    if opts.upload:
        # fail before computing anything: a missing repo or token would otherwise look like
        # "nothing uploaded yet" (404) and only surface after the first band group
        try:
            hub.head()
        except Exception as exc:
            print(f'error: cannot reach {hub.repo_id} on the Hub ({type(exc).__name__}: {exc}); '
                  f'log in (hf auth login) or use --no-upload', file=sys.stderr)
            return 2
    cache_root =Path(opts.cache_dir) if opts.cache_dir else Path(tempfile.mkdtemp(prefix='layer-cache-'))
    cache_root.mkdir(parents=True, exist_ok=True)
    failures = 0
    try:
        for pass_runs in _pass_groups(runs):
            failures += _run_pass(pass_runs, groups, opts, cache_root)
    finally:
        if not opts.cache_dir:
            shutil.rmtree(cache_root, ignore_errors=True)
    if failures:
        print(f'{failures} band group(s) or finalize step(s) failed; see the log(s) in {opts.log_dir}. '
              f'Re-run with --resume to retry only those.', file=sys.stderr, flush=True)
    return 1 if failures else 0


def _run_pass(runs: list[LayerRun], groups: list[int], opts: Options, cache_root: Path) -> int:
    names = ','.join(r.slug for r in runs)
    for run in runs:
        run.refresh()
    todo: dict[int, list[LayerRun]] = {}
    for group in groups:
        need = []
        for run in runs:
            if opts.resume and run.group_done(group):
                print(f'{run.slug} {run.planet} group {group:03d}: already complete with this '
                      f'code_version, skipped', flush=True)
                run.log.write('band_group', band_group=group, status='skipped')
            else:
                need.append(run)
        if need:
            todo[group] = need
    if opts.dry_run:
        _dry_run_plan(runs, todo, opts)
        return 0
    print(f'{names} ({opts.planet}): {len(todo)} band group(s) to run, cache cap '
          f'{opts.cache_max_bytes / GB:g} GB, {opts.workers} fetch worker(s)', flush=True)
    failures = 0
    for run in runs:
        try:
            run.prepare()
        except Exception as exc:
            run.broken = f'{type(exc).__name__}: {exc}'
            print(f'{run.slug} {run.planet}: prepare FAILED, layer skipped: {run.broken}',
                  file=sys.stderr, flush=True)
            run.log.write('prepare', status='failed', error=run.broken,
                          traceback=traceback.format_exc()[-4000:])
            failures += 1
    for group, need in todo.items():
        need = [r for r in need if not r.broken]
        if opts.upload and opts.resume:
            remaining = []
            for run in need:
                reused = run.reuse_local(group)
                if reused is None:
                    remaining.append(run)
                elif not reused:
                    failures += 1
            need = remaining
        if not need:
            continue
        outcomes, stats = run_band_group(need, group, opts, cache_root)
        for run in need:
            shared = [r.slug for r in need if r is not run]
            if not run.finish_group(group, outcomes[run.slug], dict(stats), shared):
                failures += 1
    for run in runs:
        if run.layer.has_finalize and not run.broken:
            if not run.finalize():
                failures += 1
    return failures


# --------------------------------------------------------------------------
# publishing
# --------------------------------------------------------------------------

CARD_HEADING = '## Layers'
CARD_INTRO = ('Dataset layers on the `latband5km-v1` grid, one file per 100 latitude bands with one row '
              'per cell. Join on `grid_version` + `region_id`. Each layer has its own manifest under '
              '`manifests/` and its own tag.')


def _public_columns(columns: dict[str, dict], stats: dict[str, dict]) -> list[dict]:
    out = []
    for name, spec in columns.items():
        row = {'name': name, 'dtype': spec['dtype'], 'unit': spec.get('unit'),
               'comparison': spec.get('comparison'), 'description': spec.get('description'),
               'fill_for_cells_without_data': spec.get('fill', 'NaN' if pa.types.is_floating(
                   spec['_type']) else None)}
        row.update(stats.get(name, {}))
        out.append(row)
    return out


def _aggregate_stats(entries: list[dict]) -> dict[str, dict]:
    out: dict[str, dict] = {}
    for entry in entries:
        for name, stat in entry.get('columns', {}).items():
            agg = out.setdefault(name, {'n_null': 0})
            agg['n_null'] += stat.get('n_null', 0)
            for key in ('n_nan', 'n_finite', 'sum'):
                if key in stat:
                    agg[key] = agg.get(key, 0) + stat[key]
            if stat.get('min') is not None:
                agg['min'] = stat['min'] if agg.get('min') is None else min(agg['min'], stat['min'])
            if stat.get('max') is not None:
                agg['max'] = stat['max'] if agg.get('max') is None else max(agg['max'], stat['max'])
    for agg in out.values():
        if agg.get('n_finite'):
            agg['mean'] = agg.pop('sum') / agg['n_finite']
        else:
            agg.pop('sum', None)
    return out


def _undocumented(columns: dict[str, dict]) -> list[str]:
    problems = []
    for name, spec in columns.items():
        if not spec.get('unit'):
            problems.append(f'{name}: no unit')
        if not spec.get('description'):
            problems.append(f'{name}: no description')
        if spec.get('comparison') not in COMPARISON_MODES:
            problems.append(f'{name}: comparison {spec.get("comparison")!r} not in '
                            f'{sorted(COMPARISON_MODES)}')
    return problems


def build_publication(run: LayerRun) -> dict:
    """Everything a publish would upload, and the checks that decide whether it may."""
    layer, planet = run.layer, run.planet
    run.refresh()
    progress, listing = run.progress, run.listing
    grid = planet_grid(planet)
    groups = list(range(n_groups(grid)))
    cv = layer.code_version
    entries = {g: progress.get('groups', {}).get(f'{g:03d}') for g in groups}
    checks: list[dict] = []

    def check(name, ok, detail=''):
        checks.append({'name': name, 'ok': bool(ok), 'detail': detail})

    present = [g for g in groups if _entry_on_remote(entries[g], listing, cv)]
    absent = [g for g in groups if g not in present]
    check('all_band_groups_present', not absent,
          f'{len(present)}/{len(groups)} band groups on the Hub with code_version {cv[:12]}'
          + (f'; missing or stale: {absent[:10]}' if absent else ''))
    stale = sorted(g for g, e in entries.items() if e and e.get('code_version') != cv)
    check('code_version_matches_data', not stale,
          f'band groups written by other code: {stale[:10]}' if stale else
          f'every recorded band group was written by code_version {cv[:12]}')
    expected = {g: group_cell_count(grid, g) for g in groups}
    total_rows = sum(entries[g]['rows'] for g in present)
    bad_rows = [g for g in present if entries[g]['rows'] != expected[g]]
    check('rows_match_grid', not bad_rows and not absent and total_rows == grid.number_of_cells,
          f'{total_rows} rows for {grid.number_of_cells} grid cells'
          + (f'; wrong counts in {bad_rows[:10]}' if bad_rows else ''))
    bad_ids = [g for g in present if not all(entries[g].get('checks', {}).values())]
    check('region_ids_unique_and_match_grid', not bad_ids,
          f'failing groups: {bad_ids[:10]}' if bad_ids else 'one row per cell, unique ids, grid order')
    schemas = {entries[g].get('schema_sha256') for g in present}
    check('schema_consistent', len(schemas) <= 1, f'{len(schemas)} distinct schemas')
    problems = _undocumented(layer.columns)
    for name, spec in layer.extra_columns.items():
        problems += [f'extra {name}: {p}' for p in _undocumented(spec)]
    check('columns_documented', not problems, '; '.join(problems[:10]) or 'unit, description and '
          'comparison mode for every column')
    extras_out = {}
    if layer.has_finalize:
        missing_extras = []
        for name in layer.extra_columns:
            recorded = progress.get('extras', {}).get(name, {})
            ok = [g for g in groups if _entry_on_remote(recorded.get(f'{g:03d}'), listing, cv)]
            missing_extras += [f'{name}:{g:03d}' for g in groups if g not in ok]
            extras_out[name] = {
                'pattern': f'{layer.remote_prefix(planet)}/extra={name}/band_group=NNN.parquet',
                'files': len(ok),
                'columns': _public_columns(layer.extra_columns[name], _aggregate_stats(
                    [recorded[f'{g:03d}'] for g in ok]))}
        check('extras_complete', not missing_extras,
              f'missing: {missing_extras[:10]}' if missing_extras else
              f'{len(layer.extra_columns)} extra set(s) on every band group')

    good = [entries[g] for g in present]
    stats = _aggregate_stats(good)
    flags: dict[str, int] = {}
    for entry in good:
        for flag, n in entry.get('flags', {}).items():
            flags[flag] = flags.get(flag, 0) + n
    summary = {'rows': total_rows, 'columns': stats, 'flags': flags, 'groups': len(present)}
    validate = getattr(layer.module, 'validate', None)
    if callable(validate):
        try:
            for name, ok, detail in validate(summary, run.ctx):
                check(f'layer:{name}', ok, detail)
        except Exception as exc:
            check('layer:validate', False, f'validate() raised {type(exc).__name__}: {exc}')

    planets = {}
    for p in ('mars', 'earth'):
        if p in layer.planets:
            planets[p] = {'rows': True, 'note': 'one row per latband5km-v1 cell'}
        else:
            only = layer.planets[0]
            planets[p] = {'rows': False,
                          'note': f'{only.capitalize()}-only layer: no {p.capitalize()} rows are written'}
    limitations = list(getattr(layer.module, 'LIMITATIONS', []))
    if len(layer.planets) == 1:
        limitations.append(f'{layer.planets[0].capitalize()} only; there are no rows for the other '
                           f'planet.')
    absent_items = sum(e.get('run', {}).get('items_absent', 0) for e in good)
    if absent_items:
        limitations.append(f'{absent_items} planned source item(s) did not exist at the source; the '
                           f'affected cells carry NaN and a quality flag.')

    code_files = {f'code/layers/{layer.path.name}': layer.path, 'code/layers/driver.py': DRIVER_PATH}
    for path in layer.crosswalks:
        code_files[f'code/layers/{path.name}'] = path
    tag = layer.tag(planet)
    manifest = {
        'layer': layer.slug, 'layer_version': layer.layer_version, 'planet': planet,
        'grid_version': GRID_VERSION, 'repo': run.hub.repo_id, 'tag': tag,
        'files': {'pattern': f'{layer.remote_prefix(planet)}/band_group=NNN.parquet',
                  'band_groups': len(groups), 'bands_per_group': BANDS_PER_GROUP, 'extras': extras_out},
        'code_version': cv,
        'code_version_definition': 'SHA-256 over the layer module, then pipeline/layers/driver.py, '
                                   'then each crosswalk, in that order',
        'code_files': {dest: sha256_file(src) for dest, src in code_files.items()},
        'source': layer.source,
        'source_checksums': {f'{g:03d}': entries[g].get('source_checksum') for g in present},
        'source_files': progress.get('source_files', {}),
        'feature_dictionary': {
            'planets': planets,
            'metadata_columns': [*LEADING_COLUMNS, FLAGS_COLUMN, *TRAILING_COLUMNS],
            'columns': _public_columns(layer.columns, stats),
            'comparison_modes': COMPARISON_MODES,
            'missing_flag': layer.missing_flag() if isinstance(layer.missing_flag(), str)
            else 'set per cell by the layer (MISSING_FLAG callable)',
        },
        'quality_flags': dict(sorted(flags.items())),
        'rows': {'total': total_rows, 'expected': grid.number_of_cells,
                 'with_data': sum(e.get('rows_with_data', 0) for e in good),
                 'without_data': sum(e.get('rows_without_data', 0) for e in good),
                 'by_band_group': {f'{g:03d}': entries[g]['rows'] for g in present}},
        'validation': checks,
        'runtime': {'seconds': sum(e.get('run', {}).get('seconds', 0) for e in good),
                    'finalize_seconds': progress.get('finalize', {}).get('seconds'),
                    'by_band_group': {f'{g:03d}': entries[g].get('run', {}).get('seconds')
                                      for g in present}},
        'bytes_read': sum(e.get('run', {}).get('bytes_read', 0) for e in good),
        'peak_cache_bytes': max((e.get('run', {}).get('peak_cache_bytes', 0) for e in good), default=0),
        'interim_bytes': progress.get('interim_bytes'),
        'known_limitations': limitations,
    }
    files: dict[str, bytes] = {layer.manifest_path(planet): (dumps(manifest) + '\n').encode()}
    for dest, src in code_files.items():
        files[dest] = src.read_bytes()
    return {'manifest': manifest, 'checks': checks, 'files': files, 'tag': tag,
            'ok': all(c['ok'] for c in checks), 'card_section': render_card_section(layer, manifest)}


def _check_coverage(coverage, cells: pa.Table, asset_ids: set[str], where: str) -> pa.Table:
    """A coverage table a layer returned from reduce(): validated, typed, in the catalog schema."""
    if hasattr(coverage, 'to_dict') and hasattr(coverage, 'columns') and not isinstance(coverage, pa.Table):
        coverage = pa.Table.from_pandas(coverage, preserve_index=False)
    if not isinstance(coverage, pa.Table):
        raise LayerError(f'{where}: the coverage table must be a pyarrow.Table')
    missing = {'region_id', 'asset_id', 'coverage_frac'} - set(coverage.column_names)
    if missing:
        raise LayerError(f'{where}: the coverage table lacks {sorted(missing)}')
    n = coverage.num_rows
    region = coverage['region_id'].cast(pa.string())
    asset = coverage['asset_id'].cast(pa.string())
    frac = coverage['coverage_frac'].cast(pa.float64())
    if n:
        if pc.index_in(region, value_set=cells['region_id']).null_count:
            raise LayerError(f'{where}: coverage region_id(s) are not cells of this band group')
        unknown = sorted(set(asset.to_pylist()) - asset_ids)
        if unknown:
            raise LayerError(f'{where}: coverage names asset_id(s) no planned item carries, '
                             f'e.g. {unknown[:3]}')
        values = frac.to_numpy(zero_copy_only=False)
        if frac.null_count or not np.all(np.isfinite(values)) or values.min() < 0 or values.max() > 1 + 1e-6:
            raise LayerError(f'{where}: coverage_frac must be finite and within 0-1')
        pairs = pc.count_distinct(pc.binary_join_element_wise(region, asset, '|')).as_py()
        if pairs != n:
            raise LayerError(f'{where}: duplicate (region_id, asset_id) rows in the coverage table')
    return pa.table({'grid_version': pa.array([GRID_VERSION] * n, type=pa.string()), 'region_id': region,
                     'asset_id': asset,
                     'coverage_frac': pa.array(np.clip(frac.to_numpy(zero_copy_only=False), 0, 1)
                                               .astype(np.float32))},
                    schema=catalog_schema.REGION_ASSETS_SCHEMA)


def build_catalog_publication(run: LayerRun) -> tuple[dict[str, bytes], list[dict]]:
    """The merged ``assets`` file for a layer (staged band-group rows + any existing file, one row
    per asset_id) and a consistency check against the ``region_assets`` files on the Hub."""
    hub, planet, slug = run.hub, run.planet, run.slug
    staged = hub.list(f'catalog/assets_staging/planet={planet}/layer={slug}')
    if not staged:
        return {}, []
    path = catalog_schema.assets_path(planet, slug)
    tables = [hub.read_parquet(p) for p in sorted(staged)]
    merged = catalog_schema.merge_assets([*tables, hub.read_parquet(path)])
    buffer = io.BytesIO()
    pq.write_table(merged, buffer, compression='zstd')
    ids = set(merged['asset_id'].to_pylist())
    region_files = hub.list(f'catalog/region_assets/planet={planet}/layer={slug}')
    dangling, rows = 0, 0
    for rpath in sorted(region_files):
        table = hub.read_parquet(rpath, columns=['asset_id'])
        rows += table.num_rows
        dangling += sum(1 for a in set(table['asset_id'].to_pylist()) if a not in ids)
    check = {'name': 'catalog_assets_consistent', 'ok': dangling == 0,
             'detail': f'{merged.num_rows} assets rows, {rows} region_assets rows in {len(region_files)} '
                       f'file(s)' + (f'; {dangling} asset_id(s) in region_assets missing from assets'
                                     if dangling else '')}
    return {path: buffer.getvalue()}, [check]


def render_card_section(layer: Layer, manifest: dict) -> str:
    planet = manifest['planet']
    src = layer.source
    lines = [
        f'### `{layer.slug}` ({planet.capitalize()}), `{layer.layer_version}`',
        '',
        f'Source: [{src["product"]} {src["version"]}]({src["url"]}). Licence: {src["licence"]}.',
    ]
    for aux in src.get('aux', []) or []:
        lines.append(f'Also uses [{aux.get("product")} {aux.get("version", "")}]({aux.get("url", "")})'
                     f' (licence: {aux.get("licence", "see source")}).')
    rows = manifest['rows']
    lines += [
        '',
        f'Files: `{manifest["files"]["pattern"]}` ({manifest["files"]["band_groups"]} files, '
        f'{rows["total"]:,} rows, one per grid cell; {rows["without_data"]:,} cells have no source '
        f'data and carry fill values plus a quality flag). Tag `{manifest["tag"]}`, manifest '
        f'`{layer.manifest_path(planet)}`, code `code/layers/{layer.path.name}` '
        f'(code_version `{manifest["code_version"][:12]}`).',
    ]
    for name, extra in manifest['files']['extras'].items():
        lines.append(f'Extra column set `{name}`: `{extra["pattern"]}`.')
    other = [p for p, v in manifest['feature_dictionary']['planets'].items() if not v['rows']]
    if other:
        lines.append(f'{planet.capitalize()} only: there are no {", ".join(p.capitalize() for p in other)}'
                     f' rows for this layer.')
    lines += ['', '| Column | Type | Unit | Comparison | Meaning |', '|---|---|---|---|---|']
    for col in manifest['feature_dictionary']['columns']:
        lines.append(f'| `{col["name"]}` | {col["dtype"]} | {col["unit"]} | {col["comparison"]} | '
                     f'{col["description"]} |')
    for name, extra in manifest['files']['extras'].items():
        for col in extra['columns']:
            lines.append(f'| `{col["name"]}` (extra `{name}`) | {col["dtype"]} | {col["unit"]} | '
                         f'{col["comparison"]} | {col["description"]} |')
    flags = {k: v for k, v in manifest['quality_flags'].items() if k != '(clean)'}
    if flags:
        lines += ['', 'Quality flags: ' + ', '.join(f'`{k}` ({v:,})' for k, v in flags.items()) + '.']
    if manifest['known_limitations']:
        lines += ['', 'Known limitations:', '']
        lines += [f'- {text}' for text in manifest['known_limitations']]
    lines += [
        '', '```python', 'import pandas as pd',
        f'df = pd.read_parquet("hf://datasets/{manifest["repo"]}@{manifest["tag"]}/'
        f'{manifest["files"]["pattern"].replace("NNN", "000")}")', '```',
    ]
    return '\n'.join(lines)


def update_card(text: str, slug: str, planet: str, section: str) -> str:
    """Replace (or add) this layer's marked section of the README; nothing else changes."""
    start, end = f'<!-- layer:{slug}:{planet}:start -->', f'<!-- layer:{slug}:{planet}:end -->'
    block = f'{start}\n{section.strip()}\n{end}'
    if start in text and end in text:
        before, rest = text.split(start, 1)
        _, after = rest.split(end, 1)
        return before + block + after
    text = text.rstrip('\n')
    ends = list(re.finditer(r'<!-- layer:[^>]*:end -->', text))
    if ends:
        cut = ends[-1].end()
        return text[:cut] + '\n\n' + block + text[cut:] + '\n'
    if CARD_HEADING not in text.split('\n'):
        text += f'\n\n{CARD_HEADING}\n\n{CARD_INTRO}'
    return text + '\n\n' + block + '\n'


def publish_layer(layer: Layer, opts: Options, hub: HubStore) -> int:
    planet = opts.planet
    if planet not in layer.planets:
        print(f'{layer.slug}: {layer.planets[0].capitalize()}-only layer; there is nothing to publish for '
              f'{planet}. Refusing.', file=sys.stderr)
        return 2
    run = LayerRun(layer, planet, opts, hub)
    pub = build_publication(run)
    catalog_files, catalog_checks = build_catalog_publication(run)
    pub['files'].update(catalog_files)
    pub['checks'].extend(catalog_checks)
    pub['ok'] = pub['ok'] and all(c['ok'] for c in catalog_checks)
    tag = pub['tag']
    tag_exists = tag in hub.tags()
    print(f'== publish {layer.slug} {planet} -> {hub.repo_id} tag {tag} ==')
    for c in pub['checks']:
        print(f'  [{"ok" if c["ok"] else "FAIL"}] {c["name"]}: {c["detail"]}')
    print('files:')
    for path, data in pub['files'].items():
        print(f'  {path}  ({human(len(data))})')
    print('  README.md  (this layer\'s section replaced or added; the rest of the card is untouched)')
    print('\n--- card section ---\n' + pub['card_section'] + '\n--------------------')
    refusals = []
    if not pub['ok']:
        refusals.append('validation checks are failing: ' + ', '.join(
            c['name'] for c in pub['checks'] if not c['ok']))
    if tag_exists:
        refusals.append(f'tag {tag} already exists (tags are never overwritten; bump VERSION)')
    if opts.dry_run:
        print('DRY RUN: nothing uploaded.' + (f' A real publish would refuse: {"; ".join(refusals)}'
                                               if refusals else ''))
        return 2 if refusals else 0
    if refusals:
        print('REFUSING to publish: ' + '; '.join(refusals), file=sys.stderr)
        run.log.write('publish', status='refused', reasons=refusals)
        return 2

    started = time.monotonic()
    for _ in range(CONFLICT_RETRIES):
        head = hub.head()
        readme = (hub.read_bytes('README.md', revision=head) or b'').decode('utf8')
        files = dict(pub['files'])
        files['README.md'] = update_card(readme, layer.slug, planet, pub['card_section']).encode()
        try:
            oid = hub.commit(files, f'Publish {tag}: layer {layer.layer_version} for {planet}',
                             parent_commit=head)
            break
        except Exception as exc:
            if _is_conflict(exc):
                continue
            raise
    else:
        raise UploadError(f'gave up after {CONFLICT_RETRIES} commit conflicts')
    info = hub.info(list(files), revision=oid)
    for path, data in files.items():
        remote = info.get(path)
        if remote is None or not remote.matches(len(data), hashlib.sha256(data).hexdigest(),
                                                git_blob_id(data)):
            print(f'upload of {path} did not verify; NOT tagging', file=sys.stderr)
            run.log.write('publish', status='verify_failed', path=path, commit=oid)
            return 1
    if tag in hub.tags():
        print(f'tag {tag} appeared during the upload; not touching it', file=sys.stderr)
        return 2
    hub.create_tag(tag, oid, f'{layer.layer_version} {planet}: {pub["manifest"]["rows"]["total"]} rows')
    interim = run.ctx.interim_dir
    freed = du(interim)
    if interim.exists():
        shutil.rmtree(interim)
    run.log.write('publish', status='published', tag=tag, commit=oid, files=sorted(files),
                  seconds=time.monotonic() - started, interim_bytes_deleted=freed)
    print(f'published {tag} at {oid}' + (f'; deleted interim folder {interim} ({human(freed)})'
                                         if freed else ''))
    print(f'https://huggingface.co/datasets/{hub.repo_id}/tree/{tag}')
    return 0


# --------------------------------------------------------------------------
# command line
# --------------------------------------------------------------------------

def parse_args(argv=None) -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument('slugs', help='layer slug(s), comma separated')
    parser.add_argument('--planet', required=True, choices=sorted(PLANETS))
    parser.add_argument('--bands', default=None, help='inclusive band range START-END (default: all); '
                                                      'touched band groups run in full')
    parser.add_argument('--resume', action='store_true',
                        help='skip band groups already uploaded with this code_version')
    parser.add_argument('--workers', type=int, default=4,
                        help='concurrent downloads inside a band group (1: strictly one at a time)')
    parser.add_argument('--cache-max-gb', type=float, default=10.0,
                        help='hard cap on fetched items on disk at once (GB = 1e9 bytes)')
    parser.add_argument('--retries', type=int, default=4,
                        help='attempts per item / Hub call before giving up')
    parser.add_argument('--dry-run', action='store_true',
                        help='plan only (with --publish: show files, sizes and card text)')
    parser.add_argument('--no-upload', action='store_true', help='write Parquet locally only')
    parser.add_argument('--out', type=Path, default=DEFAULT_OUT, help='local output root')
    parser.add_argument('--publish', action='store_true', help='validate, write the manifest, tag')
    parser.add_argument('--cache-dir', type=Path, default=None,
                        help='where band-group caches live (default: a temp folder)')
    parser.add_argument('--log-dir', type=Path, default=DEFAULT_LOG_DIR)
    parser.add_argument('--interim-max-gb', type=float, default=50.0,
                        help='cap on data/interim/<planet>/<slug>/ built by prepare()')
    parser.add_argument('--repo', default=REPO_ID, help='Hub dataset repo')
    parser.add_argument('--layers-dir', type=Path, default=LAYERS_DIR, help=argparse.SUPPRESS)
    return parser.parse_args(argv)


def main(argv=None, *, api=None, modules: dict | None = None) -> int:
    global _DEFAULT_HUB
    args = parse_args(argv)
    slugs = [s.strip() for s in args.slugs.split(',') if s.strip()]
    if args.publish and args.no_upload:
        print('--publish cannot be combined with --no-upload', file=sys.stderr)
        return 2
    grid = planet_grid(args.planet)
    bands = tf.parse_band_range(args.bands, len(grid.column_counts)) if args.bands else None
    opts = Options(planet=args.planet, bands=bands, resume=args.resume, workers=max(1, args.workers),
                   cache_max_bytes=int(args.cache_max_gb * GB), retries=max(1, args.retries),
                   dry_run=args.dry_run, upload=not args.no_upload, out=args.out,
                   cache_dir=args.cache_dir, log_dir=args.log_dir,
                   interim_max_bytes=int(args.interim_max_gb * GB))
    try:
        layers = [Layer((modules or {}).get(slug) or load_module(slug, args.layers_dir), slug)
                  for slug in slugs]
    except LayerError as exc:
        print(f'error: {exc}', file=sys.stderr)
        return 2
    # with --no-upload nothing is read from or written to the Hub, except terrain values a layer
    # asks for and has no local copy of (read_terrain falls back to a default client then)
    hub = (HubStore(api, repo_id=args.repo, retries=opts.retries)
           if opts.upload or args.publish or api is not None else None)
    previous_hub = _DEFAULT_HUB
    if hub is not None:
        _DEFAULT_HUB = hub          # read_terrain / earth_land_frac use the same Hub client
    try:
        if args.publish:
            return max((publish_layer(layer, opts, hub) for layer in layers), default=0)
        return run_layers(layers, opts, hub)
    finally:
        _DEFAULT_HUB = previous_hub


if __name__ == '__main__':
    # Under `python -m` this file runs as __main__; hand over to the package module so layers that
    # import `pipeline.layers.driver` share one copy of its classes and state.
    _driver = importlib.import_module(__spec__.name) if __spec__ and __spec__.name != '__main__' else None
    sys.exit((_driver.main if _driver is not None else main)())