rs-rich-cli 0.0.7

The `rich` executable: a Rust port of Python `rich-cli` 1.8.1
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
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
//! `rich` — a Rust port of the `rich-cli` terminal toolbox.
//!
//! This binary mirrors the upstream `rich-cli` command-line tool and is built on
//! the [`rich`] library crate. It implements the rendering modes `--print`,
//! `--markdown`, `--json`, `--syntax`, `--csv`, `--ipynb`, and `--rule`, plus
//! width/justify, HTML/SVG export to a file (`--export-html PATH` / `-o PATH`,
//! `--export-svg PATH`, which may be combined), the
//! `--panel`/`--padding` decorators (with `--title`/`--caption`/`--style`), a
//! plain-file printer (with extension auto-detection), **URL fetch** (`rich <url>`,
//! behind the default `fetch` feature), **paging** (`--pager`), and a capability
//! demo — i.e. the whole common rich-cli surface.

use std::io::{BufRead, IsTerminal, Read, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use rich::cells::cell_len;
use rich::markdown::Markdown;
use rich::measure::Measurement;
use rich::protocol::{LineRenderable, OwnedTableRows};
use rich::r#box::{Box as BoxSet, ASCII, ASCII2, DOUBLE, HEAVY, HEAVY_HEAD, ROUNDED, SQUARE};
use rich::text::Text;
use rich::{
    filesize, Align, AnsiDecoder, Bar, ColorSystem, Columns, Console, ConsoleOptions, Constrain,
    Control, Highlighter, HorizontalAlign, ISO8601Highlighter, Json, Justify, Layout, Live,
    LiveRender, LogLevel, LogRender, Padding, Panel, Pretty, Progress, ProgressBar, ProgressColumn,
    Renderable, Rule, Segment, Spinner, Status, Style, Styled, Syntax, Table, Traceback, Tree,
    DEFAULT_TERMINAL_THEME,
};
use rich_ext::cli::CliExtensions;
use rich_ext::encoding::{has_utf16_bom, Encoding};
use rich_ext::sanitize_terminal_controls;
use rich_ext::ConsoleExt;

/// Boxed `Text` helper to cut down on `Box::new(Text::new(...))` noise.
fn text(content: &str) -> Box<dyn Renderable> {
    Box::new(Text::new(content))
}

const VERSION: &str = env!("CARGO_PKG_VERSION");

/// How to render the resource. Mirrors the mutually-exclusive rich-cli flags.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Mode {
    /// No explicit flag: auto-detect by file extension, else print plain.
    Auto,
    /// `-p/--print`: interpret the resource as console markup.
    Print,
    /// `-m/--markdown`: render the resource as Markdown.
    Markdown,
    /// `-j/--json`: pretty-print the resource as JSON.
    Json,
    /// `-x/--syntax`: syntax-highlight the resource (language from extension).
    Syntax,
    /// `--csv`: render a CSV/TSV resource as a table.
    Csv,
    /// `.ipynb`: render a Jupyter notebook (markdown + code cells + outputs).
    Ipynb,
    /// `--gif`: animate one or more GIFs in place.
    Gif,
    /// `--diff`: perceptually compare two images (takes exactly two resources).
    Diff,
    /// `--image`: render a single still image as ASCII art, half-blocks, or Sixel.
    Image,
    /// `--rule`: draw a horizontal rule (the resource, if any, is its title).
    Rule,
    /// `--jsonl`: stream JSON Lines / NDJSON records.
    JsonLines,
    /// `--log`: stream common structured-log JSONL records.
    Log,
}

impl Mode {
    fn streams_records(self) -> bool {
        matches!(self, Self::JsonLines | Self::Log)
    }

    fn draws_directly(self) -> bool {
        matches!(self, Self::Gif | Self::Diff | Self::Image) || self.streams_records()
    }

    fn allows_extensions(self) -> bool {
        !matches!(self, Self::Gif | Self::Diff | Self::Image | Self::Rule)
            && !self.streams_records()
    }

    fn accepts_multiple_resources(self) -> bool {
        matches!(self, Self::Gif | Self::Diff)
    }
}

struct ModeSpec {
    mode: Mode,
    primary: &'static str,
    aliases: &'static [&'static str],
}

const MODE_SPECS: &[ModeSpec] = &[
    ModeSpec {
        mode: Mode::Auto,
        primary: "auto",
        aliases: &[],
    },
    ModeSpec {
        mode: Mode::Print,
        primary: "print",
        aliases: &["print"],
    },
    ModeSpec {
        mode: Mode::Markdown,
        primary: "markdown",
        aliases: &["markdown", "md"],
    },
    ModeSpec {
        mode: Mode::Json,
        primary: "json",
        aliases: &["json"],
    },
    ModeSpec {
        mode: Mode::Syntax,
        primary: "syntax",
        aliases: &["syntax", "code"],
    },
    ModeSpec {
        mode: Mode::Csv,
        primary: "csv",
        aliases: &["csv", "tsv"],
    },
    ModeSpec {
        mode: Mode::Ipynb,
        primary: "ipynb",
        aliases: &["ipynb", "notebook"],
    },
    ModeSpec {
        mode: Mode::Gif,
        primary: "gif",
        aliases: &["gif"],
    },
    ModeSpec {
        mode: Mode::Diff,
        primary: "diff",
        aliases: &["diff"],
    },
    ModeSpec {
        mode: Mode::Image,
        primary: "image",
        aliases: &["image"],
    },
    ModeSpec {
        mode: Mode::Rule,
        primary: "rule",
        aliases: &["rule"],
    },
    ModeSpec {
        mode: Mode::JsonLines,
        primary: "jsonl",
        aliases: &["jsonl", "ndjson"],
    },
    ModeSpec {
        mode: Mode::Log,
        primary: "log",
        aliases: &["log", "logs"],
    },
];

const RENDER_MODE_FLAGS: &str =
    "--print/--markdown/--json/--syntax/--csv/--ipynb/--rule/--gif/--diff/--image/--jsonl/--log";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ReportFormat {
    Human,
    Json,
}

impl ReportFormat {
    fn apply_option(&mut self, option: &str, value: Option<&str>) -> Result<(), String> {
        match option {
            "--report" => {
                *self = match value.ok_or("--report requires one of: human, json")? {
                    "human" => Self::Human,
                    "json" => Self::Json,
                    other => return Err(format!("unknown report format {other:?} (human, json)")),
                };
            }
            "--machine-json" => *self = Self::Json,
            _ => {}
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ExitClass {
    Success,
    Usage,
    Input,
    Data,
    #[cfg_attr(not(feature = "art"), allow(dead_code))]
    Gate,
}

impl ExitClass {
    fn code(self) -> u8 {
        match self {
            Self::Success => 0,
            Self::Usage => 2,
            Self::Input => 3,
            Self::Data => 4,
            Self::Gate => 5,
        }
    }

    fn name(self) -> &'static str {
        match self {
            Self::Success => "success",
            Self::Usage => "usage",
            Self::Input => "input",
            Self::Data => "data",
            Self::Gate => "gate",
        }
    }

    fn exit_code(self) -> ExitCode {
        ExitCode::from(self.code())
    }
}

/// How `--diff` draws the image part of its report.
///
/// Detection of terminal graphics support is a heuristic and will be wrong
/// somewhere (there is no reliable probe that works when output is piped), so
/// this is exposed rather than inferred: when the guess is wrong the user
/// picks.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum ImageMode {
    /// Sixel where it looks supported, else half-blocks, else ASCII.
    Auto,
    /// Real pixels via the Sixel graphics protocol.
    Sixel,
    /// Half-block characters — works in any truecolour terminal.
    Blocks,
    /// Unicode Braille cells.
    Braille,
    /// A character ramp, the jp2a-style rendering. No colour required.
    Ascii,
    /// Skip the picture; print only the numbers.
    None,
}

impl std::str::FromStr for ImageMode {
    type Err = String;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value.to_ascii_lowercase().as_str() {
            "auto" => Ok(Self::Auto),
            "sixel" => Ok(Self::Sixel),
            "blocks" | "block" | "half-block" | "half-blocks" => Ok(Self::Blocks),
            "braille" => Ok(Self::Braille),
            "ascii" | "art" => Ok(Self::Ascii),
            "none" | "off" => Ok(Self::None),
            other => Err(format!(
                "unknown image mode {other:?} (auto, sixel, blocks, ascii, none)"
            )),
        }
    }
}

/// Parsed command line.
#[derive(Clone)]
struct Cli {
    mode: Mode,
    resource: Option<String>,
    /// Every positional argument. Only `--gif` accepts more than one (so
    /// several animations can share the screen); other modes reject extras.
    /// Read only by the GIF player, hence unused without the `art` feature.
    #[cfg_attr(not(feature = "art"), allow(dead_code))]
    resources: Vec<String>,
    /// `--loop N`: how many times `--gif` repeats (0 = forever).
    #[cfg_attr(not(feature = "art"), allow(dead_code))]
    loops: Option<usize>,
    /// `--threshold PCT`: with `--diff`, exit non-zero when the changed
    /// percentage of the canvas exceeds this. Makes the tool a CI gate.
    #[cfg_attr(not(feature = "art"), allow(dead_code))]
    diff_threshold: Option<f32>,
    /// `--image-mode`: how `--diff`/`--image` draws its picture.
    #[cfg_attr(not(feature = "art"), allow(dead_code))]
    image_mode: ImageMode,
    #[cfg_attr(not(feature = "art"), allow(dead_code))]
    image_fit: Option<String>,
    #[cfg_attr(not(feature = "art"), allow(dead_code))]
    image_background: Option<[u8; 3]>,
    /// `--height N`: with `--image`, render this many rows instead of the
    /// backend's default.
    #[cfg_attr(not(feature = "art"), allow(dead_code))]
    height: Option<usize>,
    extensions: CliExtensions,
    width: Option<usize>,
    justify: Option<Justify>,
    no_color: bool,
    /// `--export-html PATH` (`-o PATH`): also write a self-contained HTML
    /// document to PATH. The resource is still rendered to the terminal.
    export_html: Option<String>,
    /// `--export-svg PATH`: also write a self-contained SVG document to PATH.
    export_svg: Option<String>,
    /// `--panel BOX`: wrap the output in a [`Panel`] with the named box.
    /// `--panel none` is upstream's default and means *no panel at all*, so it
    /// parses to `None` rather than to `box.NONE`.
    panel: Option<BoxSet>,
    /// `--padding T[,R[,B,L]]`: wrap the output in [`Padding`].
    padding: Option<(usize, usize, usize, usize)>,
    /// `--title`: the panel title, and the CSV table's title.
    title: Option<String>,
    /// `--caption`: the panel subtitle, and the CSV table's caption.
    caption: Option<String>,
    /// `-S/--panel-style`: the panel *border* style.
    panel_style: Option<Style>,
    /// `-s/--style`: a style laid under the whole renderable (upstream's
    /// `Styled`), applied outside the panel.
    style: Option<Style>,
    /// `-e/--expand`: make `--panel`/`--padding` fill the available width
    /// instead of shrinking to their content. Implied by `--width`.
    expand: bool,
    /// `--pager`: page the output through the system pager.
    pager: bool,
    /// `-y/--hyperlinks`: render a Markdown link as an OSC 8 hyperlink.
    /// Upstream's flag, and upstream's default of **false** — see
    /// [`build_markdown`], which is where it is consumed.
    hyperlinks: bool,
    /// `--sanitize`: visibly neutralize terminal controls from input and labels.
    sanitize: bool,
    /// `--report json`: emit a stable result/error envelope to stderr while
    /// leaving stdout for rendered content.
    report_format: ReportFormat,
    /// Re-render a changing local file or URL while stdout is a terminal.
    watch: bool,
    /// Polling interval for `--watch`, in seconds.
    watch_interval: f64,
    /// Avoid emitting unchanged URL responses.
    watch_cache: bool,
    batch: bool,
    continue_on_error: bool,
    jobs: usize,
    overwrite: bool,
    collision: CollisionPolicy,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CollisionPolicy {
    Error,
    Overwrite,
    Suffix,
}

/// Build the `-m/--markdown` renderable, honouring `-y/--hyperlinks`.
///
/// Upstream is `Markdown(markdown_data, code_theme=theme, hyperlinks=hyperlinks)`
/// with `@click.option("--hyperlinks", "-y", is_flag=True)`, so the default is
/// **false**: `rich -m` renders `[text](url)` as `text (url)`, with the URL
/// visible, and only `-y` turns it into an OSC 8 hyperlink whose target the
/// reader cannot see.
///
/// Without this, `rich -m` emitted the OSC 8 rendering unconditionally and the
/// destination appeared nowhere in the byte stream — so every URL in a document
/// was unrecoverable as soon as the output was piped or `NO_COLOR` was set.
fn build_markdown(source: &str, hyperlinks: bool) -> Markdown {
    Markdown::new(source).hyperlinks(hyperlinks)
}

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    match parse(&args) {
        Ok(None) => ExitCode::SUCCESS, // help/version already printed
        Ok(Some(cli)) => run(cli),
        Err(message) => emit_error(
            wants_json_report(&args),
            ExitClass::Usage,
            &format!("{message} (try --help)"),
        ),
    }
}

#[derive(Debug, Clone)]
struct ConfigRoots {
    home: Option<PathBuf>,
    cwd: PathBuf,
}

impl Default for ConfigRoots {
    fn default() -> Self {
        Self {
            home: std::env::var_os("HOME")
                .or_else(|| std::env::var_os("USERPROFILE"))
                .map(PathBuf::from),
            cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
        }
    }
}

/// Options that consume the following argument as their value. Needed to tell a
/// positional subcommand from an option's value when scanning raw arguments.
const VALUE_OPTIONS: &[&str] = &[
    "-w",
    "--width",
    "-o",
    "--export-html",
    "--export-svg",
    "--panel",
    "--padding",
    "--title",
    "--caption",
    "-s",
    "--style",
    "-S",
    "--panel-style",
    "--report",
    "--image-mode",
    "--image-fit",
    "--image-background",
    "--height",
    "--watch-interval",
    "--gif-mode",
    "--encoding",
    "--threshold",
    "--loop",
    "--jobs",
    "--collision",
    "--config",
    "--profile",
];

/// Whether the command line already picks a render mode, by flag *or* by the
/// positional subcommand form. Config must not inject a `mode` default over
/// `rich json file.json`, which selects JSON without ever naming `--json`.
fn selects_mode_explicitly(args: &[String]) -> bool {
    let mut iter = args.iter();
    let mut seen_positional = false;
    while let Some(arg) = iter.next() {
        if arg == "--" {
            break;
        }
        if VALUE_OPTIONS.contains(&arg.as_str()) {
            iter.next();
            continue;
        }
        if arg.starts_with('-') && arg.len() > 1 {
            if mode_flag_alias(arg).is_some() {
                return true;
            }
            continue;
        }
        if !seen_positional {
            seen_positional = true;
            if command_mode(arg).is_some() {
                return true;
            }
        }
    }
    false
}

/// The canonical long flag for a render-mode option, or `None` for anything else.
fn mode_flag_alias(arg: &str) -> Option<&'static str> {
    Some(match arg {
        "--print" | "-p" => "--print",
        "--markdown" | "-m" => "--markdown",
        "--json" | "-j" => "--json",
        "--syntax" | "-x" => "--syntax",
        "--csv" => "--csv",
        "--ipynb" => "--ipynb",
        "--jsonl" | "--ndjson" => "--jsonl",
        "--log" => "--log",
        "--rule" => "--rule",
        _ => return None,
    })
}

/// Drop a trailing `#` comment, ignoring a `#` that sits inside a quoted string.
///
/// Splitting on the first `#` unconditionally silently truncates a legitimate
/// value: `export_html = "report#ci.html"` became `report`, so the export
/// landed on a path the user never wrote.
fn strip_config_comment(line: &str) -> &str {
    let mut quote: Option<u8> = None;
    for (index, byte) in line.bytes().enumerate() {
        match quote {
            Some(open) if byte == open => quote = None,
            Some(_) => {}
            None => match byte {
                b'"' | b'\'' => quote = Some(byte),
                b'#' => return &line[..index],
                _ => {}
            },
        }
    }
    line
}

/// Unquote a config scalar, preserving everything the quotes were protecting.
fn config_value(raw: &str) -> &str {
    let trimmed = raw.trim();
    let bytes = trimmed.as_bytes();
    if bytes.len() >= 2 {
        let first = bytes[0];
        if (first == b'"' || first == b'\'') && bytes[bytes.len() - 1] == first {
            return &trimmed[1..trimmed.len() - 1];
        }
    }
    trimmed
}

fn config_args(args: &[String], roots: &ConfigRoots) -> Result<Vec<String>, String> {
    if args.iter().any(|a| a == "--no-config") {
        let mut result = Vec::new();
        let mut skip = false;
        for arg in args {
            if skip {
                skip = false;
                continue;
            }
            if arg == "--config" || arg == "--profile" {
                skip = true;
                continue;
            }
            if arg != "--no-config" {
                result.push(arg.clone());
            }
        }
        return Ok(result);
    }
    for flag in ["--config", "--profile"] {
        if args
            .iter()
            .position(|a| a == flag)
            .is_some_and(|i| i + 1 >= args.len())
        {
            return Err(format!("{flag} requires a value"));
        }
    }
    let explicit = args
        .windows(2)
        .find(|w| w[0] == "--config")
        .map(|w| PathBuf::from(&w[1]));
    let profile = args
        .windows(2)
        .find(|w| w[0] == "--profile")
        .map(|w| w[1].clone())
        .unwrap_or_else(|| "default".into());
    let path = explicit.or_else(|| {
        let candidates = [
            roots.cwd.join("rich.toml"),
            roots
                .home
                .as_ref()
                .map(|h| h.join(".config/rich/config.toml"))
                .unwrap_or_default(),
        ];
        candidates.into_iter().find(|p| p.is_file())
    });
    let mut result = Vec::new();
    let explicit_mode = selects_mode_explicitly(args);
    let explicit_flags: std::collections::HashSet<&str> = args
        .iter()
        .filter_map(|arg| {
            mode_flag_alias(arg).or(match arg.as_str() {
                "--width" | "-w" => Some("--width"),
                "--pager" => Some("--pager"),
                "--no-color" => Some("--no-color"),
                "--export-html" | "-o" => Some("--export-html"),
                "--export-svg" => Some("--export-svg"),
                "--batch" => Some("--batch"),
                "--continue-on-error" => Some("--continue-on-error"),
                "--overwrite" => Some("--overwrite"),
                "--jobs" => Some("--jobs"),
                "--collision" => Some("--collision"),
                "--panel" => Some("--panel"),
                "--padding" => Some("--padding"),
                _ => None,
            })
        })
        .collect();
    if let Some(path) = path {
        let text = std::fs::read_to_string(&path)
            .map_err(|e| format!("config {}: {e}", path.display()))?;
        let mut section = String::new();
        for (line_no, raw) in text.lines().enumerate() {
            let line = strip_config_comment(raw).trim();
            if line.is_empty() {
                continue;
            }
            if line.starts_with('[') && line.ends_with(']') {
                section = line[1..line.len() - 1].trim().to_string();
                continue;
            }
            if section != "defaults"
                && section != format!("profile.{profile}")
                && section != format!("profiles.{profile}")
            {
                continue;
            }
            let Some((key, value)) = line.split_once('=') else {
                return Err(format!(
                    "config {}:{}: expected key = value",
                    path.display(),
                    line_no + 1
                ));
            };
            let key = key.trim();
            let value = config_value(value);
            let flag = match key {
                "mode" => match value {
                    "print" => "--print",
                    "markdown" => "--markdown",
                    "json" => "--json",
                    "syntax" => "--syntax",
                    "csv" => "--csv",
                    "ipynb" => "--ipynb",
                    "jsonl" => "--jsonl",
                    "log" => "--log",
                    "rule" => "--rule",
                    _ => {
                        return Err(format!(
                            "config {}:{}: unknown mode",
                            path.display(),
                            line_no + 1
                        ))
                    }
                },
                "width" => "--width",
                "pager" => "--pager",
                "no_color" => "--no-color",
                "export_html" => "--export-html",
                "export_svg" => "--export-svg",
                "batch" => "--batch",
                "continue_on_error" => "--continue-on-error",
                "overwrite" => "--overwrite",
                "jobs" => "--jobs",
                "collision" => "--collision",
                "panel" => "--panel",
                "padding" => "--padding",
                "profile" | "config" | "no_config" => continue,
                _ => {
                    return Err(format!(
                        "config {}:{}: unknown key {key:?}",
                        path.display(),
                        line_no + 1
                    ))
                }
            };
            if explicit_flags.contains(flag) || (key == "mode" && explicit_mode) {
                continue;
            }
            if matches!(
                flag,
                "--pager" | "--no-color" | "--batch" | "--continue-on-error" | "--overwrite"
            ) {
                if value != "true" {
                    continue;
                }
                result.push(flag.into());
            } else {
                result.push(flag.into());
                result.push(value.into());
            }
        }
    }
    let mut skip = false;
    for arg in args {
        if skip {
            skip = false;
            continue;
        }
        if arg == "--config" || arg == "--profile" {
            skip = true;
            continue;
        }
        result.push(arg.clone());
    }
    Ok(result)
}

/// A batch child's diagnostics, captured rather than printed.
///
/// Two things depend on this. `--report json` documents exactly one envelope on
/// stderr, so a child that printed its own `rich: …` line would put unparseable
/// text in front of the aggregate object. And the child's [`ExitClass`] is the
/// only place the real failure class survives — without it every batch failure
/// collapses to one hard-coded code and the stable exit contract is lost.
#[derive(Default)]
struct ChildOutcome {
    capturing: bool,
    class: Option<ExitClass>,
    message: Option<String>,
}

thread_local! {
    static CHILD_OUTCOME: std::cell::RefCell<ChildOutcome> =
        std::cell::RefCell::new(ChildOutcome::default());
}

fn emit_error(json: bool, class: ExitClass, message: &str) -> ExitCode {
    let captured = CHILD_OUTCOME.with(|cell| {
        let mut outcome = cell.borrow_mut();
        if outcome.capturing && outcome.class.is_none() {
            outcome.class = Some(class);
            outcome.message = Some(message.to_string());
        }
        outcome.capturing
    });
    if captured {
        return class.exit_code();
    }
    if json {
        eprintln!(
            "{}",
            serde_json::json!({
                "ok": false,
                "code": class.name(),
                "exit_code": class.code(),
                "message": message,
                "error": {
                    "message": message,
                },
            })
        );
    } else {
        eprintln!("rich: {message}");
    }
    class.exit_code()
}

fn emit_success_report(format: ReportFormat) {
    if CHILD_OUTCOME.with(|cell| cell.borrow().capturing) {
        return;
    }
    if format == ReportFormat::Json {
        eprintln!(
            "{}",
            serde_json::json!({
                "ok": true,
                "code": ExitClass::Success.name(),
                "exit_code": ExitClass::Success.code(),
                "result": {},
            })
        );
    }
}

fn fail(cli: &Cli, class: ExitClass, message: impl AsRef<str>) -> ExitCode {
    emit_error(
        cli.report_format == ReportFormat::Json,
        class,
        message.as_ref(),
    )
}

fn success(cli: &Cli) -> ExitCode {
    emit_success_report(cli.report_format);
    ExitClass::Success.exit_code()
}

/// Match `text` against a simple glob supporting `*` (any run of characters)
/// and `?` (exactly one). Both apply within a single path segment.
///
/// Substring containment is not a glob: `*.md` used that way also matched
/// `notes.md.bak`, and a `?` pattern matched nothing at all because the literal
/// `?` was still being searched for.
fn glob_match(pattern: &str, text: &str) -> bool {
    let pattern: Vec<char> = pattern.chars().collect();
    let text: Vec<char> = text.chars().collect();
    let (mut p, mut t) = (0usize, 0usize);
    let (mut star, mut retry) = (None, 0usize);
    while t < text.len() {
        if p < pattern.len() && (pattern[p] == '?' || pattern[p] == text[t]) {
            p += 1;
            t += 1;
        } else if p < pattern.len() && pattern[p] == '*' {
            star = Some(p);
            retry = t;
            p += 1;
        } else if let Some(open) = star {
            p = open + 1;
            retry += 1;
            t = retry;
        } else {
            return false;
        }
    }
    while p < pattern.len() && pattern[p] == '*' {
        p += 1;
    }
    p == pattern.len()
}

