File size: 56,025 Bytes
746ff15
 
 
 
 
 
 
 
ad8a5f9
746ff15
 
 
 
 
 
 
 
ad8a5f9
f9c1358
ad8a5f9
 
f9c1358
 
746ff15
 
ad8a5f9
746ff15
 
 
ad8a5f9
746ff15
 
 
f9c1358
746ff15
 
 
 
 
 
 
 
 
 
 
 
ad8a5f9
746ff15
f9c1358
 
 
 
 
 
 
 
 
746ff15
ad8a5f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
746ff15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad8a5f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
746ff15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad8a5f9
 
746ff15
ad8a5f9
 
 
 
 
 
 
 
746ff15
ad8a5f9
 
 
746ff15
 
 
 
 
 
 
 
 
ad8a5f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
746ff15
 
 
 
 
 
 
 
f9c1358
746ff15
 
 
 
 
 
 
 
f9c1358
 
 
 
 
 
 
 
 
746ff15
 
f9c1358
746ff15
 
 
 
 
f9c1358
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad8a5f9
 
 
f9c1358
 
ad8a5f9
 
 
f9c1358
746ff15
 
 
 
 
 
f9c1358
ad8a5f9
 
 
 
f9c1358
 
 
ad8a5f9
f9c1358
ad8a5f9
 
 
 
 
 
 
 
 
 
 
f9c1358
746ff15
 
 
 
 
 
 
 
ad8a5f9
 
746ff15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9c1358
746ff15
 
 
 
f9c1358
 
 
 
 
 
 
 
 
 
 
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
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
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.9"
# dependencies = [
#     "aiohttp",
#     "typer>=0.9",
#     "rich",
#     "PyYAML",
#     "pyarrow",
# ]
# ///
"""Download ColliderML dataset assets and manage README URL updates."""

from __future__ import annotations

import asyncio
import contextlib
import hashlib
import logging
import os
import re
import shutil
import tempfile
from dataclasses import dataclass
from pathlib import Path
from typing import Annotated, Any, Dict, List, Sequence
from urllib.parse import urlparse

import aiohttp
import pyarrow.parquet as pq
import typer
import yaml
from rich.console import Console
from rich.logging import RichHandler
from rich.progress import (
    BarColumn,
    DownloadColumn,
    Progress,
    TextColumn,
    TimeElapsedColumn,
    TransferSpeedColumn,
)
from rich.table import Table


console = Console()
app = typer.Typer()

# Set up logging with rich handler
logging.basicConfig(
    level=logging.INFO,
    format="%(message)s",
    datefmt="[%X]",
    handlers=[RichHandler(console=console, show_path=False)],
)
logger = logging.getLogger(__name__)


@app.callback()
def main_callback(
    verbose: Annotated[
        bool,
        typer.Option(
            "--verbose",
            "-v",
            help="Enable verbose logging.",
        ),
    ] = False,
) -> None:
    """Manage dataset file URLs declared in README front matter."""
    if verbose:
        logging.getLogger().setLevel(logging.DEBUG)
        logger.debug("Verbose logging enabled")


@dataclass
class DataFileEntry:
    config_name: str
    path: Sequence[str]
    url: str

    def parsed(self) -> tuple[str, str]:
        parsed = urlparse(self.url)
        return parsed.netloc, parsed.path.lstrip("/")

    def relative_path(self) -> Path:
        netloc, remainder = self.parsed()
        return Path(netloc) / Path(remainder)


@dataclass
class DownloadResult:
    entry: DataFileEntry
    path: Path
    success: bool
    skipped: bool
    error: Exception | None = None
    order: int = 0


@dataclass
class VerifyResult:
    entry: DataFileEntry
    ok: bool
    status: int | None
    detail: str = ""
    order: int = 0


@dataclass
class ChecksumResult:
    entry: DataFileEntry
    filename: str
    computed_hash: str | None
    expected_hash: str | None
    matches: bool
    success: bool
    error: Exception | None = None
    order: int = 0


@dataclass
class SchemaInfo:
    config_name: str
    filename: str
    columns: List[tuple[str, str]]  # (column_name, data_type)
    num_rows: int | None
    success: bool
    error: Exception | None = None


def read_front_matter(readme_path: Path) -> tuple[str, str]:
    text = readme_path.read_text(encoding="utf-8")
    if not text.startswith("---\n"):
        raise ValueError("README.md does not start with YAML front matter.")
    try:
        front_matter, body = text[4:].split("\n---\n", 1)
    except ValueError as exc:
        raise ValueError("README.md front matter is not terminated by '---'.") from exc
    return front_matter, body


def load_data_file_entries(front_matter_text: str) -> List[DataFileEntry]:
    data = yaml.safe_load(front_matter_text)
    configs = data.get("configs", []) if isinstance(data, dict) else []
    entries: List[DataFileEntry] = []

    def _walk(value: Any, path: list[str]) -> None:
        if value is None:
            return
        if isinstance(value, str):
            entries.append(
                DataFileEntry(config_name=current_config, path=tuple(path), url=value)
            )
        elif isinstance(value, list):
            for idx, item in enumerate(value):
                _walk(item, [*path, str(idx)])
        elif isinstance(value, dict):
            for key, item in value.items():
                _walk(item, [*path, str(key)])

    for config in configs:
        if not isinstance(config, dict):
            continue
        current_config = str(config.get("config_name", "<unnamed>"))
        _walk(config.get("data_files"), ["data_files"])

    return entries


def replace_once(text: str, old: str, new: str) -> str:
    index = text.find(old)
    if index == -1:
        raise ValueError(f"Value '{old}' was not found in front matter.")
    return f"{text[:index]}{new}{text[index + len(old):]}"


def build_rewritten_url(
    result: DownloadResult, output_dir: Path, base_url: str
) -> str:
    """Build new URL by replacing output_dir with base_url in the file path.

    For example:
    - File path: /data/output/particles/file.parquet
    - Output dir: /data/output
    - Base URL: https://example.com/files
    - Result: https://example.com/files/particles/file.parquet
    """
    relative_path = result.path.relative_to(output_dir)
    # Ensure base_url doesn't end with slash, relative_path is POSIX-style
    base_url = base_url.rstrip("/")
    return f"{base_url}/{relative_path.as_posix()}"


