hf-fetch-model 0.9.7

Download, inspect, and compare HuggingFace models from Rust. Multi-connection parallel downloads plus safetensors header inspection via HTTP Range. No weight data downloaded.
Documentation
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
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
// SPDX-License-Identifier: MIT OR Apache-2.0

//! CLI binary for hf-fetch-model.
//!
//! Installed as both `hf-fetch-model` and `hf-fm`.

use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::io::IsTerminal;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use clap::{Args, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum};
use tracing_subscriber::EnvFilter;

use hf_fetch_model::cache;
use hf_fetch_model::discover;
use hf_fetch_model::inspect;
use hf_fetch_model::progress::IndicatifProgress;
use hf_fetch_model::repo;
use hf_fetch_model::{
    compile_glob_patterns, file_matches, has_glob_chars, FetchConfig, FetchError, Filter,
};

/// Downloads all files from a `HuggingFace` model repository.
///
/// Use `--preset safetensors` to download only safetensors weights,
/// config, and tokenizer files.
#[derive(Parser)]
#[command(
    name = "hf-fetch-model",
    bin_name = "hf-fm",
    version,
    about,
    before_help = concat!("hf-fetch-model v", env!("CARGO_PKG_VERSION"))
)]
#[command(args_conflicts_with_subcommands = true)]
struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,

    #[command(flatten)]
    download: DownloadArgs,
}

/// Arguments for the default download command.
#[derive(Args)]
struct DownloadArgs {
    /// Enable verbose output (download diagnostics).
    #[arg(short, long)]
    verbose: bool,

    /// The repository identifier (e.g., "google/gemma-2-2b-it").
    #[arg(value_name = "REPO_ID")]
    repo_id: Option<String>,

    /// Git revision (branch, tag, or commit SHA).
    #[arg(long)]
    revision: Option<String>,

    /// Authentication token (or set `HF_TOKEN` env var).
    #[arg(long)]
    token: Option<String>,

    /// Include glob pattern (repeatable).
    #[arg(long, action = clap::ArgAction::Append)]
    filter: Vec<String>,

    /// Exclude glob pattern (repeatable).
    #[arg(long, action = clap::ArgAction::Append)]
    exclude: Vec<String>,

    /// Filter preset.
    #[arg(long, value_enum)]
    preset: Option<Preset>,

    /// Output directory (default: HF cache).
    #[arg(long)]
    output_dir: Option<PathBuf>,

    /// Number of concurrent file downloads (auto-tuned if omitted).
    #[arg(long)]
    concurrency: Option<usize>,

    /// Minimum file size (MiB) for parallel chunked download (auto-tuned if omitted).
    #[arg(long)]
    chunk_threshold_mib: Option<u64>,

    /// Number of parallel HTTP connections per large file (auto-tuned if omitted).
    #[arg(long)]
    connections_per_file: Option<usize>,

    /// Preview what would be downloaded without actually downloading.
    #[arg(long)]
    dry_run: bool,

    /// Copy downloaded files to flat layout: `{output-dir}/{filename}`.
    ///
    /// Files are downloaded to the HF cache as normal, then copied to
    /// the target directory. Defaults to the current directory when
    /// `--output-dir` is not set.
    #[arg(long)]
    flat: bool,
}

#[derive(Subcommand)]
enum Commands {
    /// List model families in local HF cache.
    ListFamilies,
    /// Discover new model families from the `HuggingFace` Hub.
    Discover {
        /// Maximum number of models to scan.
        #[arg(long, default_value = "500")]
        limit: usize,
    },
    /// Search the `HuggingFace` Hub for models matching a query.
    ///
    /// Supports comma-separated multi-term filtering (e.g., `"mistral,3B,12"`).
    /// Slashes in queries are treated as spaces for broader matching.
    #[command(after_help = "See also: hf-fm list-families, hf-fm discover")]
    Search {
        /// Search query (e.g., `"RWKV-7"`, `"llama 3"`, `"mistral,3B,12"`).
        query: String,
        /// Maximum number of results.
        #[arg(long, default_value = "20")]
        limit: usize,
        /// Match a full repository ID exactly (e.g., `"org/model"`) and show its metadata card.
        #[arg(long)]
        exact: bool,
        /// Filter by library framework (e.g., `"transformers"`, `"peft"`, `"vllm"`).
        #[arg(long)]
        library: Option<String>,
        /// Filter by pipeline task (e.g., `"text-generation"`, `"text-classification"`).
        #[arg(long)]
        pipeline: Option<String>,
        /// Filter by model tag (e.g., `"gguf"`, `"conversational"`, `"imatrix"`).
        #[arg(long)]
        tag: Option<String>,
    },
    /// Show model card metadata and README text for a repository.
    Info {
        /// The repository identifier (e.g., `"mistralai/Ministral-3-3B-Instruct-2512"`).
        repo_id: String,
        /// Git revision (branch, tag, or commit SHA).
        #[arg(long)]
        revision: Option<String>,
        /// Authentication token (or set `HF_TOKEN` env var).
        #[arg(long)]
        token: Option<String>,
        /// Output metadata and README as JSON.
        #[arg(long)]
        json: bool,
        /// Maximum lines of README to display (0 = all).
        #[arg(long, default_value = "40")]
        lines: usize,
    },
    /// Download a single file (or glob pattern) from a `HuggingFace` repository.
    DownloadFile {
        /// Enable verbose output (download diagnostics).
        #[arg(short, long)]
        verbose: bool,

        /// The repository identifier (e.g., "mntss/clt-gemma-2-2b-426k").
        repo_id: String,

        /// Filename or glob pattern (e.g., `"model.safetensors"` or `"pytorch_model-*.bin"`).
        filename: String,

        /// Git revision (branch, tag, or commit SHA).
        #[arg(long)]
        revision: Option<String>,

        /// Authentication token (or set `HF_TOKEN` env var).
        #[arg(long)]
        token: Option<String>,

        /// Output directory (default: HF cache).
        #[arg(long)]
        output_dir: Option<PathBuf>,

        /// Minimum file size (MiB) for parallel chunked download (auto-tuned if omitted).
        #[arg(long)]
        chunk_threshold_mib: Option<u64>,

        /// Number of parallel HTTP connections per large file (auto-tuned if omitted).
        #[arg(long)]
        connections_per_file: Option<usize>,

        /// Copy the downloaded file to flat layout: `{output-dir}/{filename}`.
        ///
        /// The file is downloaded to the HF cache as normal, then copied to
        /// the target directory. Defaults to the current directory when
        /// `--output-dir` is not set.
        #[arg(long)]
        flat: bool,
    },
    /// Show download status (all models, or a specific one).
    Status {
        /// The repository identifier (omit to list all cached models).
        repo_id: Option<String>,
        /// Git revision (branch, tag, or commit SHA).
        #[arg(long)]
        revision: Option<String>,
        /// Authentication token (or set `HF_TOKEN` env var).
        #[arg(long)]
        token: Option<String>,
    },
    /// Compare tensor layouts between two models.
    ///
    /// Inspects `.safetensors` headers in both repos and classifies tensors
    /// into four buckets: only-in-A, only-in-B, dtype/shape differences,
    /// and matching. Does not download weight data.
    Diff {
        /// First model repository (labeled A).
        repo_a: String,
        /// Second model repository (labeled B).
        repo_b: String,
        /// Git revision for model A.
        #[arg(long)]
        revision_a: Option<String>,
        /// Git revision for model B.
        #[arg(long)]
        revision_b: Option<String>,
        /// Authentication token (or set `HF_TOKEN` env var).
        #[arg(long)]
        token: Option<String>,
        /// Cache-only mode: fail if files are not cached locally.
        #[arg(long)]
        cached: bool,
        /// Show only tensors whose name contains this substring.
        #[arg(long)]
        filter: Option<String>,
        /// Show only the summary line (counts per category).
        #[arg(long)]
        summary: bool,
        /// Output the full diff as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Show disk usage for cached models.
    Du {
        /// Repository identifier or numeric index (omit to show all cached repos).
        ///
        /// Use a repo ID (e.g., `"google/gemma-2-2b-it"`) or a `#` index from the
        /// `du` summary to drill into a specific repo's files.
        repo_id: Option<String>,
        /// Show a last-modified age column (e.g., `"2 days ago"`, `"3 months ago"`).
        #[arg(long)]
        age: bool,
    },
    /// Inspect `.safetensors` file headers (tensor names, shapes, dtypes).
    ///
    /// Reads tensor metadata without downloading full weight data.
    /// Checks the local cache first; falls back to HTTP Range requests.
    #[command(after_help = "Examples:\n  \
        hf-fm inspect <repo>                             # inspect every .safetensors in the repo\n  \
        hf-fm inspect <repo> --list                      # list safetensors files (no headers read)\n  \
        hf-fm inspect <repo> 3                           # inspect file #3 from --list\n  \
        hf-fm inspect <repo> model.safetensors --tree    # hierarchical view of one file\n\n\
        Indices returned by --list are stable as long as the repo has not\n\
        changed remotely between invocations. Pass --revision <sha> on both\n\
        --list and the follow-up run to lock the view end-to-end.")]
    Inspect {
        /// The repository identifier (e.g., `"google/gemma-2-2b-it"`).
        repo_id: String,
        /// Specific `.safetensors` file, numeric index from `--list`, or omit for all.
        filename: Option<String>,
        /// Git revision (branch, tag, or commit SHA).
        #[arg(long)]
        revision: Option<String>,
        /// Authentication token (or set `HF_TOKEN` env var).
        #[arg(long)]
        token: Option<String>,
        /// Cache-only mode: fail if the file is not cached locally.
        #[arg(long)]
        cached: bool,
        /// List `.safetensors` files in the repo (filename + size) and exit.
        ///
        /// Prints a numbered table; the `#` column can be used as the `filename`
        /// argument on a follow-up run (e.g. `hf-fm inspect <repo> 3`). Indices
        /// are alphabetical, so shard ordering is natural. No headers are read.
        #[arg(long, conflicts_with_all = ["filename", "no_metadata", "json", "filter", "dtypes", "limit", "tree"])]
        list: bool,
        /// Suppress the `Metadata:` line in human-readable output.
        #[arg(long)]
        no_metadata: bool,
        /// Output the full header as JSON instead of a human-readable table.
        #[arg(long)]
        json: bool,
        /// Show only tensors whose name contains this substring.
        #[arg(long)]
        filter: Option<String>,
        /// Show a per-dtype summary instead of individual tensors.
        #[arg(long)]
        dtypes: bool,
        /// Show only the first N tensors (applied after `--filter`).
        #[arg(long)]
        limit: Option<usize>,
        /// Show a hierarchical tree view grouped by dotted namespace prefix.
        ///
        /// Numeric sibling groups with identical structure are collapsed to
        /// `[0..N]` with a `×K` marker. Composes with `--filter` and `--json`.
        #[arg(long, conflicts_with_all = ["dtypes", "limit"])]
        tree: bool,
    },
    /// List files in a remote `HuggingFace` repository (no download).
    ListFiles {
        /// The repository identifier (e.g., `"google/gemma-2-2b-it"`).
        repo_id: String,
        /// Git revision (branch, tag, or commit SHA).
        #[arg(long)]
        revision: Option<String>,
        /// Authentication token (or set `HF_TOKEN` env var).
        #[arg(long)]
        token: Option<String>,
        /// Include glob pattern (repeatable).
        #[arg(long, action = clap::ArgAction::Append)]
        filter: Vec<String>,
        /// Exclude glob pattern (repeatable).
        #[arg(long, action = clap::ArgAction::Append)]
        exclude: Vec<String>,
        /// Filter preset (`safetensors`, `gguf`, `npz`, `pth`, `config-only`).
        #[arg(long, value_enum)]
        preset: Option<Preset>,
        /// Suppress the SHA256 column.
        #[arg(long)]
        no_checksum: bool,
        /// Show cache status for each file (complete, partial, or missing).
        #[arg(long)]
        show_cached: bool,
    },
    /// Manage the local `HuggingFace` cache.
    Cache {
        #[command(subcommand)]
        subcommand: CacheCommands,
    },
}

// EXHAUSTIVE: internal CLI dispatch enum; crate owns all variants
#[derive(Subcommand)]
enum CacheCommands {
    /// Remove `.chunked.part` files from interrupted downloads.
    CleanPartial {
        /// Repository identifier or numeric index (omit to clean all repos).
        repo_id: Option<String>,

        /// Skip confirmation prompt.
        #[arg(long)]
        yes: bool,

        /// Preview what would be removed without deleting.
        #[arg(long)]
        dry_run: bool,
    },
    /// Delete a cached model by repo ID or numeric index.
    Delete {
        /// Repository identifier or numeric index from `du` output.
        repo_id: String,

        /// Skip confirmation prompt.
        #[arg(long)]
        yes: bool,
    },
    /// Print the snapshot directory path for a cached model.
    ///
    /// Output is a bare path (no labels), suitable for shell substitution:
    /// `cd $(hf-fm cache path google/gemma-2-2b-it)`.
    ///
    /// Resolves the `main` ref only; repos downloaded at a non-default revision
    /// are not yet supported (planned for a future `--revision` flag).
    Path {
        /// Repository identifier or numeric index from `du` output.
        repo_id: String,
    },
}

// EXHAUSTIVE: internal CLI dispatch enum; crate owns all variants
#[derive(Clone, ValueEnum)]
enum Preset {
    Safetensors,
    Gguf,
    Npz,
    Pth,
    ConfigOnly,
}

/// Sorts a [`clap::Command`]'s subcommands alphabetically by assigning
/// ascending `display_order` values in sorted-name order. Recurses into
/// each subcommand so nested command trees (e.g., `cache …`) are sorted
/// at every level.
#[must_use]
fn sort_subcommands_alphabetically(mut cmd: clap::Command) -> clap::Command {
    let mut names: Vec<String> = cmd
        .get_subcommands()
        .map(|sc| sc.get_name().to_owned()) // BORROW: clap borrows sc; owned String outlives the closure
        .collect();
    names.sort();
    for (i, name) in names.iter().enumerate() {
        cmd = cmd.mut_subcommand(name, |sc| {
            sort_subcommands_alphabetically(sc).display_order(i)
        });
    }
    cmd
}

fn main() -> ExitCode {
    let cmd = sort_subcommands_alphabetically(Cli::command());
    let matches = cmd.get_matches();
    let cli = match Cli::from_arg_matches(&matches) {
        Ok(cli) => cli,
        Err(e) => e.exit(),
    };

    // Extract --verbose from the active command context.
    // EXHAUSTIVE: non-download subcommands have no --verbose flag
    let verbose = match &cli.command {
        Some(Commands::DownloadFile { verbose, .. }) => *verbose,
        None => cli.download.verbose,
        Some(
            Commands::ListFamilies
            | Commands::Discover { .. }
            | Commands::Search { .. }
            | Commands::Info { .. }
            | Commands::Status { .. }
            | Commands::Diff { .. }
            | Commands::Du { .. }
            | Commands::Inspect { .. }
            | Commands::ListFiles { .. }
            | Commands::Cache { .. },
        ) => false,
    };

    // Initialize tracing subscriber when --verbose is set.
    // Respects RUST_LOG if present, otherwise defaults to debug for hf_fetch_model.
    if verbose {
        let filter = EnvFilter::try_from_default_env()
            .unwrap_or_else(|_| EnvFilter::new("hf_fetch_model=debug"));
        tracing_subscriber::fmt()
            .with_env_filter(filter)
            .with_target(false)
            .with_writer(std::io::stderr)
            .init();
    }

    match run(cli) {
        Ok(()) => ExitCode::SUCCESS,
        Err(FetchError::PartialDownload { path, failures }) => {
            eprintln!();
            eprintln!("error: {} file(s) failed to download:", failures.len());
            for f in &failures {
                eprintln!("  - {}: {}", f.filename, f.reason);
            }
            if let Some(p) = path {
                eprintln!();
                eprintln!("Partial download at: {}", p.display());
            }
            let any_retryable = failures.iter().any(|f| f.retryable);
            if any_retryable {
                eprintln!();
                eprintln!(
                    "hint: re-run the same command to retry failed files \
                     (already-downloaded files will be skipped)"
                );
            }
            ExitCode::FAILURE
        }
        Err(FetchError::RepoNotFound { ref repo_id }) => {
            // BORROW: explicit .clone() for owned String in Display formatting
            eprintln!(
                "error: {e}",
                e = FetchError::RepoNotFound {
                    repo_id: repo_id.clone()
                }
            );
            // Extract model name (part after '/') as a search hint.
            // BORROW: explicit .as_str() instead of Deref coercion
            let search_term = repo_id.split('/').nth(1).unwrap_or(repo_id.as_str());
            eprintln!("hint: try `hf-fm search {search_term}` to find matching models");
            ExitCode::FAILURE
        }
        Err(e) => {
            eprintln!("error: {e}");
            ExitCode::FAILURE
        }
    }
}

fn run(cli: Cli) -> Result<(), FetchError> {
    match cli.command {
        Some(Commands::ListFamilies) => run_list_families(),
        Some(Commands::Discover { limit }) => run_discover(limit),
        // BORROW: explicit .as_str()/.as_deref() for owned → borrowed conversions
        Some(Commands::Search {
            query,
            limit,
            exact,
            library,
            pipeline,
            tag,
        }) => run_search(
            query.as_str(),
            limit,
            exact,
            library.as_deref(),
            pipeline.as_deref(),
            tag.as_deref(),
        ),
        // BORROW: explicit .as_str()/.as_deref() for owned → borrowed conversions
        Some(Commands::Info {
            repo_id,
            revision,
            token,
            json,
            lines,
        }) => run_info(
            repo_id.as_str(),
            revision.as_deref(),
            token.as_deref(),
            json,
            lines,
        ),
        // BORROW: explicit .as_str()/.as_deref() for owned → borrowed conversions
        Some(Commands::DownloadFile {
            verbose: _,
            repo_id,
            filename,
            revision,
            token,
            output_dir,
            chunk_threshold_mib,
            connections_per_file,
            flat,
        }) => run_download_file(DownloadFileParams {
            repo_id: repo_id.as_str(),
            filename: filename.as_str(),
            revision: revision.as_deref(),
            token: token.as_deref(),
            output_dir,
            chunk_threshold_mib,
            connections_per_file,
            flat,
        }),
        Some(Commands::Status {
            repo_id: Some(repo_id),
            revision,
            token,
            // BORROW: explicit .as_str()/.as_deref() for owned → borrowed conversions
        }) => run_status(repo_id.as_str(), revision.as_deref(), token.as_deref()),
        Some(Commands::Status { repo_id: None, .. }) => run_status_all(),
        // BORROW: explicit .as_str()/.as_deref() for owned → borrowed conversions
        Some(Commands::Diff {
            repo_a,
            repo_b,
            revision_a,
            revision_b,
            token,
            cached,
            filter,
            summary,
            json,
        }) => run_diff(
            repo_a.as_str(),
            repo_b.as_str(),
            revision_a.as_deref(),
            revision_b.as_deref(),
            token.as_deref(),
            cached,
            filter.as_deref(),
            summary,
            json,
        ),
        // BORROW: explicit .as_str() for String → &str conversion
        Some(Commands::Du {
            repo_id: Some(repo_id),
            age: _,
        }) => {
            // BORROW: explicit .as_str() instead of Deref coercion
            let resolved = resolve_du_arg(repo_id.as_str())?;
            run_du_repo(resolved.as_str())
        }
        Some(Commands::Du { repo_id: None, age }) => run_du(age),
        // BORROW: explicit .as_str()/.as_deref() for owned → borrowed conversions
        Some(Commands::Inspect {
            repo_id,
            filename,
            revision,
            token,
            cached,
            list,
            no_metadata,
            json,
            filter,
            dtypes,
            limit,
            tree,
        }) => run_inspect(
            repo_id.as_str(),
            filename.as_deref(),
            revision.as_deref(),
            token.as_deref(),
            cached,
            list,
            no_metadata,
            json,
            filter.as_deref(),
            dtypes,
            limit,
            tree,
        ),
        // BORROW: explicit .as_str()/.as_deref() for owned → borrowed conversions
        Some(Commands::ListFiles {
            repo_id,
            revision,
            token,
            filter,
            exclude,
            preset,
            no_checksum,
            show_cached,
        }) => run_list_files(
            repo_id.as_str(),
            revision.as_deref(),
            token.as_deref(),
            &filter,
            &exclude,
            preset.as_ref(),
            no_checksum,
            show_cached,
        ),
        // BORROW: explicit .as_str() for String → &str conversion
        Some(Commands::Cache { subcommand }) => match subcommand {
            CacheCommands::CleanPartial {
                repo_id,
                yes,
                dry_run,
            } => {
                let resolved = repo_id.map(|r| resolve_du_arg(r.as_str())).transpose()?;
                run_cache_clean_partial(resolved.as_deref(), yes, dry_run)
            }
            // BORROW: explicit .as_str() for String → &str conversion
            CacheCommands::Delete { repo_id, yes } => {
                let resolved = resolve_du_arg(repo_id.as_str())?;
                // BORROW: explicit .as_str() instead of Deref coercion
                run_cache_delete(resolved.as_str(), yes)
            }
            // BORROW: explicit .as_str() for String → &str conversion
            CacheCommands::Path { repo_id } => {
                let resolved = resolve_du_arg(repo_id.as_str())?;
                // BORROW: explicit .as_str() instead of Deref coercion
                run_cache_path(resolved.as_str())
            }
        },
        None => run_download(cli.download),
    }
}

/// Progress reporter for non-TTY contexts (pipes, CI).
///
/// Emits periodic one-line progress to stderr every 5 seconds or every 10%
/// of total size, whichever comes first.
struct NonTtyProgress {
    /// Timestamp of the last progress line emitted.
    last_report: Mutex<Instant>,
    /// Last reported 10%-bucket per file (to detect 10% boundary crossings).
    last_bucket: Mutex<HashMap<String, u64>>,
}

impl NonTtyProgress {
    fn new() -> Self {
        Self {
            last_report: Mutex::new(Instant::now()),
            last_bucket: Mutex::new(HashMap::new()),
        }
    }