fn has_glob_meta(value: &str) -> bool {
    value.contains('*') || value.contains('?')
}

/// Split `dir/sub/*.md` into its literal directory and its name pattern.
fn split_glob(resource: &str) -> (PathBuf, String) {
    let meta = resource.find(['*', '?']).unwrap_or(0);
    match resource[..meta].rfind(['/', '\\']) {
        Some(cut) => (
            PathBuf::from(&resource[..cut]),
            resource[cut + 1..].to_string(),
        ),
        None => (PathBuf::from("."), resource.to_string()),
    }
}

/// Collect every file under `dir`, skipping symlinks.
///
/// `Path::is_dir` follows links, so a directory containing a link to itself or
/// to an ancestor pushed that directory back onto the stack forever, building
/// ever longer paths until the process ran out of memory. Not following links
/// at all keeps the walk finite without having to track device/inode identity,
/// which is not portable.
fn collect_files(dir: &Path, out: &mut Vec<String>) -> Result<(), String> {
    let mut stack = vec![dir.to_path_buf()];
    while let Some(current) = stack.pop() {
        let entries = std::fs::read_dir(&current)
            .map_err(|error| format!("cannot scan {}: {error}", current.display()))?;
        for entry in entries {
            let entry = entry.map_err(|error| format!("cannot scan {}: {error}", dir.display()))?;
            let path = entry.path();
            let kind = std::fs::symlink_metadata(&path)
                .map_err(|error| format!("cannot read {}: {error}", path.display()))?
                .file_type();
            if kind.is_symlink() {
                continue;
            }
            if kind.is_dir() {
                stack.push(path);
            } else if kind.is_file() {
                out.push(path.to_string_lossy().into_owned());
            }
        }
    }
    Ok(())
}

fn expand_batch_resources(resources: &[String]) -> Result<Vec<String>, String> {
    let mut out = Vec::new();
    for resource in resources {
        if resource == "-" || is_url(resource) {
            return Err("batch resources must be local files or directories".into());
        }
        if has_glob_meta(resource) {
            let (dir, pattern) = split_glob(resource);
            if pattern.contains('/') || pattern.contains('\\') {
                return Err(format!(
                    "batch glob {resource:?} may only use * and ? in the final path segment"
                ));
            }
            let entries = std::fs::read_dir(&dir)
                .map_err(|error| format!("cannot scan {}: {error}", dir.display()))?;
            for entry in entries {
                let entry =
                    entry.map_err(|error| format!("cannot scan {}: {error}", dir.display()))?;
                let path = entry.path();
                if !path.is_file() {
                    continue;
                }
                if glob_match(&pattern, &entry.file_name().to_string_lossy()) {
                    out.push(path.to_string_lossy().into_owned());
                }
            }
            continue;
        }
        let path = Path::new(resource);
        if path.is_file() {
            out.push(resource.clone());
        } else if path.is_dir() {
            collect_files(path, &mut out)?;
        } else {
            return Err(format!("batch resource does not exist: {resource}"));
        }
    }
    out.sort();
    out.dedup();
    if out.is_empty() {
        return Err("batch plan contains no files".into());
    }
    Ok(out)
}

/// Where one batch item's exports are written.
///
/// The kind of each export is carried explicitly. Recovering it by sniffing the
/// path extension silently dropped exports whose name did not end in `.html` or
/// `.svg`, so `--export-html result.out` planned a path and then wrote nothing.
#[derive(Default, Clone)]
struct BatchOutputs {
    html: Option<String>,
    svg: Option<String>,
}

fn batch_export_path(
    path: Option<&str>,
    input: &str,
    index: usize,
    total: usize,
) -> Option<String> {
    let path = path?;
    let p = Path::new(path);
    if total == 1 {
        return Some(path.into());
    }
    let ext = p.extension().and_then(|e| e.to_str()).unwrap_or_default();
    let stem = Path::new(input)
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("output");
    let name = if ext.is_empty() {
        format!("{stem}-{index}")
    } else {
        format!("{stem}.{ext}")
    };
    Some(if p.is_dir() {
        p.join(name).to_string_lossy().into_owned()
    } else {
        p.with_file_name(name).to_string_lossy().into_owned()
    })
}

/// `out.html` -> `out-2.html`, keeping an extension-less name intact.
fn suffixed_path(path: &Path, suffix: usize) -> String {
    let stem = path
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("output");
    let name = match path.extension().and_then(|s| s.to_str()) {
        Some(ext) => format!("{stem}-{suffix}.{ext}"),
        None => format!("{stem}-{suffix}"),
    };
    path.with_file_name(name).to_string_lossy().into_owned()
}

/// Settle one planned output against the rest of the plan and against the disk.
///
/// `suffix` has to consider existing files too, not just in-plan duplicates:
/// a policy whose whole purpose is to avoid clobbering must not quietly
/// overwrite a file that was already there.
fn resolve_destination(
    cli: &Cli,
    candidate: String,
    taken: &mut std::collections::BTreeSet<String>,
) -> Result<String, (ExitClass, String)> {
    let occupied = |path: &str, taken: &std::collections::BTreeSet<String>| {
        taken.contains(path) || (!cli.overwrite && Path::new(path).exists())
    };
    match cli.collision {
        CollisionPolicy::Overwrite => {
            taken.insert(candidate.clone());
            Ok(candidate)
        }
        CollisionPolicy::Suffix => {
            let mut chosen = candidate.clone();
            let mut suffix = 2;
            while occupied(&chosen, taken) {
                chosen = suffixed_path(Path::new(&candidate), suffix);
                suffix += 1;
            }
            taken.insert(chosen.clone());
            Ok(chosen)
        }
        CollisionPolicy::Error => {
            if taken.contains(&candidate) {
                return Err((
                    ExitClass::Usage,
                    format!("batch output collision: {candidate}"),
                ));
            }
            if !cli.overwrite && Path::new(&candidate).exists() {
                return Err((
                    ExitClass::Input,
                    format!("refusing to overwrite existing output: {candidate} (use --overwrite)"),
                ));
            }
            taken.insert(candidate.clone());
            Ok(candidate)
        }
    }
}

/// Run one batch item with its diagnostics captured, yielding its failure class.
fn run_captured(item: Cli) -> Option<(ExitClass, Option<String>)> {
    CHILD_OUTCOME.with(|cell| {
        *cell.borrow_mut() = ChildOutcome {
            capturing: true,
            ..ChildOutcome::default()
        }
    });
    let status = run(item);
    let outcome = CHILD_OUTCOME.with(|cell| std::mem::take(&mut *cell.borrow_mut()));
    if status == ExitCode::SUCCESS {
        return None;
    }
    Some((
        outcome.class.unwrap_or(ExitClass::Input),
        outcome.message.clone(),
    ))
}

fn run_batch(cli: &Cli) -> ExitCode {
    let resources = match expand_batch_resources(&cli.resources) {
        Ok(v) => v,
        Err(e) => return fail(cli, ExitClass::Input, e),
    };
    let mut taken = std::collections::BTreeSet::new();
    let mut planned_outputs = Vec::with_capacity(resources.len());
    for (index, input) in resources.iter().enumerate() {
        let mut outputs = BatchOutputs::default();
        for (candidate, slot) in [
            (
                batch_export_path(cli.export_html.as_deref(), input, index, resources.len()),
                &mut outputs.html,
            ),
            (
                batch_export_path(cli.export_svg.as_deref(), input, index, resources.len()),
                &mut outputs.svg,
            ),
        ] {
            let Some(candidate) = candidate else { continue };
            match resolve_destination(cli, candidate, &mut taken) {
                Ok(path) => *slot = Some(path),
                Err((class, message)) => return fail(cli, class, message),
            }
        }
        planned_outputs.push(outputs);
    }

    let mut failures: Vec<(String, ExitClass, Option<String>)> = Vec::new();
    let mut attempted = 0usize;
    // Work is deliberately serialized for deterministic output and bounded
    // memory; `jobs` is a validated upper bound reserved for future parallel
    // workers without changing the planning contract.
    let _concurrency_limit = cli.jobs;
    for (index, input) in resources.iter().enumerate() {
        let mut one = cli.clone();
        one.batch = false;
        one.resources = vec![input.clone()];
        one.resource = Some(input.clone());
        one.report_format = ReportFormat::Human;
        one.export_html = planned_outputs[index].html.clone();
        one.export_svg = planned_outputs[index].svg.clone();
        attempted += 1;
        if let Some((class, message)) = run_captured(one) {
            if cli.report_format != ReportFormat::Json {
                match &message {
                    Some(message) => eprintln!("rich: {input}: {message}"),
                    None => eprintln!("rich: {input}: failed ({})", class.name()),
                }
            }
            failures.push((input.clone(), class, message));
            if !cli.continue_on_error {
                break;
            }
        }
    }

    // The aggregate takes the most severe child class so a data error (4) or a
    // gate (5) is not flattened into a generic input failure.
    let class = failures
        .iter()
        .map(|(_, class, _)| *class)
        .max_by_key(|class| class.code())
        .unwrap_or(ExitClass::Success);
    if cli.report_format == ReportFormat::Json {
        eprintln!(
            "{}",
            serde_json::json!({
                "ok": failures.is_empty(),
                "code": class.name(),
                "exit_code": class.code(),
                "result": {
                    "planned": resources.len(),
                    "attempted": attempted,
                    "completed": attempted - failures.len(),
                    "failed": failures.len(),
                    "skipped": resources.len() - attempted,
                    "failures": failures
                        .iter()
                        .map(|(resource, class, message)| serde_json::json!({
                            "resource": resource,
                            "code": class.name(),
                            "exit_code": class.code(),
                            "message": message,
                        }))
                        .collect::<Vec<_>>(),
                },
            })
        );
    }
    class.exit_code()
}

fn wants_json_report(args: &[String]) -> bool {
    let mut format = ReportFormat::Human;
    let mut iter = args.iter();
    while let Some(arg) = iter.next() {
        match arg.as_str() {
            "--report" => {
                if let Some(value) = iter.next() {
                    let _ = format.apply_option("--report", Some(value));
                }
            }
            "--machine-json" => {
                let _ = format.apply_option("--machine-json", None);
            }
            "--" => break,
            _ => {}
        }
    }
    format == ReportFormat::Json
}

/// Map a `--panel` box name to a box set (port of rich-cli's `BOXES` +
/// `getattr(box, name.upper())`).
///
/// `none` is upstream's *default* for `--panel`, and upstream guards the whole
/// panel step with `if panel != "none"` — so it means "no panel", not "a panel
/// drawn with `box.NONE`". Drawing box.NONE put an invisible one-cell frame and
/// a blank line around the output, which reads as the tool having mangled the
/// file for no reason.
fn parse_box(name: &str) -> Result<Option<BoxSet>, String> {
    Ok(Some(match name.to_ascii_lowercase().as_str() {
        "none" => return Ok(None),
        "ascii" => ASCII,
        "ascii2" => ASCII2,
        "square" => SQUARE,
        "rounded" => ROUNDED,
        "heavy" => HEAVY,
        "double" => DOUBLE,
        other => {
            return Err(format!(
                "unknown panel box {other:?} (use none/ascii/ascii2/square/rounded/heavy/double)"
            ))
        }
    }))
}

/// Parse a `--padding` value: 1, 2, or 4 comma-separated integers, unpacked into
/// `(top, right, bottom, left)`. Port of rich-cli's padding parsing + upstream's
/// `Padding.unpack`.
fn parse_padding(value: &str) -> Result<(usize, usize, usize, usize), String> {
    let error = || "padding should be 1, 2, or 4 integers separated by commas".to_string();
    let parts: Result<Vec<usize>, _> = value
        .split(',')
        .map(|p| p.trim().parse::<usize>())
        .collect();
    let parts = parts.map_err(|_| error())?;
    match parts.as_slice() {
        [p] => Ok((*p, *p, *p, *p)),
        [v, h] => Ok((*v, *h, *v, *h)),
        [t, r, b, l] => Ok((*t, *r, *b, *l)),
        _ => Err(error()),
    }
}

/// Set the render mode, rejecting a second, conflicting mode flag.
fn mode_name(mode: Mode) -> &'static str {
    MODE_SPECS
        .iter()
        .find_map(|spec| (spec.mode == mode).then_some(spec.primary))
        .unwrap_or("unknown")
}

fn command_mode(command: &str) -> Option<Mode> {
    MODE_SPECS
        .iter()
        .find_map(|spec| spec.aliases.contains(&command).then_some(spec.mode))
}

fn set_mode(current: &mut Mode, mode: Mode) -> Result<(), String> {
    if *current != Mode::Auto && *current != mode {
        return Err(format!(
            "only one render mode ({RENDER_MODE_FLAGS}) may be given"
        ));
    }
    *current = mode;
    Ok(())
}

/// Parse args into a [`Cli`], or `Ok(None)` when `--help`/`--version` handled it.
fn parse(args: &[String]) -> Result<Option<Cli>, String> {
    let merged = config_args(args, &ConfigRoots::default())?;
    parse_inner(&merged)
}

fn parse_inner(args: &[String]) -> Result<Option<Cli>, String> {
    let mut mode = Mode::Auto;
    let mut resources: Vec<String> = Vec::new();
    let mut loops = None;
    let mut diff_threshold = None;
    let mut image_mode = ImageMode::Auto;
    let mut image_fit = None;
    let mut image_background = None;
    let mut height = None;
    let mut extensions = CliExtensions::default();
    let mut width = None;
    let mut justify = None;
    let mut no_color = std::env::var_os("NO_COLOR").is_some_and(|value| !value.is_empty());
    let mut export_html: Option<String> = None;
    let mut export_svg: Option<String> = None;
    let mut panel = None;
    let mut padding = None;
    let mut title = None;
    let mut caption = None;
    let mut panel_style = None;
    let mut style = None;
    let mut expand = false;
    let mut pager = false;
    let mut hyperlinks = false;
    let mut sanitize = false;
    let mut report_format = ReportFormat::Human;
    let mut watch = false;
    let mut watch_interval = 1.0;
    let mut watch_cache = false;
    let mut batch = false;
    let mut continue_on_error = false;
    let mut jobs = 1usize;
    let mut overwrite = false;
    let mut collision = CollisionPolicy::Error;
    // Set by `--`: everything after it is a positional argument, however much it
    // looks like a flag. Without this nothing beginning with `-` could be
    // printed or opened at all — `rich -p -- "-5 degrees"` and `rich -- -weird.md`
    // both died with "unknown option".
    let mut end_of_options = false;

    let mut iter = args.iter();
    while let Some(arg) = iter.next() {
        if end_of_options {
            resources.push(arg.to_string());
            continue;
        }
        if extensions.parse_option(arg, &mut iter)? {
            continue;
        }
        match arg.as_str() {
            "--" => end_of_options = true,
            "-h" | "--help" => {
                print_help();
                return Ok(None);
            }
            "-V" | "--version" => {
                println!("rich (rs-rich-cli) {VERSION}");
                return Ok(None);
            }
            "-p" | "--print" => set_mode(&mut mode, Mode::Print)?,
            "-m" | "--markdown" => set_mode(&mut mode, Mode::Markdown)?,
            "-j" | "--json" => set_mode(&mut mode, Mode::Json)?,
            "-x" | "--syntax" => set_mode(&mut mode, Mode::Syntax)?,
            "--csv" => set_mode(&mut mode, Mode::Csv)?,
            "--ipynb" => set_mode(&mut mode, Mode::Ipynb)?,
            "--gif" => set_mode(&mut mode, Mode::Gif)?,
            "--diff" => set_mode(&mut mode, Mode::Diff)?,
            "--image" => set_mode(&mut mode, Mode::Image)?,
            "--jsonl" | "--ndjson" => set_mode(&mut mode, Mode::JsonLines)?,
            "--log" => set_mode(&mut mode, Mode::Log)?,
            "--report" => {
                let value = iter.next().map(String::as_str);
                report_format.apply_option("--report", value)?;
            }
            "--machine-json" => {
                report_format.apply_option("--machine-json", None)?;
            }
            "--image-mode" => {
                let value = iter.next().ok_or(
                    "--image-mode requires one of: auto, sixel, blocks, braille, ascii, none",
                )?;
                image_mode = value.parse()?;
            }
            "--image-fit" => {
                let value = iter.next().ok_or("--image-fit requires contain or cover")?;
                if !matches!(value.as_str(), "contain" | "cover") {
                    return Err("--image-fit requires contain or cover".into());
                }
                image_fit = Some(value.clone());
            }
            "--image-background" => {
                let value = iter.next().ok_or("--image-background requires #RRGGBB")?;
                let bytes = value.as_bytes();
                if bytes.len() != 7
                    || bytes[0] != b'#'
                    || !bytes[1..].iter().all(u8::is_ascii_hexdigit)
                {
                    return Err("--image-background requires #RRGGBB".into());
                }
                let mut rgb = [0; 3];
                for (index, channel) in rgb.iter_mut().enumerate() {
                    *channel = u8::from_str_radix(&value[1 + index * 2..3 + index * 2], 16)
                        .map_err(|_| "--image-background requires #RRGGBB")?;
                }
                image_background = Some(rgb);
            }
            "--height" => {
                let value = iter.next().ok_or("--height requires a number")?;
                let rows: usize = value
                    .parse()
                    .map_err(|_| format!("invalid height '{value}'"))?;
                if rows == 0 {
                    return Err("--height must be at least 1".into());
                }
                height = Some(rows);
            }
            "--threshold" => {
                let value = iter
                    .next()
                    .ok_or("--threshold requires a percentage, e.g. --threshold 2")?;
                let percent: f32 = value
                    .parse()
                    .map_err(|_| format!("invalid threshold '{value}'"))?;
                // `"NaN"` and `"inf"` both parse as f32, and every comparison
                // against NaN is false — so an empty template variable or a bad
                // substitution would turn the gate off and report a pass. A gate
                // that can be silently disabled is worse than no gate.
                if !percent.is_finite() || !(0.0..=100.0).contains(&percent) {
                    return Err(format!(
                        "threshold must be a percentage between 0 and 100, got '{value}'"
                    ));
                }
                diff_threshold = Some(percent);
            }
            "--loop" => {
                let value = iter.next().ok_or("--loop requires a count (0 = forever)")?;
                loops = Some(
                    value
                        .parse()
                        .map_err(|_| format!("invalid loop count {value:?}"))?,
                );
            }
            "--rule" => set_mode(&mut mode, Mode::Rule)?,
            "--left" => justify = Some(Justify::Left),
            "--right" if justify != Some(Justify::Left) => justify = Some(Justify::Right),
            "--right" => {}
            "--center" if justify.is_none() => justify = Some(Justify::Center),
            "--center" => {}
            "--no-color" => no_color = true,
            "--pager" => pager = true,
            "--watch" => watch = true,
            "--watch-cache" => watch_cache = true,
            "--watch-interval" | "--interval" => {
                let value = iter
                    .next()
                    .ok_or("--watch-interval requires seconds greater than zero")?;
                watch_interval = value
                    .parse::<f64>()
                    .map_err(|_| format!("invalid watch interval {value:?}"))?;
                if !watch_interval.is_finite() || watch_interval <= 0.0 {
                    return Err("--watch-interval must be greater than zero".into());
                }
            }
            "--batch" => batch = true,
            "--continue-on-error" => continue_on_error = true,
            "--overwrite" => {
                overwrite = true;
                collision = CollisionPolicy::Overwrite;
            }
            "--collision" => {
                collision = match iter
                    .next()
                    .ok_or("--collision requires error, overwrite, or suffix")?
                    .as_str()
                {
                    "error" => CollisionPolicy::Error,
                    "overwrite" => CollisionPolicy::Overwrite,
                    "suffix" => CollisionPolicy::Suffix,
                    other => return Err(format!("unknown collision policy {other:?}")),
                };
            }
            "--jobs" => {
                jobs = iter
                    .next()
                    .ok_or("--jobs requires a positive number")?
                    .parse()
                    .map_err(|_| "--jobs requires a positive number".to_string())?;
                if jobs == 0 {
                    return Err("--jobs must be at least 1".into());
                }
            }
            "--sanitize" => sanitize = true,
            // Upstream's `@click.option("--hyperlinks", "-y", is_flag=True,
            // help="Render hyperlinks in markdown.")`. Accepted in every mode,
            // as click accepts it — it is read only where markdown is rendered.
            "-y" | "--hyperlinks" => hyperlinks = true,
            // Both take a PATH and both may be given at once, matching
            // upstream: the resource still renders to the terminal and the
            // files are written alongside it.
            "--export-html" | "-o" => {
                export_html = Some(iter.next().ok_or("--export-html requires a PATH")?.clone());
            }
            "--export-svg" => {
                export_svg = Some(iter.next().ok_or("--export-svg requires a PATH")?.clone());
            }
            "--panel" => {
                let value = iter.next().ok_or("--panel requires a box name")?;
                panel = parse_box(value)?;
            }
            "--padding" => {
                let value = iter.next().ok_or("--padding requires a value")?;
                padding = Some(parse_padding(value)?);
            }
            "-e" | "--expand" => expand = true,
            "--title" => {
                title = Some(iter.next().ok_or("--title requires a value")?.clone());
            }
            "--caption" => {
                caption = Some(iter.next().ok_or("--caption requires a value")?.clone());
            }
            // `-s/--style` is the style of the *renderable* (upstream wraps it in
            // `Styled`); `-S/--panel-style` is the border. They were fused into
            // one flag that set the border, so there was no way to style the
            // content at all and `--style` aborted without `--panel`.
            "-s" | "--style" => {
                let value = iter.next().ok_or("--style requires a value")?;
                style = Some(Style::parse(value).map_err(|e| format!("invalid --style: {e}"))?);
            }
            "-S" | "--panel-style" => {
                let value = iter.next().ok_or("--panel-style requires a value")?;
                panel_style =
                    Some(Style::parse(value).map_err(|e| format!("invalid --panel-style: {e}"))?);
            }
            "-w" | "--width" => {
                let value = iter.next().ok_or("--width requires a number")?;
                let columns: usize = value.parse().map_err(|_| {
                    // The common cause is a missing value, in which case this
                    // has just eaten the filename — say so rather than quoting
                    // the path back with debug escaping.
                    if std::path::Path::new(value).exists() {
                        format!("--width needs a number, but got the file '{value}' — a value is missing")
                    } else {
                        format!("invalid width '{value}'")
                    }
                })?;
                if columns == 0 {
                    return Err("--width must be at least 1".into());
                }
                width = Some(columns);
            }
            other if other.starts_with('-') && other != "-" => {
                return Err(format!("unknown option {other:?}"));
            }
            other
                if mode == Mode::Auto && resources.is_empty() && command_mode(other).is_some() =>
            {
                set_mode(&mut mode, command_mode(other).expect("checked above"))?;
            }
            other => resources.push(other.to_string()),
        }
    }

    // `--gif`/`--diff` consume their whole resource list as one unit (a diff is
    // a pair), but a batch rewrites each item to a single resource — `run_diff`
    // would then index `resources[1]` and panic. Reject the combination.
    if batch {
        if mode.accepts_multiple_resources() {
            return Err(format!(
                "--batch cannot be combined with {}",
                if mode == Mode::Diff {
                    "--diff"
                } else {
                    "--gif"
                }
            ));
        }
        if resources.is_empty() {
            return Err("--batch needs at least one file, directory or glob".into());
        }
        // One pager per item would be N interactive pagers over one plan.
        if pager {
            return Err("--pager cannot be combined with --batch".into());
        }
    }

    // Only `--gif` animates several resources at once; every other mode renders
    // exactly one.
    if mode == Mode::Diff && resources.len() != 2 {
        return Err("--diff needs exactly two images: --diff before.png after.png".into());
    }
    if mode == Mode::Image {
        if resources.is_empty() {
            return Err(
                "--image requires an image file: rich --image photo.png (or `-` for stdin)".into(),
            );
        }
        if image_mode == ImageMode::None {
            return Err(
                "--image-mode none has no effect with --image; use auto, ascii, blocks, or sixel"
                    .into(),
            );
        }
    }
    if image_fit.is_some() && height.is_none() {
        return Err("--image-fit requires --height to define the target rectangle".into());
    }
    // `--gif` animates in place and the demo writes its own console, so neither
    // goes through the export path: both accepted -o/--export-svg, wrote no
    // file, and exited 0. Everywhere else a bad export path is a hard error, so
    // silence here reads as success.
    let effective_mode = if mode == Mode::Auto {
        detect_mode(resources.first().map(String::as_str))
    } else {
        mode
    };
    extensions.validate(
        effective_mode == Mode::Gif,
        effective_mode.allows_extensions()
            && !(mode == Mode::Auto && resources.is_empty())
            && !(mode == Mode::Print && resources.first().is_some_and(|r| r != "-" && !is_url(r))),
    )?;
    let exporting = export_html.is_some() || export_svg.is_some();
    if exporting {
        let unsupported = if effective_mode == Mode::Gif {
            Some("--gif")
        } else if effective_mode == Mode::Image {
            Some("--image")
        } else if mode == Mode::Auto && resources.is_empty() {
            Some("the capability demo")
        } else {
            None
        };
        if let Some(what) = unsupported {
            return Err(format!("--export-html/--export-svg cannot capture {what}"));
        }
    }

    // A flag whose mode is absent is almost always a mistake, and silence is the
    // dangerous response: `--threshold` without `--diff` used to render the file
    // and exit 0, so a CI job that lost its `--diff` — a typo, a refactor, an
    // argument reordered — became a permanently green gate. That is the same
    // failure the NaN check closed, reached from the other side.
    let orphans = [
        (
            "--threshold",
            diff_threshold.is_some(),
            "--diff",
            mode == Mode::Diff,
        ),
        (
            "--image-mode",
            image_mode != ImageMode::Auto,
            "--diff/--image",
            mode == Mode::Diff || mode == Mode::Image,
        ),
        ("--height", height.is_some(), "--image", mode == Mode::Image),
        (
            "--image-fit",
            image_fit.is_some(),
            "--image",
            mode == Mode::Image,
        ),
        (
            "--image-background",
            image_background.is_some(),
            "--image",
            mode == Mode::Image,
        ),
        (
            "--loop",
            loops.is_some(),
            "--gif",
            effective_mode == Mode::Gif,
        ),
        // `--title`/`--caption` are deliberately NOT here: upstream feeds them to
        // the CSV table as well as to the panel, so requiring `--panel` made
        // `rich --csv sales.csv --title Sales` — a documented upstream use —
        // impossible. `-S`/`-e` really do nothing without a panel.
        (
            "--panel-style",
            panel_style.is_some(),
            "--panel",
            panel.is_some(),
        ),
        (
            "--expand",
            expand,
            "--panel/--padding",
            panel.is_some() || padding.is_some(),
        ),
        ("--watch-interval", watch_interval != 1.0, "--watch", watch),
        ("--watch-cache", watch_cache, "--watch", watch),
    ];
    if let Some((flag, _, needs, _)) = orphans
        .iter()
        .find(|(_, given, _, mode_present)| *given && !*mode_present)
    {
        return Err(format!("{flag} only has an effect with {needs}"));
    }

    // These decorate a single rendered resource; --diff composes its own report
    // and quietly dropped them, which reads as the flag having no effect.
    let demo = mode == Mode::Auto && resources.is_empty();
    if effective_mode.draws_directly() || demo {
        let mode_name = if effective_mode == Mode::Gif {
            "--gif"
        } else if effective_mode == Mode::Image {
            "--image"
        } else if effective_mode.streams_records() {
            mode_name(effective_mode)
        } else if demo {
            "the capability demo"
        } else {
            "--diff"
        };
        let unsupported = [
            (
                "--pager",
                pager && (effective_mode == Mode::Gif || effective_mode.streams_records() || demo),
            ),
            (
                "--export-html/--export-svg",
                (export_html.is_some() || export_svg.is_some()) && effective_mode.streams_records(),
            ),
            ("--width", demo && width.is_some()),
            (
                "--hyperlinks",
                hyperlinks && (effective_mode.streams_records() || demo),
            ),
            ("--panel", panel.is_some()),
            ("--padding", padding.is_some()),
            ("--title", title.is_some()),
            ("--caption", caption.is_some()),
            ("--style", style.is_some()),
            ("--panel-style", panel_style.is_some()),
            ("--expand", expand),
            ("--left/--center/--right", justify.is_some()),
        ];
        if let Some((flag, _)) = unsupported.iter().find(|(_, given)| *given) {
            return Err(format!("{flag} cannot be combined with {mode_name}"));
        }
    }
    if !mode.accepts_multiple_resources() && resources.len() > 1 && !batch {
        return Err("only one resource may be given (except with --gif)".into());
    }
    let resource = resources.first().cloned();

    Ok(Some(Cli {
        mode,
        resource,
        resources,
        loops,
        diff_threshold,
        image_mode,
        image_fit,
        image_background,
        height,
        extensions,
        width,
        justify,
        no_color,
        export_html,
        export_svg,
        panel,
        padding,
        title,
        caption,
        panel_style,
        style,
        expand,
        pager,
        hyperlinks,
        sanitize,
        report_format,
        watch,
        watch_interval,
        watch_cache,
        batch,
        continue_on_error,
        jobs,
        overwrite,
        collision,
    }))
}