def resolve_destination(entry: DataFileEntry, output_dir: Path) -> Path:
    _, remote_path = entry.parsed()
    filename = Path(remote_path).name or remote_path
    base_dir = output_dir / entry.config_name
    return (base_dir / filename).resolve()


def move_with_progress(src: Path, dst: Path, progress: Progress, task_id: int) -> None:
    """Move file with progress tracking for cross-filesystem moves."""
    # Try fast rename first (works if same filesystem)
    try:
        os.rename(src, dst)
        return
    except OSError:
        # Cross-filesystem move - need to copy with progress
        pass

    # Get file size for progress tracking
    file_size = src.stat().st_size
    progress.update(task_id, total=file_size)

    # Copy with progress tracking - use larger buffers for remote filesystems
    buffer_size = 8 << 20  # 8 MB chunks for better performance on remote FS
    with src.open("rb") as fsrc, dst.open("wb") as fdst:
        copied = 0
        while True:
            buf = fsrc.read(buffer_size)
            if not buf:
                break
            fdst.write(buf)
            copied += len(buf)
            progress.update(task_id, completed=copied)

        # Ensure data is flushed to disk (critical for remote filesystems)
        fdst.flush()
        os.fsync(fdst.fileno())

    # Verify file was written correctly before removing source
    if dst.stat().st_size != file_size:
        raise IOError(
            f"File size mismatch after copy: expected {file_size}, got {dst.stat().st_size}"
        )

    # Remove source after successful copy
    src.unlink()


async def download_one(
    entry: DataFileEntry,
    output_dir: Path,
    session: aiohttp.ClientSession,
    semaphore: asyncio.Semaphore,
    skip_existing: bool,
    progress: Progress,
    order: int,
    staging_dir: Path | None = None,
) -> DownloadResult:
    _, remote_path = entry.parsed()
    filename = Path(remote_path).name or remote_path
    terse_name = (filename[:32] + "…") if len(filename) > 33 else filename
    description = f"{entry.config_name}: {terse_name}"
    async with semaphore:
        task_id: int | None = None
        destination = resolve_destination(entry, output_dir)

        # Determine download location (staging or direct)
        if staging_dir:
            download_dest = resolve_destination(entry, staging_dir)
            tmp_path = download_dest.parent / f"{download_dest.name}.part"
        else:
            download_dest = destination
            tmp_path = destination.parent / f"{destination.name}.part"

        try:
            destination.parent.mkdir(parents=True, exist_ok=True)
            download_dest.parent.mkdir(parents=True, exist_ok=True)
            task_id = progress.add_task(description, total=0, start=False)
            progress.start_task(task_id)
            async with session.get(entry.url) as response:
                response.raise_for_status()
                total_bytes = response.content_length or 0

                # Check if we can skip this file
                if skip_existing and destination.exists():
                    local_size = destination.stat().st_size
                    if total_bytes and local_size == total_bytes:
                        if task_id is not None:
                            progress.remove_task(task_id)
                            task_id = None
                        logger.info(
                            f"Skipped {destination.name} ({total_bytes:,} bytes) - already exists with correct size"
                        )
                        return DownloadResult(
                            entry=entry,
                            path=destination,
                            success=True,
                            skipped=True,
                            order=order,
                        )
                    else:
                        # File exists but needs re-download
                        if not total_bytes:
                            reason = f"remote size unknown, local size is {local_size:,} bytes"
                        else:
                            reason = f"size mismatch (local: {local_size:,} bytes, remote: {total_bytes:,} bytes)"
                        logger.info(f"Downloading {destination.name} - {reason}")
                else:
                    # File doesn't exist or skip_existing is disabled
                    if not destination.exists():
                        size_info = f" ({total_bytes:,} bytes)" if total_bytes else ""
                        logger.info(
                            f"Downloading {destination.name}{size_info} - file not found locally"
                        )
                    else:
                        size_info = f" ({total_bytes:,} bytes)" if total_bytes else ""
                        logger.info(
                            f"Downloading {destination.name}{size_info} - skip_existing is disabled"
                        )

                if total_bytes:
                    progress.update(task_id, total=total_bytes)
                with tmp_path.open("wb") as handle:
                    async for chunk in response.content.iter_chunked(1 << 17):
                        handle.write(chunk)
                        progress.update(task_id, advance=len(chunk))

                    # Flush and sync to ensure data is written (critical for remote filesystems)
                    handle.flush()
                    os.fsync(handle.fileno())

            # Move from .part to final location
            tmp_path.rename(download_dest)

            # If using staging, move from staging to final destination with progress
            if staging_dir:
                logger.info(
                    f"Moving {download_dest.name} from staging to {destination.parent.name}/"
                )
                # Update progress bar description for move operation
                if task_id is not None:
                    progress.update(
                        task_id, description=f"{entry.config_name}: Moving {terse_name}"
                    )
                await asyncio.to_thread(
                    move_with_progress, download_dest, destination, progress, task_id
                )

            return DownloadResult(
                entry=entry,
                path=destination,
                success=True,
                skipped=False,
                order=order,
            )
        except Exception as exc:  # noqa: BLE001
            # Report error immediately
            logger.error(f"Failed to download {entry.config_name}/{filename}: {exc}")
            with contextlib.suppress(FileNotFoundError):
                tmp_path.unlink()
            return DownloadResult(
                entry=entry,
                path=destination,
                success=False,
                skipped=False,
                error=exc,
                order=order,
            )
        finally:
            if task_id is not None:
                progress.remove_task(task_id)