    /// Handles a `ProgressEvent`, emitting a progress line to stderr when the
    /// reporting threshold is reached.
    fn handle(&self, event: &hf_fetch_model::progress::ProgressEvent) {
        // Skip completion events (the summary line handles those).
        if event.percent >= 100.0 {
            return;
        }

        // CAST: f64 → u64, precision loss acceptable; bucket index for 10% increments
        #[allow(
            clippy::cast_possible_truncation,
            clippy::cast_sign_loss,
            clippy::as_conversions
        )]
        let bucket = (event.percent / 10.0) as u64;

        let elapsed_ok = self
            .last_report
            .lock()
            .is_ok_and(|guard| guard.elapsed().as_secs() >= 5);

        let bucket_crossed = self.last_bucket.lock().is_ok_and(|mut map| {
            // BORROW: explicit .clone() for owned String as HashMap key
            let prev = map.entry(event.filename.clone()).or_insert(0);
            if bucket > *prev {
                *prev = bucket;
                true
            } else {
                false
            }
        });

        if elapsed_ok || bucket_crossed {
            if let Ok(mut ts) = self.last_report.lock() {
                *ts = Instant::now();
            }
            // CAST: f64 → u64, precision loss acceptable; display-only percentage
            #[allow(
                clippy::cast_possible_truncation,
                clippy::cast_sign_loss,
                clippy::as_conversions
            )]
            let pct = event.percent as u64;
            eprintln!(
                "[hf-fm] {}: {}/{} ({pct}%)",
                event.filename,
                format_size(event.bytes_downloaded),
                format_size(event.bytes_total)
            );
        }
    }
}

fn run_download(args: DownloadArgs) -> Result<(), FetchError> {
    let dry_run = args.dry_run;

    let repo_id = args.repo_id.as_deref().ok_or_else(|| {
        FetchError::InvalidArgument(
            "REPO_ID is required for download. Usage: hf-fm <REPO_ID>".to_owned(),
        )
    })?;

    if !repo_id.contains('/') {
        return Err(FetchError::InvalidArgument(format!(
            "invalid REPO_ID \"{repo_id}\": expected \"org/model\" format (e.g., \"EleutherAI/pythia-1.4b\")"
        )));
    }

    if dry_run {
        return run_dry_run(repo_id, &args);
    }

    // Consume repo_id for the download path.
    // BORROW: explicit .to_owned() for &str → owned String
    let repo_id = repo_id.to_owned();
    let flat = args.flat;

    // When --flat, output_dir is the flat copy target, not the HF cache root.
    // BORROW: explicit .clone() for owned Option<PathBuf>
    let flat_target = if flat { args.output_dir.clone() } else { None };

    // Build FetchConfig from CLI args.
    let mut builder = match args.preset {
        Some(Preset::Safetensors) => Filter::safetensors(),
        Some(Preset::Gguf) => Filter::gguf(),
        Some(Preset::Npz) => Filter::npz(),
        Some(Preset::Pth) => Filter::pth(),
        Some(Preset::ConfigOnly) => Filter::config_only(),
        None => FetchConfig::builder(),
    };

    if let Some(ref preset) = args.preset {
        warn_redundant_filters(preset, &args.filter);
    }

    if let Some(rev) = args.revision.as_deref() {
        builder = builder.revision(rev);
    }
    if let Some(tok) = args.token.as_deref() {
        builder = builder.token(tok);
    } else {
        builder = builder.token_from_env();
    }
    for pattern in &args.filter {
        // BORROW: explicit .as_str() instead of Deref coercion
        builder = builder.filter(pattern.as_str());
    }
    for pattern in &args.exclude {
        // BORROW: explicit .as_str() instead of Deref coercion
        builder = builder.exclude(pattern.as_str());
    }
    if let Some(c) = args.concurrency {
        builder = builder.concurrency(c);
    }
    if let Some(ct) = args.chunk_threshold_mib {
        builder = builder.chunk_threshold(ct.saturating_mul(1024 * 1024));
    }
    if let Some(cpf) = args.connections_per_file {
        builder = builder.connections_per_file(cpf);
    }
    if !flat {
        if let Some(dir) = args.output_dir {
            builder = builder.output_dir(dir);
        }
    }

    // Set up progress reporting: indicatif bars for TTY, periodic stderr for non-TTY.
    let is_tty = std::io::stderr().is_terminal();
    let indicatif = if is_tty {
        let p = Arc::new(IndicatifProgress::new());
        let handle = Arc::clone(&p);
        builder = builder.on_progress(move |e| handle.handle(e));
        Some(p)
    } else {
        let p = Arc::new(NonTtyProgress::new());
        let handle = Arc::clone(&p);
        builder = builder.on_progress(move |e| handle.handle(e));
        None
    };

    let config = builder.build()?;

    // Run the download using a new Tokio runtime.
    let rt = tokio::runtime::Runtime::new().map_err(|e| FetchError::Io {
        path: PathBuf::from("<runtime>"),
        source: e,
    })?;

    let start = Instant::now();

    if flat {
        // --flat: download to cache, then copy to flat layout.
        let outcome = rt.block_on(hf_fetch_model::download_files_with_config(repo_id, &config))?;
        let elapsed = start.elapsed();

        if let Some(ref p) = indicatif {
            p.finish();
        }

        let file_map = outcome.inner();
        let target_dir = resolve_flat_target(flat_target.as_deref())?;
        let flat_paths = flatten_files(file_map, &target_dir)?;

        println!(
            "{} file(s) copied to {}:",
            flat_paths.len(),
            target_dir.display()
        );
        for p in &flat_paths {
            println!("  {}", p.display());
        }
        print_download_summary(&target_dir, elapsed);
    } else {
        let outcome = rt.block_on(hf_fetch_model::download_with_config(repo_id, &config))?;
        let elapsed = start.elapsed();

        // Finalize progress bar before printing to avoid interleaved output.
        if let Some(ref p) = indicatif {
            p.finish();
        }

        if outcome.is_cached() {
            println!("Cached at: {}", outcome.inner().display());
        } else {
            println!("Downloaded to: {}", outcome.inner().display());
            print_download_summary(outcome.inner(), elapsed);
        }
    }
    Ok(())
}

/// Displays a download plan without downloading anything.
fn run_dry_run(repo_id: &str, args: &DownloadArgs) -> Result<(), FetchError> {
    // Build FetchConfig from CLI args (same builder logic, minus on_progress).
    let mut builder = match args.preset {
        Some(Preset::Safetensors) => Filter::safetensors(),
        Some(Preset::Gguf) => Filter::gguf(),
        Some(Preset::Npz) => Filter::npz(),
        Some(Preset::Pth) => Filter::pth(),
        Some(Preset::ConfigOnly) => Filter::config_only(),
        None => FetchConfig::builder(),
    };

    if let Some(ref preset) = args.preset {
        warn_redundant_filters(preset, &args.filter);
    }

    if let Some(rev) = args.revision.as_deref() {
        builder = builder.revision(rev);
    }
    if let Some(tok) = args.token.as_deref() {
        builder = builder.token(tok);
    } else {
        builder = builder.token_from_env();
    }
    for pattern in &args.filter {
        // BORROW: explicit .as_str() instead of Deref coercion
        builder = builder.filter(pattern.as_str());
    }
    for pattern in &args.exclude {
        // BORROW: explicit .as_str() instead of Deref coercion
        builder = builder.exclude(pattern.as_str());
    }
    if let Some(ref dir) = args.output_dir {
        // BORROW: explicit .clone() for owned PathBuf
        builder = builder.output_dir(dir.clone());
    }

    let config = builder.build()?;

    let rt = tokio::runtime::Runtime::new().map_err(|e| FetchError::Io {
        path: PathBuf::from("<runtime>"),
        source: e,
    })?;

    let plan = rt.block_on(hf_fetch_model::download_plan(repo_id, &config))?;

    // Display header.
    println!("  Repo:     {}", plan.repo_id);
    println!("  Revision: {}", plan.revision);
    if args.preset.is_some() || !args.filter.is_empty() {
        println!("  Filter:   active (preset or --filter)");
    }
    if args.flat {
        let target = resolve_flat_target(args.output_dir.as_deref())?;
        println!(
            "  Flat:     {} (files will be copied here)",
            target.display()
        );
    }
    println!();

    // Display file table.
    let fw = plan
        .files
        .iter()
        .map(|fp| fp.filename.len())
        .max()
        .unwrap_or(4)
        .max(4); // BORROW: "File".len()
    let row_width = fw + 2 + 10 + 2 + 11;
    println!("  {:<fw$} {:>10}  Status", "File", "Size");
    println!(
        "  {:\u{2500}<fw$} {:\u{2500}<10}  {:\u{2500}<12}",
        "", "", ""
    );
    for fp in &plan.files {
        let status = if fp.cached {
            "cached \u{2713}"
        } else {
            "to download"
        };
        println!(
            "  {:<fw$} {:>10}  {status}",
            fp.filename,
            format_size(fp.size)
        );
    }

    // Summary.
    println!("{:\u{2500}<row_width$}", "  ");
    let cached_count = plan.files.len() - plan.files_to_download();
    let to_dl = plan.files_to_download();
    println!(
        "  Total: {} ({} files, {} cached, {} to download)",
        format_size(plan.total_bytes),
        plan.files.len(),
        cached_count,
        to_dl
    );
    println!("  Download: {}", format_size(plan.download_bytes));

    // Recommended config.
    if !plan.fully_cached() {
        let rec = plan.recommended_config()?;
        println!();
        println!("  Recommended config:");
        println!("    concurrency:        {}", rec.concurrency());
        println!("    connections/file:   {}", rec.connections_per_file());
        if rec.chunk_threshold() == u64::MAX {
            println!("    chunk threshold:  disabled (single-connection per file)");
        } else {
            println!(
                "    chunk threshold:  {} MiB",
                rec.chunk_threshold() / 1_048_576
            );
        }
    }

    Ok(())
}

/// Bundles CLI arguments for `download-file` to avoid too-many-arguments lint.
struct DownloadFileParams<'a> {
    repo_id: &'a str,
    filename: &'a str,
    revision: Option<&'a str>,
    token: Option<&'a str>,
    output_dir: Option<PathBuf>,
    chunk_threshold_mib: Option<u64>,
    connections_per_file: Option<usize>,
    flat: bool,
}

fn run_download_file(params: DownloadFileParams<'_>) -> Result<(), FetchError> {
    let DownloadFileParams {
        repo_id,
        filename,
        revision,
        token,
        output_dir,
        chunk_threshold_mib,
        connections_per_file,
        flat,
    } = params;
    if !repo_id.contains('/') {
        return Err(FetchError::InvalidArgument(format!(
            "invalid REPO_ID \"{repo_id}\": expected \"org/model\" format (e.g., \"mntss/clt-gemma-2-2b-426k\")"
        )));
    }

    // Glob pattern: list repo files, filter, and download each match.
    if has_glob_chars(filename) {
        return run_download_file_glob(DownloadFileParams {
            repo_id,
            filename,
            revision,
            token,
            output_dir,
            chunk_threshold_mib,
            connections_per_file,
            flat,
        });
    }

    // When --flat, output_dir is the flat copy target, not the HF cache root.
    // BORROW: explicit .clone() for owned Option<PathBuf>
    let flat_target = if flat { output_dir.clone() } else { None };

    // Build FetchConfig from CLI args.
    let mut builder = FetchConfig::builder();

    if let Some(rev) = revision {
        builder = builder.revision(rev);
    }
    if let Some(tok) = token {
        builder = builder.token(tok);
    } else {
        builder = builder.token_from_env();
    }
    if let Some(ct) = chunk_threshold_mib {
        builder = builder.chunk_threshold(ct.saturating_mul(1024 * 1024));
    }
    if let Some(cpf) = connections_per_file {
        builder = builder.connections_per_file(cpf);
    }
    if !flat {
        if let Some(dir) = output_dir {
            builder = builder.output_dir(dir);
        }
    }

    // Set up progress reporting: indicatif bars for TTY, periodic stderr for non-TTY.
    let is_tty = std::io::stderr().is_terminal();
    let indicatif = if is_tty {
        let p = Arc::new(IndicatifProgress::new());
        let handle = Arc::clone(&p);
        builder = builder.on_progress(move |e| handle.handle(e));
        Some(p)
    } else {
        let p = Arc::new(NonTtyProgress::new());
        let handle = Arc::clone(&p);
        builder = builder.on_progress(move |e| handle.handle(e));
        None
    };

    let config = builder.build()?;

    // Run the download using a new Tokio runtime.
    let rt = tokio::runtime::Runtime::new().map_err(|e| FetchError::Io {
        path: PathBuf::from("<runtime>"),
        source: e,
    })?;

    // BORROW: explicit .to_owned() for &str → owned String
    let start = Instant::now();
    let outcome = rt.block_on(hf_fetch_model::download_file(
        repo_id.to_owned(),
        filename,
        &config,
    ))?;
    let elapsed = start.elapsed();

    // Finalize progress bar before printing to avoid interleaved output.
    if let Some(ref p) = indicatif {
        p.finish();
    }

    if flat {
        let target_dir = resolve_flat_target(flat_target.as_deref())?;
        let flat_path = flatten_single_file(outcome.inner(), &target_dir)?;
        println!("Copied to: {}", flat_path.display());
    } else if outcome.is_cached() {
        println!("Cached at: {}", outcome.inner().display());
    } else {
        println!("Downloaded to: {}", outcome.inner().display());
        print_download_summary(outcome.inner(), elapsed);
    }
    Ok(())
}