/// Read a resource: `-` (or `None`) means stdin, otherwise a file path.
///
/// A **file** is decoded with replacement, not rejected: upstream opens it as
/// `open(path, "rt", encoding="utf8", errors="replace")`, so a cp1252 export —
/// what Excel writes on a Windows box by default — renders with `�` where the
/// odd byte was. We refused the whole file with exit 1, which is the one
/// outcome that makes the tool useless for exactly the files people reach for
/// it with.
///
/// **Stdin stays strict.** Upstream reads it with `sys.stdin.read()`, whose
/// decode error escapes into rich-cli's `except Exception` and exits non-zero;
/// there is no `errors="replace"` on that path.
fn read_resource(resource: Option<&str>, encoding: Option<Encoding>) -> std::io::Result<String> {
    let content = match resource {
        Some(path) if path != "-" => {
            let file = std::path::Path::new(path);
            // A directory reaches the reader as "Access is denied" on Windows,
            // which sends the reader hunting for a permissions problem.
            if file.is_dir() {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidInput,
                    "is a directory, not a file",
                ));
            }
            let bytes = std::fs::read(file)?;
            if let Some(encoding) = encoding {
                return encoding.decode(&bytes).map(normalize_newlines);
            }
            if has_utf16_bom(&bytes) {
                eprintln!("rich: {path} has a UTF-16 BOM; use --encoding utf-16 to decode it (default remains UTF-8 replacement)");
            }
            match String::from_utf8(bytes) {
                Ok(text) => text,
                // An image is not text in any encoding, and lossily decoding one
                // fills the terminal with thousands of replacement characters
                // and no clue. Keep the diagnostic for those; decode everything
                // else, which is what `errors="replace"` is actually for.
                Err(_) if looks_like_image(path) => {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        "looks like an image; use `rich --image <path>` to view it, or \
                         `rich --diff <before> <after>` to compare two images",
                    ))
                }
                Err(err) => String::from_utf8_lossy(err.as_bytes()).into_owned(),
            }
        }
        _ => {
            if std::io::stdin().is_terminal() {
                let eof = if cfg!(windows) {
                    "Ctrl-Z then Enter"
                } else {
                    "Ctrl-D"
                };
                eprintln!("rich: reading stdin; finish input with {eof}");
            }
            let mut buffer = Vec::new();
            std::io::stdin().read_to_end(&mut buffer)?;
            decode_strict(buffer, encoding)?
        }
    };
    Ok(normalize_newlines(if encoding.is_some() {
        content
    } else {
        strip_bom(content)
    }))
}

fn sanitize_json_value(value: &mut serde_json::Value) {
    match value {
        serde_json::Value::String(text) => *text = sanitize_terminal_controls(text),
        serde_json::Value::Array(values) => values.iter_mut().for_each(sanitize_json_value),
        serde_json::Value::Object(values) => values.values_mut().for_each(sanitize_json_value),
        _ => {}
    }
}

fn sanitize_json_source(content: &str) -> Result<String, serde_json::Error> {
    let mut value = serde_json::from_str::<serde_json::Value>(content)?;
    sanitize_json_value(&mut value);
    serde_json::to_string(&value)
}

/// Strict stdin/URL input; the default file path separately retains replacement.
fn decode_strict(bytes: Vec<u8>, encoding: Option<Encoding>) -> std::io::Result<String> {
    if let Some(encoding) = encoding {
        return encoding.decode(&bytes);
    }
    String::from_utf8(bytes).map_err(|err| std::io::Error::new(
        std::io::ErrorKind::InvalidData,
        if has_utf16_bom(err.as_bytes()) {
            "input has a UTF-16 BOM; use --encoding utf-16"
        } else {
            "input is not valid UTF-8 text; for known headerless UTF-16 select --encoding utf-16le or utf-16be"
        },
    ))
}

/// Translate CRLF and lone CR to LF, as Python's universal newlines do.
///
/// Upstream reads text files in universal-newline mode, so it **never sees a
/// CR**; `std::fs::read_to_string` hands them straight through. That gap made
/// `--syntax` on a CRLF file render as a blank rectangle: each line was emitted
/// as `code` + CR + padding, so the CR returned the cursor to column 0 and the
/// padding overwrote the code. Exit 0, nothing visible, and piping hid it
/// because the bytes were all present — only a terminal acts on the CR.
fn normalize_newlines(text: String) -> String {
    const CR: char = '\r';
    const LF: char = '\n';
    if !text.contains(CR) {
        return text;
    }
    let mut out = String::with_capacity(text.len());
    let mut chars = text.chars().peekable();
    while let Some(c) = chars.next() {
        if c == CR {
            // CRLF and a lone CR both collapse to a single LF, matching
            // Python's universal-newline translation.
            if chars.peek() == Some(&LF) {
                chars.next();
            }
            out.push(LF);
        } else {
            out.push(c);
        }
    }
    out
}

/// Drop a leading UTF-8 byte-order mark.
///
/// Windows editors write one by default and it is invisible: it made valid JSON
/// fail to parse at "column 1", and Markdown render its first heading as
/// literal text at exit 0 — in both cases with nothing pointing at the cause.
/// Whether a path's extension names an image format `--diff`/`--image` could
/// read.
///
/// Used only to improve an error message, so a false negative costs nothing.
fn looks_like_image(path: &str) -> bool {
    std::path::Path::new(path)
        .extension()
        .and_then(|e| e.to_str())
        .map(|e| e.to_ascii_lowercase())
        .is_some_and(|e| {
            matches!(
                e.as_str(),
                "png" | "jpg" | "jpeg" | "gif" | "bmp" | "webp" | "tif" | "tiff" | "ico" | "avif"
            )
        })
}

fn strip_bom(text: String) -> String {
    match text.strip_prefix('\u{feff}') {
        Some(rest) => rest.to_string(),
        None => text,
    }
}

/// Whether `resource` is an `http(s)` URL (rich-cli's `rich <url>`). The scheme
/// is matched case-insensitively, as RFC 3986 specifies.
fn is_url(resource: &str) -> bool {
    let head: String = resource.chars().take(8).collect::<String>().to_lowercase();
    head.starts_with("http://") || head.starts_with("https://")
}

/// The lowercased file extension of a resource, taken from its basename (the
/// last path segment) with any `?query`/`#fragment` stripped — so it works for
/// URLs (`…/main.rs?raw=1` → `rs`) as well as plain paths.
fn resource_ext(resource: &str) -> Option<String> {
    let basename = resource.rsplit(['/', '\\']).next().unwrap_or(resource);
    let basename = basename.split(['?', '#']).next().unwrap_or(basename);
    basename
        .rsplit_once('.')
        .map(|(_, ext)| ext.to_ascii_lowercase())
        .filter(|ext| !ext.is_empty())
}

/// The maximum *decoded* response body we will hold in memory, in bytes.
/// Exceeding it is a hard error (we never render a truncated resource).
#[cfg(feature = "fetch")]
const MAX_BODY_BYTES: u64 = 16 * 1024 * 1024;

/// Fetch a URL over HTTP(S), returning `(body, content_type)`. Port of
/// rich-cli's `requests.get`, with two deliberate safety bounds upstream lacks:
/// a 30-second global timeout and [`MAX_BODY_BYTES`].
///
/// Like `requests.get`, a non-2xx status is **not** an error — the body is
/// returned so an error page still renders. TLS verification is on (rustls with
/// bundled webpki roots).
#[cfg(feature = "fetch")]
fn fetch_url(url: &str, encoding: Option<Encoding>) -> Result<(String, Option<String>), String> {
    use std::time::Duration;
    let mut response = ureq::get(url)
        .config()
        .timeout_global(Some(Duration::from_secs(30)))
        // Match `requests.get`: don't turn 4xx/5xx into an error, so the
        // response body (often a useful error page) is rendered instead.
        .http_status_as_error(false)
        .build()
        .call()
        .map_err(|err| format!("cannot fetch {url}: {err}"))?;
    let content_type = response
        .headers()
        .get("content-type")
        .and_then(|value| value.to_str().ok())
        .map(str::to_string);

    // Bound the *decoded* body: `.reader()` yields post-decompression bytes, so
    // capping it here (rather than via ureq's `limit()`, whose LimitReader sits
    // *under* the gzip decoder and would only bound compressed bytes) also
    // defuses a `Content-Encoding: gzip` bomb. Read one byte past the limit so
    // an oversized body is detectable rather than silently truncated.
    let mut buffer = Vec::new();
    response
        .body_mut()
        .with_config()
        .reader()
        .take(MAX_BODY_BYTES + 1)
        .read_to_end(&mut buffer)
        .map_err(|err| format!("cannot read {url}: {err}"))?;
    if buffer.len() as u64 > MAX_BODY_BYTES {
        return Err(format!(
            "{url} exceeds the {} MiB limit",
            MAX_BODY_BYTES / (1024 * 1024)
        ));
    }
    let body =
        decode_strict(buffer, encoding).map_err(|err| format!("cannot decode {url}: {err}"))?;
    Ok((body, content_type))
}

/// Stub used when the crate is built without the `fetch` feature.
#[cfg(not(feature = "fetch"))]
fn fetch_url(url: &str, _encoding: Option<Encoding>) -> Result<(String, Option<String>), String> {
    Err(format!(
        "cannot fetch {url}: this build has no URL support (rebuild with the `fetch` feature)"
    ))
}

/// The high-level render mode implied by a response `Content-Type` (the MIME
/// type, ignoring any `; charset=…`). Used only when neither a flag nor the URL
/// extension already picked a mode.
fn content_type_mode(content_type: &str) -> Option<Mode> {
    let mime = mime_of(content_type);
    match mime.as_str() {
        "text/markdown" | "text/x-markdown" => Some(Mode::Markdown),
        "application/json" | "text/json" => Some(Mode::Json),
        "text/csv" => Some(Mode::Csv),
        _ => None,
    }
}

/// A syntect lexer name for a response `Content-Type`, for syntax-highlighting a
/// fetched resource that has no informative extension. A small common subset of
/// upstream's Pygments MIME table.
fn content_type_lexer(content_type: &str) -> Option<&'static str> {
    let mime = mime_of(content_type);
    Some(match mime.as_str() {
        "text/html" | "application/xhtml+xml" => "html",
        "text/css" => "css",
        "application/javascript" | "text/javascript" => "javascript",
        "application/xml" | "text/xml" => "xml",
        "text/x-python" | "application/x-python" | "text/x-python3" => "python",
        "text/x-rust" => "rust",
        "text/x-c" | "text/x-csrc" => "c",
        "application/x-sh" | "text/x-shellscript" => "bash",
        "application/x-yaml" | "text/yaml" | "text/x-yaml" => "yaml",
        "application/toml" | "text/x-toml" => "toml",
        _ => return None,
    })
}

/// Whether an extension names no particular language, so a `Content-Type` that
/// does should win when picking a syntax lexer.
fn is_uninformative_ext(ext: &str) -> bool {
    matches!(ext, "txt" | "text" | "log" | "dat" | "out")
}

/// The bare MIME type from a `Content-Type` header (lowercased, `; charset=…`
/// and surrounding whitespace stripped).
fn mime_of(content_type: &str) -> String {
    content_type
        .split(';')
        .next()
        .unwrap_or("")
        .trim()
        .to_ascii_lowercase()
}

/// Resolve `Mode::Auto` to a concrete mode from the resource's file extension.
fn detect_mode(resource: Option<&str>) -> Mode {
    match resource.and_then(resource_ext).as_deref() {
        Some("md") | Some("markdown") => Mode::Markdown,
        Some("json") => Mode::Json,
        Some("csv") | Some("tsv") => Mode::Csv,
        Some("ipynb") => Mode::Ipynb,
        Some("gif") => Mode::Gif,
        // Anything the table above does not divert is source code, and upstream
        // highlights it: `rich main.rs` is syntax-highlighted with no flag at
        // all. We printed it raw instead, so `rich hello.py` produced no
        // highlighting and no styling in an export — while `docs/cli.md` line 12
        // advertised the upstream behaviour and `--help` documented ours. The
        // two contradicted each other; this resolves them the way the docs (and
        // upstream) say.
        Some(_) => Mode::Syntax,
        // No extension to go on (including stdin): stay in Auto and let the
        // caller decide, rather than guessing a lexer for something that may not
        // be source at all.
        None => Mode::Auto,
    }
}

/// Force a renderable to a fixed width, wherever on the screen it lands. Port
/// of rich-cli's `ForceWidth`.
///
/// `--width N` used to shrink the *console* to N, which also moved every
/// alignment inside N columns: `rich -w 20 --center` centred within 20 rather
/// than within the terminal, and an `--export-svg` frame came out N wide.
/// Upstream leaves the console alone and narrows only the renderable.
struct ForceWidth {
    child: Box<dyn Renderable>,
    width: usize,
}

impl Renderable for ForceWidth {
    fn rich_render(&self, console: &Console, options: &ConsoleOptions) -> Vec<Segment> {
        self.child
            .rich_render(console, &options.update_width(self.width))
    }

    fn measure(&self, _console: &Console, _options: &ConsoleOptions) -> Measurement {
        Measurement::new(self.width, self.width)
    }
}

/// Position a renderable within the available width. Port of the horizontal
/// axis of `rich.align.Align`, which is what `console.print(justify=…)` wraps
/// every renderable in.
///
/// The core crate's [`Align`] is not that: it renders its child at the *full*
/// width and pads each line by that line's own width, so it neither shrinks the
/// child (nothing that fills the width — `Syntax`, `Rule`, a `Panel` — moves at
/// all) nor squares the block off (multi-line output comes out ragged).
/// Upstream constrains the child to its measured width, `set_shape`s every line
/// to that one width, then pads the block. Doing that here leaves `align.rs`,
/// which other renderables depend on, untouched.
struct Aligned {
    child: Box<dyn Renderable>,
    /// The width to render the child *within* — what upstream's `Align` reads
    /// out of `console.measure(renderable)` and hands to `Constrain`. The block
    /// it then pads is measured from the output, not from this: a `--csv` table
    /// given `-w 40` still renders at its own 23 columns, and it is 23 that gets
    /// centred.
    width: usize,
    justify: Justify,
}

impl Renderable for Aligned {
    fn rich_render(&self, console: &Console, options: &ConsoleOptions) -> Vec<Segment> {
        let width = self.width.clamp(1, options.max_width);
        // The child renders with the console's own justify, not this alignment.
        // Upstream puts `print(justify=…)` into the render options, but rich-cli
        // builds its `--print`/`--rule` text with an explicit `justify="default"`
        // — a truthy string in Python — which blocks the inheritance, so
        // `-w 9 --center -p mid` centres a three-cell block within the terminal
        // rather than centring "mid" inside nine columns first. Every other
        // renderable this CLI builds (`Table`, `Json`, `Syntax`, `Markdown`)
        // ignores `options.justify` in this port, so there is nothing else for
        // the inheritance to reach.
        let lines = console.render_lines(self.child.as_ref(), &options.update_width(width), false);
        let widths: Vec<usize> = lines
            .iter()
            .map(|line| line.iter().map(Segment::cell_length).sum())
            .collect();
        // `Segment.get_shape` then `Segment.set_shape`: square the block off at
        // the widest line it actually produced, so a multi-line child moves as
        // one block instead of each line drifting to its own width.
        let shape = widths.iter().copied().max().unwrap_or(0);

        let excess = options.max_width.saturating_sub(shape);
        let (left, right) = match self.justify {
            Justify::Right => (excess, 0),
            Justify::Center => (excess / 2, excess - excess / 2),
            _ => (0, excess),
        };
        let blank = |count: usize| Segment::new(" ".repeat(count), Some(Style::new()));

        let mut segments = Vec::new();
        let last = lines.len().saturating_sub(1);
        for (index, (line, line_width)) in lines.into_iter().zip(widths).enumerate() {
            if left > 0 {
                segments.push(blank(left));
            }
            segments.extend(line);
            let pad = shape - line_width + right;
            if pad > 0 {
                segments.push(blank(pad));
            }
            if index != last {
                segments.push(Segment::line());
            }
        }
        segments
    }
}

/// The width a renderable actually occupies, found by rendering it.
///
/// `Table`, `Json` and friends inherit `(max_width, max_width)` from the
/// `Renderable` default in the core crate, so asking them to measure themselves
/// always answers "the whole console" and a fitted panel would not shrink at
/// all. Neither pads its output to the space it is given, though, so the widest
/// rendered line *is* upstream's `Measurement.get(…).maximum`, clamped to the
/// console — which is what a fitted `Panel` needs.
///
/// Not usable for `Syntax`, whose lines *are* padded out to the full width by
/// its background: that one is measured from the source instead.
fn measure_rendered(console: &Console, renderable: &dyn Renderable) -> usize {
    console
        .render_lines(renderable, &console.options(), false)
        .iter()
        .map(|line| line.iter().map(Segment::cell_length).sum::<usize>())
        .max()
        .unwrap_or(0)
}

/// Only labels consumed by a panel or CSV table should be parsed. Other modes
/// ignore these options upstream, including malformed unused markup.
fn validate_labels(cli: &Cli) -> Result<(), String> {
    for label in cli.title.iter().chain(cli.caption.iter()) {
        Text::from_markup(label).map_err(|err| err.to_string())?;
    }
    Ok(())
}