async def perform_downloads(
    entries: Sequence[DataFileEntry],
    output_dir: Path,
    max_concurrency: int,
    timeout: float,
    skip_existing: bool,
    use_staging: bool = False,
) -> List[DownloadResult]:
    if not entries:
        return []

    with contextlib.ExitStack() as stack:
        # Create staging directory if needed
        staging_dir: Path | None = None
        if use_staging:
            staging_tmp = stack.enter_context(
                tempfile.TemporaryDirectory(prefix="dataset_staging_")
            )
            staging_dir = Path(staging_tmp)
            logger.info(f"Using staging directory: {staging_dir}")

        semaphore = asyncio.Semaphore(max_concurrency)
        results: List[DownloadResult] = []
        timeout_cfg = aiohttp.ClientTimeout(total=timeout)
        progress = Progress(
            TextColumn("{task.description}"),
            BarColumn(bar_width=None),
            DownloadColumn(),
            TransferSpeedColumn(),
            TimeElapsedColumn(),
            console=console,
        )

        async with aiohttp.ClientSession(timeout=timeout_cfg) as session:
            with progress:
                tasks: list[asyncio.Task[DownloadResult]] = []
                for order, entry in enumerate(entries):
                    task = asyncio.create_task(
                        download_one(
                            entry=entry,
                            output_dir=output_dir,
                            session=session,
                            semaphore=semaphore,
                            skip_existing=skip_existing,
                            progress=progress,
                            order=order,
                            staging_dir=staging_dir,
                        )
                    )
                    tasks.append(task)

                for future in asyncio.as_completed(tasks):
                    result = await future
                    results.append(result)

        results.sort(key=lambda item: item.order)
        return results


async def get_remote_file_size(
    entry: DataFileEntry,
    session: aiohttp.ClientSession,
    semaphore: asyncio.Semaphore,
) -> int | None:
    """Get remote file size via HEAD request."""
    async with semaphore:
        try:
            async with session.head(entry.url, allow_redirects=True) as response:
                if response.status < 400:
                    return response.content_length
        except Exception:  # noqa: BLE001
            pass
    return None


async def fetch_remote_sizes(
    entries: Sequence[DataFileEntry],
    max_concurrency: int,
    timeout: float,
) -> Dict[str, int | None]:
    """Fetch remote file sizes for all entries."""
    semaphore = asyncio.Semaphore(max_concurrency)
    timeout_cfg = aiohttp.ClientTimeout(total=timeout)
    sizes: Dict[str, int | None] = {}

    progress = Progress(
        TextColumn("Fetching remote file sizes..."),
        BarColumn(),
        TextColumn("{task.completed}/{task.total}"),
        TimeElapsedColumn(),
        console=console,
    )

    async with aiohttp.ClientSession(timeout=timeout_cfg) as session:
        with progress:
            task_id = progress.add_task("Fetching sizes", total=len(entries))
            tasks = {
                entry.url: asyncio.create_task(
                    get_remote_file_size(entry, session, semaphore)
                )
                for entry in entries
            }
            for url, task in tasks.items():
                size = await task
                sizes[url] = size
                progress.advance(task_id)

    return sizes


async def verify_one(
    entry: DataFileEntry,
    session: aiohttp.ClientSession,
    semaphore: asyncio.Semaphore,
    order: int,
) -> VerifyResult:
    async with semaphore:
        last_error: str = ""
        for method in ("HEAD", "GET"):
            try:
                async with session.request(
                    method, entry.url, allow_redirects=True
                ) as response:
                    status = response.status
                    if status < 400:
                        return VerifyResult(
                            entry=entry, ok=True, status=status, order=order
                        )
                    if method == "HEAD" and status in {405, 501}:
                        last_error = f"{method} returned {status}; retrying with GET."
                        continue
                    return VerifyResult(
                        entry=entry,
                        ok=False,
                        status=status,
                        detail=f"{method} -> {status}",
                        order=order,
                    )
            except Exception as exc:  # noqa: BLE001
                last_error = str(exc)
        return VerifyResult(
            entry=entry,
            ok=False,
            status=None,
            detail=last_error or "Unknown error",
            order=order,
        )


async def perform_verification(
    entries: Sequence[DataFileEntry],
    max_concurrency: int,
    timeout: float,
) -> List[VerifyResult]:
    if not entries:
        return []

    semaphore = asyncio.Semaphore(max_concurrency)
    timeout_cfg = aiohttp.ClientTimeout(total=timeout)
    results: List[VerifyResult] = []
    progress = Progress(
        TextColumn("{task.description}"),
        BarColumn(),
        TextColumn("{task.completed}/{task.total}"),
        TimeElapsedColumn(),
        console=console,
    )

    async with aiohttp.ClientSession(timeout=timeout_cfg) as session:
        with progress:
            task_id = progress.add_task("Verifying dataset URLs", total=len(entries))
            tasks = [
                asyncio.create_task(verify_one(entry, session, semaphore, order=order))
                for order, entry in enumerate(entries)
            ]
            for future in asyncio.as_completed(tasks):
                result = await future
                results.append(result)
                progress.advance(task_id)

    results.sort(key=lambda item: item.order)
    return results


async def compute_file_hash(
    entry: DataFileEntry,
    session: aiohttp.ClientSession,
    semaphore: asyncio.Semaphore,
    progress: Progress,
    order: int,
) -> ChecksumResult:
    """Download file to temp location and compute SHA256 hash."""
    # Extract filename from URL
    _, remote_path = entry.parsed()
    filename = Path(remote_path).name or remote_path
    terse_name = (filename[:32] + "…") if len(filename) > 33 else filename
    description = f"{entry.config_name}: {terse_name}"

    async with semaphore:
        task_id: int | None = None
        try:
            task_id = progress.add_task(description, total=0, start=False)
            progress.start_task(task_id)

            async with session.get(entry.url) as response:
                response.raise_for_status()
                total_bytes = response.content_length or 0

                if total_bytes:
                    progress.update(task_id, total=total_bytes)

                hasher = hashlib.sha256()
                async for chunk in response.content.iter_chunked(1 << 17):
                    hasher.update(chunk)
                    progress.update(task_id, advance=len(chunk))

                computed_hash = hasher.hexdigest()
                return ChecksumResult(
                    entry=entry,
                    filename=filename,
                    computed_hash=computed_hash,
                    expected_hash=None,  # Will be filled in later
                    matches=False,  # Will be determined later
                    success=True,
                    order=order,
                )
        except Exception as exc:  # noqa: BLE001
            return ChecksumResult(
                entry=entry,
                filename=filename,
                computed_hash=None,
                expected_hash=None,
                matches=False,
                success=False,
                error=exc,
                order=order,
            )
        finally:
            if task_id is not None:
                progress.remove_task(task_id)