/// Downloads files matching a glob pattern from a repository.
///
/// Lists all remote files, filters by the glob, and downloads each match
/// using the multi-file download pipeline.
fn run_download_file_glob(params: DownloadFileParams<'_>) -> Result<(), FetchError> {
    let DownloadFileParams {
        repo_id,
        filename: pattern,
        revision,
        token,
        output_dir,
        chunk_threshold_mib,
        connections_per_file,
        flat,
    } = params;
    // When --flat, output_dir is the flat copy target, not the HF cache root.
    // BORROW: explicit .clone() for owned Option<PathBuf>
    let flat_target = if flat { output_dir.clone() } else { None };

    // Build FetchConfig with the glob pattern as an include filter.
    let mut builder = FetchConfig::builder().filter(pattern);

    if let Some(rev) = revision {
        builder = builder.revision(rev);
    }
    if let Some(tok) = token {
        builder = builder.token(tok);
    } else {
        builder = builder.token_from_env();
    }
    if let Some(ct) = chunk_threshold_mib {
        builder = builder.chunk_threshold(ct.saturating_mul(1024 * 1024));
    }
    if let Some(cpf) = connections_per_file {
        builder = builder.connections_per_file(cpf);
    }
    if !flat {
        if let Some(dir) = output_dir {
            builder = builder.output_dir(dir);
        }
    }

    // Set up progress reporting: indicatif bars for TTY, periodic stderr for non-TTY.
    let is_tty = std::io::stderr().is_terminal();
    let indicatif = if is_tty {
        let p = Arc::new(IndicatifProgress::new());
        let handle = Arc::clone(&p);
        builder = builder.on_progress(move |e| handle.handle(e));
        Some(p)
    } else {
        let p = Arc::new(NonTtyProgress::new());
        let handle = Arc::clone(&p);
        builder = builder.on_progress(move |e| handle.handle(e));
        None
    };

    let config = builder.build()?;

    let rt = tokio::runtime::Runtime::new().map_err(|e| FetchError::Io {
        path: PathBuf::from("<runtime>"),
        source: e,
    })?;

    // BORROW: explicit .to_owned() for &str → owned String
    let start = Instant::now();
    let outcome = rt.block_on(hf_fetch_model::download_files_with_config(
        repo_id.to_owned(),
        &config,
    ))?;
    let elapsed = start.elapsed();

    // Finalize progress bar before printing to avoid interleaved output.
    if let Some(ref p) = indicatif {
        p.finish();
    }

    let file_map = outcome.inner();
    if file_map.is_empty() {
        println!("No files matched pattern \"{pattern}\" in {repo_id}");
        return Ok(());
    }

    if flat {
        let target_dir = resolve_flat_target(flat_target.as_deref())?;
        let flat_paths = flatten_files(file_map, &target_dir)?;
        println!(
            "{} file(s) copied to {}:",
            flat_paths.len(),
            target_dir.display()
        );
        for p in &flat_paths {
            println!("  {}", p.display());
        }
    } else {
        println!("{} file(s) matched pattern \"{pattern}\":", file_map.len());
        for (name, path) in file_map {
            println!("  {name}: {}", path.display());
        }
    }

    // Summarize total download time.
    let elapsed_secs = elapsed.as_secs_f64();
    if elapsed_secs > 0.0 {
        println!("  completed in {elapsed_secs:.1}s");
    }
    Ok(())
}

fn run_list_families() -> Result<(), FetchError> {
    let cache_dir = cache::hf_cache_dir()?;
    let families = cache::list_cached_families()?;

    println!("Cache: {}", cache_dir.display());
    println!();

    if families.is_empty() {
        println!("No model families found in local cache.");
        return Ok(());
    }

    let fw = families
        .keys()
        .map(String::len)
        .max()
        .unwrap_or(6)
        .max(6) // BORROW: "Family".len()
        + 2;
    let mw = families
        .values()
        .flat_map(|repos| repos.iter().map(String::len))
        .max()
        .unwrap_or(6)
        .max(6); // BORROW: "Models".len()
    println!("{:<fw$}Models", "Family");
    println!("{:-<fw$}{:-<mw$}", "", "");
    for (model_type, repos) in &families {
        for (i, repo) in repos.iter().enumerate() {
            if i == 0 {
                println!("{model_type:<fw$}{repo}");
            } else {
                println!("{:<fw$}{repo}", "");
            }
        }
    }

    Ok(())
}

fn run_discover(limit: usize) -> Result<(), FetchError> {
    let families = cache::list_cached_families()?;
    let local_types: HashSet<String> = families.into_keys().collect();

    let rt = tokio::runtime::Runtime::new().map_err(|e| FetchError::Io {
        path: PathBuf::from("<runtime>"),
        source: e,
    })?;

    let discovered = rt.block_on(discover::discover_new_families(&local_types, limit))?;

    if discovered.is_empty() {
        println!("No new model families found.");
        return Ok(());
    }

    println!("New families not in local cache (top models by downloads):\n");
    let fw = discovered
        .iter()
        .map(|f| f.model_type.len())
        .max()
        .unwrap_or(6)
        .max(6) // BORROW: "Family".len()
        + 2;
    let mw = discovered
        .iter()
        .map(|f| f.top_model.len())
        .max()
        .unwrap_or(9)
        .max(9); // BORROW: "Top Model".len()
    println!("{:<fw$}Top Model", "Family");
    println!("{:-<fw$}{:-<mw$}", "", "");
    for family in &discovered {
        println!("{:<fw$}{}", family.model_type, family.top_model);
    }

    Ok(())
}

fn run_search(
    query: &str,
    limit: usize,
    exact: bool,
    library: Option<&str>,
    pipeline: Option<&str>,
    tag: Option<&str>,
) -> Result<(), FetchError> {
    let rt = tokio::runtime::Runtime::new().map_err(|e| FetchError::Io {
        path: PathBuf::from("<runtime>"),
        source: e,
    })?;

    // When the query contains commas, treat both `,` and `/` as term separators
    // so that "mistralai/3B,12" becomes ["mistralai", "3B", "12"].
    // Without commas, just normalize `/` to space for the API query
    // so that "mistralai/3B" becomes "mistralai 3B" (broader API matching).
    let has_commas = query.contains(',');
    let normalized = if has_commas {
        query.replace('/', ",")
    } else {
        query.replace('/', " ")
    };

    // Split on `,` for multi-term filtering; first term goes to the API,
    // all terms are used for client-side filtering.
    let terms: Vec<&str> = normalized
        .split(',')
        .map(str::trim)
        .filter(|t| !t.is_empty())
        .collect();

    let api_query = terms.first().copied().unwrap_or(normalized.as_str()); // BORROW: explicit .as_str()

    let filter_terms: Vec<String> = terms.iter().map(|t| t.to_lowercase()).collect();

    // Oversample when filtering: request more from API to compensate for
    // client-side filtering that will discard non-matching results.
    let has_client_filter =
        filter_terms.len() > 1 || library.is_some() || pipeline.is_some() || tag.is_some();
    let api_limit = if has_client_filter {
        limit.saturating_mul(5)
    } else {
        limit
    };

    let results = rt.block_on(discover::search_models(
        api_query, api_limit, library, pipeline, tag,
    ))?;

    // Client-side filtering: only applied when there are multiple comma-separated
    // terms. Single-term queries trust the API results as-is.
    // Model IDs are normalized the same way as the query (slash → space) so that
    // mixed queries like "mistralai/3B,12" match "mistralai/Ministral-3-3B...".
    let has_multi_term = filter_terms.len() > 1;

    // Pre-normalize model IDs once (avoids re-allocating per result per term).
    let normalized_ids: Vec<String> = if has_multi_term {
        results
            .iter()
            .map(|r| r.model_id.replace('/', " ").to_lowercase())
            .collect()
    } else {
        Vec::new()
    };

    let filtered: Vec<&discover::SearchResult> = results
        .iter()
        .enumerate()
        .filter(|(i, _)| {
            if !has_multi_term {
                return true;
            }
            // INDEX: i is bounded by results.len() via enumerate()
            #[allow(clippy::indexing_slicing)]
            let id_normalized = &normalized_ids[*i];
            filter_terms
                .iter()
                .all(|term| id_normalized.contains(term.as_str())) // BORROW: explicit .as_str()
        })
        .map(|(_, r)| r)
        .take(limit)
        .collect();

    if exact {
        // Exact match: compare against the original query (not normalized)
        let exact_match = filtered
            .iter()
            .find(|r| r.model_id.eq_ignore_ascii_case(query));

        if let Some(matched) = exact_match {
            println!("Exact match:\n");
            print_search_result(matched, matched.model_id.len());

            // Fetch and display model card metadata
            match rt.block_on(discover::fetch_model_card(
                matched.model_id.as_str(), // BORROW: explicit .as_str()
            )) {
                Ok(card) => print_model_card(&card),
                Err(e) => eprintln!("\n  (could not fetch model card: {e})"),
            }
        } else {
            println!("No exact match for \"{query}\".");
            if !filtered.is_empty() {
                println!("\nDid you mean:\n");
                let nw = filtered.iter().map(|r| r.model_id.len()).max().unwrap_or(0);
                for result in &filtered {
                    print_search_result(result, nw);
                }
            }
        }
    } else {
        // Normal search display
        if filtered.is_empty() {
            println!("No models found matching \"{query}\".");
        } else {
            let nw = filtered.iter().map(|r| r.model_id.len()).max().unwrap_or(0);
            println!("Models matching \"{query}\" (by downloads):\n");
            for result in &filtered {
                print_search_result(result, nw);
            }
        }
    }

    Ok(())
}

fn print_search_result(result: &discover::SearchResult, name_width: usize) {
    let suffix = match (&result.library_name, &result.pipeline_tag) {
        (Some(lib), Some(pipe)) => format!("  [{lib}, {pipe}]"),
        (Some(lib), None) => format!("  [{lib}]"),
        (None, Some(pipe)) => format!("  [{pipe}]"),
        (None, None) => String::new(),
    };
    println!(
        "  hf-fm {:<nw$} ({} downloads){suffix}",
        result.model_id,
        format_downloads(result.downloads),
        nw = name_width,
    );
}

fn print_model_card(card: &discover::ModelCardMetadata) {
    println!();
    if let Some(ref license) = card.license {
        println!("  License:      {license}");
    }
    if card.gated.is_gated() {
        println!(
            "  Gated:        {} (requires accepting terms on HF)",
            card.gated
        );
    }
    if let Some(ref pipeline) = card.pipeline_tag {
        println!("  Pipeline:     {pipeline}");
    }
    if let Some(ref library) = card.library_name {
        println!("  Library:      {library}");
    }
    if !card.tags.is_empty() {
        println!("  Tags:         {}", card.tags.join(", "));
    }
    if !card.languages.is_empty() {
        println!("  Languages:    {}", card.languages.join(", "));
    }
}

/// Displays model card metadata and README text for a repository.
fn run_info(
    repo_id: &str,
    revision: Option<&str>,
    token: Option<&str>,
    json: bool,
    max_lines: usize,
) -> Result<(), FetchError> {
    if !repo_id.contains('/') {
        return Err(FetchError::InvalidArgument(format!(
            "invalid REPO_ID \"{repo_id}\": expected \"owner/model\" format \
             (e.g., \"mistralai/Ministral-3-3B-Instruct-2512\")"
        )));
    }

    // BORROW: explicit String::from for Option<&str> → Option<String>
    let token_owned = token
        .map(String::from)
        .or_else(|| std::env::var("HF_TOKEN").ok());

    let rt = tokio::runtime::Runtime::new().map_err(|e| FetchError::Io {
        path: PathBuf::from("<runtime>"),
        source: e,
    })?;

    let card = rt.block_on(discover::fetch_model_card(repo_id))?;
    // BORROW: explicit .as_deref() for Option<String> → Option<&str>
    let readme = rt.block_on(discover::fetch_readme(
        repo_id,
        revision,
        token_owned.as_deref(),
    ))?;

    if json {
        return print_info_json(repo_id, &card, readme.as_deref());
    }

    // Human-readable output.
    println!("  Repo: {repo_id}");
    print_model_card(&card);

    if let Some(ref text) = readme {
        // Strip YAML front matter (--- ... ---) since the structured metadata
        // is already displayed above via print_model_card().
        let body = strip_yaml_front_matter(text);

        println!();
        println!("  README:");
        println!("  {}", "\u{2500}".repeat(70));
        let lines: Vec<&str> = body.lines().collect();
        let display_count = if max_lines == 0 {
            lines.len()
        } else {
            lines.len().min(max_lines)
        };
        // INDEX: display_count bounded by lines.len() computed above
        #[allow(clippy::indexing_slicing)]
        for line in &lines[..display_count] {
            println!("  {line}");
        }
        if display_count < lines.len() {
            println!(
                "  ... ({} more lines, use --lines 0 for full output)",
                lines.len().saturating_sub(display_count)
            );
        }
    } else {
        println!();
        println!("  (no README.md found)");
    }

    Ok(())
}

/// Serializable model info for `--json` output.
#[derive(serde::Serialize)]
struct InfoResult {
    /// Repository identifier.
    repo_id: String,
    /// SPDX license identifier, if present.
    #[serde(skip_serializing_if = "Option::is_none")]
    license: Option<String>,
    /// Pipeline task tag, if present.
    #[serde(skip_serializing_if = "Option::is_none")]
    pipeline_tag: Option<String>,
    /// Library framework name, if present.
    #[serde(skip_serializing_if = "Option::is_none")]
    library_name: Option<String>,
    /// Tags from the model card.
    tags: Vec<String>,
    /// Supported languages.
    languages: Vec<String>,
    /// Access control status.
    gated: String,
    /// Full README text, if available.
    #[serde(skip_serializing_if = "Option::is_none")]
    readme: Option<String>,
}

/// Prints model info as JSON.
fn print_info_json(
    repo_id: &str,
    card: &discover::ModelCardMetadata,
    readme: Option<&str>,
) -> Result<(), FetchError> {
    let result = InfoResult {
        // BORROW: explicit .to_owned() for &str → owned String
        repo_id: repo_id.to_owned(),
        // BORROW: explicit .clone() for Option<String> and Vec<String> fields
        license: card.license.clone(),
        pipeline_tag: card.pipeline_tag.clone(),
        library_name: card.library_name.clone(),
        tags: card.tags.clone(),
        languages: card.languages.clone(),
        // BORROW: explicit .to_string() for GateStatus → String
        gated: card.gated.to_string(),
        // BORROW: explicit .to_owned() for Option<&str> → Option<String>
        readme: readme.map(str::to_owned),
    };

    let output = serde_json::to_string_pretty(&result)
        .map_err(|e| FetchError::Http(format!("failed to serialize JSON: {e}")))?;
    println!("{output}");
    Ok(())
}

/// Strips YAML front matter (`--- ... ---`) from a README string.
///
/// Returns the content after the closing `---` delimiter, trimmed of
/// leading blank lines. If no front matter is found, returns the
/// original string unchanged.
#[must_use]
fn strip_yaml_front_matter(text: &str) -> &str {
    // BORROW: explicit .trim_start() for &str → &str
    let trimmed = text.trim_start();
    if !trimmed.starts_with("---") {
        return text;
    }
    // Find the closing "---" after the opening one.
    // INDEX: skip first 3 bytes ("---") which are guaranteed present by the check above
    #[allow(clippy::indexing_slicing)]
    let after_open = &trimmed[3..];
    if let Some(close_pos) = after_open.find("\n---") {
        // Skip past the closing "---" and the newline after it.
        // CAST: not needed, all offsets are usize
        let body_start = close_pos + 4; // "\n---".len()
                                        // INDEX: body_start bounded by after_open.len() (find returned a valid position)
        #[allow(clippy::indexing_slicing)]
        let body = after_open[body_start..].trim_start_matches('\n');
        // BORROW: explicit .trim_start_matches() for &str → &str
        return body.trim_start_matches('\r');
    }
    text
}

fn run_status_all() -> Result<(), FetchError> {
    let cache_dir = cache::hf_cache_dir()?;
    let summaries = cache::cache_summary()?;

    if summaries.is_empty() {
        println!("No models found in local cache.");
        return Ok(());
    }

    println!("Cache: {}\n", cache_dir.display());
    let rw = summaries
        .iter()
        .map(|s| s.repo_id.len())
        .max()
        .unwrap_or(10)
        .max(10); // BORROW: "Repository".len()
    println!(
        "  {:<rw$} {:>5}  {:>10}  Status",
        "Repository", "Files", "Size"
    );
    println!("  {:-<rw$} {:-<5}  {:-<10}  {:-<8}", "", "", "", "");

    for s in &summaries {
        let status_label = if s.has_partial { "PARTIAL" } else { "ok" };
        println!(
            "  {:<rw$} {:>5}  {:>10}  {}",
            s.repo_id,
            s.file_count,
            format_size(s.total_size),
            status_label
        );
    }

    println!("\n{} model(s) cached", summaries.len());

    Ok(())
}