/// Apply upstream's decorator chain — padding, panel, style, fixed width,
/// alignment — and print the result. Port of the tail of rich-cli's `main`.
///
/// `fit` is the width the renderable measures at; `None` means "fills whatever
/// it is given", which is what a `Markdown` reports, so nothing shrinks to it.
fn decorate_and_emit(
    cli: &Cli,
    console: &Console,
    export: &Export,
    renderable: Box<dyn Renderable>,
    fit: Option<usize>,
) -> ExitCode {
    if cli.panel.is_some() {
        if let Err(err) = validate_labels(cli) {
            return fail(cli, ExitClass::Data, err);
        }
    }
    let max_width = console.width();
    // `if width > 0: expand = True` — a fixed width is a width to fill.
    let expand = cli.expand || cli.width.is_some();
    let mut renderable = renderable;
    let mut fit = fit;

    // This port's `Padding` and `Panel` always fill the width they are given, so
    // a *fitted* box is a `Constrain` around one. Upstream instead passes
    // `expand=False` and lets the box measure its own child — the same width,
    // reached from the outside, which is the only way that works while the core
    // crate's `Table`/`Syntax`/`Json` still inherit the default measurement.
    if let Some((top, right, bottom, left)) = cli.padding {
        let padded: Box<dyn Renderable> =
            Box::new(Padding::new(renderable, (top, right, bottom, left)));
        // `Padding.__rich_measure__`: the child plus the horizontal padding,
        // capped at the available width.
        fit = fit.map(|width| (width + left + right).min(max_width));
        renderable = if expand {
            padded
        } else {
            Box::new(Constrain::new(padded, fit))
        };
    }

    if let Some(box_set) = cli.panel {
        let mut panel = Panel::new(renderable).box_set(box_set);
        if let Some(title) = cli.title.clone() {
            panel = panel.title(title);
        }
        if let Some(caption) = cli.caption.clone() {
            panel = panel.subtitle(caption);
        }
        if let Some(style) = cli.panel_style.clone() {
            panel = panel.border_style(style);
        }
        // `Panel.__rich_measure__`: the wider of the child (measured in
        // `max_width - 4`) and the title, plus a border and a pad on each side.
        // The *subtitle* is deliberately absent — upstream does not measure it,
        // so a long `--caption` is truncated by the border rather than widening
        // the panel.
        //
        // Panel parses markup, normalizes newlines/tabs, and pads the label by
        // one cell on either side. Measure visible text with the same rules.
        let inner = max_width.saturating_sub(4);
        let child = fit.unwrap_or(inner).min(inner);
        let title_width = cli
            .title
            .as_deref()
            .map(|title| {
                let mut title = Text::from_markup(&rich::emoji::replace(title).replace('\n', " "))
                    .expect("title markup validated before rendering");
                title.expand_tabs(8);
                cell_len(title.plain()) + 2
            })
            .unwrap_or(0);
        fit = Some(child.max(title_width) + 4);
        let panel: Box<dyn Renderable> = Box::new(panel);
        renderable = if expand {
            panel
        } else {
            Box::new(Constrain::new(panel, fit))
        };
    }

    // `-s/--style` lays a style under everything, outside the panel — upstream's
    // `Styled(renderable, text_style)`. It does not change any width.
    if let Some(style) = cli.style.clone() {
        renderable = Box::new(Styled::new(renderable, style));
    }

    // `if width > 0 and not pager` — the pager lays out at its own width.
    if let Some(width) = cli.width.filter(|_| !cli.pager) {
        renderable = Box::new(ForceWidth {
            child: renderable,
            width,
        });
        fit = Some(width);
    }

    if let Some(justify) = cli.justify {
        renderable = Box::new(Aligned {
            child: renderable,
            width: fit.unwrap_or(max_width),
            justify,
        });
    }

    emit_exit_code(cli, emit(console, export, |c| c.print(renderable.as_ref())))
}

fn run(cli: Cli) -> ExitCode {
    if cli.watch {
        return run_watch(cli);
    }
    run_once(cli)
}

fn run_watch(mut cli: Cli) -> ExitCode {
    let Some(resource) = cli.resource.as_deref() else {
        return fail(
            &cli,
            ExitClass::Usage,
            "--watch requires a file path or URL",
        );
    };
    if resource == "-" || (cli.mode == Mode::Print && !is_url(resource)) {
        return fail(
            &cli,
            ExitClass::Usage,
            "--watch requires a local file or URL, not stdin or literal markup",
        );
    }
    let effective_mode = if cli.mode == Mode::Auto {
        detect_mode(Some(resource))
    } else {
        cli.mode
    };
    if effective_mode.draws_directly() || effective_mode == Mode::Rule {
        return fail(
            &cli,
            ExitClass::Usage,
            "--watch requires a resource-backed render mode",
        );
    }
    // Redirected output must be a finite, deterministic command. This also
    // keeps `rich --watch file > snapshot.txt` from hanging in a pipeline.
    if !std::io::stdout().is_terminal() {
        cli.watch = false;
        return run_once(cli);
    }
    if is_url(resource) {
        #[cfg(not(feature = "fetch"))]
        {
            cli.watch = false;
            return run_once(cli);
        }
    }

    let interval = std::time::Duration::from_secs_f64(cli.watch_interval);
    let mut previous = None;
    loop {
        #[cfg(feature = "fetch")]
        let cached = if is_url(resource) && cli.watch_cache {
            Some(fetch_url(resource, cli.extensions.encoding))
        } else {
            None
        };
        #[cfg(not(feature = "fetch"))]
        let cached: Option<Result<(String, Option<String>), String>> = None;
        let fingerprint = match cached.as_ref() {
            Some(Ok((body, content_type))) => {
                use std::hash::{Hash, Hasher};
                let mut hasher = std::collections::hash_map::DefaultHasher::new();
                body.hash(&mut hasher);
                content_type.hash(&mut hasher);
                format!("url:{:x}", hasher.finish())
            }
            Some(Err(error)) => format!("url-error:{error}"),
            None => watch_fingerprint(resource, false, cli.extensions.encoding),
        };
        let changed = previous.as_ref() != Some(&fingerprint);
        if changed || (is_url(resource) && !cli.watch_cache) {
            previous = Some(fingerprint);
            // Each watch frame owns the viewport; clear stale rows when a
            // replacement is shorter, then start the new frame at the top.
            let console = Console::new();
            console.clear();
            console.control(&Control::home());
            let _ = std::io::stdout().flush();
            let mut iteration = cli.clone();
            iteration.watch = false;
            let status = run_once_with_fetch(iteration, cached.and_then(Result::ok));
            if status != ExitClass::Success.exit_code() {
                // A temporary disappearance or parse failure is a frame error,
                // not a reason to abandon a watch that may recover.
                eprintln!("rich: watch will retry after the next change");
            }
        }
        std::thread::sleep(interval);
    }
}

fn watch_fingerprint(resource: &str, cache_url: bool, encoding: Option<Encoding>) -> String {
    if is_url(resource) {
        #[cfg(feature = "fetch")]
        if cache_url {
            return match fetch_url(resource, encoding) {
                Ok((body, content_type)) => {
                    use std::hash::{Hash, Hasher};
                    let mut hasher = std::collections::hash_map::DefaultHasher::new();
                    body.hash(&mut hasher);
                    content_type.hash(&mut hasher);
                    format!("url:{:x}", hasher.finish())
                }
                Err(error) => format!("url-error:{error}"),
            };
        }
        #[cfg(not(feature = "fetch"))]
        let _ = (cache_url, encoding);
        return "url".to_string();
    }
    match std::fs::metadata(resource) {
        Ok(metadata) if metadata.is_file() => {
            use std::hash::Hasher;
            // Atomic saves and in-place writes may preserve both size and
            // mtime. Read regular files each poll using a fixed-size buffer,
            // so detection is portable and memory does not grow with input.
            let mut file = match std::fs::File::open(resource) {
                Ok(file) => file,
                Err(error) => return format!("file-error:{error}"),
            };
            let mut hasher = std::collections::hash_map::DefaultHasher::new();
            let mut buffer = [0u8; 64 * 1024];
            loop {
                match file.read(&mut buffer) {
                    Ok(0) => break,
                    Ok(count) => hasher.write(&buffer[..count]),
                    Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
                    Err(error) => return format!("file-error:{error}"),
                }
            }
            format!("file:{:x}", hasher.finish())
        }
        Ok(_) => "not-file".to_string(),
        Err(_) => "missing".to_string(),
    }
}

fn run_once(cli: Cli) -> ExitCode {
    run_once_with_fetch(cli, None)
}

fn run_once_with_fetch(mut cli: Cli, prefetched: Option<(String, Option<String>)>) -> ExitCode {
    if cli.sanitize {
        cli.title = cli
            .title
            .take()
            .map(|title| sanitize_terminal_controls(&title));
        cli.caption = cli
            .caption
            .take()
            .map(|caption| sanitize_terminal_controls(&caption));
    }

    if cli.batch {
        return run_batch(&cli);
    }

    // With no flags and no resource, show the capability demo.
    if cli.mode == Mode::Auto && cli.resource.is_none() {
        run_demo(cli.no_color);
        return success(&cli);
    }

    let mut mode = match cli.mode {
        Mode::Auto => detect_mode(cli.resource.as_deref()),
        other => other,
    };

    // Modes that render incrementally write directly to the console instead of
    // composing one renderable, so no `ForceWidth` wrapper can reach them.
    let mut builder = Console::builder().no_color(cli.no_color);
    if let Some(width) = cli.width.filter(|_| mode.draws_directly()) {
        builder = builder.width(width);
    }
    let mut console = builder.build();
    console.install_extensions();

    if mode == Mode::Rule {
        if let Some(title) = &cli.resource {
            if let Err(err) = Text::from_markup(title) {
                return fail(&cli, ExitClass::Data, err.to_string());
            }
        }
    }

    // SVG export needs a title (the resource's basename, else "rich") and a
    // stable id. Upstream's auto id hashes Python reprs, so we use a fixed one
    // (see the rich crate's svg module / DIVERGENCES #15).
    let mut svg_title = cli
        .resource
        .as_deref()
        .filter(|r| *r != "-")
        .map(|r| r.rsplit(['/', '\\']).next().unwrap_or(r).to_string())
        .unwrap_or_else(|| "rich".to_string());
    if cli.sanitize {
        svg_title = sanitize_terminal_controls(&svg_title);
    }
    let export = Export {
        html_path: cli.export_html.as_deref(),
        svg_path: cli.export_svg.as_deref(),
        svg_title: &svg_title,
        pager: cli.pager,
    };

    // GIF playback consumes the resource list itself (it can take several) and
    // animates rather than rendering once.
    if mode == Mode::Gif {
        return play_gifs(&cli, &console);
    }

    // `--diff` consumes both resources and reports rather than rendering one.
    #[cfg(feature = "art")]
    if mode == Mode::Diff {
        return run_diff(&cli, &console, &export);
    }

    // `--image` renders a single still image directly through rich-art's
    // `ImageArt` facade rather than composing a decorated renderable.
    #[cfg(feature = "art")]
    if mode == Mode::Image {
        return run_image(&cli, &console, &export);
    }
    #[cfg(not(feature = "art"))]
    if mode == Mode::Image {
        return fail(
            &cli,
            ExitClass::Usage,
            "this build has no image support (rebuild with the `art` feature)",
        );
    }

    if mode.streams_records() {
        return run_json_lines(&cli, &console, mode == Mode::Log);
    }

    // A rule takes its optional title from the resource string directly (no
    // fetch/read) — but it still goes through the decorators, because upstream
    // wraps it like anything else, so `--rule --panel` really does draw a panel.
    if mode == Mode::Rule {
        let rule = match cli.resource.as_deref() {
            Some(title) if title != "-" && cli.sanitize => {
                Rule::new(sanitize_terminal_controls(title))
            }
            Some(title) if title != "-" => Rule::new(title),
            _ => Rule::line(),
        };
        // `Rule.__rich_measure__` is `Measurement(1, 1)`: a rule claims no width
        // of its own, so a fitted panel around one is 5 cells wide.
        return decorate_and_emit(&cli, &console, &export, Box::new(rule), Some(1));
    }

    // Obtain the content: fetch it over HTTP(S) when the resource is a URL,
    // treat it as a literal markup string under `--print`, else read the
    // file/stdin. A URL also yields a `Content-Type` used below.
    let resource_is_url = matches!(cli.resource.as_deref(), Some(r) if is_url(r));
    let (mut content, content_type) = if let Some(fetched) = prefetched {
        fetched
    } else if resource_is_url {
        match fetch_url(cli.resource.as_deref().unwrap(), cli.extensions.encoding) {
            Ok(fetched) => fetched,
            Err(err) => {
                return fail(&cli, ExitClass::Input, err);
            }
        }
    } else if mode == Mode::Print && matches!(cli.resource.as_deref(), Some(r) if r != "-") {
        (cli.resource.clone().unwrap(), None)
    } else {
        match read_resource(cli.resource.as_deref(), cli.extensions.encoding) {
            Ok(content) => (content, None),
            Err(err) => {
                let name = cli.resource.as_deref().unwrap_or("<stdin>");
                return fail(&cli, ExitClass::Input, format!("cannot read {name}: {err}"));
            }
        }
    };
    if cli.sanitize {
        content = sanitize_terminal_controls(&content);
    }

    // For a URL that neither a flag nor a telltale extension resolved: upstream
    // renders fetched content as syntax-highlighted source by default, unless the
    // Content-Type marks it markdown / json / csv.
    if resource_is_url && mode == Mode::Auto {
        mode = content_type
            .as_deref()
            .and_then(content_type_mode)
            .unwrap_or(Mode::Syntax);
    }

    // Pre-parse JSON so a parse error surfaces before any (HTML) rendering.
    let json_content = if mode == Mode::Json && cli.sanitize {
        match sanitize_json_source(content.trim()) {
            Ok(content) => Some(content),
            Err(err) => {
                return fail(&cli, ExitClass::Data, format!("invalid JSON: {err}"));
            }
        }
    } else {
        None
    };

    let json = if mode == Mode::Json {
        let source = json_content.as_deref().unwrap_or_else(|| content.trim());
        match Json::new(source) {
            Ok(json) => Some(json),
            Err(err) => {
                return fail(&cli, ExitClass::Data, format!("invalid JSON: {err}"));
            }
        }
    } else {
        None
    };

    // Same treatment for a notebook. Without this the parse failure was printed
    // from inside the render closure, which cannot influence the exit code — so
    // a broken notebook reported an error and exited 0, while a broken .json
    // exited 1. A malformed input must not look like success to a script.
    if mode == Mode::Ipynb {
        let notebook = match serde_json::from_str::<serde_json::Value>(&content) {
            Ok(mut value) if value.get("cells").and_then(|c| c.as_array()).is_some() => {
                if cli.sanitize {
                    sanitize_json_value(&mut value);
                }
                value
            }
            Ok(_) => {
                return fail(&cli, ExitClass::Data, "not a notebook: no `cells` array");
            }
            Err(err) => {
                return fail(
                    &cli,
                    ExitClass::Data,
                    format!("invalid notebook JSON: {err}"),
                );
            }
        };
        let renderable = build_ipynb(&notebook, cli.hyperlinks, cli.justify);
        let fit = renderable.measure(&console, &console.options()).maximum;
        return decorate_and_emit(&cli, &console, &export, Box::new(renderable), Some(fit));
    }

    // Markup comes from the user in Print mode, so a mistake in it should be
    // reported rather than printed literally (upstream raises `MarkupError`).
    // Checked up front because the render closure below cannot fail.
    if mode == Mode::Print {
        if let Err(err) = console.try_build_text(&content) {
            return fail(&cli, ExitClass::Data, err.to_string());
        }
    }

    // The highlighting language comes from the resource extension, falling back
    // (for a URL) to a lexer guessed from its Content-Type. An *uninformative*
    // extension (.txt/.log/…) doesn't shadow a Content-Type that names a real
    // language, so `snippet.txt` served as `text/x-python` still highlights.
    let extension = resource_ext(cli.resource.as_deref().unwrap_or_default())
        .filter(|ext| !is_uninformative_ext(ext));
    let language = extension
        .or_else(|| {
            content_type
                .as_deref()
                .and_then(content_type_lexer)
                .map(str::to_string)
        })
        .unwrap_or_default();

    // Build the renderable, and the width a non-expanding `Panel`/`Padding`
    // would shrink around it — upstream's `Measurement.get(…).maximum`.
    let (renderable, fit): (Box<dyn Renderable>, Option<usize>) = match mode {
        // `Markdown` defines no `__rich_measure__`, so upstream measures it as
        // the whole available width and a panel around it never shrinks.
        Mode::Markdown => (Box::new(build_markdown(&content, cli.hyperlinks)), None),
        Mode::Json => {
            // `rich.json.JSON` sets `text.no_wrap = True`, and every decorator
            // upstream can wrap the document in — `Padding`, `Panel`, `Styled`,
            // `ForceWidth` — is a `ConsoleRenderable`, so the `Text` reaches
            // `Text.__rich_console__` with the flag intact and each line is
            // CROPPED at the width. A *bare* document is a `Text`, which
            // `_collect_renderables` re-joins through `Text(sep).join(...)`;
            // `Text.join` copies its metadata from the separator, so the flag
            // is lost and the default fold wrap applies instead.
            //
            // `--left/--center/--right` is not on the list: `align_append`
            // wraps whatever `check_text` produced, so the join — and the loss
            // — has already happened by the time `Align` sees it.
            //
            // `--pager` skips `ForceWidth`, but pages through
            // `console.render_lines(renderable, …)`, which renders the `Text`
            // directly and keeps the flag.
            let nested = cli.padding.is_some()
                || cli.panel.is_some()
                || cli.style.is_some()
                || cli.width.is_some()
                || cli.pager;
            let json = json.expect("json parsed above").no_wrap(nested);
            #[cfg(feature = "json-escape-safe")]
            let json = json.escape_safe(true);
            let fit = measure_rendered(&console, &json);
            (Box::new(json), Some(fit))
        }
        Mode::Csv => {
            if let Err(err) = validate_labels(&cli) {
                return fail(&cli, ExitClass::Data, err);
            }
            // `.tsv` only picks the fallback dialect; the sniffer reads the file
            // itself, so a comma-separated `.tsv` still renders as a table.
            let fallback = csv_fallback_delimiter(cli.resource.as_deref());
            let table = match build_csv_table(
                &content,
                fallback,
                cli.title.as_deref(),
                cli.caption.as_deref(),
            ) {
                Some(table) => table,
                // Upstream's `on_error(str(error))`. The message is CPython's,
                // verbatim, because it is the one a script would grep for.
                None => {
                    return fail(&cli, ExitClass::Data, "Could not determine delimiter");
                }
            };
            // Stream undecorated CSV rows: measuring or collecting the complete
            // styled table first multiplies memory by hundreds on tall inputs.
            // Containers, alignment, paging and exports still need the full view.
            if cli.panel.is_none()
                && cli.padding.is_none()
                && cli.style.is_none()
                && cli.justify.is_none()
                && !cli.pager
                && cli.export_html.is_none()
                && cli.export_svg.is_none()
            {
                let mut options = console.options();
                options.max_width = cli.width.unwrap_or_else(|| {
                    table
                        .measure(&console, &options)
                        .maximum
                        .min(options.max_width)
                        .max(1)
                });
                let stdout = std::io::stdout();
                let mut output = std::io::BufWriter::new(stdout.lock());
                let result = table
                    .try_for_each_line(&console, &options, |line| {
                        let line = Segment::crop_lines(&line, console.width());
                        writeln!(output, "{}", console.segments_to_string(&line))
                    })
                    .and_then(|()| output.flush());
                if let Err(error) = result {
                    // A consumer such as `head` may finish before this table.
                    // Match the other stdout paths: a closed pipe is success.
                    if error.kind() == std::io::ErrorKind::BrokenPipe {
                        return success(&cli);
                    }
                    return fail(
                        &cli,
                        ExitClass::Input,
                        format!("could not write CSV output: {error}"),
                    );
                }
                return success(&cli);
            }
            let fit = measure_rendered(&console, &table);
            (Box::new(table), Some(fit))
        }
        Mode::Syntax => {
            // `Syntax.__rich_measure__`: the widest source line, plus padding and
            // a line-number column — neither of which this CLI turns on.
            let fit = content.lines().map(cell_len).max().unwrap_or(0);
            (
                Box::new(Syntax::new(content.as_str(), language.as_str()).word_wrap(true)),
                Some(fit),
            )
        }
        // Print + auto: parse markup (Print) or take plain text (auto).
        _ => {
            let text = if mode == Mode::Print {
                console.build_text(&content)
            } else {
                Text::new(content.as_str())
            };
            let fit = text.measurement().1;
            (Box::new(text), Some(fit))
        }
    };
    decorate_and_emit(&cli, &console, &export, renderable, fit)
}

/// Turn an "everything written successfully" flag into a process exit code.
/// A failed `--export-html`/`--export-svg` write must not report success.
#[allow(dead_code)]
fn exit_code(ok: bool) -> ExitCode {
    if ok {
        ExitCode::SUCCESS
    } else {
        ExitCode::FAILURE
    }
}

fn emit_exit_code(cli: &Cli, result: Result<(), String>) -> ExitCode {
    match result {
        Ok(()) => success(cli),
        Err(message) => fail(cli, ExitClass::Input, message),
    }
}

fn write_rendered_stdout(console: &Console, renderable: &dyn Renderable) -> std::io::Result<()> {
    let output = console.render_export(renderable);
    let stdout = std::io::stdout();
    let mut lock = stdout.lock();
    lock.write_all(output.as_bytes())
}

fn run_json_lines(cli: &Cli, console: &Console, log_mode: bool) -> ExitCode {
    if cli.extensions.encoding.is_some() {
        return fail(
            cli,
            ExitClass::Usage,
            "--encoding is not supported with streaming JSONL/log mode",
        );
    }
    if matches!(cli.resource.as_deref(), Some(resource) if is_url(resource)) {
        return fail(
            cli,
            ExitClass::Usage,
            "streaming JSONL/log mode reads files or stdin, not URLs",
        );
    }

    let mut input: Box<dyn BufRead> = match cli.resource.as_deref() {
        Some(path) if path != "-" => {
            let file = std::path::Path::new(path);
            if file.is_dir() {
                return fail(
                    cli,
                    ExitClass::Input,
                    format!("cannot read {path}: is a directory, not a file"),
                );
            }
            match std::fs::File::open(file) {
                Ok(file) => Box::new(std::io::BufReader::new(file)),
                Err(err) => {
                    return fail(cli, ExitClass::Input, format!("cannot read {path}: {err}"));
                }
            }
        }
        _ => {
            if std::io::stdin().is_terminal() {
                let eof = if cfg!(windows) {
                    "Ctrl-Z then Enter"
                } else {
                    "Ctrl-D"
                };
                eprintln!("rich: reading stdin; finish input with {eof}");
            }
            Box::new(std::io::BufReader::new(std::io::stdin()))
        }
    };

    let mut line = String::new();
    let mut line_number = 0usize;
    loop {
        line.clear();
        let read = match input.read_line(&mut line) {
            Ok(read) => read,
            Err(err) => {
                return fail(
                    cli,
                    ExitClass::Input,
                    format!("cannot read JSONL stream: {err}"),
                );
            }
        };
        if read == 0 {
            break;
        }
        line_number += 1;
        let record = line.trim_end_matches(['\r', '\n']);
        let mut value = match serde_json::from_str::<serde_json::Value>(record) {
            Ok(value) => value,
            Err(err) => {
                return fail(
                    cli,
                    ExitClass::Data,
                    format!("invalid JSONL at line {line_number}: {err}"),
                );
            }
        };
        if cli.sanitize {
            sanitize_json_value(&mut value);
        }
        let wrote = if log_mode {
            let text = Text::new(format_log_record(&value));
            write_rendered_stdout(console, &text)
        } else {
            let source = serde_json::to_string(&value).expect("JSON value serializes");
            let json = Json::new(&source).expect("serialized JSON parses");
            write_rendered_stdout(console, &json)
        };
        if let Err(error) = wrote {
            if error.kind() == std::io::ErrorKind::BrokenPipe {
                return success(cli);
            }
            return fail(
                cli,
                ExitClass::Input,
                format!("could not write JSONL output: {error}"),
            );
        }
    }
    success(cli)
}

fn format_log_record(value: &serde_json::Value) -> String {
    let Some(object) = value.as_object() else {
        return serde_json::to_string(value).expect("JSON value serializes");
    };
    let take_value = |keys: &[&'static str]| {
        keys.iter().find_map(|key| {
            object.get(*key).map(|value| {
                let display = value.as_str().map(str::to_string).unwrap_or_else(|| {
                    serde_json::to_string(value).expect("JSON value serializes")
                });
                (*key, display, value.is_string())
            })
        })
    };
    let timestamp = take_value(&["timestamp", "time", "@timestamp"]);
    let level = take_value(&["level", "severity"]);
    let message = take_value(&["message", "msg"]);
    let mut rest = serde_json::Map::new();
    for (key, value) in object {
        let consumed = timestamp
            .as_ref()
            .is_some_and(|(consumed, _, _)| consumed == key)
            || level
                .as_ref()
                .is_some_and(|(consumed, _, _)| consumed == key)
            || message
                .as_ref()
                .is_some_and(|(consumed, _, _)| consumed == key);
        if !consumed {
            rest.insert(key.clone(), value.clone());
        }
    }
    let mut parts = Vec::new();
    if let Some((_, timestamp, _)) = timestamp {
        parts.push(timestamp);
    }
    if let Some((_, level, is_string)) = level {
        parts.push(if is_string {
            level.to_ascii_uppercase()
        } else {
            level
        });
    }
    if let Some((_, message, _)) = message {
        parts.push(message);
    }
    if !rest.is_empty() {
        parts.push(
            serde_json::to_string(&serde_json::Value::Object(rest)).expect("JSON value serializes"),
        );
    }
    if parts.is_empty() {
        serde_json::to_string(value).expect("JSON value serializes")
    } else {
        parts.join(" ")
    }
}