async def perform_checksum_verification(
    entries: Sequence[DataFileEntry],
    expected_hashes_by_config: Dict[str, Dict[str, str]],
    max_concurrency: int,
    timeout: float,
) -> List[ChecksumResult]:
    """Download files and verify their checksums.

    expected_hashes_by_config: dict mapping config_name -> (filename -> hash)
    """
    if not entries:
        return []

    semaphore = asyncio.Semaphore(max_concurrency)
    timeout_cfg = aiohttp.ClientTimeout(total=timeout)
    results: List[ChecksumResult] = []
    progress = Progress(
        TextColumn("{task.description}"),
        BarColumn(),
        DownloadColumn(),
        TransferSpeedColumn(),
        TimeElapsedColumn(),
        console=console,
    )

    async with aiohttp.ClientSession(timeout=timeout_cfg) as session:
        with progress:
            tasks = [
                asyncio.create_task(
                    compute_file_hash(
                        entry, session, semaphore, order=order, progress=progress
                    )
                )
                for order, entry in enumerate(entries)
            ]
            for future in asyncio.as_completed(tasks):
                result = await future
                # Fill in expected hash and match status
                config_hashes = expected_hashes_by_config.get(
                    result.entry.config_name, {}
                )
                result.expected_hash = config_hashes.get(result.filename)
                if result.success and result.expected_hash:
                    result.matches = result.computed_hash == result.expected_hash
                results.append(result)

    results.sort(key=lambda item: item.order)
    return results