/// Resolves a `du` argument to a repo ID.
///
/// If the argument contains `/`, it is treated as a repo ID. If it parses
/// as a number, it is treated as a 1-based index into the size-sorted cache
/// summary. Otherwise, returns an error.
///
/// # Errors
///
/// Returns [`FetchError::InvalidArgument`] if the index is out of range
/// or the argument is not a valid repo ID or numeric index.
fn resolve_du_arg(arg: &str) -> Result<String, FetchError> {
    // Repo ID: contains '/' (e.g., "google/gemma-2-2b-it").
    if arg.contains('/') {
        // BORROW: explicit .to_owned() for &str → owned String
        return Ok(arg.to_owned());
    }

    // Numeric index: resolve against the size-sorted cache summary.
    if let Ok(n) = arg.parse::<usize>() {
        let mut summaries = cache::cache_summary()?;
        summaries.sort_by_key(|s| std::cmp::Reverse(s.total_size));

        if n == 0 || n > summaries.len() {
            return Err(FetchError::InvalidArgument(format!(
                "index {n} is out of range (cache has {} repos — use 1..{})",
                summaries.len(),
                summaries.len()
            )));
        }

        // INDEX: n is bounded by 1..=summaries.len() checked above
        // BORROW: explicit .clone() for owned String
        #[allow(clippy::indexing_slicing)]
        return Ok(summaries[n - 1].repo_id.clone());
    }

    Err(FetchError::InvalidArgument(format!(
        "\"{arg}\" is not a valid repo ID (expected \"org/model\") or numeric index"
    )))
}

/// Shows disk usage summary for all cached repos, sorted by size descending.
fn run_du(age: bool) -> Result<(), FetchError> {
    let cache_dir = cache::hf_cache_dir()?;
    println!("Cache: {}\n", cache_dir.display());

    let mut summaries = cache::cache_summary()?;

    if summaries.is_empty() {
        println!("No models found in local cache.");
        return Ok(());
    }

    summaries.sort_by_key(|s| std::cmp::Reverse(s.total_size));

    // Compute REPO column width from the longest repo ID (minimum 48).
    let repo_width = summaries
        .iter()
        .map(|s| s.repo_id.len())
        .max()
        .unwrap_or(0)
        .max(48);

    if age {
        println!(
            "  {:>3}  {:>10}  {:<repo_width$} {:>5}  {:<15}",
            "#", "SIZE", "REPO", "FILES", "AGE"
        );
    } else {
        println!(
            "  {:>3}  {:>10}  {:<repo_width$} {:>5}",
            "#", "SIZE", "REPO", "FILES"
        );
    }

    let mut total_size: u64 = 0;
    let mut total_files: usize = 0;
    let mut any_partial = false;

    for (i, s) in summaries.iter().enumerate() {
        total_size = total_size.saturating_add(s.total_size);
        total_files = total_files.saturating_add(s.file_count);

        let partial_marker = if s.has_partial {
            any_partial = true;
            "  \u{25cf}"
        } else {
            ""
        };

        if age {
            let age_str = s
                .last_modified
                .map_or_else(|| "\u{2014}".to_owned(), format_age);
            println!(
                "  {:>3}  {:>10}  {:<repo_width$} {:>5}  {:<15}{}",
                i + 1,
                format_size(s.total_size),
                s.repo_id,
                s.file_count,
                age_str,
                partial_marker,
            );
        } else {
            println!(
                "  {:>3}  {:>10}  {:<repo_width$} {:>5}{}",
                i + 1,
                format_size(s.total_size),
                s.repo_id,
                s.file_count,
                partial_marker,
            );
        }
    }

    // 3 (pad) + 2 + 3 (#) + 2 + 10 (SIZE) + 2 + repo_width + 2 + 5 (FILES) = repo_width + 29
    // When --age is active, add 2 (gap) + 15 (AGE column) = 17 extra.
    let rule_width = if age {
        repo_width + 46
    } else {
        repo_width + 29
    };
    println!("  {}", "\u{2500}".repeat(rule_width));
    println!(
        "  {:>10}  total ({} repos, {} files)",
        format_size(total_size),
        summaries.len(),
        total_files,
    );
    if any_partial {
        println!("  \u{25cf} = partial downloads");
    }

    Ok(())
}

/// Shows per-file disk usage for a specific cached repo, sorted by size descending.
fn run_du_repo(repo_id: &str) -> Result<(), FetchError> {
    let cache_dir = cache::hf_cache_dir()?;
    println!("Cache: {}\n", cache_dir.display());

    let files = cache::cache_repo_usage(repo_id)?;

    if files.is_empty() {
        println!("No cached files found for {repo_id}.");
        return Ok(());
    }

    println!("  {repo_id}:\n");
    let fw = files
        .iter()
        .map(|f| f.filename.len())
        .max()
        .unwrap_or(4)
        .max(4); // BORROW: "FILE".len()
    let row_width = 3 + 2 + 10 + 2 + fw;
    println!("  {:>3}  {:>10}  FILE", "#", "SIZE");

    let mut total_size: u64 = 0;

    for (i, f) in files.iter().enumerate() {
        total_size = total_size.saturating_add(f.size);
        println!(
            "  {:>3}  {:>10}  {}",
            i + 1,
            format_size(f.size),
            f.filename
        );
    }

    println!("  {}", "\u{2500}".repeat(row_width));
    println!(
        "  {:>10}  total ({} files)",
        format_size(total_size),
        files.len(),
    );

    // Check if this repo has partial downloads and hint the user
    // (targeted scan, not full cache).
    if cache::repo_has_partial(repo_id)? {
        println!("\n  \u{25cf} partial downloads — run `hf-fm status {repo_id}` for details");
    }

    Ok(())
}

/// Removes `.chunked.part` temp files from the `HuggingFace` cache.
///
/// When `repo_filter` is `Some`, only that repo is scanned.
/// With `--dry-run`, prints what would be removed without deleting.
/// With `--yes`, skips the confirmation prompt.
fn run_cache_clean_partial(
    repo_filter: Option<&str>,
    yes: bool,
    dry_run: bool,
) -> Result<(), FetchError> {
    let cache_dir = cache::hf_cache_dir()?;

    if !cache_dir.exists() {
        println!("No HuggingFace cache found at {}", cache_dir.display());
        return Ok(());
    }

    println!("Cache: {}\n", cache_dir.display());

    let partials = cache::find_partial_files(repo_filter)?;

    if partials.is_empty() {
        println!("No partial downloads found.");
        return Ok(());
    }

    let total_size: u64 = partials.iter().map(|p| p.size).sum();

    if dry_run {
        println!(
            "Would remove {} file(s) ({}):",
            partials.len(),
            format_size(total_size)
        );
        for p in &partials {
            println!("  {}: {}  ({})", p.repo_id, p.filename, format_size(p.size));
        }
        return Ok(());
    }

    println!("Found {} partial download(s):", partials.len());
    for p in &partials {
        println!("  {}: {}  ({})", p.repo_id, p.filename, format_size(p.size));
    }

    if !yes {
        let prompt = format!(
            "Clean {} file(s) ({})? [y/N]",
            partials.len(),
            format_size(total_size)
        );
        // BORROW: explicit .as_str() instead of Deref coercion
        if !confirm_prompt(prompt.as_str()) {
            println!("Aborted.");
            return Ok(());
        }
    }

    for p in &partials {
        std::fs::remove_file(&p.path).map_err(|e| FetchError::Io {
            // BORROW: explicit .clone() for owned PathBuf
            path: p.path.clone(),
            source: e,
        })?;
    }

    println!(
        "Removed {} file(s). Freed {}.",
        partials.len(),
        format_size(total_size)
    );
    Ok(())
}

/// Deletes a cached model by removing its `models--org--name/` directory.
///
/// Shows a size preview and prompts for confirmation unless `--yes` is passed.
fn run_cache_delete(repo_id: &str, yes: bool) -> Result<(), FetchError> {
    let cache_dir = cache::hf_cache_dir()?;

    if !cache_dir.exists() {
        println!("No HuggingFace cache found at {}", cache_dir.display());
        return Ok(());
    }

    let repo_dir = hf_fetch_model::cache_layout::repo_dir(&cache_dir, repo_id);

    if !repo_dir.exists() {
        return Err(FetchError::InvalidArgument(format!(
            "{repo_id} is not cached"
        )));
    }

    // Get size and file count for the preview (targeted scan, not full cache).
    let (file_count, size) = cache::repo_disk_usage(repo_id)?;

    println!("  {repo_id}  ({}, {} files)", format_size(size), file_count);

    if !yes && !confirm_prompt("  Delete? [y/N]") {
        println!("  Aborted.");
        return Ok(());
    }

    std::fs::remove_dir_all(&repo_dir).map_err(|e| FetchError::Io {
        // BORROW: explicit .clone() for owned PathBuf
        path: repo_dir.clone(),
        source: e,
    })?;

    println!("  Deleted. Freed {}.", format_size(size));
    Ok(())
}

/// Prints the snapshot directory path for a cached model.
///
/// Resolves the `main` ref to a commit hash and constructs the snapshot
/// path. Output is a bare path with no decoration, intended for shell
/// substitution: `cd $(hf-fm cache path org/model)`.
fn run_cache_path(repo_id: &str) -> Result<(), FetchError> {
    let cache_dir = cache::hf_cache_dir()?;
    let repo_dir = hf_fetch_model::cache_layout::repo_dir(&cache_dir, repo_id);

    if !repo_dir.exists() {
        return Err(FetchError::InvalidArgument(format!(
            "{repo_id} is not cached"
        )));
    }

    let commit_hash = cache::read_ref(&repo_dir, "main").ok_or_else(|| {
        FetchError::InvalidArgument(format!("{repo_id} is cached but has no ref for \"main\""))
    })?;

    // BORROW: explicit .as_str() instead of Deref coercion
    let snapshot_dir = hf_fetch_model::cache_layout::snapshot_dir(&repo_dir, commit_hash.as_str());

    if !snapshot_dir.exists() {
        return Err(FetchError::InvalidArgument(format!(
            "snapshot directory for {repo_id} does not exist"
        )));
    }

    // Print bare path (no labels) for shell substitution.
    println!("{}", snapshot_dir.display());
    Ok(())
}

/// Prompts the user for confirmation via stdin.
///
/// Returns `true` if the user enters `y` or `Y`, `false` otherwise.
fn confirm_prompt(message: &str) -> bool {
    eprint!("{message} ");
    let mut input = String::new();
    std::io::stdin().read_line(&mut input).is_ok() && input.trim().eq_ignore_ascii_case("y")
}

/// Collects all tensors from a repo into a name-keyed map.
///
/// Inspects all `.safetensors` files (cached or remote) and flattens
/// tensors across shards into a single `HashMap`.
fn collect_repo_tensors(
    repo_id: &str,
    revision: Option<&str>,
    token: Option<&str>,
    cached: bool,
) -> Result<HashMap<String, inspect::TensorInfo>, FetchError> {
    let results: Vec<(String, inspect::SafetensorsHeaderInfo)> = if cached {
        inspect::inspect_repo_safetensors_cached(repo_id, revision)?
    } else {
        // BORROW: explicit String::from for Option<&str> → Option<String>
        let token = token
            .map(String::from)
            .or_else(|| std::env::var("HF_TOKEN").ok());

        let rt = tokio::runtime::Runtime::new().map_err(|e| FetchError::Io {
            path: PathBuf::from("<runtime>"),
            source: e,
        })?;
        // BORROW: explicit .as_deref() for Option<String> → Option<&str>
        let remote_results = rt.block_on(inspect::inspect_repo_safetensors(
            repo_id,
            token.as_deref(),
            revision,
        ))?;
        remote_results
            .into_iter()
            .map(|(name, info, _source)| (name, info))
            .collect()
    };

    let mut tensors = HashMap::new();
    for (_filename, info) in results {
        for t in info.tensors {
            // BORROW: explicit .clone() for owned String key
            tensors.insert(t.name.clone(), t);
        }
    }

    Ok(tensors)
}

/// Compares tensor layouts between two model repositories.
#[allow(clippy::too_many_arguments, clippy::fn_params_excessive_bools)]
fn run_diff(
    repo_a: &str,
    repo_b: &str,
    revision_a: Option<&str>,
    revision_b: Option<&str>,
    token: Option<&str>,
    cached: bool,
    filter: Option<&str>,
    summary: bool,
    json: bool,
) -> Result<(), FetchError> {
    let tensors_a = collect_repo_tensors(repo_a, revision_a, token, cached)?;
    let tensors_b = collect_repo_tensors(repo_b, revision_b, token, cached)?;

    if tensors_a.is_empty() {
        println!("No .safetensors files found in {repo_a}.");
        println!("Hint: use `hf-fm list-files {repo_a}` to see available file types");
        return Ok(());
    }
    if tensors_b.is_empty() {
        println!("No .safetensors files found in {repo_b}.");
        println!("Hint: use `hf-fm list-files {repo_b}` to see available file types");
        return Ok(());
    }

    // Collect all tensor names from both repos (BTreeSet deduplicates and sorts).
    let mut all_names: Vec<&str> = tensors_a
        .keys()
        .chain(tensors_b.keys())
        // BORROW: explicit .as_str() instead of Deref coercion
        .map(String::as_str)
        .collect::<BTreeSet<&str>>()
        .into_iter()
        .collect();

    // Apply filter.
    if let Some(pattern) = filter {
        all_names.retain(|name| name.contains(pattern));
    }

    // Classify into four buckets.
    let mut only_a: Vec<&str> = Vec::new();
    let mut only_b: Vec<&str> = Vec::new();
    let mut differ: Vec<&str> = Vec::new();
    let mut matching: Vec<&str> = Vec::new();

    for name in &all_names {
        match (tensors_a.get(*name), tensors_b.get(*name)) {
            (Some(_), None) => only_a.push(name),
            (None, Some(_)) => only_b.push(name),
            (Some(a), Some(b)) => {
                if a.dtype == b.dtype && a.shape == b.shape {
                    matching.push(name);
                } else {
                    differ.push(name);
                }
            }
            (None, None) => {} // EXPLICIT: impossible — name comes from one of the two maps
        }
    }

    // Compute totals for the summary.
    let total_a = if filter.is_some() {
        only_a.len() + differ.len() + matching.len()
    } else {
        tensors_a.len()
    };
    let total_b = if filter.is_some() {
        only_b.len() + differ.len() + matching.len()
    } else {
        tensors_b.len()
    };

    // JSON output mode.
    if json {
        return print_diff_json(
            repo_a, repo_b, &tensors_a, &tensors_b, &only_a, &only_b, &differ, &matching, filter,
        );
    }

    // Print header.
    println!("  A: {repo_a}");
    println!("  B: {repo_b}");

    if !summary {
        // Compute name width across only-A and only-B sections for consistent columns.
        let nw = only_a
            .iter()
            .chain(only_b.iter())
            .map(|n| n.len())
            .max()
            .unwrap_or(0);

        println!();

        // Print only-in-A.
        if !only_a.is_empty() {
            let label = if only_a.len() == 1 {
                "tensor"
            } else {
                "tensors"
            };
            println!("  Only in A ({} {label}):", only_a.len());
            for name in &only_a {
                if let Some(t) = tensors_a.get(*name) {
                    let shape_str = format!("{:?}", t.shape);
                    println!("    {name:<nw$} {:<8} {shape_str}", t.dtype);
                }
            }
            println!();
        }

        // Print only-in-B.
        if !only_b.is_empty() {
            let label = if only_b.len() == 1 {
                "tensor"
            } else {
                "tensors"
            };
            println!("  Only in B ({} {label}):", only_b.len());
            for name in &only_b {
                if let Some(t) = tensors_b.get(*name) {
                    let shape_str = format!("{:?}", t.shape);
                    println!("    {name:<nw$} {:<8} {shape_str}", t.dtype);
                }
            }
            println!();
        }

        // Print dtype/shape differences.
        if !differ.is_empty() {
            let label = if differ.len() == 1 {
                "tensor"
            } else {
                "tensors"
            };
            println!("  Dtype/shape differences ({} {label}):", differ.len());
            for name in &differ {
                if let Some((a, b)) = tensors_a.get(*name).zip(tensors_b.get(*name)) {
                    let shape_a = format!("{:?}", a.shape);
                    let shape_b = format!("{:?}", b.shape);
                    println!("    {name}");
                    println!("      A: {:<8} {shape_a}", a.dtype);
                    println!("      B: {:<8} {shape_b}", b.dtype);
                }
            }
            println!();
        }

        // Print matching count.
        let match_label = if matching.len() == 1 {
            "tensor"
        } else {
            "tensors"
        };
        println!("  Matching: {} {match_label} identical", matching.len());
    }

    // Summary line.
    println!("  {}", "\u{2500}".repeat(70));
    print!(
        "  A: {} tensors | B: {} tensors | only-A: {} | only-B: {} | differ: {} | match: {}",
        total_a,
        total_b,
        only_a.len(),
        only_b.len(),
        differ.len(),
        matching.len(),
    );
    if let Some(pattern) = filter {
        println!(" (filter: {pattern:?})");
    } else {
        println!();
    }

    Ok(())
}