/// A CSV dialect: everything `csv.Sniffer` decides and `csv.reader` consumes.
#[derive(Debug, Clone, Copy)]
struct Dialect {
    delimiter: char,
    quotechar: char,
    doublequote: bool,
    skipinitialspace: bool,
}

impl Dialect {
    /// `csv.get_dialect("excel")` (or `"excel-tab"` for a tab): upstream's
    /// fallback for a `.csv`/`.tsv` the sniffer cannot read.
    fn excel(delimiter: char) -> Self {
        Dialect {
            delimiter,
            quotechar: '"',
            doublequote: true,
            skipinitialspace: false,
        }
    }
}

/// Whether `c` is a `\w` character for CPython's `re` over `str`.
fn is_word_char(c: char) -> bool {
    c.is_alphanumeric() || c == '_'
}

/// The `[^\w\n"']` class the sniffer accepts as a candidate delimiter.
fn is_delimiter_char(c: char) -> bool {
    !is_word_char(c) && c != '\n' && c != '"' && c != '\''
}

/// The `["']` class the sniffer accepts as a candidate quote character.
fn is_quote_char(c: char) -> bool {
    c == '"' || c == '\''
}

/// One hit from the quote/delimiter scan: the quote, the delimiter bracketing
/// it (absent in the fourth, delimiter-free pattern), and whether a space sat
/// between the two.
struct QuoteHit {
    quote: char,
    delim: Option<char>,
    space: bool,
}

/// Port of `csv.Sniffer.sniff`, restricted to `delimiters` when given (rich-cli
/// passes `",\t|;"`). `None` is CPython's `csv.Error`: no delimiter found.
///
/// `doublequote` is **not** sniffed; it is left at excel's `true`. CPython
/// decides it with a regex that only fires when a `""` pair sits inside a
/// quoted field containing neither the delimiter nor a newline, and when it
/// does not fire `csv.reader` stops unescaping — `"he said ""hi"""` reads back
/// as `he said "hi"""`. Reproducing that can only ever make a well-formed file
/// render worse, and upstream's own fallback (`csv.get_dialect("excel")`, used
/// for every file the sniffer rejects) already sets it true. The divergence is
/// confined to files that use `""` escaping *and* defeat the heuristic, e.g. a
/// `""` inside a multi-line cell: there we unescape and upstream does not.
fn sniff(sample: &str, delimiters: Option<&[char]>) -> Option<Dialect> {
    let data: Vec<char> = sample.chars().collect();
    let (quote, mut delimiter, mut skipinitialspace) = guess_quote_and_delimiter(&data, delimiters);
    if delimiter.is_none() {
        let (guessed, spaced) = guess_delimiter(sample, delimiters);
        delimiter = guessed;
        skipinitialspace = spaced;
    }
    Some(Dialect {
        delimiter: delimiter?,
        // `_csv.reader` won't accept an empty quotechar, so upstream falls back
        // to `"` when the scan found no quotes at all.
        quotechar: quote.unwrap_or('"'),
        doublequote: true,
        skipinitialspace,
    })
}

/// Port of `csv.Sniffer._guess_quote_and_delimiter`: look for text enclosed in
/// two identical quotes that are themselves bracketed by the same character.
///
/// CPython uses four backreferencing regexes (`(?P=quote)`, `(?P=delim)`),
/// which no Rust regex engine can express, so they are scanned by hand below.
/// The first pattern that hits anywhere decides; the most frequent quote wins,
/// and so does the most frequent delimiter seen beside it.
fn guess_quote_and_delimiter(
    data: &[char],
    delimiters: Option<&[char]>,
) -> (Option<char>, Option<char>, bool) {
    let hits = quote_hits(data);
    if hits.is_empty() {
        return (None, None, false);
    }

    // Insertion-ordered tallies: Python's `max(dict, key=dict.get)` returns the
    // FIRST key holding the maximum, so the order these were first seen in
    // decides ties.
    let mut quotes: Vec<(char, usize)> = Vec::new();
    let mut delims: Vec<(char, usize)> = Vec::new();
    let mut spaces = 0usize;
    fn bump(table: &mut Vec<(char, usize)>, key: char) {
        match table.iter_mut().find(|(existing, _)| *existing == key) {
            Some(entry) => entry.1 += 1,
            None => table.push((key, 1)),
        }
    }
    for hit in &hits {
        bump(&mut quotes, hit.quote);
        // The fourth pattern has no delimiter group at all, so it contributes
        // only a quote — upstream `continue`s past both tallies below.
        let Some(delim) = hit.delim else { continue };
        if delimiters.is_none_or(|allowed| allowed.contains(&delim)) {
            bump(&mut delims, delim);
        }
        if hit.space {
            spaces += 1;
        }
    }

    let first_max = |table: &[(char, usize)]| -> Option<(char, usize)> {
        let mut best: Option<(char, usize)> = None;
        for &(key, count) in table {
            if best.is_none_or(|(_, seen)| count > seen) {
                best = Some((key, count));
            }
        }
        best
    };
    let quotechar = first_max(&quotes).map(|(key, _)| key);
    match first_max(&delims) {
        Some((delim, count)) => (quotechar, Some(delim), count == spaces),
        // A single column of quoted data: quotes but nothing bracketing them.
        None => (quotechar, None, false),
    }
}

/// One of CPython's four quote/delimiter patterns, scanned over the sample.
type QuoteScan = fn(&[char]) -> Vec<QuoteHit>;

/// Run CPython's four quote/delimiter patterns in order, returning the hits of
/// the first that matches anything.
fn quote_hits(data: &[char]) -> Vec<QuoteHit> {
    let scans: [QuoteScan; 4] = [
        scan_delim_quote_delim,
        scan_line_quote_delim,
        scan_delim_quote_line,
        scan_line_quote_line,
    ];
    for scan in scans {
        let hits = scan(data);
        if !hits.is_empty() {
            return hits;
        }
    }
    Vec::new()
}

/// `(?P<delim>[^\w\n"'])(?P<space> ?)(?P<quote>["']).*?(?P=quote)(?P=delim)` —
/// `,"some text",`. The ` ?` needs no backtracking: if the space is there and
/// the next character is not a quote, dropping the space only offers the space
/// itself as the quote, which it is not.
fn scan_delim_quote_delim(data: &[char]) -> Vec<QuoteHit> {
    scan_delim_quote(data, |data, quote, delim, from| {
        let mut k = from;
        while k + 1 < data.len() {
            if data[k] == quote && data[k + 1] == delim {
                return Some(k + 2);
            }
            k += 1;
        }
        None
    })
}

/// `(?P<delim>[^\w\n"'])(?P<space> ?)(?P<quote>["']).*?(?P=quote)(?:$|\n)` —
/// `,"some text"` at the end of a line.
fn scan_delim_quote_line(data: &[char]) -> Vec<QuoteHit> {
    scan_delim_quote(data, |data, quote, _delim, from| {
        let mut k = from;
        while k < data.len() {
            if data[k] == quote && (k + 1 == data.len() || data[k + 1] == '\n') {
                // `$` is zero-width and the engine prefers it, so the match ends
                // at the closing quote either way.
                return Some(k + 1);
            }
            k += 1;
        }
        None
    })
}

/// The shared `<delim><space?><quote> … ` head of patterns one and three;
/// `close` finds the closing quote and reports where the match ends.
fn scan_delim_quote(
    data: &[char],
    close: fn(&[char], char, char, usize) -> Option<usize>,
) -> Vec<QuoteHit> {
    let mut hits = Vec::new();
    let mut i = 0;
    while i < data.len() {
        if is_delimiter_char(data[i]) {
            let delim = data[i];
            let mut j = i + 1;
            let mut space = false;
            if j < data.len() && data[j] == ' ' {
                space = true;
                j += 1;
            }
            if j < data.len() && is_quote_char(data[j]) {
                let quote = data[j];
                if let Some(end) = close(data, quote, delim, j + 1) {
                    hits.push(QuoteHit {
                        quote,
                        delim: Some(delim),
                        space,
                    });
                    i = end;
                    continue;
                }
            }
        }
        i += 1;
    }
    hits
}

/// `(?:^|\n)(?P<quote>["']).*?(?P=quote)(?P<delim>[^\w\n"'])(?P<space> ?)` —
/// `"some text",` at the start of a line.
fn scan_line_quote_delim(data: &[char]) -> Vec<QuoteHit> {
    scan_line_quote(data, |data, quote, from| {
        let mut k = from;
        while k + 1 < data.len() {
            if data[k] == quote && is_delimiter_char(data[k + 1]) {
                let space = k + 2 < data.len() && data[k + 2] == ' ';
                return Some((Some(data[k + 1]), space, if space { k + 3 } else { k + 2 }));
            }
            k += 1;
        }
        None
    })
}

/// `(?:^|\n)(?P<quote>["']).*?(?P=quote)(?:$|\n)` — a whole line that is one
/// quoted field, with no delimiter to learn from.
fn scan_line_quote_line(data: &[char]) -> Vec<QuoteHit> {
    scan_line_quote(data, |data, quote, from| {
        let mut k = from;
        while k < data.len() {
            if data[k] == quote && (k + 1 == data.len() || data[k + 1] == '\n') {
                return Some((None, false, k + 1));
            }
            k += 1;
        }
        None
    })
}

/// The shared `(?:^|\n)<quote> … ` head of patterns two and four; `close`
/// reports `(delimiter, saw a space, match end)`.
#[allow(clippy::type_complexity)]
fn scan_line_quote(
    data: &[char],
    close: fn(&[char], char, usize) -> Option<(Option<char>, bool, usize)>,
) -> Vec<QuoteHit> {
    let mut hits = Vec::new();
    let mut i = 0;
    while i < data.len() {
        // `^` is zero-width at a line start; the `\n` branch consumes the
        // newline and puts the quote on the character after it. The engine tries
        // them in that order at each position.
        let mut starts: Vec<usize> = Vec::new();
        if i == 0 || data[i - 1] == '\n' {
            starts.push(i);
        }
        if data[i] == '\n' {
            starts.push(i + 1);
        }
        let mut advanced = false;
        for quote_at in starts {
            if quote_at >= data.len() || !is_quote_char(data[quote_at]) {
                continue;
            }
            let quote = data[quote_at];
            if let Some((delim, space, end)) = close(data, quote, quote_at + 1) {
                hits.push(QuoteHit {
                    quote,
                    delim,
                    space,
                });
                i = end;
                advanced = true;
                break;
            }
        }
        if !advanced {
            i += 1;
        }
    }
    hits
}

/// Port of `csv.Sniffer._guess_delimiter`: the character whose per-line
/// occurrence count is most consistent across the sample wins.
fn guess_delimiter(sample: &str, delimiters: Option<&[char]>) -> (Option<char>, bool) {
    // `filter(None, data.split('\n'))` — blank lines carry no evidence.
    let data: Vec<&str> = sample.split('\n').filter(|line| !line.is_empty()).collect();
    if data.is_empty() {
        return (None, false);
    }
    /// CPython scans `[chr(c) for c in range(127)]` — 7-bit ASCII.
    const ASCII: usize = 127;

    let chunk_length = 10.min(data.len());
    let mut iteration = 0usize;
    // Per character, an insertion-ordered list of (occurrences on a line, how
    // many lines had exactly that many) — upstream's "meta-frequency".
    let mut char_frequency: Vec<Vec<(usize, usize)>> = vec![Vec::new(); ASCII];
    // The winning (frequency, confidence) per character. Confidence can go
    // negative once every competing frequency is subtracted, hence `isize`.
    let mut modes: Vec<Option<(usize, isize)>> = vec![None; ASCII];
    let mut delims: Vec<(char, (usize, isize))> = Vec::new();

    let (mut start, mut end) = (0usize, chunk_length);
    while start < data.len() {
        iteration += 1;
        for line in &data[start..end.min(data.len())] {
            for (code, table) in char_frequency.iter_mut().enumerate() {
                let c = code as u8 as char;
                // Counted even when zero: a character absent from a line is
                // evidence against it being the delimiter.
                let freq = line.matches(c).count();
                match table.iter_mut().find(|(seen, _)| *seen == freq) {
                    Some(entry) => entry.1 += 1,
                    None => table.push((freq, 1)),
                }
            }
        }

        for (code, items) in char_frequency.iter().enumerate() {
            if items.len() == 1 && items[0].0 == 0 {
                continue;
            }
            if items.len() > 1 {
                // The first frequency with the highest count, less the sum of
                // every other count.
                let mut best = 0usize;
                for (index, item) in items.iter().enumerate() {
                    if item.1 > items[best].1 {
                        best = index;
                    }
                }
                let others: usize = items
                    .iter()
                    .enumerate()
                    .filter(|(index, _)| *index != best)
                    .map(|(_, item)| item.1)
                    .sum();
                modes[code] = Some((items[best].0, items[best].1 as isize - others as isize));
            } else if let Some(&(freq, count)) = items.first() {
                modes[code] = Some((freq, count as isize));
            }
        }

        let total = (chunk_length * iteration).min(data.len()) as f64;
        let mut consistency = 1.0f64;
        let threshold = 0.9f64;
        while delims.is_empty() && consistency >= threshold {
            for (code, mode) in modes.iter().enumerate() {
                let Some((freq, count)) = *mode else { continue };
                let c = code as u8 as char;
                if freq > 0
                    && count > 0
                    && (count as f64 / total) >= consistency
                    && delimiters.is_none_or(|allowed| allowed.contains(&c))
                {
                    delims.push((c, (freq, count)));
                }
            }
            consistency -= 0.01;
        }

        if delims.len() == 1 {
            let delim = delims[0].0;
            return (Some(delim), saw_space_after(data[0], delim));
        }

        start = end;
        end += chunk_length;
    }

    if delims.is_empty() {
        return (None, false);
    }
    if delims.len() > 1 {
        for preferred in [',', '\t', ';', ' ', ':'] {
            if delims.iter().any(|(c, _)| *c == preferred) {
                return (Some(preferred), saw_space_after(data[0], preferred));
            }
        }
    }
    // `items = [(v, k) …]; items.sort()` — ordered by the mode, then the char.
    let best = delims
        .iter()
        .max_by_key(|(c, mode)| (*mode, *c))
        .expect("delims is non-empty");
    (Some(best.0), saw_space_after(data[0], best.0))
}

/// Upstream's `skipinitialspace` test: every delimiter on the first line is
/// followed by a space.
fn saw_space_after(line: &str, delimiter: char) -> bool {
    line.matches(delimiter).count() == line.matches(&format!("{delimiter} ")).count()
}

/// What `csv.Sniffer.has_header` decides a column holds.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ColumnType {
    /// Every value so far parsed as a Python `complex`.
    Number,
    /// They did not, but all had this many characters.
    Length(usize),
}

/// Whether a column is still in play, and what it has looked like so far.
#[derive(Debug, Clone, Copy)]
enum ColumnVote {
    /// In `columnTypes` with the value `None`: no data row typed it yet.
    Untyped,
    Typed(ColumnType),
    /// `del columnTypes[col]` — the column was inconsistent.
    Dropped,
}

/// Port of `csv.Sniffer.has_header`: if a column is one consistent type in every
/// row *except* the first, the first row is a label. Each column casts one vote.
///
/// The typing is CPython's current one — a single `complex` attempt, falling
/// back to the string's length. The historical `for thisType in [int, float,
/// complex]` loop is NOT equivalent: it makes a column mixing `10` and `9.5`
/// read as inconsistent (int then float), so `price,note / 10,aa / 9.5,bbb`
/// loses its header.
///
/// `None` is CPython's `csv.Error` escaping from the re-sniff, which upstream
/// handles the same way as a failed `sniff`.
fn has_header(sample: &str) -> Option<bool> {
    // Note the missing `delimiters` argument: upstream re-sniffs here with the
    // full candidate set, not the four it renders with.
    let dialect = sniff(sample, None)?;
    let mut rows = read_csv_rows(sample, &dialect).into_iter();
    let header = rows.next()?;
    let columns = header.len();
    let mut votes = vec![ColumnVote::Untyped; columns];

    for (checked, row) in rows.enumerate() {
        // An arbitrary cap, "to keep it sane" — the 22nd data row and beyond are
        // never looked at, however inconsistent they are.
        if checked > 20 {
            break;
        }
        if row.len() != columns {
            continue;
        }
        for (col, vote) in votes.iter_mut().enumerate() {
            if matches!(vote, ColumnVote::Dropped) {
                continue;
            }
            let this = if parses_as_complex(&row[col]) {
                ColumnType::Number
            } else {
                ColumnType::Length(row[col].chars().count())
            };
            match vote {
                ColumnVote::Untyped => *vote = ColumnVote::Typed(this),
                ColumnVote::Typed(known) if *known != this => *vote = ColumnVote::Dropped,
                _ => {}
            }
        }
    }

    let mut tally = 0isize;
    for (col, vote) in votes.iter().enumerate() {
        match vote {
            ColumnVote::Dropped => {}
            // `colType` is still `None`, and `None(header[col])` raises
            // TypeError — which counts as "the header does not fit the column".
            ColumnVote::Untyped => tally += 1,
            ColumnVote::Typed(ColumnType::Length(len)) => {
                if header[col].chars().count() == *len {
                    tally -= 1;
                } else {
                    tally += 1;
                }
            }
            ColumnVote::Typed(ColumnType::Number) => {
                if parses_as_complex(&header[col]) {
                    tally -= 1;
                } else {
                    tally += 1;
                }
            }
        }
    }
    Some(tally > 0)
}

/// Whether Python's `complex(value)` would succeed — the type test at the heart
/// of `has_header`.
///
/// `complex()` is much looser than "looks like a number": it takes surrounding
/// whitespace, one level of parentheses, a sign, `inf`/`infinity`/`nan` in any
/// case, an exponent, `_` digit separators and an imaginary `j` suffix. All of
/// that is honoured. The single narrowing is the digit set — Python accepts any
/// Unicode decimal digit, this accepts ASCII — which can only ever move one
/// has-header vote, and only for a column written in non-ASCII numerals.
fn parses_as_complex(value: &str) -> bool {
    let trimmed = value.trim();
    let body = match trimmed.strip_prefix('(') {
        Some(inner) => match inner.strip_suffix(')') {
            Some(inner) => inner.trim(),
            None => return false,
        },
        None if trimmed.ends_with(')') => return false,
        None => trimmed,
    };
    if body.is_empty() {
        return false;
    }
    // `a`, `aj`, or `a±bj`. The split is the first sign that is not an
    // exponent's, so `1e-5` stays one number.
    let chars: Vec<char> = body.chars().collect();
    let split = (1..chars.len())
        .find(|&i| matches!(chars[i], '+' | '-') && !matches!(chars[i - 1], 'e' | 'E'));
    match split {
        Some(index) => {
            let at: usize = chars[..index].iter().map(|c| c.len_utf8()).sum();
            let (real, imaginary) = body.split_at(at);
            is_float_literal(real) && is_imaginary_literal(imaginary)
        }
        None => is_float_literal(body) || is_imaginary_literal(body),
    }
}

/// A Python float literal: optional sign, then `inf`/`infinity`/`nan`, or
/// digits with an optional fraction and exponent.
fn is_float_literal(value: &str) -> bool {
    let body = value.strip_prefix(['+', '-']).unwrap_or(value);
    if matches!(
        body.to_ascii_lowercase().as_str(),
        "inf" | "infinity" | "nan"
    ) {
        return true;
    }
    let chars: Vec<char> = body.chars().collect();
    let mut index = 0usize;
    let mut digits = 0usize;
    let take_digits = |index: &mut usize, digits: &mut usize| {
        while *index < chars.len() && (chars[*index].is_ascii_digit() || chars[*index] == '_') {
            if chars[*index].is_ascii_digit() {
                *digits += 1;
            }
            *index += 1;
        }
    };
    take_digits(&mut index, &mut digits);
    if index < chars.len() && chars[index] == '.' {
        index += 1;
        take_digits(&mut index, &mut digits);
    }
    if digits == 0 {
        return false;
    }
    if index < chars.len() && (chars[index] == 'e' || chars[index] == 'E') {
        index += 1;
        if index < chars.len() && matches!(chars[index], '+' | '-') {
            index += 1;
        }
        let mut exponent = 0usize;
        take_digits(&mut index, &mut exponent);
        if exponent == 0 {
            return false;
        }
    }
    index == chars.len()
}

/// `<number>j`, or a bare `j`/`+j`/`-j` (which Python reads as ±1j).
fn is_imaginary_literal(value: &str) -> bool {
    let Some(body) = value.strip_suffix(['j', 'J']) else {
        return false;
    };
    matches!(body, "" | "+" | "-") || is_float_literal(body)
}

/// Where [`read_csv_rows`] is within a record. Port of `_csv.c`'s reader states
/// (its `EAT_CRNL` is unreachable here: universal newlines ran first).
enum State {
    StartRecord,
    StartField,
    InField,
    InQuotedField,
    QuoteInQuotedField,
}

/// Parse `content` into rows of fields with `dialect`. Port of `_csv.reader`'s
/// state machine, minus the escape character (no sniffed dialect sets one) and
/// `strict` (always off, as `QUOTE_MINIMAL` leaves it).
///
/// A blank line yields an **empty** row, as `csv.reader` does — upstream drops
/// those before building the table, where a `[""]` row would have drawn a
/// spurious blank line in it. `\r` never reaches here: the reader has already
/// applied Python's universal newlines.
fn read_csv_rows(content: &str, dialect: &Dialect) -> Vec<Vec<String>> {
    // Strip a leading UTF-8 BOM so it doesn't cling to the first header cell.
    let content = content.strip_prefix('\u{feff}').unwrap_or(content);
    let mut rows: Vec<Vec<String>> = Vec::new();
    let mut row: Vec<String> = Vec::new();
    let mut field = String::new();
    let mut state = State::StartRecord;

    for c in content.chars() {
        match state {
            State::StartRecord => {
                if c == '\n' {
                    rows.push(Vec::new());
                } else {
                    state = State::StartField;
                    // Re-dispatch this character as the start of a field.
                    read_csv_char(c, dialect, &mut state, &mut field, &mut row, &mut rows);
                }
            }
            _ => read_csv_char(c, dialect, &mut state, &mut field, &mut row, &mut rows),
        }
    }
    if !matches!(state, State::StartRecord) {
        row.push(std::mem::take(&mut field));
        row.shrink_to_fit();
        rows.push(std::mem::take(&mut row));
    }
    rows
}

/// One character of [`read_csv_rows`]'s state machine, for every state but
/// `StartRecord`.
fn read_csv_char(
    c: char,
    dialect: &Dialect,
    state: &mut State,
    field: &mut String,
    row: &mut Vec<String>,
    rows: &mut Vec<Vec<String>>,
) {
    let end_record = |field: &mut String, row: &mut Vec<String>, rows: &mut Vec<Vec<String>>| {
        row.push(std::mem::take(field));
        // Completed records keep only their fields, not Vec's spare growth slots.
        row.shrink_to_fit();
        rows.push(std::mem::take(row));
    };
    match state {
        State::StartRecord => unreachable!("handled by the caller"),
        State::StartField => {
            if c == '\n' {
                end_record(field, row, rows);
                *state = State::StartRecord;
            } else if c == dialect.quotechar {
                *state = State::InQuotedField;
            } else if c == ' ' && dialect.skipinitialspace {
                // Stay in StartField, swallowing the padding.
            } else if c == dialect.delimiter {
                row.push(std::mem::take(field));
            } else {
                field.push(c);
                *state = State::InField;
            }
        }
        State::InField => {
            if c == '\n' {
                end_record(field, row, rows);
                *state = State::StartRecord;
            } else if c == dialect.delimiter {
                row.push(std::mem::take(field));
                *state = State::StartField;
            } else {
                field.push(c);
            }
        }
        State::InQuotedField => {
            if c == dialect.quotechar {
                *state = if dialect.doublequote {
                    State::QuoteInQuotedField
                } else {
                    // Without doublequote the quote simply ends the quoted part;
                    // anything after it, quotes included, is literal.
                    State::InField
                };
            } else {
                field.push(c);
            }
        }
        State::QuoteInQuotedField => {
            if c == dialect.quotechar {
                field.push(c);
                *state = State::InQuotedField;
            } else if c == dialect.delimiter {
                row.push(std::mem::take(field));
                *state = State::StartField;
            } else if c == '\n' {
                end_record(field, row, rows);
                *state = State::StartRecord;
            } else {
                field.push(c);
                *state = State::InField;
            }
        }
    }
}