def load_checksums_for_config(checksum_dir: Path, config_name: str) -> Dict[str, str]:
    """Load expected hashes from SHA256SUM-style file for a specific config.

    Returns a dict mapping filename -> hash.
    """
    checksum_file = checksum_dir / f"{config_name}.sha256"
    if not checksum_file.exists():
        return {}

    hashes: Dict[str, str] = {}
    try:
        with checksum_file.open("r", encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if not line or line.startswith("#"):
                    continue
                # Format: <hash>  <filename>
                parts = line.split(None, 1)
                if len(parts) == 2:
                    hash_value, filename = parts
                    hashes[filename] = hash_value
    except OSError as exc:
        logger.warning(f"Failed to load checksum file {checksum_file}: {exc}")

    return hashes


def save_checksums_for_config(
    checksum_dir: Path, config_name: str, file_hashes: Dict[str, str]
) -> None:
    """Save hashes to SHA256SUM-style file for a specific config.

    file_hashes: dict mapping filename -> hash
    """
    checksum_dir.mkdir(parents=True, exist_ok=True)
    checksum_file = checksum_dir / f"{config_name}.sha256"

    with checksum_file.open("w", encoding="utf-8") as f:
        for filename in sorted(file_hashes.keys()):
            hash_value = file_hashes[filename]
            f.write(f"{hash_value}  {filename}\n")

    logger.info(f"Saved {len(file_hashes)} checksums to {checksum_file}")




@app.command()
def download(
    output_dir: Annotated[
        Path,
        typer.Option(
            "--output-dir",
            "-o",
            help="Directory where files will be stored.",
            resolve_path=True,
        ),
    ],
    readme_path: Annotated[
        Path,
        typer.Option(
            "--readme-path",
            "-r",
            help="Path to the README file with YAML front matter.",
            exists=True,
            resolve_path=True,
            dir_okay=False,
        ),
    ] = Path("README.md"),
    max_concurrency: Annotated[
        int,
        typer.Option(
            "--max-concurrency",
            "-c",
            min=1,
            show_default=True,
            help="Maximum number of concurrent downloads.",
        ),
    ] = 4,
    timeout: Annotated[
        float,
        typer.Option(
            "--timeout",
            min=1.0,
            show_default=True,
            help="Request timeout in seconds.",
        ),
    ] = 600.0,
    dry_run: Annotated[
        bool,
        typer.Option(
            "--dry-run/--no-dry-run",
            show_default=True,
            help="Preview downloads and README rewrites without performing any changes.",
        ),
    ] = False,
    skip_existing: Annotated[
        bool,
        typer.Option(
            "--skip-existing/--no-skip-existing",
            show_default=True,
            help="Skip downloading files that already exist locally.",
        ),
    ] = True,
    use_staging: Annotated[
        bool,
        typer.Option(
            "--stage/--no-stage",
            show_default=True,
            help="Download to a temporary staging directory first, then move to final destination.",
        ),
    ] = False,
    clean_invalid: Annotated[
        bool,
        typer.Option(
            "--clean-invalid",
            help="Delete files with incorrect sizes but don't download. Useful for cleaning up failed downloads.",
        ),
    ] = False,
) -> None:
    front_matter_text, body_text = read_front_matter(readme_path)
    entries = load_data_file_entries(front_matter_text)
    if not entries:
        logger.warning("No data_files entries found in README front matter.")
        raise typer.Exit(code=0)

    logger.info(f"Found {len(entries)} data file URLs across {readme_path}.")
    output_dir = output_dir.resolve()

    if clean_invalid:
        # Fetch remote file sizes
        logger.info("Fetching remote file sizes to check for invalid files...")
        remote_sizes = asyncio.run(
            fetch_remote_sizes(
                entries=entries,
                max_concurrency=max_concurrency,
                timeout=timeout,
            )
        )

        # Check and delete invalid files
        deleted = 0
        skipped = 0
        missing = 0
        size_unknown = 0

        table = Table(title="Cleaning invalid files")
        table.add_column("Config")
        table.add_column("File")
        table.add_column("Status")
        table.add_column("Local size")
        table.add_column("Remote size")

        for entry in entries:
            destination = resolve_destination(entry, output_dir)
            _, remote_path = entry.parsed()
            filename = Path(remote_path).name or remote_path

            if not destination.exists():
                missing += 1
                table.add_row(
                    entry.config_name,
                    filename,
                    "[dim]Not found[/dim]",
                    "-",
                    "-",
                )
                continue

            local_size = destination.stat().st_size
            remote_size = remote_sizes.get(entry.url)

            if not remote_size:
                size_unknown += 1
                table.add_row(
                    entry.config_name,
                    filename,
                    "[cyan]Skipped (remote size unknown)[/cyan]",
                    f"{local_size:,}",
                    "Unknown",
                )
                continue

            if local_size == remote_size:
                skipped += 1
                table.add_row(
                    entry.config_name,
                    filename,
                    "[green]Valid[/green]",
                    f"{local_size:,}",
                    f"{remote_size:,}",
                )
            else:
                # Size mismatch - delete the file
                destination.unlink()
                deleted += 1
                logger.warning(
                    f"Deleted {destination} (size mismatch: {local_size:,} != {remote_size:,})"
                )
                table.add_row(
                    entry.config_name,
                    filename,
                    "[red]Deleted (size mismatch)[/red]",
                    f"{local_size:,}",
                    f"{remote_size:,}",
                )

        console.print(table)
        logger.info(
            f"Summary: {deleted} deleted, {skipped} valid, {missing} missing, {size_unknown} unknown size"
        )
        return

    if dry_run:
        # Fetch remote file sizes
        logger.info("Fetching remote file sizes for dry-run preview...")
        remote_sizes = asyncio.run(
            fetch_remote_sizes(
                entries=entries,
                max_concurrency=max_concurrency,
                timeout=timeout,
            )
        )

        preview = Table(title="Download plan (dry-run)")
        preview.add_column("Config")
        preview.add_column("Local file", overflow="fold")
        preview.add_column("Status")
        preview.add_column("Local size")
        preview.add_column("Remote size")
        preview.add_column("Source URL", overflow="fold")

        for order, entry in enumerate(entries):
            destination = resolve_destination(entry, output_dir)
            try:
                relative = destination.relative_to(output_dir)
            except ValueError:
                relative = Path(destination)

            # Check local file
            local_exists = destination.exists()
            local_size = destination.stat().st_size if local_exists else None
            remote_size = remote_sizes.get(entry.url)

            # Determine status
            if not local_exists:
                status = "[yellow]Will download[/yellow]"
                local_size_str = "-"
            elif not skip_existing:
                status = "[red]Will overwrite[/red]"
                local_size_str = f"{local_size:,}"
            elif remote_size and local_size == remote_size:
                status = "[green]Will skip (exists)[/green]"
                local_size_str = f"{local_size:,}"
            elif not remote_size:
                status = "[cyan]Will skip (exists, size unknown)[/cyan]"
                local_size_str = f"{local_size:,}"
            else:
                # skip_existing=True but sizes don't match
                status = "[red]Will overwrite (size mismatch)[/red]"
                local_size_str = f"{local_size:,}"

            remote_size_str = f"{remote_size:,}" if remote_size else "Unknown"

            row_data = [
                entry.config_name,
                relative.as_posix(),
                status,
                local_size_str,
                remote_size_str,
                entry.url,
            ]

            preview.add_row(*row_data)

        console.print(preview)

        # Summary statistics
        will_download = 0
        will_skip = 0
        will_overwrite = 0

        for entry in entries:
            dest = resolve_destination(entry, output_dir)
            local_exists = dest.exists()
            local_size = dest.stat().st_size if local_exists else None
            remote_size = remote_sizes.get(entry.url)

            if not local_exists:
                will_download += 1
            elif not skip_existing:
                will_overwrite += 1
            elif remote_size and local_size == remote_size:
                will_skip += 1
            elif not remote_size:
                will_skip += 1
            else:
                will_overwrite += 1

        logger.info(
            f"Summary: {will_download} new, {will_skip} will skip, {will_overwrite} will overwrite"
        )
        logger.info("Dry run: no files downloaded and README left unchanged.")
        return

    output_dir.mkdir(parents=True, exist_ok=True)

    results = asyncio.run(
        perform_downloads(
            entries=entries,
            output_dir=output_dir,
            max_concurrency=max_concurrency,
            timeout=timeout,
            skip_existing=skip_existing,
            use_staging=use_staging,
        )
    )

    successes = sum(1 for item in results if item.success)
    failures = len(results) - successes
    skipped = sum(1 for item in results if item.skipped)
    logger.info(f"{successes} succeeded, {failures} failed, {skipped} skipped.")

    if failures:
        for item in results:
            if not item.success:
                logger.error(f"Error: {item.entry.url} -> {item.error}")
        raise typer.Exit(code=1)


@app.command()
def rewrite(
    output_dir: Annotated[
        Path,
        typer.Option(
            "--output-dir",
            "-o",
            help="Directory where downloaded files are stored.",
            resolve_path=True,
        ),
    ],
    base_url: Annotated[
        str,
        typer.Option(
            "--base-url",
            "-u",
            help=(
                "Base URL for rewriting URLs in README. Files under output_dir will be rewritten "
                "to use this base URL. Example: if output_dir=/data/files and base_url=https://example.com/dataset, "
                "then /data/files/particles/file.parquet becomes https://example.com/dataset/particles/file.parquet"
            ),
        ),
    ],
    readme_path: Annotated[
        Path,
        typer.Option(
            "--readme-path",
            "-r",
            help="Path to the README file with YAML front matter.",
            exists=True,
            resolve_path=True,
            dir_okay=False,
        ),
    ] = Path("README.md"),
    dry_run: Annotated[
        bool,
        typer.Option(
            "--dry-run/--no-dry-run",
            show_default=True,
            help="Preview URL rewrites without modifying the README.",
        ),
    ] = False,
    skip_missing: Annotated[
        bool,
        typer.Option(
            "--skip-missing/--no-skip-missing",
            show_default=True,
            help="Skip rewriting URLs for files that don't exist locally.",
        ),
    ] = True,
) -> None:
    """Rewrite URLs in README to point to local files served at a base URL."""
    front_matter_text, body_text = read_front_matter(readme_path)
    entries = load_data_file_entries(front_matter_text)
    if not entries:
        logger.warning("No data_files entries found in README front matter.")
        raise typer.Exit(code=0)

    logger.info(f"Found {len(entries)} data file URLs in {readme_path}.")
    output_dir = output_dir.resolve()

    # Build list of results for files that exist
    results: List[DownloadResult] = []
    missing_files = []

    for order, entry in enumerate(entries):
        destination = resolve_destination(entry, output_dir)
        if destination.exists():
            results.append(
                DownloadResult(
                    entry=entry,
                    path=destination,
                    success=True,
                    skipped=False,
                    order=order,
                )
            )
        else:
            missing_files.append((entry, destination))

    if missing_files:
        if not skip_missing:
            logger.error(f"Found {len(missing_files)} missing files:")
            for entry, dest in missing_files:
                logger.error(f"  {entry.config_name}: {dest}")
            logger.error(
                "Use --skip-missing to rewrite URLs only for existing files, "
                "or download the missing files first."
            )
            raise typer.Exit(code=1)
        else:
            logger.warning(
                f"Skipping {len(missing_files)} missing files "
                f"(rewriting {len(results)} existing files)"
            )

    if not results:
        logger.error("No files found to rewrite URLs for.")
        raise typer.Exit(code=1)

    # Preview or perform rewrite
    table = Table(title="URL rewrite preview" if dry_run else "README URL updates")
    table.add_column("Config")
    table.add_column("Local file", overflow="fold")
    table.add_column("Old URL", overflow="fold")
    table.add_column("New URL", overflow="fold")

    replacements: list[tuple[DownloadResult, str]] = []
    for result in results:
        relative_path = result.path.relative_to(output_dir)
        new_url = build_rewritten_url(result, output_dir, base_url)
        replacements.append((result, new_url))
        table.add_row(
            result.entry.config_name,
            relative_path.as_posix(),
            result.entry.url,
            new_url,
        )

    console.print(table)

    if dry_run:
        logger.info(
            f"Dry run: would rewrite {len(results)} URLs. "
            "Remove --dry-run to apply changes."
        )
        return

    # Apply rewrites
    updated_front = front_matter_text
    for result, new_url in replacements:
        updated_front = replace_once(updated_front, result.entry.url, new_url)

    readme_path.write_text(f"---\n{updated_front}\n---\n{body_text}", encoding="utf-8")
    logger.info(f"Successfully rewrote {len(results)} URLs in {readme_path}")


@app.command()
def verify(
    readme_path: Annotated[
        Path,
        typer.Option(
            "--readme-path",
            "-r",
            help="Path to the README file with YAML front matter.",
            exists=True,
            resolve_path=True,
            dir_okay=False,
        ),
    ] = Path("README.md"),
    max_concurrency: Annotated[
        int,
        typer.Option(
            "--max-concurrency",
            "-c",
            min=1,
            show_default=True,
            help="Maximum concurrent verification requests.",
        ),
    ] = 8,
    timeout: Annotated[
        float,
        typer.Option(
            "--timeout",
            min=1.0,
            show_default=True,
            help="Request timeout in seconds.",
        ),
    ] = 60.0,
) -> None:
    front_matter_text, _ = read_front_matter(readme_path)
    entries = load_data_file_entries(front_matter_text)
    if not entries:
        logger.warning("No data_files entries found in README front matter.")
        raise typer.Exit(code=0)

    logger.info(f"Verifying {len(entries)} URLs from {readme_path}.")
    results = asyncio.run(
        perform_verification(
            entries=entries,
            max_concurrency=max_concurrency,
            timeout=timeout,
        )
    )

    table = Table(title="URL verification results")
    table.add_column("Config")
    table.add_column("Status")
    table.add_column("Detail", overflow="fold")
    failed = 0
    for result in sorted(results, key=lambda r: (not r.ok, r.order)):
        status_text = str(result.status) if result.status is not None else "-"
        if result.ok:
            table.add_row(
                result.entry.config_name,
                f"[green]{status_text}[/green]",
                result.entry.url,
            )
        else:
            failed += 1
            detail = result.detail or result.entry.url
            table.add_row(
                result.entry.config_name,
                f"[red]{status_text}[/red]",
                f"{result.entry.url}\n{detail}",
            )

    console.print(table)
    if failed:
        logger.error(f"{failed} URLs failed verification.")
        raise typer.Exit(code=1)
    logger.info("All URLs verified successfully.")


@app.command()
def checksum(
    readme_path: Annotated[
        Path,
        typer.Option(
            "--readme-path",
            "-r",
            help="Path to the README file with YAML front matter.",
            exists=True,
            resolve_path=True,
            dir_okay=False,
        ),
    ] = Path("README.md"),
    checksum_dir: Annotated[
        Path,
        typer.Option(
            "--checksum-dir",
            "-d",
            help="Directory containing SHA256 checksum files (one per config).",
            resolve_path=True,
        ),
    ] = Path("checksums"),
    max_concurrency: Annotated[
        int,
        typer.Option(
            "--max-concurrency",
            "-c",
            min=1,
            show_default=True,
            help="Maximum concurrent checksum operations.",
        ),
    ] = 8,
    timeout: Annotated[
        float,
        typer.Option(
            "--timeout",
            min=1.0,
            show_default=True,
            help="Request timeout in seconds.",
        ),
    ] = 300.0,
    generate: Annotated[
        bool,
        typer.Option(
            "--generate",
            help="Generate/update checksum files with current remote file checksums.",
        ),
    ] = False,
    update_mismatches: Annotated[
        bool,
        typer.Option(
            "--update-mismatches",
            help="Update checksum files with new hashes for files that don't match.",
        ),
    ] = False,
) -> None:
    """Verify file integrity using SHA256 checksums."""
    front_matter_text, _ = read_front_matter(readme_path)
    entries = load_data_file_entries(front_matter_text)
    if not entries:
        logger.warning("No data_files entries found in README front matter.")
        raise typer.Exit(code=0)

    logger.info(f"Computing checksums for {len(entries)} files from {readme_path}.")

    # Get unique config names
    config_names = sorted(set(entry.config_name for entry in entries))

    # Load existing hashes per config unless we're regenerating
    expected_hashes_by_config: Dict[str, Dict[str, str]] = {}
    if not generate:
        for config_name in config_names:
            expected_hashes_by_config[config_name] = load_checksums_for_config(
                checksum_dir, config_name
            )

    # Compute checksums
    results = asyncio.run(
        perform_checksum_verification(
            entries=entries,
            expected_hashes_by_config=expected_hashes_by_config,
            max_concurrency=max_concurrency,
            timeout=timeout,
        )
    )

    # Display results
    table = Table(title="Checksum verification results")
    table.add_column("Config")
    table.add_column("Filename")
    table.add_column("Status")
    table.add_column("SHA256", overflow="fold")

    failed = 0
    mismatched = 0
    # new_hashes_by_config: config_name -> (filename -> hash)
    new_hashes_by_config: Dict[str, Dict[str, str]] = {}

    for result in results:
        if not result.success:
            failed += 1
            error_msg = str(result.error) if result.error else "Unknown error"
            table.add_row(
                result.entry.config_name,
                result.filename,
                "[red]ERROR[/red]",
                error_msg,
            )
        elif generate:
            # In generate mode, just collect all hashes
            if result.entry.config_name not in new_hashes_by_config:
                new_hashes_by_config[result.entry.config_name] = {}
            new_hashes_by_config[result.entry.config_name][result.filename] = (
                result.computed_hash or ""
            )
            table.add_row(
                result.entry.config_name,
                result.filename,
                "[cyan]COMPUTED[/cyan]",
                result.computed_hash or "-",
            )
        elif result.expected_hash is None:
            # No expected hash available
            table.add_row(
                result.entry.config_name,
                result.filename,
                "[yellow]NEW[/yellow]",
                result.computed_hash or "-",
            )
            if update_mismatches and result.computed_hash:
                if result.entry.config_name not in new_hashes_by_config:
                    new_hashes_by_config[result.entry.config_name] = {}
                new_hashes_by_config[result.entry.config_name][
                    result.filename
                ] = result.computed_hash
        elif result.matches:
            # Hash matches
            table.add_row(
                result.entry.config_name,
                result.filename,
                "[green]OK[/green]",
                result.computed_hash or "-",
            )
        else:
            # Hash mismatch
            mismatched += 1
            table.add_row(
                result.entry.config_name,
                result.filename,
                "[red]MISMATCH[/red]",
                f"Expected: {result.expected_hash}\nComputed: {result.computed_hash}",
            )
            if update_mismatches and result.computed_hash:
                if result.entry.config_name not in new_hashes_by_config:
                    new_hashes_by_config[result.entry.config_name] = {}
                new_hashes_by_config[result.entry.config_name][
                    result.filename
                ] = result.computed_hash

    console.print(table)

    # Handle checksum file updates
    if generate:
        total_saved = 0
        for config_name, file_hashes in new_hashes_by_config.items():
            save_checksums_for_config(checksum_dir, config_name, file_hashes)
            total_saved += len(file_hashes)
        logger.info(
            f"Generated {len(new_hashes_by_config)} checksum files with {total_saved} total checksums."
        )
    elif update_mismatches and new_hashes_by_config:
        total_updated = 0
        for config_name, new_file_hashes in new_hashes_by_config.items():
            # Merge with existing hashes for this config
            all_hashes = load_checksums_for_config(checksum_dir, config_name)
            all_hashes.update(new_file_hashes)
            save_checksums_for_config(checksum_dir, config_name, all_hashes)
            total_updated += len(new_file_hashes)
        logger.warning(
            f"Updated {total_updated} checksums across {len(new_hashes_by_config)} checksum files."
        )

    # Exit with appropriate code
    if failed:
        logger.error(f"{failed} files failed checksum computation.")
        raise typer.Exit(code=1)
    if mismatched and not update_mismatches:
        logger.error(f"{mismatched} files have checksum mismatches.")
        logger.warning("Use --update-mismatches to update the checksum files.")
        raise typer.Exit(code=1)
    if not generate and not mismatched and not failed:
        logger.info("All checksums verified successfully.")


def clean_arrow_type(type_str: str) -> str:
    """Clean up Arrow type string for display."""
    # Remove "element: " from list types
    # Pattern: list<element: TYPE> -> list<TYPE>
    cleaned = re.sub(r"list<element:\s*", "list<", type_str)
    return cleaned


def escape_latex(text: str) -> str:
    """Escape special LaTeX characters."""
    # Map of characters to escape
    replacements = {
        "\\": r"\\",  # Backslash must be first to avoid double-escaping
        "&": r"\&",
        "%": r"\%",
        "$": r"\$",
        "#": r"\#",
        "_": r"\_",
        "{": r"\{",
        "}": r"\}",
        "~": r"\textasciitilde{}",
        "^": r"\^{}",
    }
    for char, escaped in replacements.items():
        text = text.replace(char, escaped)
    return text


async def inspect_file_schema(
    entry: DataFileEntry,
    session: aiohttp.ClientSession,
    semaphore: asyncio.Semaphore,
    progress: Progress,
) -> SchemaInfo:
    """Download file and extract schema information using PyArrow."""
    _, remote_path = entry.parsed()
    filename = Path(remote_path).name or remote_path
    terse_name = (filename[:32] + "…") if len(filename) > 33 else filename
    description = f"{entry.config_name}: {terse_name}"

    async with semaphore:
        task_id: int | None = None
        temp_file = None
        try:
            task_id = progress.add_task(description, total=0, start=False)
            progress.start_task(task_id)

            # Download to temporary file
            async with session.get(entry.url) as response:
                response.raise_for_status()
                total_bytes = response.content_length or 0

                if total_bytes:
                    progress.update(task_id, total=total_bytes)

                with tempfile.NamedTemporaryFile(delete=False, suffix=".parquet") as f:
                    temp_file = Path(f.name)
                    async for chunk in response.content.iter_chunked(1 << 17):
                        f.write(chunk)
                        progress.update(task_id, advance=len(chunk))

                    # Read schema with PyArrow
                    parquet_file = pq.read_table(temp_file)
                    schema = parquet_file.schema

            columns = [
                (field.name, clean_arrow_type(str(field.type))) for field in schema
            ]
            num_rows = len(parquet_file)

            return SchemaInfo(
                config_name=entry.config_name,
                filename=filename,
                columns=columns,
                num_rows=num_rows,
                success=True,
            )

        except Exception as exc:  # noqa: BLE001
            return SchemaInfo(
                config_name=entry.config_name,
                filename=filename,
                columns=[],
                num_rows=None,
                success=False,
                error=exc,
            )
        finally:
            if task_id is not None:
                progress.remove_task(task_id)
            # Clean up temp file
            if temp_file and temp_file.exists():
                temp_file.unlink()


async def perform_schema_inspection(
    entries: Sequence[DataFileEntry],
    max_concurrency: int,
    timeout: float,
) -> List[SchemaInfo]:
    """Download first file from each config and inspect schema."""
    if not entries:
        return []

    semaphore = asyncio.Semaphore(max_concurrency)
    timeout_cfg = aiohttp.ClientTimeout(total=timeout)
    results: List[SchemaInfo] = []
    progress = Progress(
        TextColumn("{task.description}"),
        BarColumn(bar_width=None),
        DownloadColumn(),
        TransferSpeedColumn(),
        TimeElapsedColumn(),
        console=console,
    )

    async with aiohttp.ClientSession(timeout=timeout_cfg) as session:
        with progress:
            tasks = [
                asyncio.create_task(
                    inspect_file_schema(entry, session, semaphore, progress)
                )
                for entry in entries
            ]
            for future in asyncio.as_completed(tasks):
                result = await future
                results.append(result)

    # Sort by config name for consistent output
    results.sort(key=lambda r: r.config_name)
    return results


@app.command()
def schema(
    readme_path: Annotated[
        Path,
        typer.Option(
            "--readme-path",
            "-r",
            help="Path to the README file with YAML front matter.",
            exists=True,
            resolve_path=True,
            dir_okay=False,
        ),
    ] = Path("README.md"),
    output_file: Annotated[
        Path | None,
        typer.Option(
            "--output-file",
            "-o",
            help="Write schema information to plain text file.",
            resolve_path=True,
            dir_okay=False,
        ),
    ] = None,
    latex: Annotated[
        bool,
        typer.Option(
            "--latex",
            help="Output schema in LaTeX format (requires --output-file).",
        ),
    ] = False,
    max_concurrency: Annotated[
        int,
        typer.Option(
            "--max-concurrency",
            "-c",
            min=1,
            show_default=True,
            help="Maximum concurrent downloads.",
        ),
    ] = 4,
    timeout: Annotated[
        float,
        typer.Option(
            "--timeout",
            min=1.0,
            show_default=True,
            help="Request timeout in seconds.",
        ),
    ] = 300.0,
    types: Annotated[bool, typer.Option(help="Add column type info")] = True,
) -> None:
    """Inspect schema of first file from each dataset config."""
    # Validate options
    if latex and not output_file:
        logger.error("--latex requires --output-file to be specified.")
        raise typer.Exit(code=1)

    front_matter_text, _ = read_front_matter(readme_path)
    entries = load_data_file_entries(front_matter_text)
    if not entries:
        logger.warning("No data_files entries found in README front matter.")
        raise typer.Exit(code=0)

    # Get first file from each config
    configs_seen = set()
    first_files = []
    for entry in entries:
        if entry.config_name not in configs_seen:
            first_files.append(entry)
            configs_seen.add(entry.config_name)

    logger.info(f"Inspecting schema for {len(first_files)} configs.")

    # Perform schema inspection
    results = asyncio.run(
        perform_schema_inspection(
            entries=first_files,
            max_concurrency=max_concurrency,
            timeout=timeout,
        )
    )

    # Display results
    failed = 0
    text_output_lines = []
    latex_items = []

    for result in results:
        if not result.success:
            failed += 1
            error_msg = str(result.error) if result.error else "Unknown error"
            logger.error(
                f"Failed to inspect {result.config_name}/{result.filename}: {error_msg}"
            )
            continue

        # Prepare output file content
        if output_file:
            if latex:
                # LaTeX format: \item \textbf{CONFIG}: \texttt{col1} (\texttt{type1}), ...
                escaped_config = escape_latex(result.config_name)
                column_parts = []
                for col_name, col_type in result.columns:
                    escaped_col = escape_latex(col_name)
                    escaped_type = escape_latex(col_type)
                    part = f"\\texttt{{{escaped_col}}}"
                    if types:
                        part += f" (\\texttt{{{escaped_type}}})"
                    column_parts.append(part)
                columns_str = ", ".join(column_parts)
                latex_items.append(
                    f"\\item \\textbf{{{escaped_config}}}: {columns_str}"
                )
            else:
                # Plain text format
                text_output_lines.append(f"# {result.config_name}{result.filename}")
                if result.num_rows is not None:
                    text_output_lines.append(
                        f"# {len(result.columns)} columns, {result.num_rows:,} rows"
                    )
                text_output_lines.append("")
                for col_name, col_type in result.columns:
                    text_output_lines.append(f"{col_name}: {col_type}")
                text_output_lines.append("")

        # Create table for console display
        table = Table(title=f"[bold]{result.config_name}[/bold] — {result.filename}")
        table.add_column("Column", style="cyan")
        table.add_column("Type", style="yellow")

        for col_name, col_type in result.columns:
            table.add_row(col_name, col_type)

        console.print(table)
        if result.num_rows is not None:
            logger.info(
                f"{result.config_name}: {len(result.columns)} columns, {result.num_rows:,} rows"
            )
        console.print()  # Empty line between configs

    # Write to output file if specified
    if output_file:
        if latex and latex_items:
            latex_content = (
                "\\begin{itemize}\n" + "\n".join(latex_items) + "\n\\end{itemize}"
            )
            output_file.write_text(latex_content, encoding="utf-8")
            logger.info(f"Wrote LaTeX schema to {output_file}")
        elif text_output_lines:
            output_file.write_text("\n".join(text_output_lines), encoding="utf-8")
            logger.info(f"Wrote schema information to {output_file}")

    if failed:
        logger.error(f"{failed} configs failed schema inspection.")
        raise typer.Exit(code=1)
    logger.info("Schema inspection completed successfully.")


if __name__ == "__main__":
    app()