/// Serializable diff entry for `--json` output.
#[derive(serde::Serialize)]
struct DiffTensorEntry {
    /// Tensor name.
    name: String,
    /// Tensor info from model A, if present.
    #[serde(skip_serializing_if = "Option::is_none")]
    a: Option<DiffTensorSide>,
    /// Tensor info from model B, if present.
    #[serde(skip_serializing_if = "Option::is_none")]
    b: Option<DiffTensorSide>,
}

/// One side of a diff entry (dtype + shape).
#[derive(serde::Serialize)]
struct DiffTensorSide {
    /// Element dtype string.
    dtype: String,
    /// Tensor shape.
    shape: Vec<usize>,
}

/// Serializable diff result for `--json` output.
#[derive(serde::Serialize)]
struct DiffResult {
    /// Model A repository identifier.
    repo_a: String,
    /// Model B repository identifier.
    repo_b: String,
    /// Tensors only in model A.
    only_a: Vec<DiffTensorEntry>,
    /// Tensors only in model B.
    only_b: Vec<DiffTensorEntry>,
    /// Tensors with different dtypes or shapes.
    differ: Vec<DiffTensorEntry>,
    /// Number of tensors that match exactly.
    matching_count: usize,
    /// Filter pattern applied, if any.
    #[serde(skip_serializing_if = "Option::is_none")]
    filter: Option<String>,
}

/// Prints diff results as JSON.
#[allow(clippy::too_many_arguments)]
fn print_diff_json(
    repo_a: &str,
    repo_b: &str,
    tensors_a: &HashMap<String, inspect::TensorInfo>,
    tensors_b: &HashMap<String, inspect::TensorInfo>,
    only_a: &[&str],
    only_b: &[&str],
    differ: &[&str],
    matching: &[&str],
    filter: Option<&str>,
) -> Result<(), FetchError> {
    let make_entry = |name: &str,
                      a: Option<&inspect::TensorInfo>,
                      b: Option<&inspect::TensorInfo>|
     -> DiffTensorEntry {
        DiffTensorEntry {
            name: name.to_owned(),
            a: a.map(|t| DiffTensorSide {
                // BORROW: explicit .clone() for owned String
                dtype: t.dtype.clone(),
                shape: t.shape.clone(),
            }),
            b: b.map(|t| DiffTensorSide {
                // BORROW: explicit .clone() for owned String
                dtype: t.dtype.clone(),
                shape: t.shape.clone(),
            }),
        }
    };

    let result = DiffResult {
        repo_a: repo_a.to_owned(),
        repo_b: repo_b.to_owned(),
        only_a: only_a
            .iter()
            .map(|n| make_entry(n, tensors_a.get(*n), None))
            .collect(),
        only_b: only_b
            .iter()
            .map(|n| make_entry(n, None, tensors_b.get(*n)))
            .collect(),
        differ: differ
            .iter()
            .map(|n| make_entry(n, tensors_a.get(*n), tensors_b.get(*n)))
            .collect(),
        matching_count: matching.len(),
        filter: filter.map(str::to_owned),
    };

    let output = serde_json::to_string_pretty(&result)
        .map_err(|e| FetchError::Http(format!("failed to serialize JSON: {e}")))?;
    println!("{output}");
    Ok(())
}

/// Returns whether `filename` ends in `.safetensors` (case-insensitive).
fn has_safetensors_extension(filename: &str) -> bool {
    Path::new(filename)
        .extension()
        .and_then(|e| e.to_str())
        .is_some_and(|e| e.eq_ignore_ascii_case("safetensors"))
}

/// Inspects `.safetensors` file headers for tensor metadata.
#[allow(clippy::fn_params_excessive_bools, clippy::too_many_arguments)]
fn run_inspect(
    repo_id: &str,
    filename: Option<&str>,
    revision: Option<&str>,
    token: Option<&str>,
    cached: bool,
    list: bool,
    no_metadata: bool,
    json: bool,
    filter: Option<&str>,
    dtypes: bool,
    limit: Option<usize>,
    tree: bool,
) -> Result<(), FetchError> {
    if list {
        return run_inspect_list(repo_id, revision, token, cached);
    }
    match filename {
        Some(f) => {
            let resolved = resolve_inspect_filename_arg(f, repo_id, revision, token, cached)?;
            // BORROW: explicit .as_str() for String → &str argument
            run_inspect_single(
                repo_id,
                resolved.as_str(),
                revision,
                token,
                cached,
                no_metadata,
                json,
                filter,
                dtypes,
                limit,
                tree,
            )
        }
        None => run_inspect_repo(repo_id, revision, token, cached, json, filter),
    }
}

/// Resolves an inspect filename argument to a concrete filename.
///
/// If `arg` parses as a positive `usize`, treats it as a 1-based index into
/// the repository's alphabetically-sorted list of `.safetensors` files and
/// returns the corresponding filename. Otherwise returns `arg` unchanged.
///
/// When an index is resolved, a one-line `Resolving index N → <name>` note
/// is printed to stderr so the user can confirm the pick before the inspect
/// proceeds.
fn resolve_inspect_filename_arg(
    arg: &str,
    repo_id: &str,
    revision: Option<&str>,
    token: Option<&str>,
    cached: bool,
) -> Result<String, FetchError> {
    let Ok(n) = arg.parse::<usize>() else {
        // Not a number — treat as a literal filename.
        // BORROW: explicit .to_owned() for &str → owned String
        return Ok(arg.to_owned());
    };

    let (entries, commit_sha) = gather_safetensors_listing(repo_id, revision, token, cached)?;

    if entries.is_empty() {
        return Err(FetchError::InvalidArgument(format!(
            "index {n} cannot be resolved: no .safetensors files in repository {repo_id} \
             (run `hf-fm inspect {repo_id} --list` to confirm)"
        )));
    }

    if n == 0 || n > entries.len() {
        return Err(FetchError::InvalidArgument(format!(
            "index {n} is out of range (repository has {count} .safetensors files — \
             use 1..{count}; run `hf-fm inspect {repo_id} --list` to see them)",
            count = entries.len()
        )));
    }

    // INDEX: n is bounded by 1..=entries.len() checked above
    #[allow(clippy::indexing_slicing)]
    let (filename, _size) = &entries[n - 1];

    // Transparency: show what the index resolved to before proceeding.
    let rev_note = match &commit_sha {
        Some(sha) => format!(" (repo rev: {})", short_sha(sha)),
        None => String::new(),
    };
    eprintln!("Resolving index {n}{filename}{rev_note}");

    // BORROW: explicit .clone() for owned String result
    Ok(filename.clone())
}

/// Returns a short (12-char) prefix of a commit SHA for display.
fn short_sha(sha: &str) -> String {
    // BORROW: explicit .to_owned() for &str → owned String fallback
    sha.get(..12).map_or_else(|| sha.to_owned(), str::to_owned)
}

/// Fetches the `(filename, size_bytes)` list of safetensors files for a repo,
/// from either the local cache or the `HuggingFace` API, sorted alphabetically.
///
/// Also returns the commit SHA of the resolved revision when available.
fn gather_safetensors_listing(
    repo_id: &str,
    revision: Option<&str>,
    token: Option<&str>,
    cached: bool,
) -> Result<inspect::SafetensorsListing, FetchError> {
    if cached {
        return inspect::list_cached_safetensors(repo_id, revision);
    }

    // BORROW: explicit .to_owned() for Option<&str> → Option<String>
    let resolved_token = token
        .map(ToOwned::to_owned)
        .or_else(|| std::env::var("HF_TOKEN").ok());

    let rt = tokio::runtime::Runtime::new().map_err(|e| FetchError::Io {
        path: PathBuf::from("<runtime>"),
        source: e,
    })?;
    let client = hf_fetch_model::build_client(resolved_token.as_deref())?;
    let (files, commit_sha) = rt.block_on(repo::list_repo_files_with_commit(
        repo_id,
        resolved_token.as_deref(),
        revision,
        &client,
    ))?;

    let mut entries: Vec<(String, u64)> = files
        .into_iter()
        .filter(|f| f.filename.ends_with(".safetensors"))
        .map(|f| (f.filename, f.size.unwrap_or(0)))
        .collect();
    entries.sort_by(|a, b| a.0.cmp(&b.0));
    Ok((entries, commit_sha))
}

/// Prints the numbered list of `.safetensors` files in `repo_id`.
///
/// Used for discovery: tells the user what filenames / indices they can pass
/// to a follow-up `hf-fm inspect <repo> <n>` run. Does not read file headers.
fn run_inspect_list(
    repo_id: &str,
    revision: Option<&str>,
    token: Option<&str>,
    cached: bool,
) -> Result<(), FetchError> {
    let (entries, commit_sha) = gather_safetensors_listing(repo_id, revision, token, cached)?;

    println!("Repo: {repo_id}");
    let rev_label = revision.unwrap_or("main");
    match &commit_sha {
        Some(sha) => println!("Rev:  {sha} ({rev_label})"),
        None => println!("Rev:  (unknown) ({rev_label})"),
    }
    println!();

    if entries.is_empty() {
        println!("No .safetensors files in this repository.");
        if cached {
            println!();
            println!("Hint: the repo may not be cached locally. Try without --cached.");
        }
        return Ok(());
    }

    let count = entries.len();
    // Column widths: index gutter matches the highest number; filename/size scale to data.
    let index_width = count.to_string().len();
    let file_width = entries
        .iter()
        .map(|(f, _)| f.len())
        .max()
        .unwrap_or(4)
        .max(4); // BORROW: "File".len()
    let size_strings: Vec<String> = entries.iter().map(|(_, s)| format_size(*s)).collect();
    let size_width = size_strings
        .iter()
        .map(String::len)
        .max()
        .unwrap_or(4)
        .max(4); // BORROW: "Size".len()

    println!(
        "{:>index_width$}  {:<file_width$}  {:>size_width$}",
        "#", "File", "Size"
    );
    println!(
        "{:->index_width$}  {:-<file_width$}  {:->size_width$}",
        "", "", ""
    );
    let mut total: u64 = 0;
    for (i, ((filename, size), size_str)) in entries.iter().zip(size_strings.iter()).enumerate() {
        let n = i + 1;
        println!("{n:>index_width$}  {filename:<file_width$}  {size_str:>size_width$}");
        total = total.saturating_add(*size);
    }
    println!();
    println!("{count} file(s), {} total", format_size(total));

    // Reproducibility hints: only show when the user did not pin a revision.
    if revision.is_none() {
        if let Some(sha) = commit_sha.as_deref() {
            println!();
            println!(
                "Tip: run `hf-fm inspect {repo_id} <n>` to inspect file #n.\n     \
                 Pass `--revision {sha}` on both sides to lock against this view."
            );
        } else {
            println!();
            println!("Tip: run `hf-fm inspect {repo_id} <n>` to inspect file #n.");
        }
    }

    Ok(())
}

// ============================================================================
// --tree: hierarchical tensor-name view with auto-collapsing of numeric ranges
// ============================================================================

/// One node in a displayable tensor-name tree.
#[allow(clippy::exhaustive_enums)] // EXHAUSTIVE: internal view type; crate owns all render paths
#[derive(Debug, Clone)]
enum TreeNode {
    /// A single tensor (terminal leaf).
    Leaf(LeafNode),
    /// An internal node with named children.
    Branch(BranchNode),
    /// A collapsed numeric range like `layers.[0..27]` with shared sub-structure.
    Ranged(RangedNode),
}

/// Leaf node: one tensor with its display-relevant metadata.
#[derive(Debug, Clone)]
struct LeafNode {
    /// Segment(s) of the tensor name, collapsed from any single-child ancestor chain.
    name: String,
    /// Dtype string (`"BF16"`, `"F32"`, `"F8_E4M3"`, ...).
    dtype: String,
    /// Tensor shape.
    shape: Vec<usize>,
    /// Number of elements (product of shape).
    params: u64,
    /// Byte length of the tensor data.
    bytes: u64,
}

/// Internal branch: children under a common dotted prefix.
#[derive(Debug, Clone)]
struct BranchNode {
    /// Segment(s) for this level, collapsed from single-child ancestor chains.
    segment: String,
    /// Child nodes, sorted by segment (from `BTreeMap` iteration).
    children: Vec<TreeNode>,
    /// Aggregate tensor count across the subtree.
    total_tensors: usize,
    /// Aggregate parameter count across the subtree.
    total_params: u64,
    /// Aggregate byte count across the subtree.
    total_bytes: u64,
}

/// Collapsed numeric range: `layers.[0..N]` with an N+1-instance identical sub-structure.
#[derive(Debug, Clone)]
struct RangedNode {
    /// Segment name (e.g., `"layers"`).
    segment: String,
    /// Inclusive start index.
    range_start: usize,
    /// Inclusive end index.
    range_end: usize,
    /// Sub-structure appearing once; multiplied by `count` instances at display time.
    template: Vec<TreeNode>,
    /// Aggregate tensor count across all instances.
    total_tensors: usize,
    /// Aggregate parameter count across all instances.
    total_params: u64,
    /// Aggregate byte count across all instances.
    total_bytes: u64,
}

impl TreeNode {
    /// Aggregate tensor count at this subtree (including all instances for `Ranged`).
    fn total_tensors(&self) -> usize {
        match self {
            Self::Leaf(_) => 1,
            Self::Branch(b) => b.total_tensors,
            Self::Ranged(r) => r.total_tensors,
        }
    }

    /// Aggregate parameter count at this subtree.
    fn total_params(&self) -> u64 {
        match self {
            Self::Leaf(l) => l.params,
            Self::Branch(b) => b.total_params,
            Self::Ranged(r) => r.total_params,
        }
    }

    /// Aggregate byte count at this subtree.
    fn total_bytes(&self) -> u64 {
        match self {
            Self::Leaf(l) => l.bytes,
            Self::Branch(b) => b.total_bytes,
            Self::Ranged(r) => r.total_bytes,
        }
    }
}

/// Intermediate trie used while building a `TreeNode` tree.
///
/// Each node may terminate a tensor (if `tensor` is `Some`) AND/OR have children
/// (in the `BTreeMap`). Using a `BTreeMap` gives deterministic, sorted iteration.
#[derive(Debug, Default)]
struct TrieNode {
    /// Tensor whose full name terminates at this node, if any.
    tensor: Option<inspect::TensorInfo>,
    /// Child nodes keyed by segment, sorted alphabetically.
    children: BTreeMap<String, TrieNode>,
}

/// Builds a `TreeNode` forest from a slice of tensors.
///
/// Splits each tensor name on `.`, inserts into a trie, then converts to
/// `TreeNode`s, collapsing single-child chains into dotted paths.
fn build_tree(tensors: &[inspect::TensorInfo]) -> Vec<TreeNode> {
    let mut root = TrieNode::default();
    for t in tensors {
        // BORROW: explicit .as_str() instead of Deref coercion
        let segments: Vec<&str> = t.name.as_str().split('.').collect();
        insert_trie(&mut root, &segments, t.clone());
    }
    // Top-level nodes come from root's children (root itself has no segment).
    root.children
        .into_iter()
        .map(|(seg, child)| trie_to_tree(seg, child))
        .collect()
}

/// Inserts a tensor into the trie along a path of segments.
fn insert_trie(node: &mut TrieNode, segments: &[&str], tensor: inspect::TensorInfo) {
    // INDEX: slice split — first element and tail used; empty segments unreachable
    //        because .split('.') on a non-empty string always yields at least one item
    let Some((head, rest)) = segments.split_first() else {
        node.tensor = Some(tensor);
        return;
    };
    if rest.is_empty() {
        // BORROW: (*head).to_owned() for &&str → String key
        let child = node.children.entry((*head).to_owned()).or_default();
        child.tensor = Some(tensor);
    } else {
        // BORROW: (*head).to_owned() for &&str → String key
        let child = node.children.entry((*head).to_owned()).or_default();
        insert_trie(child, rest, tensor);
    }
}

/// Converts a trie node into a `TreeNode`, collapsing single-child chains.
fn trie_to_tree(segment: String, mut node: TrieNode) -> TreeNode {
    // No children: must be a leaf (or a degenerate empty node — treat as empty branch).
    if node.children.is_empty() {
        if let Some(tensor) = node.tensor {
            // Compute stats before moving out dtype/shape.
            let params = tensor.num_elements();
            let bytes = tensor.byte_len();
            return TreeNode::Leaf(LeafNode {
                name: segment,
                dtype: tensor.dtype,
                shape: tensor.shape,
                params,
                bytes,
            });
        }
        // EXPLICIT: unreachable in well-formed input; fall through to empty branch for safety
        return TreeNode::Branch(BranchNode {
            segment,
            children: Vec::new(),
            total_tensors: 0,
            total_params: 0,
            total_bytes: 0,
        });
    }

    // Single-child collapse: if no own tensor and exactly one child, merge segments.
    if node.tensor.is_none() && node.children.len() == 1 {
        if let Some((child_segment, child)) = node.children.pop_first() {
            let merged = format!("{segment}.{child_segment}");
            return trie_to_tree(merged, child);
        }
    }

    // Multi-child branch: recurse into each, compute aggregates.
    let mut children: Vec<TreeNode> = node
        .children
        .into_iter()
        .map(|(seg, child)| trie_to_tree(seg, child))
        .collect();

    // If this node also carries its own tensor alongside children, surface it as
    // a pseudo-leaf with an empty name (rare in safetensors; kept for correctness).
    if let Some(tensor) = node.tensor {
        // Compute stats before moving out dtype/shape.
        let params = tensor.num_elements();
        let bytes = tensor.byte_len();
        children.insert(
            0,
            TreeNode::Leaf(LeafNode {
                name: String::new(),
                dtype: tensor.dtype,
                shape: tensor.shape,
                params,
                bytes,
            }),
        );
    }

    let total_tensors: usize = children.iter().map(TreeNode::total_tensors).sum();
    let total_params: u64 = children
        .iter()
        .map(TreeNode::total_params)
        .fold(0u64, u64::saturating_add);
    let total_bytes: u64 = children
        .iter()
        .map(TreeNode::total_bytes)
        .fold(0u64, u64::saturating_add);

    TreeNode::Branch(BranchNode {
        segment,
        children,
        total_tensors,
        total_params,
        total_bytes,
    })
}