/// Whether `value` matches rich-cli's `is_number`, i.e. Python's
/// `re.fullmatch(r"\-?[0-9]*?\.?[0-9]*?", value)`.
///
/// Note how loose that is: `-`, `.`, `-.` and the empty string all pass, and a
/// leading space does not. The caller only asks about non-empty cells.
fn is_number(value: &str) -> bool {
    let body = value.strip_prefix('-').unwrap_or(value);
    let (integer, fraction) = match body.split_once('.') {
        Some((integer, fraction)) => (integer, Some(fraction)),
        None => (body, None),
    };
    let digits = |part: &str| part.bytes().all(|b| b.is_ascii_digit());
    digits(integer) && fraction.is_none_or(digits)
}

/// Build the CSV table for `content`, sniffing the dialect and the header the
/// way upstream's `render_csv` does.
///
/// `fallback_delimiter` is the dialect to use when `csv.Sniffer` raises, and
/// `None` means upstream has none to offer: its `except csv.Error` arm falls
/// back to `csv.get_dialect("excel")` for a resource whose name ends `.csv`
/// and to `"excel-tab"` for one ending `.tsv`, and for **everything else** —
/// any other extension, a bare name, a URL, stdin — calls
/// `on_error(str(error))`, which prints the message and exits non-zero.
///
/// So `None` here is a failure, and the caller must report it. Rendering a
/// fabricated one-column table at exit 0 instead is the worst possible
/// outcome: `rich --csv "$f" && publish` proceeds on a file nothing could
/// parse, with empty stderr to say so.
fn build_csv_table(
    content: &str,
    fallback_delimiter: Option<char>,
    title: Option<&str>,
    caption: Option<&str>,
) -> Option<Table> {
    // The sniffer sees only the first 1024 *characters* — upstream's
    // `csv_data[:1024]` — however long the file is.
    let sample: String = content.chars().take(1024).collect();
    let sniffed = sniff(&sample, Some(&[',', '\t', '|', ';'])).zip(has_header(&sample));
    let (dialect, header) = match sniffed {
        Some(sniffed) => sniffed,
        None => (Dialect::excel(fallback_delimiter?), true),
    };
    Some(render_csv(
        read_csv_rows(content, &dialect),
        header,
        title,
        caption,
    ))
}

/// The dialect upstream falls back to when `csv.Sniffer` cannot read
/// `resource`, or `None` when it has none — a failure, not a default.
///
/// Upstream tests the **resource string**, not the detected language:
/// `resource.lower().endswith(".csv")` then `.endswith(".tsv")`. So a URL
/// ending `.tsv` gets the tab dialect, and `-` (stdin) gets nothing.
fn csv_fallback_delimiter(resource: Option<&str>) -> Option<char> {
    let name = resource.unwrap_or_default().to_lowercase();
    if name.ends_with(".csv") {
        Some(',')
    } else if name.ends_with(".tsv") {
        Some('\t')
    } else {
        None
    }
}

/// Build a table from parsed CSV `rows`, mirroring rich-cli's `render_csv`: a
/// blue border, `HEAVY_HEAD` when the sniffer found a header and `SQUARE` when
/// it did not, and any all-numeric column right-justified with bold-green body
/// and header cells.
fn render_csv(
    rows: Vec<Vec<String>>,
    has_header: bool,
    title: Option<&str>,
    caption: Option<&str>,
) -> Table {
    let mut table = Table::new()
        .border_style(Style::parse("blue").expect("valid style"))
        .show_header(has_header)
        .box_set(if has_header { HEAVY_HEAD } else { SQUARE });
    if let Some(title) = title {
        table = table.title(title);
    }
    if let Some(caption) = caption {
        table = table.caption(caption);
    }

    let empty: Vec<String> = Vec::new();
    let (header, body) = if has_header {
        match rows.split_first() {
            Some((header, body)) => (header, body),
            None => return table,
        }
    } else {
        (&empty, rows.as_slice())
    };
    // `[row for row in rows if row]`: a blank line is not a table row.
    let data: Vec<&Vec<String>> = body.iter().filter(|row| !row.is_empty()).collect();

    // A row may carry more fields than the header names, and upstream's
    // `table.add_row(*row)` grows the table to hold them. Columns came from the
    // header alone, so those fields had nowhere to go and were dropped -- a
    // silent data loss in a tool whose job is showing you the file.
    let widest = data.iter().map(|row| row.len()).max().unwrap_or(0);
    let columns = header.len().max(widest);

    for index in 0..columns {
        // A column is numeric when no data cell is a non-empty non-number. A
        // row too SHORT to reach the column disqualifies it (upstream's
        // `except Exception: break`), while an empty cell does not; and an
        // empty data set counts as numeric, as upstream's `for … else` does.
        let numeric = data.iter().all(|row| match row.get(index) {
            Some(value) => value.is_empty() || is_number(value),
            None => false,
        });
        let name = header.get(index).map(String::as_str).unwrap_or("");
        if numeric {
            table.add_column_justify(name, Justify::Right);
            table.column_style(Style::parse("bold green").expect("valid style"));
            table.column_header_fill(Style::parse("bold green").expect("valid style"));
        } else {
            table.add_column(name);
        }
    }
    // Measurement/style inference is complete. Move the parsed cells into the
    // table rather than retaining and cloning the complete input row set.
    drop(data);
    table.extend_owned_rows(
        rows.into_iter()
            .skip(usize::from(has_header))
            .filter(|row| !row.is_empty())
            .collect(),
    );
    table
}

/// Join a notebook cell/output `source` field (a JSON string, or an array of
/// line strings that already include their trailing newlines).
fn join_source(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::String(s) => s.clone(),
        serde_json::Value::Array(a) => a.iter().filter_map(|v| v.as_str()).collect(),
        _ => String::new(),
    }
}

/// Join a notebook `traceback`, whose elements are lines WITHOUT trailing
/// newlines (unlike `source`/`text`, which carry their own). Using
/// [`join_source`] here fused a whole stack trace onto one line.
fn join_traceback(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::String(s) => s.clone(),
        serde_json::Value::Array(a) => a
            .iter()
            .filter_map(|v| v.as_str())
            .collect::<Vec<_>>()
            .join(
                "
",
            ),
        _ => String::new(),
    }
}

/// Build an `In [n]:` / `Out[n]:` execution-count label. Port of rich-cli's
/// `[green]In [[#66ff00]{count}[/#66ff00]]:[/green]` markup (built as spans to
/// avoid markup-escaping the literal brackets).
fn io_label(word: &str, count: Option<i64>, base: &str, number: &str) -> Text {
    let base_style = Style::parse(base).ok();
    let number_style = Style::parse(number).ok();
    let n = count.map_or_else(|| " ".to_string(), |c| c.to_string());
    let mut text = Text::new("");
    text.append(&format!("{word}["), base_style.clone().map(Into::into));
    text.append(&n, number_style.map(Into::into));
    text.append("]:", base_style.map(Into::into));
    text
}

/// Port of the Group returned by rich-cli's `render_ipynb`. Keeping the cells
/// composable lets the common padding/panel/style/width/alignment chain apply.
struct Notebook {
    items: Vec<Box<dyn Renderable>>,
    // Console.print(justify=...) also reaches the group's Text children in
    // upstream. Their individual lines align within the group's measured width.
    justify: Option<Justify>,
}

impl Renderable for Notebook {
    fn rich_render(&self, console: &Console, options: &ConsoleOptions) -> Vec<Segment> {
        let mut options = options.clone();
        if let Some(justify) = self.justify {
            options.justify = justify;
        }
        let mut segments = Vec::new();
        for item in &self.items {
            let rendered = item.rich_render(console, &options);
            if !rendered.is_empty() {
                segments.extend(rendered);
                segments.push(Segment::line());
            }
        }
        // Console supplies the final newline. Empty groups produce no output.
        if !segments.is_empty() {
            segments.pop();
        }
        segments
    }

    fn measure(&self, console: &Console, options: &ConsoleOptions) -> Measurement {
        self.items
            .iter()
            .map(|item| item.measure(console, options))
            .fold(Measurement::new(0, 0), |width, item| {
                Measurement::new(
                    width.minimum.max(item.minimum),
                    width.maximum.max(item.maximum),
                )
            })
    }
}

/// Text.from_ansi joins decoded lines, preserving their style spans.
fn notebook_ansi(source: &str) -> Text {
    let mut result = Text::new("");
    for (index, line) in AnsiDecoder::new().decode(source).iter().enumerate() {
        if index > 0 {
            result.append("\n", None);
        }
        result = result.append_text(line);
    }
    result
}

/// Port of rich-cli 1.8.1's notebook cell/output grouping. Parse once, then use
/// the same renderable for terminal output, paging and recorded exports.
fn build_ipynb(
    notebook: &serde_json::Value,
    hyperlinks: bool,
    justify: Option<Justify>,
) -> Notebook {
    let language = notebook["metadata"]["kernelspec"]["language"]
        .as_str()
        .or_else(|| notebook["metadata"]["language_info"]["name"].as_str())
        .unwrap_or("python");
    let empty = Vec::new();
    let mut items: Vec<Box<dyn Renderable>> = Vec::new();
    let mut new_line = true;
    for cell in notebook["cells"].as_array().unwrap_or(&empty) {
        if new_line {
            items.push(text(""));
        }
        if cell.get("execution_count").is_some() {
            items.push(Box::new(io_label(
                "In ",
                cell["execution_count"].as_i64().filter(|n| *n != 0),
                "green",
                "#66ff00",
            )));
        }
        let source = join_source(&cell["source"]);
        items.push(match cell["cell_type"].as_str().unwrap_or("") {
            "markdown" => Box::new(build_markdown(&source, hyperlinks)),
            "code" => Box::new(
                Panel::new(Box::new(Syntax::new(&source, language)))
                    .border_style(Style::parse("dim").expect("valid style")),
            ),
            _ => text(&source),
        });
        new_line = true;
        for output in cell["outputs"].as_array().unwrap_or(&empty) {
            let rendered = match output["output_type"].as_str().unwrap_or("") {
                "stream" => {
                    new_line = false;
                    notebook_ansi(&join_source(&output["text"]))
                }
                "error" => {
                    new_line = true;
                    notebook_ansi(join_traceback(&output["traceback"]).trim_end())
                }
                "execute_result" => {
                    new_line = true;
                    let mut label = io_label(
                        "Out",
                        output["execution_count"].as_i64().filter(|n| *n != 0),
                        "red",
                        "#ee4b2b",
                    );
                    label.append("\n", None);
                    label.append_text(&notebook_ansi(&join_source(&output["data"]["text/plain"])))
                }
                _ => continue,
            };
            items.push(Box::new(rendered));
        }
    }
    Notebook { items, justify }
}

#[cfg(feature = "art")]
fn diff_threshold_exceeded(changed: f32, limit: f32) -> bool {
    // Use the formatter's rounding for BOTH displayed operands, including
    // ties. f32::round uses a different tie rule from the report's formatting.
    let displayed = |value: f32| {
        format!("{value:.1}")
            .parse::<f32>()
            .expect("formatted percentage is a number")
    };
    displayed(changed) > displayed(limit)
}

/// Compare two images perceptually and report where they differ.
///
/// Prints a heat map of the ΔE field plus a ranked table of changed regions.
/// The table is the point: it is text, so it survives a pipe, a log, and a CI
/// transcript, which a picture does not.
///
/// With `--threshold`, exits non-zero when the changed percentage exceeds it,
/// which is what makes this usable as a visual-regression gate.
/// Open an image file, translating a few common failure modes (a directory
/// instead of a file, an unrecognized extension) into one actionable message.
/// Shared by `--diff` (which loads two images) and `--image` (which loads
/// one) so neither reimplements the other's error handling.
///
/// The directory check reached the plain read path but not this one, so
/// `rich --diff a.png somedir` still reported "Access is denied".
#[cfg(feature = "art")]
fn open_image_path(path: &str) -> Result<rich_art::image::DynamicImage, String> {
    if std::path::Path::new(path).is_dir() {
        return Err(format!("cannot read {path}: is a directory, not a file"));
    }
    match rich_art::image::open(path) {
        Ok(image) => Ok(image),
        Err(err) => {
            use rich_art::image::error::{ImageFormatHint, UnsupportedErrorKind};
            let hint = match &err {
                rich_art::image::ImageError::Unsupported(error) => match error.kind() {
                    UnsupportedErrorKind::Format(ImageFormatHint::PathExtension(ext)) =>
                        Some(format!("unsupported image extension {}; use a supported image format such as PNG or JPEG", ext.display())),
                    _ => None,
                },
                _ => None,
            };
            Err(format!(
                "cannot read {path}: {}",
                hint.unwrap_or_else(|| err.to_string())
            ))
        }
    }
}

/// Map the CLI's own `ImageMode` (which also carries `None`, meaning "print no
/// picture at all") onto `rich_art`'s `ImageMode` (which has no such variant ?
/// a facade that always draws something has no notion of "nothing"). Argument
/// parsing rejects `--image-mode none` together with `--image` before this can
/// ever see it.
#[cfg(feature = "art")]
fn to_art_image_mode(mode: ImageMode) -> rich_art::ImageMode {
    match mode {
        ImageMode::Auto => rich_art::ImageMode::Auto,
        ImageMode::Sixel => rich_art::ImageMode::Sixel,
        ImageMode::Blocks => rich_art::ImageMode::Blocks,
        ImageMode::Braille => rich_art::ImageMode::Braille,
        ImageMode::Ascii => rich_art::ImageMode::Ascii,
        ImageMode::None => unreachable!("--image-mode none is rejected during argument parsing"),
    }
}

/// Render one still image through rich-art's [`rich_art::ImageArt`] facade.
///
/// This function only opens the file and maps CLI flags onto the facade's
/// builder; picking a backend, sizing and colour handling all stay inside
/// [`rich_art::ImageArt`]; nothing here reimplements that logic (see
/// AGENTS.md's mirror/ext boundary).
#[cfg(feature = "art")]
fn run_image(cli: &Cli, console: &Console, export: &Export) -> ExitCode {
    use rich_art::ImageArt;

    let Some(resource) = cli.resource.as_deref() else {
        return fail(
            cli,
            ExitClass::Usage,
            "--image requires an image file: rich --image photo.png (or `-` for stdin)",
        );
    };

    let image = if resource == "-" {
        let mut buffer = Vec::new();
        if let Err(err) = std::io::stdin().read_to_end(&mut buffer) {
            return fail(cli, ExitClass::Input, format!("cannot read stdin: {err}"));
        }
        match rich_art::image::load_from_memory(&buffer) {
            Ok(image) => image,
            Err(err) => {
                return fail(
                    cli,
                    ExitClass::Input,
                    format!("cannot decode image from stdin: {err}"),
                )
            }
        }
    } else {
        match open_image_path(resource) {
            Ok(image) => image,
            Err(message) => return fail(cli, ExitClass::Input, message),
        }
    };

    let width = cli.width.unwrap_or_else(|| console.width());
    let mut art = ImageArt::new(image)
        .mode(to_art_image_mode(cli.image_mode))
        .width(width)
        .color(!cli.no_color);
    if let Some(height) = cli.height {
        art = art.height(height);
    }

    if let Some(fit) = cli.image_fit.as_deref() {
        art = art.fit(match fit {
            "cover" => rich_art::ImageFit::Cover,
            _ => rich_art::ImageFit::Contain,
        });
    }
    if let Some(background) = cli.image_background {
        art = art.background(background);
    }

    // Validate up front: `Renderable::rich_render` cannot fail and would
    // silently fall back to ASCII, which is the wrong answer for a CLI that
    // promised a clear error (e.g. `--image-mode sixel` on a build without
    // the `sixel` feature, or an image Sixel cannot encode).
    let options = console.options();
    if let Err(err) = art.render(console, &options) {
        return fail(cli, ExitClass::Input, err.to_string());
    }

    if let Err(message) = emit(console, export, |c| c.print(&art)) {
        return fail(cli, ExitClass::Input, message);
    }
    success(cli)
}

#[cfg(feature = "art")]
fn run_diff(cli: &Cli, console: &Console, export: &Export) -> ExitCode {
    use rich::Table;
    use rich_art::imagediff::{diff, DiffSettings};
    use rich_art::{AsciiArt, BlockArt, BrailleArt, SixelArt};

    let (before_path, after_path) = (&cli.resources[0], &cli.resources[1]);
    let before = match open_image_path(before_path) {
        Ok(image) => image,
        Err(message) => return fail(cli, ExitClass::Input, message),
    };
    let after = match open_image_path(after_path) {
        Ok(image) => image,
        Err(message) => return fail(cli, ExitClass::Input, message),
    };

    let report = match diff(&before, &after, &DiffSettings::default()) {
        Ok(report) => report,
        Err(err) => return fail(cli, ExitClass::Data, err.to_string()),
    };

    let width = cli.width.unwrap_or_else(|| console.width());
    let changed = report.changed_fraction * 100.0;
    let naive = report.naive_changed_fraction * 100.0;

    // Decided before rendering so the verdict can be part of the output (and
    // therefore part of an --export-svg capture), while the exit code is
    // settled outside the closure.
    // Compare the number that is PRINTED, not the one behind it. Comparing full
    // precision against a one-decimal display produced "FAIL 5.4% changed, limit
    // 5.4%" -- a verdict that contradicts itself and cannot be explained from
    // the output, which is what anyone tuning a threshold to the reported figure
    // runs straight into.
    let failed = cli
        .diff_threshold
        .is_some_and(|limit| diff_threshold_exceeded(changed, limit));

    let render_report = |c: &Console, for_export: bool| {
        // Leave room for the summary, the table and the prompt, so the top of
        // the picture is not scrolled off before the reader sees it.
        let rows_cap = console.height().saturating_sub(14).clamp(6, 30);

        // Resolve `auto` from what this console can ACTUALLY do, not from the
        // --no-color flag alone. Redirected output has no colour, and a
        // half-block render without colour is a solid rectangle of identical
        // characters -- 30 rows carrying no information. Sixel is a control
        // sequence, so it is dropped entirely when the destination is not a
        // terminal.
        let has_color = c.color_system().is_some() && !cli.no_color;
        let is_terminal = c.is_terminal();
        let mut mode = cli.image_mode;
        if mode == ImageMode::Auto {
            if !has_color && !for_export && cli.report_format == ReportFormat::Human {
                eprintln!("rich: auto image mode has no terminal colour, drawing the diff as ASCII instead");
            }
            mode = if !has_color {
                ImageMode::Ascii
            } else if is_terminal && rich_art::sixel::is_probably_supported() {
                ImageMode::Sixel
            } else {
                ImageMode::Blocks
            };
        }

        // An explicit choice still has to produce something. Downgrade rather
        // than emit a rectangle of identical blocks or nothing at all, and say
        // why on stderr so the change is visible rather than mysterious.
        if mode == ImageMode::Blocks && !has_color {
            if !for_export && cli.report_format == ReportFormat::Human {
                eprintln!("rich: no colour available, drawing the diff as ASCII art");
            }
            mode = ImageMode::Ascii;
        }
        if mode == ImageMode::Sixel && !is_terminal {
            if cli.image_mode != ImageMode::Sixel
                && !for_export
                && cli.report_format == ReportFormat::Human
            {
                eprintln!(
                    "rich: Sixel graphics need a terminal, drawing the diff as {} instead",
                    if has_color { "blocks" } else { "ASCII art" }
                );
            }
            mode = if has_color {
                ImageMode::Blocks
            } else {
                ImageMode::Ascii
            };
        }

        match mode {
            ImageMode::None => {}
            ImageMode::Ascii => c.print(
                &AsciiArt::new(report.heatmap())
                    .width(width)
                    .color(has_color),
            ),
            ImageMode::Blocks => c.print(
                &BlockArt::new(report.heatmap())
                    .width(width)
                    .height(rows_cap),
            ),
            ImageMode::Braille => c.print(
                &BrailleArt::new(report.heatmap())
                    .width(width)
                    .height(rows_cap),
            ),
            ImageMode::Sixel => {
                let art = SixelArt::new(report.heatmap())
                    .width(width)
                    .height(rows_cap);
                // Encoding can still fail on a terminal; the report must stay
                // useful, so fall back rather than leaving an empty gap.
                if art.encode(width).is_some() {
                    c.print(&art);
                } else {
                    if cli.report_format == ReportFormat::Human {
                        eprintln!("rich: could not encode Sixel, drawing the diff as blocks");
                    }
                    c.print(
                        &BlockArt::new(report.heatmap())
                            .width(width)
                            .height(rows_cap),
                    );
                }
            }
            ImageMode::Auto => unreachable!("resolved above"),
        }
        // The blank line separates the picture from the summary, so it belongs
        // to the picture — with --image-mode none it was just a stray first
        // line in every report and every redirected file.
        if mode != ImageMode::None {
            c.print_str("");
        }
        c.print_str(&format!(
            "[bold]{changed:.1}%[/] of the canvas changed perceptibly \
             [dim](a plain pixel diff would say {naive:.1}%)[/]"
        ));

        if report.regions.is_empty() {
            c.print_str("[dim]No region large enough to report.[/]");
        } else {
            let mut table = Table::new().title("Where it changed");
            table.add_column("#");
            table.add_column_justify("Share", rich::Justify::Right);
            table.add_column_justify("Mean ΔE", rich::Justify::Right);
            table.add_column_justify("Area px", rich::Justify::Right);
            table.add_column("Box (x,y w×h)");
            for (rank, r) in report.regions.iter().enumerate() {
                table.add_row(&[
                    &format!("{}", rank + 1),
                    &format!("{:.0}%", r.share_of_change * 100.0),
                    &format!("{:.1}", r.mean_delta_e),
                    &format!("{}", r.area_px),
                    &format!("{},{} {}×{}", r.x, r.y, r.width, r.height),
                ]);
            }
            c.print(&table);
        }

        // The gate is compared against the perceptual figure, never the naive
        // one — gating on a pixel diff is what makes visual regression testing
        // useless in the first place.
        if let Some(limit) = cli.diff_threshold {
            if failed {
                c.print_str(&format!(
                    "[bold red]FAIL[/] {changed:.1}% changed, limit {limit:.1}%"
                ));
            } else {
                c.print_str(&format!(
                    "[bold green]OK[/] {changed:.1}% changed, within {limit:.1}%"
                ));
            }
        }
    };

    let terminal_only = Export {
        html_path: None,
        svg_path: None,
        ..*export
    };
    let mut wrote = emit(console, &terminal_only, |c| render_report(c, false));
    if export.html_path.is_some() || export.svg_path.is_some() {
        // HTML/SVG support truecolor independently of stdout. Render the already
        // loaded report for that destination; never reread images or recompute
        // the comparison. A nonterminal console prevents Sixel control data.
        let mut export_console = Console::builder()
            .force_terminal(false)
            .color_system(Some(ColorSystem::Truecolor))
            .no_color(cli.no_color)
            .width(console.width())
            .height(console.height())
            .theme(console.theme().clone())
            .build();
        export_console.install_extensions();
        let segments = export_console.record_output(|c| render_report(c, true));
        wrote = wrote.and_then(|()| save_exports(&export_console, export, &segments));
    }

    if let Err(message) = wrote {
        return fail(cli, ExitClass::Input, message);
    }
    if failed {
        return fail(cli, ExitClass::Gate, "diff threshold exceeded");
    }
    success(cli)
}