/// Post-processes a tree in place, collapsing numeric-indexed sibling branches
/// into `Ranged` nodes when their sub-structures match.
fn collapse_ranges(nodes: Vec<TreeNode>) -> Vec<TreeNode> {
    nodes.into_iter().map(collapse_node).collect()
}

fn collapse_node(node: TreeNode) -> TreeNode {
    match node {
        TreeNode::Leaf(_) => node,
        TreeNode::Branch(mut branch) => {
            // Recurse first: child-level collapses before parent-level check.
            branch.children = collapse_ranges(branch.children);
            try_collapse_range(&branch).map_or(TreeNode::Branch(branch), TreeNode::Ranged)
        }
        TreeNode::Ranged(mut ranged) => {
            // Already ranged — recurse into template anyway for nested structure.
            ranged.template = collapse_ranges(ranged.template);
            TreeNode::Ranged(ranged)
        }
    }
}

/// Checks whether a branch's children form a collapsible contiguous numeric range
/// `0..N` with structurally identical sub-trees. Returns the collapsed `RangedNode`
/// if so, or `None` if any requirement fails.
fn try_collapse_range(branch: &BranchNode) -> Option<RangedNode> {
    // Require at least 2 children; a single numeric child isn't a range.
    if branch.children.len() < 2 {
        return None;
    }

    // All children must be Branches with purely numeric segments.
    let mut indexed: Vec<(usize, &BranchNode)> = Vec::with_capacity(branch.children.len());
    for child in &branch.children {
        let TreeNode::Branch(sub) = child else {
            return None;
        };
        // BORROW: explicit .as_str() instead of Deref coercion
        let idx: usize = sub.segment.as_str().parse().ok()?;
        indexed.push((idx, sub));
    }

    // Indices must already be sorted ascending (BTreeMap order) — verify contiguous 0..N.
    indexed.sort_by_key(|(i, _)| *i);
    for (expected, (actual, _)) in indexed.iter().enumerate() {
        if expected != *actual {
            return None;
        }
    }

    // Structurally compare every branch's children against the first.
    // INDEX: indexed.len() >= 2 checked above, so indexed[0] is valid
    #[allow(clippy::indexing_slicing)]
    let (_, first_branch) = &indexed[0];
    #[allow(clippy::indexing_slicing)]
    for (_, other) in &indexed[1..] {
        if !branches_structurally_equal(first_branch, other) {
            return None;
        }
    }

    // Collapse: use the first branch's children as the template.
    let count = indexed.len();
    // CAST: usize → usize, no cast needed; range_end is last index
    let range_end = count.saturating_sub(1);

    Some(RangedNode {
        segment: branch.segment.clone(),
        range_start: 0,
        range_end,
        template: first_branch.children.clone(),
        total_tensors: branch.total_tensors,
        total_params: branch.total_params,
        total_bytes: branch.total_bytes,
    })
}

/// Compares two branches' children for structural equivalence. Ignores the top-level
/// segment (which is the numeric index — different by construction in a range).
fn branches_structurally_equal(a: &BranchNode, b: &BranchNode) -> bool {
    if a.children.len() != b.children.len() {
        return false;
    }
    a.children
        .iter()
        .zip(b.children.iter())
        .all(|(c1, c2)| nodes_structurally_equal(c1, c2))
}

/// Full structural equality including segments and leaf dtype/shape.
fn nodes_structurally_equal(a: &TreeNode, b: &TreeNode) -> bool {
    match (a, b) {
        (TreeNode::Leaf(l1), TreeNode::Leaf(l2)) => {
            l1.name == l2.name && l1.dtype == l2.dtype && l1.shape == l2.shape
        }
        (TreeNode::Branch(b1), TreeNode::Branch(b2)) => {
            b1.segment == b2.segment && branches_structurally_equal(b1, b2)
        }
        (TreeNode::Ranged(r1), TreeNode::Ranged(r2)) => {
            r1.segment == r2.segment
                && r1.range_end == r2.range_end
                && r1.template.len() == r2.template.len()
                && r1
                    .template
                    .iter()
                    .zip(r2.template.iter())
                    .all(|(c1, c2)| nodes_structurally_equal(c1, c2))
        }
        // EXPLICIT: mismatched variants cannot be structurally equal
        _ => false,
    }
}

// --- Human-readable rendering ---

/// Renders a tree forest to stdout using Unicode box-drawing connectors.
fn render_tree(nodes: &[TreeNode]) {
    render_children(nodes, "");
}

/// Renders children of a node, computing per-level leaf alignment.
fn render_children(children: &[TreeNode], prefix: &str) {
    // Compute max leaf-name width at THIS level for column alignment.
    let leaf_name_width: usize = children
        .iter()
        .filter_map(|c| match c {
            TreeNode::Leaf(l) => Some(l.name.len()),
            // EXPLICIT: branch/ranged children don't contribute to leaf-name width
            TreeNode::Branch(_) | TreeNode::Ranged(_) => None,
        })
        .max()
        .unwrap_or(0);

    // Max dtype width for aligned leaf rows.
    let dtype_width: usize = children
        .iter()
        .filter_map(|c| match c {
            TreeNode::Leaf(l) => Some(l.dtype.len()),
            // EXPLICIT: branch/ranged children don't contribute to dtype width
            TreeNode::Branch(_) | TreeNode::Ranged(_) => None,
        })
        .max()
        .unwrap_or(0);

    for (i, child) in children.iter().enumerate() {
        let is_last = i + 1 == children.len();
        render_node(child, prefix, is_last, leaf_name_width, dtype_width);
    }
}

fn render_node(
    node: &TreeNode,
    prefix: &str,
    is_last: bool,
    leaf_name_width: usize,
    dtype_width: usize,
) {
    let connector = if is_last { "└── " } else { "├── " };
    let indent = if is_last { "    " } else { "" };

    match node {
        TreeNode::Leaf(leaf) => {
            let shape_str = format!("{:?}", leaf.shape);
            let size_str = format_size(leaf.bytes);
            // Leaf columns: name (padded) | dtype (padded) | shape | size
            println!(
                "  {prefix}{connector}{name:<nw$}  {dtype:<dw$}  {shape_str}  {size_str}",
                name = leaf.name,
                dtype = leaf.dtype,
                nw = leaf_name_width,
                dw = dtype_width,
            );
        }
        TreeNode::Branch(branch) => {
            println!(
                "  {prefix}{connector}{seg}.",
                seg = branch.segment.as_str(), // BORROW: explicit .as_str()
            );
            let new_prefix = format!("{prefix}{indent}");
            render_children(&branch.children, new_prefix.as_str()); // BORROW: explicit .as_str()
        }
        TreeNode::Ranged(ranged) => {
            let count = ranged.range_end - ranged.range_start + 1;
            println!(
                "  {prefix}{connector}{seg}.[{start}..{end}].   (\u{00d7}{count})",
                seg = ranged.segment.as_str(), // BORROW: explicit .as_str()
                start = ranged.range_start,
                end = ranged.range_end,
            );
            let new_prefix = format!("{prefix}{indent}");
            render_children(&ranged.template, new_prefix.as_str()); // BORROW: explicit .as_str()
        }
    }
}

// --- JSON rendering ---

/// JSON node: tagged enum mirroring `TreeNode` for serialization.
#[derive(serde::Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum TreeJsonNode<'a> {
    Leaf {
        name: &'a str,
        dtype: &'a str,
        shape: &'a [usize],
        params: u64,
        bytes: u64,
    },
    Branch {
        name: &'a str,
        tensors: usize,
        params: u64,
        bytes: u64,
        children: Vec<TreeJsonNode<'a>>,
    },
    Ranged {
        name: &'a str,
        range_start: usize,
        range_end: usize,
        count: usize,
        tensors: usize,
        params: u64,
        bytes: u64,
        template: Vec<TreeJsonNode<'a>>,
    },
}

/// Top-level JSON wrapper for `--tree --json`.
#[derive(serde::Serialize)]
struct TreeJsonOutput<'a> {
    repo_id: &'a str,
    filename: &'a str,
    total_tensors: usize,
    total_params: u64,
    tree: Vec<TreeJsonNode<'a>>,
}

fn tree_to_json(nodes: &[TreeNode]) -> Vec<TreeJsonNode<'_>> {
    nodes.iter().map(node_to_json).collect()
}

/// Builds, collapses, and prints a tensor-name tree to stdout.
///
/// `total_tensor_count` and `total_params` are used only for the footer line
/// (show `X/Y tensors` when `filter` is active, or `N tensors` otherwise).
fn print_tree_summary(
    tensors: &[inspect::TensorInfo],
    filter: Option<&str>,
    total_tensor_count: usize,
    total_params: u64,
) {
    let forest = collapse_ranges(build_tree(tensors));
    println!();
    render_tree(&forest);

    // Footer: mirror the regular inspect footer conventions.
    let shown: usize = forest.iter().map(TreeNode::total_tensors).sum();
    let shown_params: u64 = forest
        .iter()
        .map(TreeNode::total_params)
        .fold(0u64, u64::saturating_add);
    let tensor_label = if shown == 1 { "tensor" } else { "tensors" };
    if let Some(pattern) = filter {
        println!(
            "  {shown}/{total_tensor_count} {tensor_label}, {}/{} params (filter: {pattern:?})",
            inspect::format_params(shown_params),
            inspect::format_params(total_params),
        );
    } else {
        println!(
            "  {shown} {tensor_label}, {} params",
            inspect::format_params(shown_params),
        );
    }
}

/// Builds, collapses, and emits the tree as JSON to stdout.
fn print_tree_json(
    repo_id: &str,
    filename: &str,
    tensors: &[inspect::TensorInfo],
    total_tensor_count: usize,
    total_params: u64,
) -> Result<(), FetchError> {
    let forest = collapse_ranges(build_tree(tensors));
    let output = TreeJsonOutput {
        repo_id,
        filename,
        total_tensors: total_tensor_count,
        total_params,
        tree: tree_to_json(&forest),
    };
    let serialized = serde_json::to_string_pretty(&output)
        .map_err(|e| FetchError::Http(format!("failed to serialize JSON: {e}")))?;
    println!("{serialized}");
    Ok(())
}

fn node_to_json(node: &TreeNode) -> TreeJsonNode<'_> {
    match node {
        TreeNode::Leaf(l) => TreeJsonNode::Leaf {
            name: l.name.as_str(),     // BORROW: explicit .as_str()
            dtype: l.dtype.as_str(),   // BORROW: explicit .as_str()
            shape: l.shape.as_slice(), // BORROW: explicit .as_slice()
            params: l.params,
            bytes: l.bytes,
        },
        TreeNode::Branch(b) => TreeJsonNode::Branch {
            name: b.segment.as_str(), // BORROW: explicit .as_str()
            tensors: b.total_tensors,
            params: b.total_params,
            bytes: b.total_bytes,
            children: tree_to_json(&b.children),
        },
        TreeNode::Ranged(r) => {
            let count = r.range_end - r.range_start + 1;
            TreeJsonNode::Ranged {
                name: r.segment.as_str(), // BORROW: explicit .as_str()
                range_start: r.range_start,
                range_end: r.range_end,
                count,
                tensors: r.total_tensors,
                params: r.total_params,
                bytes: r.total_bytes,
                template: tree_to_json(&r.template),
            }
        }
    }
}

// ============================================================================

/// Truncation metadata added to `--json` output when `--limit` cuts the tensor list short.
#[derive(serde::Serialize)]
struct TruncationInfo {
    /// Number of tensors in the `tensors` array (after filter and limit).
    shown: usize,
    /// Total tensors in the file (before any filter or limit).
    total: usize,
}

/// JSON wrapper that adds a top-level `truncated` field when the output was capped by `--limit`.
///
/// The field is omitted entirely when the tensor list is complete, preserving
/// the plain `SafetensorsHeaderInfo` schema for non-truncated output.
#[derive(serde::Serialize)]
struct InspectJsonOutput<'a> {
    #[serde(flatten)]
    header: &'a inspect::SafetensorsHeaderInfo,
    #[serde(skip_serializing_if = "Option::is_none")]
    truncated: Option<TruncationInfo>,
}

/// Inspects a single `.safetensors` file and prints the result.
#[allow(clippy::fn_params_excessive_bools, clippy::too_many_arguments)]
fn run_inspect_single(
    repo_id: &str,
    filename: &str,
    revision: Option<&str>,
    token: Option<&str>,
    cached: bool,
    no_metadata: bool,
    json: bool,
    filter: Option<&str>,
    dtypes: bool,
    limit: Option<usize>,
    tree: bool,
) -> Result<(), FetchError> {
    if !has_safetensors_extension(filename) {
        // BORROW: owned Strings for error variant fields
        let extension = Path::new(filename)
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("unknown")
            .to_owned();
        return Err(FetchError::UnsupportedInspectFormat {
            filename: filename.to_owned(),
            extension,
        });
    }

    let (mut info, source) = if cached {
        let info = inspect::inspect_safetensors_cached(repo_id, filename, revision)?;
        (info, inspect::InspectSource::Cached)
    } else {
        // BORROW: explicit String::from for Option<&str> → Option<String>
        let token = token
            .map(String::from)
            .or_else(|| std::env::var("HF_TOKEN").ok());

        let rt = tokio::runtime::Runtime::new().map_err(|e| FetchError::Io {
            path: PathBuf::from("<runtime>"),
            source: e,
        })?;
        // BORROW: explicit .as_deref() for Option<String> → Option<&str>
        rt.block_on(inspect::inspect_safetensors(
            repo_id,
            filename,
            token.as_deref(),
            revision,
        ))?
    };

    // Apply tensor name filter.
    let total_tensor_count = info.tensors.len();
    let total_params = info.total_params();
    if let Some(pattern) = filter {
        // BORROW: explicit .as_str() instead of Deref coercion
        info.tensors.retain(|t| t.name.as_str().contains(pattern));
    }

    // Apply limit after filter. Track matched counts to report truncation.
    let matched_count = info.tensors.len();
    let matched_params = info.total_params();
    let truncated_by_limit = limit.is_some_and(|n| matched_count > n);
    if let Some(n) = limit {
        info.tensors.truncate(n);
    }

    // `--tree --json`: hierarchical tree as JSON (distinct schema from plain --json).
    if tree && json {
        return print_tree_json(
            repo_id,
            filename,
            &info.tensors,
            total_tensor_count,
            total_params,
        );
    }

    // `--dtypes --json`: compact dtype breakdown as JSON (distinct schema from plain --json).
    if dtypes && json {
        return print_dtype_summary_json(&info.tensors, total_tensor_count, total_params);
    }

    if json {
        // `truncated` is `None` when the list is complete, which `skip_serializing_if`
        // suppresses — so non-truncated output is schema-identical to v0.9.5.
        let wrapped = InspectJsonOutput {
            header: &info,
            truncated: truncated_by_limit.then_some(TruncationInfo {
                shown: info.tensors.len(),
                total: total_tensor_count,
            }),
        };
        let output = serde_json::to_string_pretty(&wrapped)
            .map_err(|e| FetchError::Http(format!("failed to serialize JSON: {e}")))?;
        println!("{output}");
        return Ok(());
    }

    // Human-readable output.
    let source_label = match source {
        inspect::InspectSource::Cached => "cached",
        inspect::InspectSource::Remote => "remote (2 HTTP requests)",
        _ => "unknown",
    };
    println!("  Repo:     {repo_id}");
    println!("  File:     {filename}");
    println!("  Source:   {source_label}");

    let header_display = format_size(info.header_size);
    if let Some(fs) = info.file_size {
        println!(
            "  Header:   {header_display} (JSON), {} total",
            format_size(fs)
        );
    } else {
        println!("  Header:   {header_display} (JSON)");
    }

    if !no_metadata {
        if let Some(ref meta) = info.metadata {
            let entries: Vec<String> = meta.iter().map(|(k, v)| format!("{k}={v}")).collect();
            // BORROW: explicit .join() on slice
            println!("  Metadata: {}", entries.join(", "));
        }
    }

    // Hierarchical tree mode.
    if tree {
        print_tree_summary(&info.tensors, filter, total_tensor_count, total_params);
        return Ok(());
    }

    // Per-dtype summary mode.
    if dtypes {
        print_dtype_summary(&info.tensors, filter, total_tensor_count, total_params);
        return Ok(());
    }

    // Compute dynamic column widths from the actual data.
    let nw = info
        .tensors
        .iter()
        .map(|t| t.name.len())
        .max()
        .unwrap_or(6)
        .max(6); // BORROW: "Tensor".len()
    let shape_strs: Vec<String> = info
        .tensors
        .iter()
        .map(|t| format!("{:?}", t.shape))
        .collect();
    let sw = shape_strs.iter().map(String::len).max().unwrap_or(5).max(5); // BORROW: "Shape".len()
    let row_width = nw + 2 + 8 + sw + 2 + 10 + 2 + 10;

    println!();
    println!(
        "  {:<nw$} {:<8} {:<sw$} {:>10} {:>10}",
        "Tensor", "Dtype", "Shape", "Size", "Params",
    );

    for (t, shape_str) in info.tensors.iter().zip(shape_strs.iter()) {
        let size_str = format_size(t.byte_len());
        let params_str = inspect::format_params(t.num_elements());
        println!(
            "  {:<nw$} {:<8} {:<sw$} {:>10} {:>10}",
            t.name, t.dtype, shape_str, size_str, params_str,
        );
    }

    println!("  {}", "\u{2500}".repeat(row_width));
    let shown_count = info.tensors.len();
    let shown_params = info.total_params();
    let tensor_label = if shown_count == 1 {
        "tensor"
    } else {
        "tensors"
    };

    match (filter.is_some(), truncated_by_limit) {
        (false, false) => {
            println!(
                "  {shown_count} {tensor_label}, {} params",
                inspect::format_params(shown_params)
            );
        }
        (true, false) => {
            println!(
                "  {shown_count}/{total_tensor_count} {tensor_label}, {}/{} params (filter: {:?})",
                inspect::format_params(shown_params),
                inspect::format_params(total_params),
                filter.unwrap_or_default(),
            );
        }
        (false, true) => {
            println!(
                "  {shown_count}/{total_tensor_count} {tensor_label} shown, {}/{} params (limit: {})",
                inspect::format_params(shown_params),
                inspect::format_params(total_params),
                limit.unwrap_or(0),
            );
        }
        (true, true) => {
            // Three-number format: shown/matched/total.
            println!(
                "  {shown_count}/{matched_count}/{total_tensor_count} {tensor_label} shown, {}/{}/{} params (filter: {:?}, limit: {})",
                inspect::format_params(shown_params),
                inspect::format_params(matched_params),
                inspect::format_params(total_params),
                filter.unwrap_or_default(),
                limit.unwrap_or(0),
            );
        }
    }

    Ok(())
}

/// Inspects all `.safetensors` files in a repository (summary or per-file).
#[allow(clippy::too_many_arguments)]
fn run_inspect_repo(
    repo_id: &str,
    revision: Option<&str>,
    token: Option<&str>,
    cached: bool,
    json: bool,
    filter: Option<&str>,
) -> Result<(), FetchError> {
    if cached {
        // Cache-only: try shard index first, then walk snapshot.
        if let Some(index) = inspect::fetch_shard_index_cached(repo_id, revision)? {
            print_shard_index_summary(repo_id, &index, filter);
            print_adapter_config_if_present(repo_id, revision, None, true, json);
            return Ok(());
        }

        let results = inspect::inspect_repo_safetensors_cached(repo_id, revision)?;
        if results.is_empty() {
            println!("No cached .safetensors files found for {repo_id}.");
            println!("Hint: use `hf-fm list-files {repo_id}` to see available file types");
            return Ok(());
        }

        if json {
            print_multi_file_json(&results, filter)?;
            print_adapter_config_if_present(repo_id, revision, None, true, true);
            return Ok(());
        }

        print_multi_file_summary(repo_id, "cached", &results, filter);
        print_adapter_config_if_present(repo_id, revision, None, true, false);
        return Ok(());
    }

    // Network-enabled: try shard index first, then full inspection.
    // BORROW: explicit String::from for Option<&str> → Option<String>
    let token = token
        .map(String::from)
        .or_else(|| std::env::var("HF_TOKEN").ok());

    let rt = tokio::runtime::Runtime::new().map_err(|e| FetchError::Io {
        path: PathBuf::from("<runtime>"),
        source: e,
    })?;

    // BORROW: explicit .as_deref() for Option<String> → Option<&str>
    let shard_index = rt.block_on(inspect::fetch_shard_index(
        repo_id,
        token.as_deref(),
        revision,
    ))?;

    if let Some(index) = shard_index {
        print_shard_index_summary(repo_id, &index, filter);
        print_adapter_config_if_present(repo_id, revision, token.as_deref(), false, json);
        return Ok(());
    }

    // BORROW: explicit .as_deref() for Option<String> → Option<&str>
    let results = rt.block_on(inspect::inspect_repo_safetensors(
        repo_id,
        token.as_deref(),
        revision,
    ))?;

    if results.is_empty() {
        println!("No .safetensors files found in {repo_id}.");
        println!("Hint: use `hf-fm list-files {repo_id}` to see available file types");
        return Ok(());
    }

    if json {
        let mapped: Vec<(String, inspect::SafetensorsHeaderInfo)> = results
            .into_iter()
            .map(|(name, info, _source)| (name, info))
            .collect();
        print_multi_file_json(&mapped, filter)?;
        print_adapter_config_if_present(repo_id, revision, token.as_deref(), false, true);
        return Ok(());
    }

    let mapped: Vec<(String, inspect::SafetensorsHeaderInfo)> = results
        .into_iter()
        .map(|(name, info, _source)| (name, info))
        .collect();
    print_multi_file_summary(repo_id, "mixed", &mapped, filter);
    print_adapter_config_if_present(repo_id, revision, token.as_deref(), false, false);
    Ok(())
}

/// Prints adapter configuration if `adapter_config.json` is found in the repository.
///
/// Silently returns if the file does not exist or cannot be fetched.
fn print_adapter_config_if_present(
    repo_id: &str,
    revision: Option<&str>,
    token: Option<&str>,
    cached: bool,
    json: bool,
) {
    let result = if cached {
        inspect::fetch_adapter_config_cached(repo_id, revision)
    } else {
        let Ok(rt) = tokio::runtime::Runtime::new() else {
            return;
        };
        rt.block_on(inspect::fetch_adapter_config(repo_id, token, revision))
    };

    let Ok(Some(config)) = result else { return };

    if json {
        if let Ok(output) = serde_json::to_string_pretty(&config) {
            println!("{output}");
        }
        return;
    }

    println!();
    println!("  Adapter config:");
    if let Some(ref peft_type) = config.peft_type {
        println!("    PEFT type:       {peft_type}");
    }
    if let Some(ref base) = config.base_model_name_or_path {
        println!("    Base model:      {base}");
    }
    if let Some(r) = config.r {
        println!("    Rank (r):        {r}");
    }
    if let Some(alpha) = config.lora_alpha {
        println!("    LoRA alpha:      {alpha}");
    }
    if let Some(ref task) = config.task_type {
        println!("    Task type:       {task}");
    }
    if !config.target_modules.is_empty() {
        println!("    Target modules:  {}", config.target_modules.join(", "));
    }
}

/// One row of a `--dtypes` summary.
#[derive(serde::Serialize)]
struct DtypeGroup<'a> {
    dtype: &'a str,
    tensors: usize,
    params: u64,
    bytes: u64,
}

/// JSON shape emitted by `inspect --dtypes --json`.
///
/// `total_tensors` and `total_params` always reflect the whole file, before any
/// filter. Summing the `dtypes` array gives the filtered totals.
#[derive(serde::Serialize)]
struct DtypeSummaryJson<'a> {
    dtypes: Vec<DtypeGroup<'a>>,
    total_tensors: usize,
    total_params: u64,
}

/// Groups tensors by dtype and returns rows sorted by tensor count descending.
///
/// Each row is `(dtype, count, params, bytes)`.
fn compute_dtype_groups(tensors: &[inspect::TensorInfo]) -> Vec<(&str, usize, u64, u64)> {
    let mut groups: HashMap<&str, (usize, u64, u64)> = HashMap::new();
    for t in tensors {
        let entry = groups
            .entry(t.dtype.as_str()) // BORROW: explicit .as_str()
            .or_insert((0, 0, 0));
        entry.0 += 1;
        entry.1 = entry.1.saturating_add(t.num_elements());
        entry.2 = entry.2.saturating_add(t.byte_len());
    }
    // BORROW: flatten nested HashMap tuple into (dtype, count, params, bytes)
    let mut rows: Vec<(&str, usize, u64, u64)> = groups
        .into_iter()
        .map(|(dtype, (count, params, bytes))| (dtype, count, params, bytes))
        .collect();
    rows.sort_by_key(|r| std::cmp::Reverse(r.1));
    rows
}

/// Emits the `--dtypes` summary as JSON.
fn print_dtype_summary_json(
    tensors: &[inspect::TensorInfo],
    total_tensor_count: usize,
    total_params: u64,
) -> Result<(), FetchError> {
    let rows = compute_dtype_groups(tensors);
    let output = DtypeSummaryJson {
        dtypes: rows
            .into_iter()
            .map(|(dtype, tensors, params, bytes)| DtypeGroup {
                dtype,
                tensors,
                params,
                bytes,
            })
            .collect(),
        total_tensors: total_tensor_count,
        total_params,
    };
    let serialized = serde_json::to_string_pretty(&output)
        .map_err(|e| FetchError::Http(format!("failed to serialize JSON: {e}")))?;
    println!("{serialized}");
    Ok(())
}

/// Prints a per-dtype summary table (tensor count, param count, byte size per dtype).
fn print_dtype_summary(
    tensors: &[inspect::TensorInfo],
    filter: Option<&str>,
    total_tensor_count: usize,
    total_params: u64,
) {
    let rows = compute_dtype_groups(tensors);

    // Dynamic column widths.
    let dw = rows
        .iter()
        .map(|(d, _, _, _)| d.len())
        .max()
        .unwrap_or(5)
        .max(5); // BORROW: "Dtype".len()
    let row_width = dw + 2 + 8 + 2 + 12 + 2 + 10;

    println!();
    println!(
        "  {:<dw$} {:>8} {:>12} {:>10}",
        "Dtype", "Tensors", "Params", "Size",
    );

    for (dtype, count, params, bytes) in &rows {
        println!(
            "  {:<dw$} {:>8} {:>12} {:>10}",
            dtype,
            count,
            inspect::format_params(*params),
            format_size(*bytes),
        );
    }

    println!("  {}", "\u{2500}".repeat(row_width));

    let filtered_count: usize = rows.iter().map(|(_, count, _, _)| count).sum();
    let filtered_params: u64 = rows.iter().map(|(_, _, params, _)| params).sum();
    let tensor_label = if filtered_count == 1 {
        "tensor"
    } else {
        "tensors"
    };

    if filter.is_some() {
        println!(
            "  {filtered_count}/{total_tensor_count} {tensor_label}, {}/{} params",
            inspect::format_params(filtered_params),
            inspect::format_params(total_params),
        );
    } else {
        println!(
            "  {filtered_count} {tensor_label}, {} params",
            inspect::format_params(filtered_params),
        );
    }
}

/// Prints shard index summary (tensor counts per shard).
fn print_shard_index_summary(repo_id: &str, index: &inspect::ShardedIndex, filter: Option<&str>) {
    println!("  Repo:   {repo_id}");
    println!("  Source: shard index (model.safetensors.index.json)");
    println!();

    // Count tensors per shard, optionally filtering by tensor name.
    let total_tensors = index.weight_map.len();
    let mut by_shard: HashMap<String, usize> = HashMap::new();
    let mut filtered_total: usize = 0;
    for (tensor_name, shard_name) in &index.weight_map {
        if let Some(pattern) = filter {
            if !tensor_name.contains(pattern) {
                continue;
            }
        }
        // BORROW: explicit .clone() for owned String key
        *by_shard.entry(shard_name.clone()).or_default() += 1;
        filtered_total += 1;
    }

    let fw = index
        .shards
        .iter()
        .map(String::len)
        .max()
        .unwrap_or(4)
        .max(4); // BORROW: "File".len()
    let row_width = fw + 2 + 8;
    println!("  {:<fw$} {:>8}", "File", "Tensors");

    for shard in &index.shards {
        let count = by_shard.get(shard).copied().unwrap_or(0);
        if filter.is_some() && count == 0 {
            continue;
        }
        println!("  {shard:<fw$} {count:>8}");
    }

    println!("  {}", "\u{2500}".repeat(row_width));

    let displayed_shards = if filter.is_some() {
        by_shard.len()
    } else {
        index.shards.len()
    };
    let shard_label = if displayed_shards == 1 {
        "shard"
    } else {
        "shards"
    };
    let tensor_label = if filtered_total == 1 {
        "tensor"
    } else {
        "tensors"
    };

    if filter.is_some() {
        println!(
            "  {displayed_shards} {shard_label}, {filtered_total}/{total_tensors} {tensor_label} (filter: {:?})",
            filter.unwrap_or_default(),
        );
    } else {
        println!("  {displayed_shards} {shard_label}, {filtered_total} {tensor_label}");
    }
    println!("  Hint: use `hf-fm inspect {repo_id} <filename>` for per-tensor detail");
}

/// Prints multi-file inspection results as JSON, optionally filtering tensors.
fn print_multi_file_json(
    results: &[(String, inspect::SafetensorsHeaderInfo)],
    filter: Option<&str>,
) -> Result<(), FetchError> {
    if let Some(pattern) = filter {
        // Filter tensors before cloning to avoid O(T) clone-then-discard.
        let filtered: Vec<(String, inspect::SafetensorsHeaderInfo)> = results
            .iter()
            .filter_map(|(name, info)| {
                let matching: Vec<inspect::TensorInfo> = info
                    .tensors
                    .iter()
                    .filter(|t| t.name.as_str().contains(pattern)) // BORROW: explicit .as_str()
                    .cloned()
                    .collect();
                if matching.is_empty() {
                    return None;
                }
                Some((
                    name.clone(), // BORROW: explicit .clone() for owned String
                    inspect::SafetensorsHeaderInfo {
                        tensors: matching,
                        metadata: info.metadata.clone(),
                        header_size: info.header_size,
                        file_size: info.file_size,
                    },
                ))
            })
            .collect();
        let output = serde_json::to_string_pretty(&filtered)
            .map_err(|e| FetchError::Http(format!("failed to serialize JSON: {e}")))?;
        println!("{output}");
    } else {
        let output = serde_json::to_string_pretty(results)
            .map_err(|e| FetchError::Http(format!("failed to serialize JSON: {e}")))?;
        println!("{output}");
    }
    Ok(())
}

/// Prints multi-file inspection results as a human-readable summary.
fn print_multi_file_summary(
    repo_id: &str,
    source: &str,
    results: &[(String, inspect::SafetensorsHeaderInfo)],
    filter: Option<&str>,
) {
    println!("  Repo:   {repo_id}");
    println!("  Source: {source}");
    println!();

    let fw = results
        .iter()
        .map(|(name, _)| name.len())
        .max()
        .unwrap_or(4)
        .max(4); // BORROW: "File".len()
    let row_width = fw + 2 + 8 + 1 + 12;
    println!("  {:<fw$} {:>8} {:>12}", "File", "Tensors", "Params");

    let mut total_tensors_unfiltered: usize = 0;
    let mut total_params_unfiltered: u64 = 0;
    let mut total_tensors_filtered: usize = 0;
    let mut total_params_filtered: u64 = 0;
    let mut files_with_matches: usize = 0;

    for (name, info) in results {
        total_tensors_unfiltered = total_tensors_unfiltered.saturating_add(info.tensors.len());
        total_params_unfiltered = total_params_unfiltered.saturating_add(info.total_params());

        let (tensor_count, params) = if let Some(pattern) = filter {
            let matching: Vec<&inspect::TensorInfo> = info
                .tensors
                .iter()
                // BORROW: explicit .as_str() instead of Deref coercion
                .filter(|t| t.name.as_str().contains(pattern))
                .collect();
            let p: u64 = matching.iter().map(|t| t.num_elements()).sum();
            (matching.len(), p)
        } else {
            (info.tensors.len(), info.total_params())
        };

        if filter.is_some() && tensor_count == 0 {
            continue;
        }

        files_with_matches += 1;
        total_tensors_filtered = total_tensors_filtered.saturating_add(tensor_count);
        total_params_filtered = total_params_filtered.saturating_add(params);
        println!(
            "  {name:<fw$} {tensor_count:>8} {:>12}",
            inspect::format_params(params)
        );
    }

    println!("  {}", "\u{2500}".repeat(row_width));
    let file_label = if files_with_matches == 1 {
        "file"
    } else {
        "files"
    };
    let tensor_label = if total_tensors_filtered == 1 {
        "tensor"
    } else {
        "tensors"
    };

    if filter.is_some() {
        println!(
            "  {} {file_label}, {total_tensors_filtered}/{total_tensors_unfiltered} {tensor_label}, {}/{} params (filter: {:?})",
            files_with_matches,
            inspect::format_params(total_params_filtered),
            inspect::format_params(total_params_unfiltered),
            filter.unwrap_or_default(),
        );
    } else {
        println!(
            "  {} {file_label}, {total_tensors_filtered} {tensor_label}, {} params",
            files_with_matches,
            inspect::format_params(total_params_filtered)
        );
    }
}