/// Animate every `--gif` resource at once, sharing the console width.
#[cfg(feature = "art")]
fn play_gifs(cli: &Cli, console: &Console) -> ExitCode {
    use rich_art::{AnimatedArt, Repeat, Stage};

    if cli.resources.is_empty() {
        return fail(cli, ExitClass::Usage, "--gif needs at least one GIF path");
    }
    let count = cli.resources.len();
    const GAP: usize = 2;

    // Share the width between the animations, leaving room for the gaps.
    let total = cli.width.unwrap_or_else(|| console.width());
    let per_gif = total
        .saturating_sub(GAP * count.saturating_sub(1))
        .checked_div(count)
        .unwrap_or(total)
        .max(8);

    let repeat = match cli.loops {
        Some(0) => Repeat::Forever,
        Some(n) => Repeat::Times(n),
        None => Repeat::Times(1),
    };

    let mut stage = Stage::new().gap(GAP);
    for path in &cli.resources {
        match AnimatedArt::from_path(path) {
            Ok(art) => {
                stage = stage.with(
                    art.width(per_gif)
                        .blocks(cli.extensions.gif_blocks())
                        .color(!cli.no_color)
                        .repeat(repeat)
                        // Colour art is byte-heavy; keep it comfortable.
                        .max_fps(30.0),
                );
            }
            Err(err) => {
                return fail(cli, ExitClass::Input, format!("cannot read {path}: {err}"));
            }
        }
    }

    if !console.is_terminal() && cli.report_format == ReportFormat::Human {
        eprintln!("rich: GIF animation needs a terminal; rendering the first frame only");
    }

    // `play` needs its own console (it moves into the Live display).
    let mut builder = Console::builder().no_color(cli.no_color);
    if let Some(width) = cli.width {
        builder = builder.width(width);
    }
    match stage.play_stdout(builder.build()) {
        Ok(()) => success(cli),
        Err(err) => fail(cli, ExitClass::Input, format!("playback failed: {err}")),
    }
}

/// Without the `art` feature there is no GIF support.
#[cfg(not(feature = "art"))]
fn play_gifs(_cli: &Cli, _console: &Console) -> ExitCode {
    fail(
        _cli,
        ExitClass::Usage,
        "this build has no GIF support (rebuild with the `art` feature)",
    )
}

/// Where a render action's output goes: straight to the terminal, or captured
/// into a self-contained HTML or SVG document.
struct Export<'a> {
    /// `--export-html PATH`, if given.
    html_path: Option<&'a str>,
    /// `--export-svg PATH`, if given.
    svg_path: Option<&'a str>,
    /// Document title for the SVG frame (the resource's file name).
    svg_title: &'a str,
    /// `--pager`: page the terminal output instead of writing it straight out.
    pager: bool,
}

/// Render once and deliver it everywhere it was asked for.
///
/// The exports do **not** replace the terminal output — upstream prints the
/// resource *and* saves the files, and both `--export-html` and `--export-svg`
/// may be given together. So when either is set the render is recorded once and
/// the same segments are turned into terminal bytes, HTML and SVG. Diff reports
/// use separate destination capabilities after loading/comparing the images;
/// ordinary input renderables are recorded once here.
///
/// Returns false if a file could not be written, so the caller can exit non-zero.
fn emit(console: &Console, export: &Export, render: impl FnOnce(&Console)) -> Result<(), String> {
    if export.html_path.is_none() && export.svg_path.is_none() {
        if export.pager {
            // Keep styles: unlike a plain `console.pager()`, the point of `rich
            // --pager` is to page *rich* output.
            console
                .page(true, render)
                .map_err(|err| format!("cannot page output: {err}"))?;
        } else {
            render(console);
        }
        return Ok(());
    }

    let segments = console.record_output(render);
    let mut first_error = None;

    // The terminal still gets the output, exports or not.
    let terminal = console.segments_to_string(&segments);
    if export.pager {
        // The text is already rendered, so hand it straight to the pager
        // rather than re-rendering through `Console::page`.
        if let Err(err) = rich::pager::Pager::show(&rich::pager::SystemPager, &terminal) {
            first_error = Some(format!("cannot page output: {err}"));
        }
    } else {
        let stdout = std::io::stdout();
        let mut lock = stdout.lock();
        if let Err(err) = lock.write_all(terminal.as_bytes()) {
            first_error = Some(format!("could not write output: {err}"));
        }
    }

    save_exports(console, export, &segments).and(first_error.map_or(Ok(()), Err))
}

fn save_exports(console: &Console, export: &Export, segments: &[Segment]) -> Result<(), String> {
    let mut first_error = None;
    if let Some(path) = export.html_path {
        // CSS-class stylesheet form, as upstream's `save_html` default.
        let html = rich::export::export_html_classes(segments, &DEFAULT_TERMINAL_THEME);
        if let Err(err) = std::fs::write(path, html) {
            first_error = Some(format!("failed to save HTML: {err}"));
        }
    }
    if let Some(path) = export.svg_path {
        let svg = rich::svg::export_svg(
            segments,
            &rich::SVG_EXPORT_THEME,
            export.svg_title,
            // Upstream derives this id by hashing Python reprs; a fixed one keeps
            // our output deterministic (DIVERGENCES #15).
            "rich-cli",
            console.width(),
        );
        if let Err(err) = std::fs::write(path, svg) {
            first_error.get_or_insert_with(|| format!("failed to save SVG: {err}"));
        }
    }
    first_error.map_or(Ok(()), Err)
}

fn print_help() {
    let extension_help = rich_ext::cli::HELP;
    // A RAW string: `\`-continuations would eat the leading spaces of every
    // line and print the whole thing flush-left.
    println!(
        r#"rich {VERSION} — Rust port of the rich-cli terminal toolbox

USAGE:
    rich [OPTIONS] [RESOURCE]
    rich [OPTIONS] <COMMAND> [RESOURCE]
    rich --batch [OPTIONS] RESOURCE...

RESOURCE is a file path, an http(s) URL, or `-` for stdin. Everything after a
bare `--` is a RESOURCE, however much it looks like an option. Input modes with
no RESOURCE read stdin until EOF; `-p -` reads markup from stdin too. Terminal
stdin shows an input hint. Repeated scalar options use their last value.

COMMANDS:
    print       Treat RESOURCE as literal markup TEXT (`--print`)
    markdown    Render Markdown (`--markdown`)
    syntax      Syntax-highlight source (`--syntax`)
    json        Pretty-print JSON (`--json`)
    csv         Render CSV/TSV as a table (`--csv`)
    ipynb       Render a Jupyter notebook (`--ipynb`)
    jsonl       Stream JSON Lines / NDJSON records
    log         Stream common structured-log JSONL records
    gif         Animate GIFs (`--gif`)
    diff        Perceptually compare two images (`--diff`)
    image       Render a still image as ASCII/Braille/blocks/Sixel (`--image`)
    rule        Draw a horizontal rule (`--rule`)

RENDER MODE (choose at most one; default auto-detects .md/.json/.csv/.tsv/.ipynb
by extension — anything else with a file extension is syntax-highlighted):
    -p, --print      Treat RESOURCE as literal markup TEXT, not a file path
    -m, --markdown   Render RESOURCE as Markdown
    -j, --json       Pretty-print RESOURCE as JSON
    -x, --syntax     Syntax-highlight RESOURCE (language from its extension)
        --csv        Render RESOURCE as a CSV/TSV table
        --ipynb      Render RESOURCE as a Jupyter notebook
        --jsonl      Stream JSON Lines / NDJSON records
        --log        Stream common structured-log JSONL records
        --gif        Animate GIFs side by side; pipes receive the first frame
        --loop N     With --gif, repeat N times (default 1; 0 = forever)
        --rule       Draw a horizontal rule (RESOURCE is its title)
        --diff       Perceptually compare two images (needs exactly two)
        --image      Render RESOURCE as a still image (ASCII/Braille/blocks/Sixel)

OPTIONS:
    -w, --width N    Render the output N columns wide (the console keeps its
                     own width, so --left/--center/--right still use it)
        --height N   With --image, render this many rows instead of the
                     backend's default
        --image-fit M With --image and --height: contain (letterbox) or cover
                     (centre-crop); preserves aspect ratio in terminal cells
        --image-background #RRGGBB
                     With --image: flatten transparency onto this RGB colour
                     (also colours contain padding; quote the # in your shell)
        --image-mode M
                     With --diff/--image, how to draw the picture: auto
                     (default), sixel (real pixels), blocks, braille, ascii, none
                     (--image rejects none: there would be nothing to draw)
{extension_help}
        --threshold PCT
                     With --diff, exit non-zero above PCT% changed.
                     Also sets the exit code: 0 within, 5 over.
        --left       Left-justify output
        --center     Center output
        --right      Right-justify output
    -o, --export-html PATH
                     Also write a self-contained HTML document to PATH
        --export-svg PATH
                     Also write an SVG document to PATH. Unlike the HTML,
                     it references its font from a CDN, so it is not
                     self-contained offline.
        --panel BOX  Wrap output in a panel, shrunk to fit its content
                     (ascii/ascii2/square/rounded/heavy/double; none = no panel)
        --padding P  Wrap output in padding (1, 2, or 4 comma-separated ints)
    -e, --expand     Make --panel/--padding fill the width instead of fitting
                     (implied by --width)
        --title T    Panel title; also the CSV table's title
        --caption T  Panel subtitle; also the CSV table's caption
    -y, --hyperlinks Render a Markdown link as a clickable OSC 8 hyperlink.
                     Off by default, which shows the URL as `text (url)`
    -s, --style S    Style laid under the whole output, e.g. "bold red"
    -S, --panel-style S
                     Panel border style, e.g. "dim" (with --panel)
        --pager      Page via MANPAGER, then PAGER, then less/more.com
        --watch      Re-render a changing file or URL while stdout is a terminal
        --watch-interval SEC
                     Poll interval in seconds (default 1)
        --watch-cache With URLs, render only when the response body changes
        --batch      Convert explicit files, directories, or globs deterministically
        --jobs N     Reserved worker limit; execution is currently serial
        --continue-on-error
                     Process all planned inputs and aggregate failures
        --overwrite  Allow existing batch export destinations
        --collision P
                     Batch policy: error (default), overwrite, or suffix
        --config PATH
                     Read versioned TOML defaults from PATH
        --profile NAME
                     Select a config profile (default: default)
        --no-config  Disable config discovery
        --sanitize   Replace input terminal controls, JSON/notebook strings,
                     titles and captions with visible inert text
        --report F   Emit a result/error envelope on stderr: human (default) or json.
        --machine-json
                     Alias for --report json
        --no-color   Disable colored output (as does a non-empty NO_COLOR)
    -h, --help       Show this help
    -V, --version    Show the rs-rich-cli package version

ENVIRONMENT:
    NO_COLOR         Any non-empty value disables colour
    COLUMNS          Console width (default 80 when unavailable)
    MANPAGER, PAGER   Pager command; fallback is less (Unix), more.com (Windows)
    FORCE_COLOR      Not supported; redirected stdout stays plain
    RICH_SIXEL       0/1 overrides Sixel detection for --image-mode auto

With no RESOURCE and no mode flag, a capability demo is shown. Layout, style,
paging, hyperlinks and export options require a resource or render mode.

EXIT CODES:
    0 success
    2 usage/config error
    3 input/read/write error
    4 parse/render data error
    5 threshold/gate failure
"#
    );
}

fn run_demo(no_color: bool) {
    // Force truecolor so the demo looks the same regardless of TERM — but only
    // when it is actually going to a terminal. Forcing it unconditionally wrote
    // escape sequences into a pipe, and made `--no-color` a no-op on this path
    // alone while every other mode honoured it.
    let to_terminal = std::io::stdout().is_terminal() && !no_color;
    let mut console = Console::builder()
        .force_terminal(to_terminal)
        .no_color(no_color)
        .color_system(if to_terminal {
            Some(ColorSystem::Truecolor)
        } else {
            None
        })
        // `[error]`/`[warning]`/`[info]` are rich-ext's additions, not upstream
        // styles — the core theme is a faithful 154-entry port.
        .theme(rich_ext::extended_theme())
        .build();
    console.install_extensions();

    console.print(&Rule::new("rs-rich-cli"));
    console.print_str("[bold magenta]rs-rich-cli[/] — a Rust port of [italic]rich[/]");
    console.print_str("Everything below is byte-parity-tested against Python rich 15.0.0.");

    // Markup, color, theme, and the rich-ext highlighter.
    console.print(&Rule::new("markup · color · theme · extension"));
    console.print_str(
        "Styles:   [bold]bold[/] [dim]dim[/] [italic]italic[/] [underline]underline[/] [reverse]reverse[/]",
    );
    console.print_str(
        "Color:    [red]red[/] [green]green[/] [blue]blue[/] [#ff8800]#ff8800[/] [white on blue]on blue[/]",
    );
    console.print_str("Theme:    [error]error[/], [warning]warning[/], [info]info[/]");
    console.print_str("Extension: numbers like 3.14 and 2026 are auto-highlighted");
    // Built-in ReprHighlighter (highlight=true): auto-colors numbers, bools,
    // strings, paths, calls, etc.
    // A second console, so it needs the same terminal/colour decision as the
    // main one — building it with force_terminal(true) unconditionally was what
    // leaked escape sequences into a pipe after the demo itself stopped.
    let hl = Console::builder()
        .force_terminal(to_terminal)
        .no_color(no_color)
        .color_system(if to_terminal {
            Some(ColorSystem::Truecolor)
        } else {
            None
        })
        .highlight(true)
        .build();
    hl.print_str("Highlight:  result = func(42, True, None, '/usr/bin')");
    // ISO8601Highlighter — colors date/time/timezone fields.
    let mut stamp = Text::new("2023-06-15T13:45:30+02:00");
    ISO8601Highlighter::new().highlight(&mut stamp);
    console.print(&Text::new("ISO 8601:   ").append_text(&stamp));
    console.print_str("Emoji:     :rocket: :fire: :sparkles: :thumbs_up: :snake: :coffee:");

    // Rule variants (title alignment).
    console.print(&Rule::new("rule"));
    console.print(&Rule::line());
    console.print(&Rule::new("centered"));
    console.print(&Rule::new("left").align(HorizontalAlign::Left));
    console.print(&Rule::new("right").align(HorizontalAlign::Right));

    // Panels with different boxes.
    console.print(&Rule::new("panel"));
    console.print(&Panel::new(text("rounded box (default)")).title("rounded"));
    console.print(
        &Panel::new(text("square box"))
            .box_set(SQUARE)
            .title("square"),
    );
    console.print(
        &Panel::new(text("double box"))
            .box_set(DOUBLE)
            .title("double"),
    );
    console.print(
        &Panel::new(text("title + subtitle"))
            .title("top")
            .subtitle("bottom"),
    );
    // Legacy-Windows box substitution: a ROUNDED panel falls back to SQUARE.
    let legacy = Console::builder()
        .force_terminal(true)
        .color_system(Some(ColorSystem::Truecolor))
        .width(console.width())
        .legacy_windows(true)
        .build();
    legacy.print(&Panel::new(text("rounded → square on legacy Windows")).title("legacy"));

    // Padding (shown inside a panel so the blank space is visible).
    console.print(&Rule::new("padding"));
    console.print(
        &Panel::new(Box::new(Padding::new(text("padded (1, 4)"), (1, 4, 1, 4)))).title("padding"),
    );

    // Styled — lay one style under an entire renderable.
    console.print(&Rule::new("styled"));
    console.print(&Styled::new(
        Box::new(Panel::new(text("green under the whole panel")).title("styled")),
        Style::parse("green").unwrap(),
    ));

    // Horizontal alignment (fills the console width).
    console.print(&Rule::new("align"));
    console.print(&Align::left(text("← left")));
    console.print(&Align::center(text("center")));
    console.print(&Align::right(text("right →")));

    // Text justify (via print(justify=…)).
    console.print(&Rule::new("justify"));
    console.print_justified("left justified", Justify::Left);
    console.print_justified("centered", Justify::Center);
    console.print_justified("right justified", Justify::Right);

    // Constrain — same panel, capped to 24 cells.
    console.print(&Rule::new("constrain (width 24)"));
    console.print(&Constrain::new(
        Box::new(Panel::new(text("constrained")).title("≤24")),
        Some(24),
    ));

    // Table.
    console.print(&Rule::new("table"));
    let mut table = Table::new().title("ported renderables");
    // A styled column and a fixed-width column (content wraps with ellipsis).
    table
        .add_column("Renderable")
        .column_style(Style::parse("cyan").unwrap());
    table.add_column("Module").column_width(12);
    table.add_column_justify("Parity", Justify::Center);
    for (renderable, module, parity) in [
        ("Text / markup", "text, markup", "✓"),
        ("Rule", "rule", "✓"),
        ("Panel", "panel", "✓"),
        ("Padding", "padding", "✓"),
        ("Align", "align", "✓"),
        ("Constrain", "constrain", "✓"),
        ("Columns", "columns", "✓"),
        ("Table", "table", "✓"),
        ("Tree", "tree", "✓"),
        ("ProgressBar", "progress_bar", "✓"),
    ] {
        table.add_row(&[renderable, module, parity]);
    }
    console.print(&table);

    // Columns — packs items into as many columns as fit the width.
    console.print(&Rule::new("columns"));
    let months = [
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December",
    ];
    console.print(&Columns::new(
        months.iter().map(|m| m.to_string()).collect(),
    ));

    // Tree.
    console.print(&Rule::new("tree"));
    let mut tree = Tree::new("rs-rich-cli");
    let core = tree.add("crates/rich (core, mirrors rich 15.0.0)");
    core.add("color · style · text · console");
    core.add("box · rule · panel · padding · align");
    core.add("table · tree · wrap · filesize");
    tree.add("crates/rich-ext (our extensions)");
    tree.add("crates/rich-cli (this binary)");
    console.print(&tree);

    // Progress bars at a few completion levels (0 → 100%).
    console.print(&Rule::new("progress bar"));
    for pct in [0.0, 33.0, 66.0, 100.0] {
        console.print(&ProgressBar::new(100.0, pct).width(48));
    }

    // Progress display — description + flexing bar + percentage (static frame).
    console.print(&Rule::new("progress"));
    let mut progress = Progress::new();
    progress.add_task("Downloading", 100.0, 50.0);
    progress.add_task("Processing", 100.0, 100.0);
    progress.add_task("Waiting", 100.0, 0.0);
    console.print(&progress);

    // Progress with custom columns — description + bar + M-of-N counter.
    let mut mofn = Progress::new().columns(vec![
        ProgressColumn::Description,
        ProgressColumn::Bar,
        ProgressColumn::MofN,
    ]);
    mofn.add_task("Files", 8.0, 3.0);
    mofn.add_task("Chunks", 128.0, 128.0);
    console.print(&mofn);

    // Progress with a download column — completed/total in shared byte units.
    let mut download = Progress::new().columns(vec![
        ProgressColumn::Description,
        ProgressColumn::Bar,
        ProgressColumn::Download,
    ]);
    download.add_task("archive.tar", 10_000_000.0, 4_200_000.0);
    console.print(&download);

    // JSON — pretty-printed and highlighted.
    console.print(&Rule::new("json"));
    if let Ok(json) = Json::new(
        r#"{"port": "rich", "version": "15.0.0", "parity": true, "widgets": ["panel", "table", "tree"]}"#,
    ) {
        console.print(&json);
    }

    // Pretty — colorize a Rust value's Debug output (Rust-native rich.pretty).
    console.print(&Rule::new("pretty"));
    let value = vec![("panel", 1u32), ("table", 2), ("tree", 3)];
    console.print(&Pretty::new(&value));

    // Log records — a severity-colored line per record (Rust-native rich.logging).
    console.print(&Rule::new("log"));
    for (level, message) in [
        (LogLevel::Info, "server started on port 8080"),
        (LogLevel::Debug, "cache warm: 128 entries"),
        (LogLevel::Warn, "disk usage at 85%"),
        (LogLevel::Error, "connection reset by peer"),
    ] {
        console.print(
            &LogRender::new(level, message)
                .time("12:00:00")
                .path("main.rs:42"),
        );
    }

    // Traceback — render an error + its source chain (Rust-native rich.traceback).
    console.print(&Rule::new("traceback"));
    let cause = std::io::Error::new(std::io::ErrorKind::NotFound, "no such file: config.toml");
    let err = std::io::Error::other(cause);
    console.print(&Traceback::new(&err));

    // Bar — a filled span within a range (eighth-block resolution).
    console.print(&Rule::new("bar (range)"));
    for (begin, end) in [(0.0, 100.0), (0.0, 62.0), (20.0, 80.0), (55.0, 100.0)] {
        console.print(&Bar::new(100.0, begin, end).width(48));
    }

    // Markdown — headings, inline styles, lists, block quotes, tables, and rules.
    console.print(&Rule::new("markdown"));
    console.print(&Markdown::new(
        "# Heading\n\nA paragraph with **bold**, *italic*, `code`, and a [link](https://example.com).\n\n- bullet item\n- another\n\n1. first\n2. second\n\n> a block quote\n\n| Name | Age |\n| :--- | ---: |\n| Alice | 30 |\n| Bob | 7 |\n\n```rust\nfn main() {\n    println!(\"hi\");\n}\n```\n\n---",
    ));

    // Syntax highlighting (via syntect — functional, not byte-parity with rich).
    console.print(&Rule::new("syntax"));
    console.print(&Syntax::new(
        "fn main() {\n    let msg = \"hello, rich\";\n    println!(\"{msg}\");\n}",
        "rust",
    ));

    // Control codes — cursor/screen sequences (shown escaped, not executed).
    console.print(&Rule::new("control codes"));
    let show_escape = |label: &str, control: &Control| {
        // Escaped so the sequence is visible (and its `[` isn't read as markup).
        let escaped = control
            .as_str()
            .replace('\x1b', "\\x1b")
            .replace('\x07', "\\a")
            .replace('\r', "\\r");
        console.print(&Text::new(format!("  {label:>14}: {escaped}")));
    };
    show_escape("clear screen", &Control::clear());
    show_escape("home", &Control::home());
    show_escape("move (2,-1)", &Control::move_(2, -1));
    show_escape("move_to (3,4)", &Control::move_to(3, 4));
    show_escape("hide cursor", &Control::show_cursor(false));
    show_escape("bell", &Control::bell());
    // LiveRender — the in-place redraw sequence for a 3-line render.
    let live_render = LiveRender::new(text("a\nb\nc"));
    let _ = console.render_to_string(&live_render); // render once to record the shape
    show_escape("live refresh", &live_render.position_cursor());
    // Live — the full control stream for a two-frame in-place update (captured
    // to a buffer so the demo stays static instead of animating).
    let live_console = Console::builder()
        .force_terminal(true)
        .color_system(Some(ColorSystem::Truecolor))
        .width(20)
        .build();
    let mut live = Live::new(text("frame one"), live_console, Vec::<u8>::new());
    live.start();
    live.update(text("frame two"));
    live.stop();
    let stream = String::from_utf8_lossy(live.writer())
        .replace('\x1b', "\\x1b")
        .replace('\r', "\\r")
        .replace('\n', "\\n");
    console.print(&Text::new(format!("  {:>14}: {stream}", "live stream")));

    // ANSI decoder — parse a raw SGR string back into styled Text, then re-render.
    console.print(&Rule::new("ansi decoder"));
    let raw =
        "\x1b[1;31mred bold\x1b[0m \x1b[38;5;214morange\x1b[0m \x1b[3;4mitalic underline\x1b[0m";
    console.print(&Text::new(format!(
        "  input:  {}",
        raw.replace('\x1b', "\\x1b")
    )));
    let mut decoder = rich::AnsiDecoder::new();
    for line in decoder.decode(raw) {
        console.print(&Text::new("  output: ").append_text(&line));
    }

    // Capture / export — record a rendering to a buffer, then strip its styles.
    console.print(&Rule::new("capture · export_text"));
    let plain = console.export_text(|c| {
        c.print(&Panel::new(text("captured panel")).box_set(SQUARE));
    });
    console.print(&Text::new("  export_text (styles stripped):"));
    for line in plain.lines() {
        console.print(&Text::new(format!("    {line}")));
    }
    // export_html — the inline CSS a style compiles to (via `--export-html`).
    let html_rule = Style::parse("bold red")
        .unwrap()
        .get_html_style(&DEFAULT_TERMINAL_THEME);
    console.print(&Text::new(format!(
        "  export_html: [bold red] → <span style=\"{html_rule}\">"
    )));

    // Layout — split a region into ratioed rows/columns; Panel leaves expand
    // to fill their region (rendered here at a fixed size).
    console.print(&Rule::new("layout"));
    let panel_leaf = |title: &str, body: &str| {
        Layout::with_renderable(Box::new(
            Panel::new(text(body))
                .box_set(SQUARE)
                .title(title.to_string()),
        ))
    };
    let mut header = Layout::new();
    header.split_row(vec![
        panel_leaf("left", "pane A"),
        panel_leaf("right", "pane B"),
    ]);
    let mut root = Layout::new();
    root.split_column(vec![
        header,
        Layout::with_renderable(text("footer (fixed size 3)")).size(3),
    ]);
    let grid = Console::builder()
        .force_terminal(true)
        .color_system(Some(ColorSystem::Truecolor))
        .width(48)
        .height(7)
        .build();
    for line in grid.export_text(|c| c.print(&root)).lines() {
        console.print(&Text::new(line));
    }

    // Spinners — a few frames of each built-in (animation needs a Live loop).
    console.print(&Rule::new("spinner (frames)"));
    for name in ["dots", "line", "arrow", "simpleDots"] {
        let spinner = Spinner::new(name);
        let frames: String = (0..6)
            .map(|i| console.render_to_string(&spinner.render(i as f64 * 0.15)))
            .collect::<Vec<_>>()
            .join(" ");
        console.print_str(&format!("  {name:>11}: {frames}"));
    }
    // Status — a spinner + message (green frame; animation needs a Live loop).
    let status = Status::new("Loading…").renderable().render(0.0);
    console.print(&Text::new("       status: ").append_text(&status));

    // CSV rendered as a table (blue border, numeric columns bold-green + right).
    console.print(&Rule::new("csv"));
    let csv = "Product,Qty,Price\nWidget,3,9.99\nGadget,12,19.50\nGizmo,1,4.25";
    if let Some(table) = build_csv_table(csv, Some(','), None, None) {
        console.print(&table);
    }

    // filesize.
    console.print(&Rule::new("filesize"));
    for bytes in [1u64, 999, 1_000, 1_500, 1_000_000, 1_500_000_000] {
        console.print_str(&format!("  {bytes:>13} → {}", filesize::decimal(bytes)));
    }
    console.print(&Rule::line());
}

#[cfg(test)]
mod tests {
    use super::*;
    use rich::ColorSystem;

    #[cfg(feature = "art")]
    #[test]
    fn diff_threshold_uses_the_reports_tie_rounding() {
        // The report prints 0.2 against 0.2, then 0.8 against 0.7.
        assert!(!diff_threshold_exceeded(0.25, 0.24));
        assert!(diff_threshold_exceeded(0.75, 0.74));
        assert!(!diff_threshold_exceeded(0.75, 0.76));
    }

    #[test]
    fn read_csv_rows_handles_quotes_and_delimiters() {
        let comma = Dialect::excel(',');
        // Quoted field containing the delimiter, and `""` escaping.
        let rows = read_csv_rows("a,\"b,c\",d\n\"he said \"\"hi\"\"\",2\n", &comma);
        assert_eq!(
            rows,
            vec![
                vec!["a".to_string(), "b,c".to_string(), "d".to_string()],
                vec!["he said \"hi\"".to_string(), "2".to_string()],
            ]
        );
        // No trailing empty row after a final newline (`\r` is gone by now:
        // the reader applies universal newlines first).
        assert_eq!(read_csv_rows("x\ny\n", &comma), vec![vec!["x"], vec!["y"]]);
        // Tab delimiter.
        assert_eq!(
            read_csv_rows("a\tb", &Dialect::excel('\t')),
            vec![vec!["a", "b"]]
        );
        // A leading UTF-8 BOM is stripped, not glued to the first cell.
        assert_eq!(read_csv_rows("\u{feff}a,b", &comma), vec![vec!["a", "b"]]);
        // A blank line is an EMPTY record, as `csv.reader` reports it — upstream
        // then drops it, where a `[""]` row would have drawn a blank table row.
        assert_eq!(
            read_csv_rows("a,b\n\nc,d\n", &comma),
            vec![vec!["a", "b"], vec![], vec!["c", "d"]]
        );
        // `skipinitialspace` eats the padding after a delimiter, but only there.
        let padded = Dialect {
            skipinitialspace: true,
            ..Dialect::excel(',')
        };
        assert_eq!(
            read_csv_rows("a,  b , c", &padded),
            vec![vec!["a", "b ", "c"]]
        );
    }

    #[test]
    fn the_sniffer_finds_the_delimiter_and_the_header() {
        // Every expectation here was read out of CPython's own `csv.Sniffer`.
        let candidates = [',', '\t', '|', ';'];
        let sniffed =
            |sample: &str| sniff(sample, Some(&candidates)).map(|dialect| dialect.delimiter);
        assert_eq!(
            sniffed("name;age;city\nAlice;30;Paris\nBob;25;Lyon\n"),
            Some(';')
        );
        assert_eq!(sniffed("a|b|c\n1|2|3\n4|5|6\n"), Some('|'));
        assert_eq!(sniffed("a\tb\tc\n1\t2\t3\n4\t5\t6\n"), Some('\t'));
        assert_eq!(sniffed("a, b, c\n1, 2, 3\n4, 5, 6\n"), Some(','));
        // A quoted, multi-line cell: only the quote/delimiter scan can find the
        // comma here, because the line counts are inconsistent.
        assert_eq!(
            sniffed("name,bio\nAlice,\"line one\nline two\"\nBob,short\n"),
            Some(',')
        );
        // Ragged rows and a single column defeat the sniffer, exactly as they do
        // upstream — that is what the excel fallback is for.
        assert_eq!(sniffed("a,b,c\n1,2\n3,4,5,6\n"), None);
        assert_eq!(sniffed("alpha\nbeta\ngamma\n"), None);

        assert_eq!(has_header("name,age\nAlice,30\nBob,25\n"), Some(true));
        // A column mixing an int and a float must stay ONE type. The historical
        // `for thisType in [int, float, complex]` loop reads it as inconsistent
        // and loses the header.
        assert_eq!(has_header("price,note\n10,aa\n9.5,bbb\n"), Some(true));
        assert_eq!(has_header("1,2,3\n4,5,6\n7,8,9\n"), Some(false));
    }

    #[test]
    fn detects_urls() {
        assert!(is_url("http://example.com"));
        assert!(is_url("https://example.com/x"));
        // RFC 3986: the scheme is case-insensitive.
        assert!(is_url("HTTPS://example.com"));
        assert!(is_url("Http://example.com"));
        assert!(!is_url("example.com"));
        assert!(!is_url("./file.md"));
        assert!(!is_url("-"));
        assert!(!is_url("")); // must not panic on a short/empty resource
        assert!(!is_url("ht"));
        assert!(!is_url("ftp://example.com"));
    }

    #[test]
    fn uninformative_extensions_defer_to_content_type() {
        assert!(is_uninformative_ext("txt"));
        assert!(is_uninformative_ext("log"));
        assert!(!is_uninformative_ext("py"));
        assert!(!is_uninformative_ext("rs"));
    }

    #[test]
    fn resource_ext_uses_basename_without_query() {
        assert_eq!(resource_ext("a.md").as_deref(), Some("md"));
        assert_eq!(resource_ext("path/to/b.RS").as_deref(), Some("rs"));
        assert_eq!(
            resource_ext("https://x.com/c.py?raw=1").as_deref(),
            Some("py")
        );
        // Dots in the host must not be mistaken for an extension.
        assert_eq!(resource_ext("https://api.example.com/data"), None);
        assert_eq!(resource_ext("https://x.com/"), None);
        assert_eq!(resource_ext("noext"), None);
    }

    #[test]
    fn content_type_maps_mode_and_lexer() {
        assert_eq!(mime_of("text/html; charset=utf-8"), "text/html");
        assert_eq!(content_type_mode("text/markdown"), Some(Mode::Markdown));
        assert_eq!(
            content_type_mode("application/json; charset=utf-8"),
            Some(Mode::Json)
        );
        assert_eq!(content_type_mode("text/csv"), Some(Mode::Csv));
        assert_eq!(content_type_mode("text/html"), None); // -> syntax, not a mode
        assert_eq!(content_type_lexer("text/html"), Some("html"));
        assert_eq!(content_type_lexer("text/x-python"), Some("python"));
        assert_eq!(content_type_lexer("text/plain"), None);
    }

    #[test]
    fn join_source_handles_string_and_array() {
        use serde_json::json;
        assert_eq!(join_source(&json!("a\nb")), "a\nb");
        // Array elements already carry their trailing newlines; they concat.
        assert_eq!(join_source(&json!(["a\n", "b"])), "a\nb");
        assert_eq!(join_source(&json!(null)), "");
    }

    #[test]
    fn ipynb_extension_auto_detects() {
        assert_eq!(detect_mode(Some("notebook.ipynb")), Mode::Ipynb);
    }

    #[test]
    fn io_label_builds_execution_count() {
        // "In [1]:" — the plain text (styles aside) should read back exactly.
        assert_eq!(
            io_label("In ", Some(1), "green", "#66ff00").plain(),
            "In [1]:"
        );
        assert_eq!(io_label("Out", None, "red", "#ee4b2b").plain(), "Out[ ]:");
    }

    #[test]
    fn parse_padding_unpacks_like_upstream() {
        assert_eq!(parse_padding("2"), Ok((2, 2, 2, 2)));
        assert_eq!(parse_padding("1,2"), Ok((1, 2, 1, 2)));
        assert_eq!(parse_padding("1,2,3,4"), Ok((1, 2, 3, 4)));
        assert_eq!(parse_padding(" 1 , 2 "), Ok((1, 2, 1, 2)));
        assert!(parse_padding("1,2,3").is_err()); // 3 values not allowed
        assert!(parse_padding("x").is_err());
    }

    #[test]
    fn parse_box_maps_names() {
        assert!(matches!(parse_box("rounded"), Ok(Some(_))));
        assert!(matches!(parse_box("HEAVY"), Ok(Some(_))));
        // `none` is upstream's default and means NO panel, not `box.NONE`.
        assert!(matches!(parse_box("none"), Ok(None)));
        assert!(parse_box("bogus").is_err());
    }

    #[test]
    fn parses_pager_flag() {
        let s = |v: &str| v.to_string();
        assert!(parse(&[s("--pager"), s("x")]).unwrap().unwrap().pager);
        assert!(!parse(&[s("x")]).unwrap().unwrap().pager);
    }

    #[test]
    fn parses_watch_options_and_rejects_orphans() {
        let s = |v: &str| v.to_string();
        let cli = parse(&[
            s("--watch"),
            s("--watch-interval"),
            s("0.25"),
            s("--watch-cache"),
            s("file.md"),
        ])
        .unwrap()
        .unwrap();
        assert!(cli.watch);
        assert_eq!(cli.watch_interval, 0.25);
        assert!(cli.watch_cache);
        assert!(parse(&[s("--watch-cache"), s("file.md")]).is_err());
        assert!(parse(&[s("--watch-interval"), s("2"), s("file.md")]).is_err());
    }

    #[test]
    fn watch_fingerprint_distinguishes_missing_and_replaced_files() {
        let path = std::env::temp_dir().join(format!("rs-rich-watch-{}.txt", std::process::id(),));
        let _ = std::fs::remove_file(&path);
        let missing = watch_fingerprint(path.to_str().unwrap(), false, None);
        std::fs::write(&path, "first").unwrap();
        let first = watch_fingerprint(path.to_str().unwrap(), false, None);
        std::fs::write(&path, "second content").unwrap();
        let second = watch_fingerprint(path.to_str().unwrap(), false, None);
        let _ = std::fs::remove_file(&path);
        assert_eq!(missing, "missing");
        assert_ne!(first, missing);
        assert_ne!(first, second);
    }

    #[test]
    fn parses_batch_controls_and_cli_values_override_config_defaults() {
        let s = |v: &str| v.to_string();
        let cli = parse(&[
            s("--no-config"),
            s("--batch"),
            s("--jobs"),
            s("3"),
            s("--continue-on-error"),
            s("--collision"),
            s("suffix"),
            s("input"),
        ])
        .unwrap()
        .unwrap();
        assert!(cli.batch);
        assert_eq!(cli.jobs, 3);
        assert!(cli.continue_on_error);
        assert_eq!(cli.collision, CollisionPolicy::Suffix);
    }

    #[test]
    fn batch_expansion_is_recursive_sorted_and_deduplicated() {
        let root = std::env::temp_dir().join(format!("rich-batch-test-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        let nested = root.join("nested");
        std::fs::create_dir_all(&nested).unwrap();
        std::fs::write(root.join("richbatchonly.md"), "# b").unwrap();
        std::fs::write(nested.join("richbatchnested.md"), "# a").unwrap();

        let root_arg = root.to_string_lossy().into_owned();
        let glob_arg = root
            .join("*richbatchonly.md")
            .to_string_lossy()
            .into_owned();
        let inputs = expand_batch_resources(&[root_arg, glob_arg]).unwrap();
        assert_eq!(inputs.len(), 2);
        assert!(inputs[0].ends_with("richbatchnested.md"));
        assert!(inputs[1].ends_with("richbatchonly.md"));

        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn batch_output_suffixes_are_deterministic_for_collisions() {
        let inputs = ["one.md", "two.md"];
        let first = batch_export_path(Some("out.html"), inputs[0], 0, 2).unwrap();
        let second = batch_export_path(Some("out.html"), inputs[1], 1, 2).unwrap();
        assert_eq!(first, "one.html");
        assert_eq!(second, "two.html");
        assert_eq!(
            Path::new("one.html")
                .with_file_name("one-2.html")
                .to_string_lossy(),
            "one-2.html"
        );
    }

    #[test]
    fn config_profiles_support_profiles_section_and_source_errors() {
        let root = std::env::temp_dir().join(format!("rich-config-test-{}", std::process::id()));
        std::fs::create_dir_all(&root).unwrap();
        let config = root.join("config.toml");
        std::fs::write(&config, "[profiles.ci]\nmode = \"json\"\njobs = 4\n").unwrap();
        let args = vec![
            "--config".to_string(),
            config.to_string_lossy().into_owned(),
            "--profile".to_string(),
            "ci".to_string(),
        ];
        let merged = config_args(
            &args,
            &ConfigRoots {
                home: None,
                cwd: root.clone(),
            },
        )
        .unwrap();
        assert!(merged.windows(1).any(|arg| arg[0] == "--json"));
        assert!(merged
            .windows(2)
            .any(|pair| pair[0] == "--jobs" && pair[1] == "4"));

        let bad = root.join("bad.toml");
        std::fs::write(&bad, "[defaults]\nnot-a-setting = true\n").unwrap();
        let error = config_args(
            &["--config".to_string(), bad.to_string_lossy().into_owned()],
            &ConfigRoots {
                home: None,
                cwd: root.clone(),
            },
        )
        .unwrap_err();
        assert!(error.contains("config "));
        assert!(error.contains("unknown key"));
        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn batch_rejects_modes_that_consume_their_whole_resource_list() {
        let s = |v: &str| v.to_string();
        let error = parse(&[s("--no-config"), s("--batch"), s("--diff"), s("a"), s("b")])
            .err()
            .unwrap();
        assert!(error.contains("--batch cannot be combined with --diff"));
        let error = parse(&[s("--no-config"), s("--batch"), s("--gif"), s("a")])
            .err()
            .unwrap();
        assert!(error.contains("--batch cannot be combined with --gif"));
        // One pager per item would open N interactive pagers over one plan.
        let error = parse(&[s("--no-config"), s("--batch"), s("--pager"), s("a")])
            .err()
            .unwrap();
        assert!(error.contains("--pager cannot be combined with --batch"));
    }

    #[test]
    fn glob_matches_metacharacters_rather_than_substrings() {
        assert!(glob_match("*.md", "notes.md"));
        // `.md` appears in the name, but the pattern anchors at the end.
        assert!(!glob_match("*.md", "notes.md.bak"));
        assert!(glob_match("a?c.md", "abc.md"));
        assert!(!glob_match("a?c.md", "ac.md"));
        assert!(glob_match("*", "anything"));
        assert!(glob_match("a*b*c", "axxbyyc"));
        assert!(!glob_match("a*b*c", "axxbyy"));
    }

    #[test]
    fn batch_expansion_skips_symlinked_directories() {
        let root = std::env::temp_dir().join(format!("rich-batch-link-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join("a.md"), "# a").unwrap();
        // A link back to the containing directory used to be walked forever.
        #[cfg(unix)]
        let linked = std::os::unix::fs::symlink(&root, root.join("loop")).is_ok();
        #[cfg(windows)]
        let linked = std::os::windows::fs::symlink_dir(&root, root.join("loop")).is_ok();
        let inputs = expand_batch_resources(&[root.to_string_lossy().into_owned()]).unwrap();
        if linked {
            assert_eq!(inputs.len(), 1, "symlinked directory must not be followed");
        }
        assert!(inputs[0].ends_with("a.md"));
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn config_values_keep_hashes_inside_quotes() {
        assert_eq!(
            strip_config_comment("mode = \"json\" # note"),
            "mode = \"json\" "
        );
        // A `#` inside quotes is part of the value, not the start of a comment.
        assert_eq!(
            strip_config_comment("export_html = \"report#ci.html\""),
            "export_html = \"report#ci.html\""
        );
        assert_eq!(config_value(" \"report#ci.html\" "), "report#ci.html");
        // Only a matched surrounding pair is stripped.
        assert_eq!(config_value("\"quoted"), "\"quoted");
    }

    #[test]
    fn subcommand_mode_wins_over_config_mode_default() {
        let s = |v: &str| v.to_string();
        assert!(selects_mode_explicitly(&[s("json"), s("file.json")]));
        assert!(selects_mode_explicitly(&[s("--markdown"), s("file.md")]));
        // A value that happens to look like a subcommand is not a subcommand.
        assert!(!selects_mode_explicitly(&[
            s("--title"),
            s("json"),
            s("file")
        ]));
        assert!(!selects_mode_explicitly(&[s("file.md")]));

        let root = std::env::temp_dir().join(format!("rich-config-mode-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(&root).unwrap();
        let config = root.join("config.toml");
        std::fs::write(&config, "[defaults]\nmode = \"markdown\"\n").unwrap();
        let merged = config_args(
            &[
                "--config".to_string(),
                config.to_string_lossy().into_owned(),
                "json".to_string(),
                "file.json".to_string(),
            ],
            &ConfigRoots {
                home: None,
                cwd: root.clone(),
            },
        )
        .unwrap();
        assert!(
            !merged.iter().any(|arg| arg == "--markdown"),
            "config mode must not override an explicit subcommand: {merged:?}"
        );
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn suffix_collisions_step_past_files_already_on_disk() {
        let root = std::env::temp_dir().join(format!("rich-batch-suffix-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(&root).unwrap();
        let target = root.join("out.html");
        std::fs::write(&target, "existing").unwrap();
        let target = target.to_string_lossy().into_owned();

        let cli = parse(&[
            "--no-config".to_string(),
            "--batch".to_string(),
            "--collision".to_string(),
            "suffix".to_string(),
            "x".to_string(),
        ])
        .unwrap()
        .unwrap();
        let mut taken = std::collections::BTreeSet::new();
        let first = resolve_destination(&cli, target.clone(), &mut taken).unwrap();
        assert!(
            first.ends_with("out-2.html"),
            "existing file must be kept: {first}"
        );
        let second = resolve_destination(&cli, target.clone(), &mut taken).unwrap();
        assert!(second.ends_with("out-3.html"));

        // `error` refuses rather than clobbering, and says how to proceed.
        let mut cli_error = cli.clone();
        cli_error.collision = CollisionPolicy::Error;
        let mut taken = std::collections::BTreeSet::new();
        let (class, message) =
            resolve_destination(&cli_error, target.clone(), &mut taken).unwrap_err();
        assert_eq!(class, ExitClass::Input);
        assert!(message.contains("--overwrite"));

        // `--overwrite` opts in explicitly.
        let mut cli_overwrite = cli.clone();
        cli_overwrite.overwrite = true;
        let mut taken = std::collections::BTreeSet::new();
        assert_eq!(
            resolve_destination(&cli_overwrite, target.clone(), &mut taken).unwrap(),
            target
        );
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn batch_outputs_keep_their_export_kind() {
        // The planned path need not end in `.html`; the kind is carried, not sniffed.
        let outputs = BatchOutputs {
            html: batch_export_path(Some("result.out"), "a.md", 0, 1),
            ..BatchOutputs::default()
        };
        assert_eq!(outputs.html.as_deref(), Some("result.out"));
        assert!(outputs.svg.is_none());
    }

    #[test]
    fn parses_export_flags() {
        let s = |v: &str| v.to_string();
        // Both take a PATH, and the resource is a separate positional.
        let cli = parse(&[s("--export-svg"), s("out.svg"), s("x")])
            .unwrap()
            .unwrap();
        assert_eq!(cli.export_svg.as_deref(), Some("out.svg"));
        assert!(cli.export_html.is_none());
        assert_eq!(cli.resource.as_deref(), Some("x"));

        let cli = parse(&[s("-o"), s("out.html"), s("x")]).unwrap().unwrap();
        assert_eq!(cli.export_html.as_deref(), Some("out.html"));

        // Both together is allowed — upstream writes both files.
        let cli = parse(&[
            s("--export-html"),
            s("a.html"),
            s("--export-svg"),
            s("b.svg"),
            s("x"),
        ])
        .unwrap()
        .unwrap();
        assert_eq!(cli.export_html.as_deref(), Some("a.html"));
        assert_eq!(cli.export_svg.as_deref(), Some("b.svg"));

        // A missing PATH is an error rather than swallowing the next argument.
        assert!(parse(&[s("--export-html")]).is_err());
        // The two export formats are mutually exclusive.
    }

    #[test]
    fn is_number_matches_pattern() {
        // Every case checked against Python's own
        // `re.compile(r"\-?[0-9]*?\.?[0-9]*?").fullmatch`. The loose ones are
        // not oversights: that pattern really does accept a lone `-`, a lone
        // `.` and the empty string, and really does reject a padded `" 12 "`.
        for ok in [
            "0", "42", "-7", "3.14", "-0.5", "", "-", ".", "-.", "5.", ".5",
        ] {
            assert!(is_number(ok), "{ok:?} should be numeric");
        }
        for no in [" 12 ", "1.2.3", "1e5", "abc", "5%"] {
            assert!(!is_number(no), "{no:?} should not be numeric");
        }
    }

    #[test]
    fn render_csv_matches_upstream() {
        // Byte-parity with the Table real rich-cli's render_csv builds for this
        // CSV (captured from rich 15.0.0): HEAVY_HEAD box, blue border, the
        // numeric Age column right-justified with bold-green body + header cells.
        let table = build_csv_table(
            "Name,Age,City\nAlice,30,NYC\nBob,25,LA\n",
            Some(','),
            None,
            None,
        )
        .expect("the sniffer reads this one");
        let out = Console::builder()
            .force_terminal(true)
            .color_system(Some(ColorSystem::Truecolor))
            .width(40)
            .no_color(false)
            .build()
            .render_to_string(&table);
        let expected = concat!(
            "\x1b[34m┏━━━━━━━┳━━━━━┳━━━━━━┓\x1b[0m\n",
            "\x1b[34m┃\x1b[0m\x1b[1m \x1b[0m\x1b[1mName \x1b[0m\x1b[1m \x1b[0m\x1b[34m┃\x1b[0m",
            "\x1b[1;32m \x1b[0m\x1b[1;32mAge\x1b[0m\x1b[1;32m \x1b[0m\x1b[34m┃\x1b[0m",
            "\x1b[1m \x1b[0m\x1b[1mCity\x1b[0m\x1b[1m \x1b[0m\x1b[34m┃\x1b[0m\n",
            "\x1b[34m┡━━━━━━━╇━━━━━╇━━━━━━┩\x1b[0m\n",
            "\x1b[34m│\x1b[0m Alice \x1b[34m│\x1b[0m\x1b[1;32m \x1b[0m\x1b[1;32m 30\x1b[0m",
            "\x1b[1;32m \x1b[0m\x1b[34m│\x1b[0m NYC  \x1b[34m│\x1b[0m\n",
            "\x1b[34m│\x1b[0m Bob   \x1b[34m│\x1b[0m\x1b[1;32m \x1b[0m\x1b[1;32m 25\x1b[0m",
            "\x1b[1;32m \x1b[0m\x1b[34m│\x1b[0m LA   \x1b[34m│\x1b[0m\n",
            "\x1b[34m└───────┴─────┴──────┘\x1b[0m",
        );
        assert_eq!(out, expected);
    }
}