fn run_status(
    repo_id: &str,
    revision: Option<&str>,
    token: Option<&str>,
) -> Result<(), FetchError> {
    // BORROW: explicit String::from (equivalent to .to_owned()) for Option<&str> → Option<String>
    let token = token
        .map(String::from)
        .or_else(|| std::env::var("HF_TOKEN").ok());

    let rt = tokio::runtime::Runtime::new().map_err(|e| FetchError::Io {
        path: PathBuf::from("<runtime>"),
        source: e,
    })?;

    // BORROW: explicit .as_deref() for Option<String> → Option<&str>
    let status = rt.block_on(cache::repo_status(repo_id, token.as_deref(), revision))?;

    // Header
    let rev_display = revision.unwrap_or("main");
    match &status.commit_hash {
        Some(hash) => println!("{repo_id} ({rev_display} @ {hash})"),
        None => println!("{repo_id} ({rev_display}, not yet cached)"),
    }
    println!("Cache: {}\n", status.cache_path.display());

    if status.files.is_empty() {
        println!("  (no files found in remote repository)");
        return Ok(());
    }

    // File table
    let fw = status
        .files
        .iter()
        .map(|(name, _)| name.len())
        .max()
        .unwrap_or(4)
        .max(4); // BORROW: "File".len()
    for (filename, file_status) in &status.files {
        match file_status {
            cache::FileStatus::Complete { local_size } => {
                println!(
                    "  {:<fw$} {:>10}  complete",
                    filename,
                    format_size(*local_size)
                );
            }
            cache::FileStatus::Partial {
                local_size,
                expected_size,
            } => {
                println!(
                    "  {:<fw$} {:>10} / {:<10}  PARTIAL",
                    filename,
                    format_size(*local_size),
                    format_size(*expected_size)
                );
            }
            cache::FileStatus::Missing { expected_size } => {
                if *expected_size > 0 {
                    println!(
                        "  {:<fw$} {:>10}  MISSING",
                        filename,
                        format_size(*expected_size)
                    );
                } else {
                    println!("  {filename:<fw$} {:>10}  MISSING", "\u{2014}");
                }
            }
            // EXPLICIT: future FileStatus variants display as UNKNOWN
            _ => {
                println!("  {filename:<fw$}              UNKNOWN");
            }
        }
    }

    // Summary
    let total = status.files.len();
    let complete = status.complete_count();
    let partial = status.partial_count();
    let missing = status.missing_count();
    println!();
    println!("{complete}/{total} complete, {partial} partial, {missing} missing");

    Ok(())
}

/// Lists files in a remote `HuggingFace` repository without downloading.
#[allow(clippy::too_many_arguments, clippy::fn_params_excessive_bools)]
fn run_list_files(
    repo_id: &str,
    revision: Option<&str>,
    token: Option<&str>,
    filter_patterns: &[String],
    exclude_patterns: &[String],
    preset: Option<&Preset>,
    no_checksum: bool,
    show_cached: bool,
) -> Result<(), FetchError> {
    if !repo_id.contains('/') {
        return Err(FetchError::InvalidArgument(format!(
            "invalid REPO_ID \"{repo_id}\": expected \"org/model\" format \
             (e.g., \"google/gemma-2-2b-it\")"
        )));
    }

    // Build glob filters from preset + explicit patterns.
    let mut include_patterns: Vec<String> = match preset {
        Some(&Preset::Safetensors) => vec![
            "*.safetensors".to_owned(),
            "*.json".to_owned(),
            "*.txt".to_owned(),
        ],
        Some(&Preset::Gguf) => vec!["*.gguf".to_owned(), "*.json".to_owned(), "*.txt".to_owned()],
        Some(&Preset::Npz) => vec![
            "*.npz".to_owned(),
            "*.npy".to_owned(),
            "config.yaml".to_owned(),
            "*.json".to_owned(),
            "*.txt".to_owned(),
        ],
        Some(&Preset::Pth) => vec![
            "pytorch_model*.bin".to_owned(),
            "*.json".to_owned(),
            "*.txt".to_owned(),
        ],
        Some(&Preset::ConfigOnly) => {
            vec!["*.json".to_owned(), "*.txt".to_owned(), "*.md".to_owned()]
        }
        None => Vec::new(),
    };
    for p in filter_patterns {
        // BORROW: explicit .clone() for owned String
        include_patterns.push(p.clone());
    }
    let include = compile_glob_patterns(&include_patterns)?;
    let exclude = compile_glob_patterns(exclude_patterns)?;

    // Resolve token from arg or env.
    // BORROW: explicit .to_owned() for Option<&str> → Option<String>
    let resolved_token = token
        .map(ToOwned::to_owned)
        .or_else(|| std::env::var("HF_TOKEN").ok());

    // Fetch remote file list with metadata.
    let rt = tokio::runtime::Runtime::new().map_err(|e| FetchError::Io {
        path: PathBuf::from("<runtime>"),
        source: e,
    })?;
    let client = hf_fetch_model::build_client(resolved_token.as_deref())?;
    let files = rt.block_on(repo::list_repo_files_with_metadata(
        repo_id,
        resolved_token.as_deref(),
        revision,
        &client,
    ))?;

    // Apply glob filters.
    let filtered: Vec<_> = files
        .into_iter()
        .filter(|f| {
            // BORROW: explicit .as_str() instead of Deref coercion
            file_matches(f.filename.as_str(), include.as_ref(), exclude.as_ref())
        })
        .collect();

    // Resolve cache state if requested.
    // Three states: "✓" (complete), "partial" (local < expected), "✗" (missing).
    // Uses the same size-comparison logic as `status` (cache.rs).
    let cache_marks: Vec<String> = if show_cached {
        let cache_dir = cache::hf_cache_dir()?;
        let repo_dir = hf_fetch_model::cache_layout::repo_dir(&cache_dir, repo_id);
        let revision_str = revision.unwrap_or("main");
        let commit_hash = cache::read_ref(&repo_dir, revision_str);
        let snapshot_dir =
            commit_hash.map(|h| hf_fetch_model::cache_layout::snapshot_dir(&repo_dir, &h));

        filtered
            .iter()
            .map(|f| {
                let local_path = snapshot_dir
                    .as_ref()
                    // BORROW: explicit .as_str() instead of Deref coercion
                    .map(|dir| dir.join(f.filename.as_str()));
                match local_path {
                    Some(ref path) if path.exists() => {
                        let local_size = std::fs::metadata(path).map_or(0, |m| m.len());
                        let expected = f.size.unwrap_or(0);
                        if expected > 0 && local_size < expected {
                            "partial".to_owned()
                        } else {
                            "\u{2713}".to_owned()
                        }
                    }
                    _ => "\u{2717}".to_owned(),
                }
            })
            .collect()
    } else {
        Vec::new()
    };

    // Compute file-name column width from the actual data.
    let fw = filtered
        .iter()
        .map(|f| f.filename.len())
        .max()
        .unwrap_or(4)
        .max(4); // BORROW: "File".len()

    // Print table header.
    if no_checksum {
        if show_cached {
            println!("  {:<fw$} {:>10}  Cached", "File", "Size");
            println!("  {:<fw$} {:>10}  {:-<6}", "", "", "");
        } else {
            println!("  {:<fw$} {:>10}", "File", "Size");
            println!("  {:<fw$} {:>10}", "", "");
        }
    } else if show_cached {
        println!("  {:<fw$} {:>10}  {:<12}  Cached", "File", "Size", "SHA256");
        println!("  {:<fw$} {:>10}  {:<12}  {:-<6}", "", "", "", "");
    } else {
        println!("  {:<fw$} {:>10}  {:<12}", "File", "Size", "SHA256");
        println!("  {:<fw$} {:>10}  {:<12}", "", "", "");
    }

    // Print each file row.
    let mut total_bytes: u64 = 0;
    let mut cached_count: usize = 0;
    let mut any_no_sha = false;

    for (i, f) in filtered.iter().enumerate() {
        let size = f.size.unwrap_or(0);
        total_bytes = total_bytes.saturating_add(size);

        let size_str = format_size(size);
        let sha_str = if no_checksum {
            String::new()
        } else if let Some(hash) = f.sha256.as_deref().and_then(|s| s.get(..12)) {
            hash.to_owned() // BORROW: &str → String for column display
        } else {
            any_no_sha = true;
            "\u{2014}".to_owned()
        };

        if show_cached {
            let mark = cache_marks.get(i).map_or("\u{2717}", String::as_str);
            if mark == "\u{2713}" {
                cached_count += 1;
            }
            if no_checksum {
                println!("  {:<fw$} {:>10}  {mark}", f.filename, size_str);
            } else {
                println!(
                    "  {:<fw$} {:>10}  {:<12}  {mark}",
                    f.filename, size_str, sha_str
                );
            }
        } else if no_checksum {
            println!("  {:<fw$} {:>10}", f.filename, size_str);
        } else {
            println!("  {:<fw$} {:>10}  {sha_str}", f.filename, size_str);
        }
    }

    // Summary line.
    let count = filtered.len();
    let row_width = fw + 2 + 10 + 2 + 12;
    println!("  {:\u{2500}<row_width$}", "");
    if show_cached {
        println!(
            "  {count} files, {} total ({cached_count} cached)",
            format_size(total_bytes)
        );
    } else {
        println!("  {count} files, {} total", format_size(total_bytes));
    }
    if any_no_sha && !no_checksum {
        println!("  \u{2014} = not an LFS file (no SHA256 tracked by the Hub)");
    }

    Ok(())
}

/// Formats a byte size with human-readable suffixes (B, KiB, MiB, GiB).
fn format_size(bytes: u64) -> String {
    const KIB: u64 = 1024;
    const MIB: u64 = 1024 * 1024;
    const GIB: u64 = 1024 * 1024 * 1024;
    const TIB: u64 = 1024 * GIB;

    // Use TiB for values >= 1000 GiB, GiB for >= 1000 MiB.
    if bytes >= 1000 * GIB {
        // CAST: u64 → f64, precision loss acceptable; value is a display-only size scalar
        #[allow(clippy::cast_precision_loss, clippy::as_conversions)]
        let val = bytes as f64 / TIB as f64;
        format!("{val:.2} TiB")
    } else if bytes >= 1000 * MIB {
        // CAST: u64 → f64, precision loss acceptable; value is a display-only size scalar
        #[allow(clippy::cast_precision_loss, clippy::as_conversions)]
        let val = bytes as f64 / GIB as f64;
        format!("{val:.2} GiB")
    } else if bytes >= MIB {
        // CAST: u64 → f64, precision loss acceptable; value is a display-only size scalar
        #[allow(clippy::cast_precision_loss, clippy::as_conversions)]
        let val = bytes as f64 / MIB as f64;
        format!("{val:.2} MiB")
    } else if bytes >= KIB {
        // CAST: u64 → f64, precision loss acceptable; value is a display-only size scalar
        #[allow(clippy::cast_precision_loss, clippy::as_conversions)]
        let val = bytes as f64 / KIB as f64;
        format!("{val:.1} KiB")
    } else {
        format!("{bytes} B")
    }
}

/// Formats a [`SystemTime`] as a human-readable relative age string.
///
/// Buckets: `"< 1 hour"`, `"N hours ago"`, `"N days ago"`,
/// `"N months ago"`, `"N years ago"`.
///
/// [`SystemTime`]: std::time::SystemTime
fn format_age(time: std::time::SystemTime) -> String {
    const HOUR: u64 = 3600;
    const DAY: u64 = 86_400;
    const MONTH: u64 = 30 * DAY;
    const YEAR: u64 = 365 * DAY;

    let Ok(elapsed) = time.elapsed() else {
        return "\u{2014}".to_owned(); // clock skew or future timestamp
    };
    let secs = elapsed.as_secs();

    if secs < HOUR {
        "< 1 hour".to_owned()
    } else if secs < DAY {
        let hours = secs / HOUR;
        if hours == 1 {
            "1 hour ago".to_owned()
        } else {
            format!("{hours} hours ago")
        }
    } else if secs < MONTH {
        let days = secs / DAY;
        if days == 1 {
            "1 day ago".to_owned()
        } else {
            format!("{days} days ago")
        }
    } else if secs < YEAR {
        let months = secs / MONTH;
        if months == 1 {
            "1 month ago".to_owned()
        } else {
            format!("{months} months ago")
        }
    } else {
        let years = secs / YEAR;
        if years == 1 {
            "1 year ago".to_owned()
        } else {
            format!("{years} years ago")
        }
    }
}

/// Resolves the flat-copy target directory from an optional `--output-dir`.
///
/// Falls back to the current working directory when no explicit directory is given.
///
/// # Errors
///
/// Returns [`FetchError::Io`] if the current directory cannot be determined.
fn resolve_flat_target(output_dir: Option<&Path>) -> Result<PathBuf, FetchError> {
    match output_dir {
        // BORROW: explicit .to_path_buf() for &Path → owned PathBuf
        Some(dir) => Ok(dir.to_path_buf()),
        None => std::env::current_dir().map_err(|e| FetchError::Io {
            path: PathBuf::from("."),
            source: e,
        }),
    }
}

/// Copies downloaded files to a flat directory layout.
///
/// Each file is copied from the HF cache to `{target_dir}/{basename}`.
///
/// # Errors
///
/// Returns [`FetchError::Io`] if directory creation or file copy fails.
fn flatten_files(
    file_map: &HashMap<String, PathBuf>,
    target_dir: &Path,
) -> Result<Vec<PathBuf>, FetchError> {
    // BORROW: explicit .to_path_buf() for &Path → owned PathBuf
    std::fs::create_dir_all(target_dir).map_err(|e| FetchError::Io {
        path: target_dir.to_path_buf(),
        source: e,
    })?;

    let mut flat_paths = Vec::with_capacity(file_map.len());
    for (filename, cache_path) in file_map {
        // BORROW: explicit .as_str() instead of Deref coercion
        let basename = Path::new(filename)
            .file_name()
            .unwrap_or(std::ffi::OsStr::new(filename.as_str()));
        let flat_path = target_dir.join(basename);
        // BORROW: explicit .clone() for owned PathBuf
        std::fs::copy(cache_path, &flat_path).map_err(|e| FetchError::Io {
            path: flat_path.clone(),
            source: e,
        })?;
        flat_paths.push(flat_path);
    }
    Ok(flat_paths)
}

/// Copies a single downloaded file to a flat directory layout.
///
/// # Errors
///
/// Returns [`FetchError::Io`] if directory creation or file copy fails.
fn flatten_single_file(cache_path: &Path, target_dir: &Path) -> Result<PathBuf, FetchError> {
    // BORROW: explicit .to_path_buf() for &Path → owned PathBuf
    std::fs::create_dir_all(target_dir).map_err(|e| FetchError::Io {
        path: target_dir.to_path_buf(),
        source: e,
    })?;

    let basename = cache_path
        .file_name()
        .unwrap_or(std::ffi::OsStr::new("file"));
    let flat_path = target_dir.join(basename);
    // BORROW: explicit .clone() for owned PathBuf
    std::fs::copy(cache_path, &flat_path).map_err(|e| FetchError::Io {
        path: flat_path.clone(),
        source: e,
    })?;
    Ok(flat_path)
}

/// Warns when `--filter` globs are redundant with the active `--preset`.
fn warn_redundant_filters(preset: &Preset, filters: &[String]) {
    let (preset_globs, preset_name): (&[&str], &str) = match preset {
        Preset::Safetensors => (&["*.safetensors", "*.json", "*.txt"], "safetensors"),
        Preset::Gguf => (&["*.gguf", "*.json", "*.txt"], "gguf"),
        Preset::Npz => {
            let globs: &[&str] = &["*.npz", "*.npy", "config.yaml", "*.json", "*.txt"];
            (globs, "npz")
        }
        Preset::Pth => {
            let globs: &[&str] = &["pytorch_model*.bin", "*.json", "*.txt"];
            (globs, "pth")
        }
        Preset::ConfigOnly => (&["*.json", "*.txt", "*.md"], "config-only"),
    };
    for filter in filters {
        // BORROW: explicit .as_str() instead of Deref coercion
        if preset_globs.contains(&filter.as_str()) {
            eprintln!("warning: --filter \"{filter}\" is redundant with --preset {preset_name}");
        }
    }
}

/// Recursively sums the sizes of all files under `dir`.
///
/// Returns `0` if the directory cannot be read.
fn walk_dir_size(dir: &Path) -> u64 {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return 0;
    };
    let mut total: u64 = 0;
    for entry in entries.flatten() {
        let Ok(meta) = entry.metadata() else {
            continue;
        };
        if meta.is_dir() {
            total = total.saturating_add(walk_dir_size(&entry.path()));
        } else {
            total = total.saturating_add(meta.len());
        }
    }
    total
}

/// Prints a download summary line showing total size, elapsed time, and throughput.
fn print_download_summary(path: &Path, elapsed: Duration) {
    let total_bytes = if path.is_dir() {
        walk_dir_size(path)
    } else {
        std::fs::metadata(path).map_or(0, |m| m.len())
    };
    let elapsed_secs = elapsed.as_secs_f64();
    if total_bytes > 0 && elapsed_secs > 0.0 {
        // CAST: u64 → f64, precision loss acceptable; display-only throughput
        #[allow(clippy::cast_precision_loss, clippy::as_conversions)]
        let throughput = total_bytes as f64 / elapsed_secs / (1024.0 * 1024.0);
        println!(
            "  {} in {:.1}s ({:.1} MiB/s)",
            format_size(total_bytes),
            elapsed_secs,
            throughput
        );
    }
}

/// Formats a download count with thousand separators (e.g., `1,234,567`).
fn format_downloads(n: u64) -> String {
    // BORROW: explicit .to_string() for u64 → String
    let s = n.to_string();
    let mut result = String::with_capacity(s.len() + s.len() / 3);
    for (i, ch) in s.chars().enumerate() {
        if i > 0 && (s.len() - i).is_multiple_of(3) {
            result.push(',');
        }
        result.push(ch);
    }
    result
}