rich_rust 0.2.1

A Rust port of Python's Rich library for beautiful terminal output
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
//! Console - the central entry point for styled terminal output.
//!
//! The [`Console`] handles rendering styled content to the terminal,
//! including color detection, width calculation, and ANSI code generation.
//!
//! # Examples
//!
//! ## Basic Printing with Markup
//!
//! ```rust,ignore
//! use rich_rust::Console;
//!
//! let console = Console::new();
//!
//! // Print with markup syntax
//! console.print("[bold red]Error:[/] Something went wrong");
//! console.print("[green]Success![/] Operation completed");
//!
//! // Markup supports colors, attributes, and combinations
//! console.print("[bold italic #ff8800 on blue]Custom styling[/]");
//! ```
//!
//! ## Console Builder
//!
//! ```rust,ignore
//! use rich_rust::console::{Console, ConsoleBuilder};
//! use rich_rust::color::ColorSystem;
//!
//! let console = Console::builder()
//!     .color_system(ColorSystem::EightBit)  // Force 256 colors
//!     .width(80)                            // Fixed width
//!     .markup(true)                         // Enable markup parsing
//!     .build();
//! ```
//!
//! ## Print Options
//!
//! ```rust,ignore
//! use rich_rust::console::{Console, PrintOptions};
//! use rich_rust::style::Style;
//! use rich_rust::text::JustifyMethod;
//!
//! let console = Console::new();
//!
//! let options = PrintOptions::new()
//!     .with_style(Style::new().bold())
//!     .with_justify(JustifyMethod::Center)
//!     .with_markup(true);
//!
//! console.print_with_options("Centered bold text", &options);
//! ```
//!
//! ## Capturing Output
//!
//! ```rust,ignore
//! use rich_rust::Console;
//!
//! let mut console = Console::new();
//!
//! // Start capturing
//! console.begin_capture();
//! console.print("[bold]Hello[/]");
//!
//! // Get captured segments
//! let segments = console.end_capture();
//! for seg in &segments {
//!     println!("Text: {:?}, Style: {:?}", seg.text, seg.style);
//! }
//! ```
//!
//! # Terminal Detection
//!
//! The Console automatically detects terminal capabilities:
//!
//! - **Color system**: `TrueColor` (24-bit), 256 colors, or 16 colors
//! - **Terminal dimensions**: Width and height in character cells
//! - **TTY status**: Whether output is to an interactive terminal
//!
//! You can override these with the builder pattern or by setting explicit values.

use std::collections::HashMap;
use std::fmt::Write as FmtWrite;
use std::io::{self, Write};
use std::sync::{
    Arc, Mutex, Weak,
    atomic::{AtomicBool, Ordering},
};
use time::OffsetDateTime;

use crate::color::{ColorSystem, DEFAULT_TERMINAL_THEME, SVG_EXPORT_THEME, TerminalTheme};
use crate::emoji;
use crate::highlighter::{Highlighter, ReprHighlighter};
use crate::live::LiveInner;
use crate::markup;
use crate::measure::{Measurement, RichMeasure};
use crate::protocol::{RichCast, RichCastOutput};
use crate::renderables::Renderable;
use crate::segment::{ControlCode, ControlType, Segment};
use crate::style::{Attributes, Style, StyleParseError};
use crate::sync::lock_recover;
use crate::terminal;
use crate::text::{JustifyMethod, OverflowMethod, Text};
use crate::theme::{Theme, ThemeStack, ThemeStackError};

/// Console dimensions in cells.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConsoleDimensions {
    /// Width in cells.
    pub width: usize,
    /// Height in rows.
    pub height: usize,
}

impl Default for ConsoleDimensions {
    fn default() -> Self {
        Self {
            width: 80,
            height: 24,
        }
    }
}

/// Options for rendering.
#[derive(Debug, Clone)]
pub struct ConsoleOptions {
    /// Terminal dimensions.
    pub size: ConsoleDimensions,
    /// Using legacy Windows console.
    pub legacy_windows: bool,
    /// Minimum width constraint.
    pub min_width: usize,
    /// Maximum width constraint.
    pub max_width: usize,
    /// Output is a terminal (vs file/pipe).
    pub is_terminal: bool,
    /// Output encoding.
    pub encoding: String,
    /// Maximum height for rendering.
    pub max_height: usize,
    /// Default justification.
    pub justify: Option<JustifyMethod>,
    /// Default overflow handling.
    pub overflow: Option<OverflowMethod>,
    /// Default `no_wrap` setting.
    pub no_wrap: Option<bool>,
    /// Enable highlighting.
    pub highlight: Option<bool>,
    /// Parse markup in strings.
    pub markup: Option<bool>,
    /// Explicit height override.
    pub height: Option<usize>,
}

impl Default for ConsoleOptions {
    fn default() -> Self {
        Self {
            size: ConsoleDimensions::default(),
            legacy_windows: false,
            min_width: 1,
            max_width: 80,
            is_terminal: true,
            encoding: String::from("utf-8"),
            max_height: usize::MAX,
            justify: None,
            overflow: None,
            no_wrap: None,
            highlight: None,
            markup: None,
            height: None,
        }
    }
}

impl ConsoleOptions {
    /// Create options with a different `max_width`.
    #[must_use]
    pub fn update_width(&self, width: usize) -> Self {
        Self {
            max_width: width.min(self.max_width),
            ..self.clone()
        }
    }

    /// Create options with a different height.
    #[must_use]
    pub fn update_height(&self, height: usize) -> Self {
        Self {
            height: Some(height),
            ..self.clone()
        }
    }

    /// Create options with updated width and height.
    #[must_use]
    pub fn update_dimensions(&self, width: usize, height: usize) -> Self {
        Self {
            size: ConsoleDimensions { width, height },
            max_width: width,
            max_height: height,
            height: Some(height),
            ..self.clone()
        }
    }
}

/// Print options for controlling output.
#[derive(Clone, Default)]
pub struct PrintOptions {
    /// String to separate multiple objects.
    pub sep: String,
    /// String to append at end.
    pub end: String,
    /// Apply style to output.
    pub style: Option<Style>,
    /// Override justification.
    pub justify: Option<JustifyMethod>,
    /// Override overflow handling.
    pub overflow: Option<OverflowMethod>,
    /// Override `no_wrap`.
    pub no_wrap: Option<bool>,
    /// Suppress newline.
    pub no_newline: bool,
    /// Parse markup.
    pub markup: Option<bool>,
    /// Enable/disable highlighting (None = inherit Console setting).
    pub highlight: Option<bool>,
    /// Override the highlighter used when highlighting is enabled.
    pub highlighter: Option<Arc<dyn Highlighter>>,
    /// Override width.
    pub width: Option<usize>,
    /// Crop output to width.
    pub crop: bool,
    /// Soft wrap at width.
    pub soft_wrap: bool,
}

impl PrintOptions {
    /// Create new print options with defaults.
    #[must_use]
    pub fn new() -> Self {
        Self {
            sep: String::from(" "),
            end: String::from("\n"),
            ..Default::default()
        }
    }

    /// Set markup parsing.
    #[must_use]
    pub fn with_markup(mut self, markup: bool) -> Self {
        self.markup = Some(markup);
        self
    }

    /// Set style.
    #[must_use]
    pub fn with_style(mut self, style: Style) -> Self {
        self.style = Some(style);
        self
    }

    /// Set the separator between objects.
    #[must_use]
    pub fn with_sep(mut self, sep: impl Into<String>) -> Self {
        self.sep = sep.into();
        self
    }

    /// Set the end string appended after output.
    #[must_use]
    pub fn with_end(mut self, end: impl Into<String>) -> Self {
        self.end = end.into();
        self
    }

    /// Override justification.
    #[must_use]
    pub fn with_justify(mut self, justify: JustifyMethod) -> Self {
        self.justify = Some(justify);
        self
    }

    /// Override overflow handling.
    #[must_use]
    pub fn with_overflow(mut self, overflow: OverflowMethod) -> Self {
        self.overflow = Some(overflow);
        self
    }

    /// Override `no_wrap`.
    #[must_use]
    pub fn with_no_wrap(mut self, no_wrap: bool) -> Self {
        self.no_wrap = Some(no_wrap);
        self
    }

    /// Suppress newline at end.
    #[must_use]
    pub fn with_no_newline(mut self, no_newline: bool) -> Self {
        self.no_newline = no_newline;
        self
    }

    /// Enable/disable highlighting.
    #[must_use]
    pub fn with_highlight(mut self, highlight: bool) -> Self {
        self.highlight = Some(highlight);
        self
    }

    /// Override the highlighter for this print call.
    #[must_use]
    pub fn with_highlighter<H: Highlighter + 'static>(mut self, highlighter: H) -> Self {
        self.highlighter = Some(Arc::new(highlighter));
        self
    }

    /// Override width.
    #[must_use]
    pub fn with_width(mut self, width: usize) -> Self {
        self.width = Some(width);
        self
    }

    /// Crop output to width.
    #[must_use]
    pub fn with_crop(mut self, crop: bool) -> Self {
        self.crop = crop;
        self
    }

    /// Soft wrap at width.
    #[must_use]
    pub fn with_soft_wrap(mut self, soft_wrap: bool) -> Self {
        self.soft_wrap = soft_wrap;
        self
    }
}

impl std::fmt::Debug for PrintOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PrintOptions")
            .field("sep", &self.sep)
            .field("end", &self.end)
            .field("style", &self.style)
            .field("justify", &self.justify)
            .field("overflow", &self.overflow)
            .field("no_wrap", &self.no_wrap)
            .field("no_newline", &self.no_newline)
            .field("markup", &self.markup)
            .field("highlight", &self.highlight)
            .field(
                "highlighter",
                &self.highlighter.as_ref().map(|_| "<Highlighter>"),
            )
            .field("width", &self.width)
            .field("crop", &self.crop)
            .field("soft_wrap", &self.soft_wrap)
            .finish()
    }
}

/// Hook for intercepting rendered segments before output.
pub trait RenderHook: Send + Sync {
    fn process(&self, console: &Console, segments: &[Segment<'static>]) -> Vec<Segment<'static>>;
}

/// The main Console for rendering styled output.
///
/// `Console` is the central entry point for all terminal output operations.
/// It handles color detection, terminal dimensions, markup parsing, and
/// ANSI escape code generation.
///
/// # Thread Safety
///
/// `Console` is `Send + Sync` and can be safely shared between threads using
/// `Arc<Console>`. All internal state is protected by mutexes that use poison
/// recovery (see the [`sync`](crate::sync) module).
///
/// When multiple threads print concurrently, their output may interleave at
/// the line level. For strictly ordered output, synchronize at the application
/// level or use a single printing thread.
///
/// # Example
///
/// ```rust,ignore
/// use std::sync::Arc;
/// use std::thread;
/// use rich_rust::Console;
///
/// let console = Arc::new(Console::new());
///
/// let handles: Vec<_> = (0..4).map(|i| {
///     let c = Arc::clone(&console);
///     thread::spawn(move || {
///         c.print(&format!("Hello from thread {i}"));
///     })
/// }).collect();
///
/// for h in handles {
///     h.join().unwrap();
/// }
/// ```
pub struct Console {
    /// Color system to use (None = auto-detect).
    color_system: Option<ColorSystem>,
    /// Force terminal mode.
    force_terminal: Option<bool>,
    /// Tab expansion size.
    tab_size: usize,
    /// Buffer output for export.
    record: AtomicBool,
    /// Parse markup by default.
    markup: bool,
    /// Enable emoji rendering.
    emoji: bool,
    /// Enable syntax highlighting.
    highlight: bool,
    /// Highlighter used when `highlight` is enabled (Python Rich `rich.highlighter` parity).
    highlighter: Arc<dyn Highlighter>,
    /// Theme stack for named styles (Python Rich parity).
    theme_stack: Mutex<ThemeStack>,
    /// Override width.
    width: Option<usize>,
    /// Override height.
    height: Option<usize>,
    /// Use ASCII-safe box characters.
    safe_box: bool,
    /// Output stream (defaults to stdout).
    file: Mutex<Box<dyn Write + Send>>,
    /// Recording buffer.
    buffer: Mutex<Vec<Segment<'static>>>,
    /// Cached terminal detection.
    is_terminal: bool,
    /// Detected/configured color system.
    detected_color_system: Option<ColorSystem>,
    /// Render hooks (Live uses this).
    render_hooks: Mutex<Vec<Arc<dyn RenderHook>>>,
    /// Active Live stack for nested Live handling.
    live_stack: Mutex<Vec<Weak<LiveInner>>>,
}

impl std::fmt::Debug for Console {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Console")
            .field("color_system", &self.color_system)
            .field("force_terminal", &self.force_terminal)
            .field("tab_size", &self.tab_size)
            .field("record", &self.record.load(Ordering::Relaxed))
            .field("markup", &self.markup)
            .field("emoji", &self.emoji)
            .field("highlight", &self.highlight)
            .field("width", &self.width)
            .field("height", &self.height)
            .field("safe_box", &self.safe_box)
            .field("file", &"<dyn Write>")
            .field("buffer_len", &lock_recover(&self.buffer).len())
            .field("is_terminal", &self.is_terminal)
            .field("detected_color_system", &self.detected_color_system)
            .finish_non_exhaustive()
    }
}

impl Default for Console {
    fn default() -> Self {
        Self::new()
    }
}

impl Console {
    /// Create a new console with default settings.
    #[must_use]
    pub fn new() -> Self {
        let is_terminal = terminal::is_terminal();
        let detected_color_system = if is_terminal {
            terminal::detect_color_system()
        } else {
            None
        };

        Self {
            color_system: None,
            force_terminal: None,
            tab_size: 8,
            record: AtomicBool::new(false),
            markup: true,
            emoji: true,
            highlight: true,
            highlighter: Arc::new(ReprHighlighter::default()),
            theme_stack: Mutex::new(ThemeStack::new(Theme::default())),
            width: None,
            height: None,
            safe_box: false,
            file: Mutex::new(Box::new(io::stdout())),
            buffer: Mutex::new(Vec::new()),
            is_terminal,
            detected_color_system,
            render_hooks: Mutex::new(Vec::new()),
            live_stack: Mutex::new(Vec::new()),
        }
    }

    /// Create a console builder for custom configuration.
    #[must_use]
    pub fn builder() -> ConsoleBuilder {
        ConsoleBuilder::default()
    }

    /// Convert this Console into a shared reference-counted handle.
    #[must_use]
    pub fn shared(self) -> Arc<Self> {
        Arc::new(self)
    }

    /// Get the console width.
    #[must_use]
    pub fn width(&self) -> usize {
        self.width.unwrap_or_else(terminal::get_terminal_width)
    }

    /// Get the console height.
    #[must_use]
    pub fn height(&self) -> usize {
        self.height.unwrap_or_else(terminal::get_terminal_height)
    }

    /// Get the console dimensions.
    #[must_use]
    pub fn size(&self) -> ConsoleDimensions {
        ConsoleDimensions {
            width: self.width(),
            height: self.height(),
        }
    }

    /// Check if this console outputs to a terminal.
    #[must_use]
    pub fn is_terminal(&self) -> bool {
        self.force_terminal.unwrap_or(self.is_terminal)
    }

    /// Terminal detection result without `force_terminal` overrides.
    ///
    /// This is used for behaviors that must not affect non-TTY contexts even if
    /// a caller forces terminal rendering (e.g. process-wide stdio redirection).
    #[must_use]
    pub(crate) const fn is_terminal_detected(&self) -> bool {
        self.is_terminal
    }

    /// Get the color system in use.
    #[must_use]
    pub fn color_system(&self) -> Option<ColorSystem> {
        self.color_system.or(self.detected_color_system)
    }

    /// Check if Rich-style emoji code replacement is enabled.
    #[must_use]
    pub const fn emoji(&self) -> bool {
        self.emoji
    }

    /// Check if ASCII-safe box drawing is enabled.
    #[must_use]
    pub const fn safe_box(&self) -> bool {
        self.safe_box
    }

    /// Get a style by theme name or parse a style definition.
    ///
    /// Mirrors Python Rich `Console.get_style()`:
    /// - Check the active theme stack for an exact name match
    /// - Fall back to parsing a style definition
    ///
    /// If parsing fails, this returns an empty style.
    #[must_use]
    pub fn get_style(&self, name: &str) -> Style {
        self.try_get_style(name).unwrap_or_else(|_| Style::new())
    }

    /// Like [`Self::get_style`], but returns an error if the style can't be parsed.
    pub fn try_get_style(&self, name: &str) -> Result<Style, StyleParseError> {
        {
            let stack = lock_recover(&self.theme_stack);
            if let Some(style) = stack.get(name) {
                return Ok(style.clone());
            }
        }
        Style::parse(name)
    }

    /// Push a theme on to the theme stack.
    pub fn push_theme(&self, theme: Theme, inherit: bool) {
        lock_recover(&self.theme_stack).push_theme(theme, inherit);
    }

    /// Pop the current theme from the theme stack.
    pub fn pop_theme(&self) -> Result<(), ThemeStackError> {
        lock_recover(&self.theme_stack).pop_theme()
    }

    /// Use a theme for the duration of the returned guard.
    #[must_use]
    pub fn use_theme(&self, theme: Theme, inherit: bool) -> ThemeGuard<'_> {
        self.push_theme(theme, inherit);
        ThemeGuard { console: self }
    }

    /// Check if colors are enabled.
    #[must_use]
    pub fn is_color_enabled(&self) -> bool {
        self.color_system().is_some()
    }

    /// Get the tab size.
    #[must_use]
    pub const fn tab_size(&self) -> usize {
        self.tab_size
    }

    /// Create console options for rendering.
    #[must_use]
    pub fn options(&self) -> ConsoleOptions {
        ConsoleOptions {
            size: self.size(),
            legacy_windows: false,
            min_width: 1,
            max_width: self.width(),
            is_terminal: self.is_terminal(),
            encoding: String::from("utf-8"),
            max_height: self.height(),
            justify: None,
            overflow: None,
            no_wrap: None,
            highlight: Some(self.highlight),
            markup: Some(self.markup),
            height: None,
        }
    }

    pub(crate) fn apply_highlighter_to_text(&self, options: &ConsoleOptions, text: &mut Text) {
        let highlight_enabled = options.highlight.unwrap_or(self.highlight);
        if highlight_enabled {
            self.highlighter.highlight(self, text);
        }
    }

    /// Measure a renderable via the measurement protocol (Python Rich `Console.measure` parity).
    #[must_use]
    pub fn measure(
        &self,
        renderable: &dyn RichMeasure,
        options: Option<ConsoleOptions>,
    ) -> Measurement {
        let options = options.unwrap_or_else(|| self.options());
        Measurement::get(self, &options, Some(renderable))
    }

    /// Check if the terminal is "dumb".
    #[must_use]
    pub fn is_dumb_terminal(&self) -> bool {
        terminal::is_dumb_terminal()
    }

    /// Check if the console is interactive (TTY and not dumb).
    #[must_use]
    pub fn is_interactive(&self) -> bool {
        self.is_terminal() && !self.is_dumb_terminal()
    }

    pub(crate) fn push_render_hook(&self, hook: Arc<dyn RenderHook>) {
        lock_recover(&self.render_hooks).push(hook);
    }

    pub(crate) fn pop_render_hook(&self) -> Option<Arc<dyn RenderHook>> {
        lock_recover(&self.render_hooks).pop()
    }

    pub(crate) fn set_live(&self, live: &Arc<LiveInner>) -> bool {
        let mut stack = lock_recover(&self.live_stack);
        stack.push(Arc::downgrade(live));
        stack.len() == 1
    }

    pub(crate) fn clear_live(&self) {
        let mut stack = lock_recover(&self.live_stack);
        if !stack.is_empty() {
            stack.pop();
        }
    }

    pub(crate) fn live_stack_snapshot(&self) -> Vec<Arc<LiveInner>> {
        let mut stack = lock_recover(&self.live_stack);
        stack.retain(|entry| entry.strong_count() > 0);
        let mut result = Vec::new();
        for entry in stack.iter() {
            if let Some(live) = entry.upgrade() {
                result.push(live);
            }
        }
        result
    }

    pub(crate) fn write_control_codes(&self, control_codes: Vec<ControlCode>) -> io::Result<()> {
        if control_codes.is_empty() {
            return Ok(());
        }
        let segment = Segment::control(control_codes);
        let mut file = lock_recover(&self.file);
        self.write_segments_raw(&mut *file, &[segment])
    }

    pub(crate) fn swap_file(&self, writer: Box<dyn Write + Send>) -> Box<dyn Write + Send> {
        std::mem::replace(&mut *lock_recover(&self.file), writer)
    }

    /// Show or hide the cursor.
    pub fn show_cursor(&self, show: bool) -> io::Result<()> {
        let control = if show {
            ControlCode::new(ControlType::ShowCursor)
        } else {
            ControlCode::new(ControlType::HideCursor)
        };
        self.write_control_codes(vec![control])
    }

    /// Enable or disable the alternate screen buffer.
    pub fn set_alt_screen(&self, enable: bool) -> io::Result<()> {
        let control = if enable {
            ControlCode::new(ControlType::EnableAltScreen)
        } else {
            ControlCode::new(ControlType::DisableAltScreen)
        };
        self.write_control_codes(vec![control])
    }

    /// Enable recording mode.
    ///
    /// All subsequent console output will be captured to an internal buffer
    /// until [`end_capture`](Self::end_capture) is called.
    pub fn begin_capture(&self) {
        self.record.store(true, Ordering::Relaxed);
        lock_recover(&self.buffer).clear();
    }

    /// End recording and return captured segments.
    ///
    /// Returns all segments captured since [`begin_capture`](Self::begin_capture)
    /// was called, and clears the internal buffer.
    pub fn end_capture(&self) -> Vec<Segment<'static>> {
        self.record.store(false, Ordering::Relaxed);
        std::mem::take(&mut *lock_recover(&self.buffer))
    }

    /// Print styled text to the console.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use rich_rust::Console;
    ///
    /// let console = Console::new();
    /// console.print("[bold red]Hello[/] World!");
    /// ```
    pub fn print(&self, content: &str) {
        self.print_with_options(content, &PrintOptions::new().with_markup(self.markup));
    }

    /// Print a prepared Text object.
    pub fn print_text(&self, text: &Text) {
        let mut file = lock_recover(&self.file);
        let _ = self.print_text_to(&mut *file, text);
    }

    /// Print a prepared Text object to a specific writer.
    pub fn print_text_to<W: Write>(&self, writer: &mut W, text: &Text) -> io::Result<()> {
        let segments: Vec<Segment<'static>> = text
            .render(&text.end)
            .into_iter()
            .map(Segment::into_owned)
            .collect();
        let segments = self.apply_render_hooks(segments);
        self.write_segments_raw(writer, &segments)
    }

    /// Print prepared segments.
    pub fn print_segments(&self, segments: &[Segment<'_>]) {
        let mut file = lock_recover(&self.file);
        let _ = self.print_segments_to(&mut *file, segments);
    }

    /// Print prepared segments to a specific writer.
    pub fn print_segments_to<W: Write>(
        &self,
        writer: &mut W,
        segments: &[Segment<'_>],
    ) -> io::Result<()> {
        let owned: Vec<Segment<'static>> =
            segments.iter().cloned().map(Segment::into_owned).collect();
        let processed = self.apply_render_hooks(owned);
        self.write_segments_raw(writer, &processed)
    }

    /// Print any object implementing the Renderable trait.
    pub fn print_renderable(&self, renderable: &impl Renderable) {
        let options = self.options();
        let segments = renderable.render(self, &options);
        self.print_segments(&segments);
    }

    fn render_rich_cast_segments(
        &self,
        value: &dyn RichCast,
        options: &PrintOptions,
    ) -> Vec<Segment<'static>> {
        match crate::protocol::rich_cast(value) {
            RichCastOutput::Str(text) => self.render_str_segments(&text, options),
            RichCastOutput::Renderable(renderable) => {
                let options = self.options();
                renderable
                    .render(self, &options)
                    .into_iter()
                    .map(Segment::into_owned)
                    .collect()
            }
            RichCastOutput::Castable(renderable) => {
                let options = self.options();
                renderable
                    .render(self, &options)
                    .into_iter()
                    .map(Segment::into_owned)
                    .collect()
            }
        }
    }

    /// Print a value via the protocol casting hook (Python Rich `rich.protocol.rich_cast` parity).
    pub fn print_cast(&self, value: &dyn RichCast) {
        self.print_cast_with_options(value, &PrintOptions::new().with_markup(self.markup));
    }

    /// Print a castable value with custom options (string options apply when the cast yields a string).
    pub fn print_cast_with_options(&self, value: &dyn RichCast, options: &PrintOptions) {
        let mut file = lock_recover(&self.file);
        let _ = self.print_cast_to(&mut *file, value, options);
    }

    /// Print a castable value to a specific writer.
    pub fn print_cast_to<W: Write>(
        &self,
        writer: &mut W,
        value: &dyn RichCast,
        options: &PrintOptions,
    ) -> io::Result<()> {
        let segments = self.render_rich_cast_segments(value, options);
        let segments = self.apply_render_hooks(segments);
        self.write_segments_raw(writer, &segments)
    }

    /// Print an exception / traceback renderable.
    ///
    /// This is a convenience wrapper mirroring Python Rich's `Console.print_exception`.
    pub fn print_exception(&self, traceback: &crate::renderables::Traceback) {
        self.print_renderable(traceback);
    }

    /// Print with custom options.
    pub fn print_with_options(&self, content: &str, options: &PrintOptions) {
        let mut file = lock_recover(&self.file);
        // Keep `Console::print_*` infallible (matches Rich's ergonomics). If callers need
        // I/O error handling they can use `Console::print_to(...)` directly.
        let _ = self.print_to(&mut *file, content, options);
    }

    /// Export rendered text (no ANSI) using default print options.
    #[must_use]
    pub fn export_text(&self, content: &str) -> String {
        self.export_text_with_options(content, &PrintOptions::new().with_markup(self.markup))
    }

    /// Export rendered text (no ANSI) using custom print options.
    #[must_use]
    pub fn export_text_with_options(&self, content: &str, options: &PrintOptions) -> String {
        let segments = self.render_str_segments(content, options);
        Self::segments_to_plain(&segments)
    }

    /// Export a castable value to plain text (no ANSI).
    #[must_use]
    pub fn export_cast_text(&self, value: &dyn RichCast) -> String {
        self.export_cast_text_with_options(value, &PrintOptions::new().with_markup(self.markup))
    }

    /// Export a castable value to plain text (no ANSI) using custom print options.
    #[must_use]
    pub fn export_cast_text_with_options(
        &self,
        value: &dyn RichCast,
        options: &PrintOptions,
    ) -> String {
        let segments = self.render_rich_cast_segments(value, options);
        Self::segments_to_plain(&segments)
    }

    /// Export a renderable to plain text (no ANSI).
    #[must_use]
    pub fn export_renderable_text(&self, renderable: &impl Renderable) -> String {
        let options = self.options();
        let segments = renderable.render(self, &options);
        Self::segments_to_plain(&segments)
    }

    /// Export recorded output to HTML.
    #[must_use]
    pub fn export_html(&self, clear: bool) -> String {
        self.export_html_with_options(&ExportHtmlOptions {
            clear,
            ..ExportHtmlOptions::default()
        })
    }

    /// Export recorded output to SVG.
    #[must_use]
    pub fn export_svg(&self, clear: bool) -> String {
        self.export_svg_with_options(&ExportSvgOptions {
            clear,
            ..ExportSvgOptions::default()
        })
    }

    /// Export recorded output to HTML with Rich-style options.
    ///
    /// Mirrors Python Rich's `Console.export_html(...)` behavior.
    #[must_use]
    pub fn export_html_with_options(&self, options: &ExportHtmlOptions) -> String {
        assert!(
            self.record.load(Ordering::Relaxed),
            "To export console contents call Console::begin_capture() first"
        );
        let segments = self.recorded_segments(options.clear);
        export_segments_to_html_rich(&segments, options)
    }

    /// Export recorded output to SVG with Rich-style options.
    ///
    /// Mirrors Python Rich's `Console.export_svg(...)` behavior.
    #[must_use]
    pub fn export_svg_with_options(&self, options: &ExportSvgOptions) -> String {
        assert!(
            self.record.load(Ordering::Relaxed),
            "To export console contents call Console::begin_capture() first"
        );
        let segments = self.recorded_segments(options.clear);
        export_segments_to_svg_rich(&segments, self.width(), options)
    }

    /// Print to a specific writer.
    pub fn print_to<W: Write>(
        &self,
        writer: &mut W,
        content: &str,
        options: &PrintOptions,
    ) -> io::Result<()> {
        let segments = self.render_str_segments(content, options);
        let segments = self.apply_render_hooks(segments);
        self.write_segments_raw(writer, &segments)
    }

    fn render_str_segments(&self, content: &str, options: &PrintOptions) -> Vec<Segment<'static>> {
        let content = if self.emoji {
            emoji::replace(content, None)
        } else {
            std::borrow::Cow::Borrowed(content)
        };

        // Parse markup if enabled
        let parse_markup = options.markup.unwrap_or(self.markup);
        let mut text = if parse_markup {
            markup::render_or_plain_with_style_resolver(content.as_ref(), |definition| {
                self.get_style(definition)
            })
        } else {
            Text::new(content.as_ref())
        };

        let highlight_enabled = options.highlight.unwrap_or(self.highlight);
        if highlight_enabled {
            let highlighter = options.highlighter.as_ref().unwrap_or(&self.highlighter);
            highlighter.highlight(self, &mut text);
        }

        if let Some(justify) = options.justify {
            text.justify = justify;
        }
        if let Some(overflow) = options.overflow {
            text.overflow = overflow;
        }
        if let Some(no_wrap) = options.no_wrap {
            text.no_wrap = no_wrap;
        }
        if options.crop {
            text.overflow = OverflowMethod::Crop;
        }
        // soft_wrap enables wrapping by overriding text's no_wrap setting
        if options.soft_wrap {
            text.no_wrap = false;
        }

        let width = options.width.or_else(|| {
            if options.justify.is_some()
                || options.overflow.is_some()
                || options.no_wrap.is_some()
                || options.crop
                || options.soft_wrap
            {
                Some(self.width())
            } else {
                None
            }
        });

        let end = if options.no_newline { "" } else { &options.end };
        let mut segments: Vec<Segment<'static>> = if let Some(width) = width {
            let mut rendered = Vec::new();
            let lines = if text.no_wrap {
                text.split_lines()
            } else {
                text.wrap(width)
            };
            let last_index = lines.len().saturating_sub(1);
            let justify = match text.justify {
                JustifyMethod::Default => JustifyMethod::Left,
                other => other,
            };

            for (index, mut line) in lines.into_iter().enumerate() {
                if text.no_wrap && line.cell_len() > width {
                    line.truncate(width, line.overflow, false);
                }

                if matches!(
                    justify,
                    JustifyMethod::Center | JustifyMethod::Right | JustifyMethod::Full
                ) && line.cell_len() < width
                {
                    line.pad(width, justify);
                }

                let line_end = if index == last_index { end } else { "\n" };
                rendered.extend(line.render(line_end).into_iter().map(Segment::into_owned));
            }

            rendered
        } else {
            text.render(end)
                .into_iter()
                .map(Segment::into_owned)
                .collect()
        };

        // Apply any overall style
        if let Some(ref style) = options.style {
            for segment in &mut segments {
                if !segment.is_control() {
                    segment.style = Some(match segment.style {
                        Some(ref s) => style.combine(s),
                        None => style.clone(),
                    });
                }
            }
        }

        segments
    }

    fn segments_to_plain(segments: &[Segment<'_>]) -> String {
        let capacity: usize = segments
            .iter()
            .filter(|segment| !segment.is_control())
            .map(|segment| segment.text.len())
            .sum();
        let mut output = String::with_capacity(capacity);
        for segment in segments {
            if !segment.is_control() {
                output.push_str(segment.text.as_ref());
            }
        }
        output
    }

    fn recorded_segments(&self, clear: bool) -> Vec<Segment<'static>> {
        let mut buffer = lock_recover(&self.buffer);
        let segments = buffer.clone();
        if clear {
            buffer.clear();
        }
        segments
    }

    fn apply_render_hooks(&self, segments: Vec<Segment<'static>>) -> Vec<Segment<'static>> {
        let hooks = lock_recover(&self.render_hooks).clone();
        if hooks.is_empty() {
            return segments;
        }
        let mut current = segments;
        for hook in hooks {
            current = hook.process(self, &current);
        }
        current
    }

    /// Write segments to a writer without invoking render hooks.
    fn write_segments_raw<W: Write>(
        &self,
        writer: &mut W,
        segments: &[Segment<'_>],
    ) -> io::Result<()> {
        if self.record.load(Ordering::Relaxed) {
            lock_recover(&self.buffer).extend(segments.iter().cloned().map(Segment::into_owned));
        }

        let color_system = self.color_system();

        for segment in segments {
            if segment.is_control() {
                self.write_control_segment(writer, segment)?;
                continue;
            }

            // Get ANSI codes for style
            let ansi_codes;
            let (prefix, suffix) = if let Some(ref style) = segment.style {
                if let Some(cs) = color_system {
                    ansi_codes = style.render_ansi(cs);
                    (&ansi_codes.0, &ansi_codes.1)
                } else {
                    static EMPTY: (String, String) = (String::new(), String::new());
                    (&EMPTY.0, &EMPTY.1)
                }
            } else {
                static EMPTY: (String, String) = (String::new(), String::new());
                (&EMPTY.0, &EMPTY.1)
            };

            // Write styled text
            write!(writer, "{prefix}{}{suffix}", segment.text)?;
        }

        writer.flush()
    }

    fn write_control_segment<W: Write>(
        &self,
        writer: &mut W,
        segment: &Segment<'_>,
    ) -> io::Result<()> {
        let Some(ref controls) = segment.control else {
            return Ok(());
        };

        for control in controls {
            match control.control_type {
                crate::segment::ControlType::Bell => {
                    write!(writer, "\x07")?;
                }
                crate::segment::ControlType::CarriageReturn => {
                    write!(writer, "\r")?;
                }
                crate::segment::ControlType::Home => {
                    write!(writer, "\x1b[H")?;
                }
                crate::segment::ControlType::Clear => {
                    write!(writer, "\x1b[2J")?;
                }
                crate::segment::ControlType::ShowCursor => {
                    write!(writer, "\x1b[?25h")?;
                }
                crate::segment::ControlType::HideCursor => {
                    write!(writer, "\x1b[?25l")?;
                }
                crate::segment::ControlType::EnableAltScreen => {
                    write!(writer, "\x1b[?1049h")?;
                }
                crate::segment::ControlType::DisableAltScreen => {
                    write!(writer, "\x1b[?1049l")?;
                }
                crate::segment::ControlType::CursorUp => {
                    let n = control_param(&control.params, 0, 1);
                    write!(writer, "\x1b[{n}A")?;
                }
                crate::segment::ControlType::CursorDown => {
                    let n = control_param(&control.params, 0, 1);
                    write!(writer, "\x1b[{n}B")?;
                }
                crate::segment::ControlType::CursorForward => {
                    let n = control_param(&control.params, 0, 1);
                    write!(writer, "\x1b[{n}C")?;
                }
                crate::segment::ControlType::CursorBackward => {
                    let n = control_param(&control.params, 0, 1);
                    write!(writer, "\x1b[{n}D")?;
                }
                crate::segment::ControlType::CursorMoveToColumn => {
                    // Python Rich expects 0-based columns in ControlCode parameters and
                    // formats with +1 (terminal control sequences are 1-based).
                    let column0 = control_param(&control.params, 0, 0);
                    write!(writer, "\x1b[{}G", column0 + 1)?;
                }
                crate::segment::ControlType::CursorMoveTo => {
                    // Python Rich stores (x, y) 0-based and formats as (y+1; x+1).
                    let x0 = control_param(&control.params, 0, 0);
                    let y0 = control_param(&control.params, 1, 0);
                    write!(writer, "\x1b[{};{}H", y0 + 1, x0 + 1)?;
                }
                crate::segment::ControlType::EraseInLine => {
                    let mode = erase_in_line_mode(&control.params);
                    write!(writer, "\x1b[{mode}K")?;
                }
                crate::segment::ControlType::SetWindowTitle => {
                    let title = control_title(segment, control);
                    write!(writer, "\x1b]0;{title}\x07")?;
                }
            }
        }

        Ok(())
    }

    /// Print a blank line.
    pub fn line(&self) {
        let mut file = lock_recover(&self.file);
        let _ = writeln!(file);
    }

    /// Print a rule (horizontal line).
    pub fn rule(&self, title: Option<&str>) {
        let width = self.width();
        let line_char = if self.safe_box { '-' } else { '\u{2500}' };

        let mut file = lock_recover(&self.file);
        if let Some(title) = title {
            // Ensure title fits within width, accounting for 2 spaces padding
            let max_title_width = width.saturating_sub(2);
            let title_len = crate::cells::cell_len(title);

            let display_title = if title_len > max_title_width {
                let mut t = Text::new(title);
                t.truncate(max_title_width, OverflowMethod::Ellipsis, false);
                t.plain().to_string()
            } else {
                title.to_string()
            };

            let display_len = crate::cells::cell_len(&display_title);
            let available = width.saturating_sub(display_len + 2);
            let left_pad = available / 2;
            let right_pad = available - left_pad;
            let left = line_char.to_string().repeat(left_pad);
            let right = line_char.to_string().repeat(right_pad);
            let _ = writeln!(file, "{left} {display_title} {right}");
        } else {
            let _ = writeln!(file, "{}", line_char.to_string().repeat(width));
        }
    }

    /// Clear the screen.
    pub fn clear(&self) {
        let mut file = lock_recover(&self.file);
        let _ = terminal::control::clear_screen(&mut *file);
    }

    /// Clear the current line.
    pub fn clear_line(&self) {
        let mut file = lock_recover(&self.file);
        let _ = terminal::control::clear_line(&mut *file);
    }

    /// Set the terminal title.
    pub fn set_title(&self, title: &str) {
        let mut file = lock_recover(&self.file);
        let _ = terminal::control::set_title(&mut *file, title);
    }

    /// Ring the terminal bell.
    pub fn bell(&self) {
        let mut file = lock_recover(&self.file);
        let _ = terminal::control::bell(&mut *file);
    }

    /// Print text without parsing markup.
    pub fn print_plain(&self, content: &str) {
        self.print_with_options(content, &PrintOptions::new().with_markup(false));
    }

    /// Print a styled message.
    pub fn print_styled(&self, content: &str, style: Style) {
        self.print_with_options(
            content,
            &PrintOptions::new()
                .with_markup(self.markup)
                .with_style(style),
        );
    }

    /// Print a log message with a level indicator.
    ///
    /// This is a simple version that just shows the level prefix and message.
    /// For timestamps and file/line info, use [`log_with_options`](Self::log_with_options).
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use rich_rust::console::{Console, LogLevel};
    ///
    /// let console = Console::new();
    /// console.log("Starting server", LogLevel::Info);
    /// console.log("Something went wrong", LogLevel::Error);
    /// ```
    pub fn log(&self, message: &str, level: LogLevel) {
        self.log_with_options(message, level, &LogOptions::new());
    }

    /// Print a log message with a level indicator, timestamp, and optional file/line info.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use rich_rust::console::{Console, LogLevel, LogOptions};
    ///
    /// let console = Console::new();
    ///
    /// // With timestamp
    /// let opts = LogOptions::new().with_timestamp(true);
    /// console.log_with_options("Server started", LogLevel::Info, &opts);
    /// // Output: [12:34:56] [INFO] Server started
    ///
    /// // With timestamp and file/line
    /// let opts = LogOptions::new()
    ///     .with_timestamp(true)
    ///     .with_path("src/main.rs", 42);
    /// console.log_with_options("Debug info", LogLevel::Debug, &opts);
    /// // Output: [12:34:56] src/main.rs:42 [DEBUG] Debug info
    /// ```
    pub fn log_with_options(&self, message: &str, level: LogLevel, options: &LogOptions) {
        let (level_prefix, level_style) = match level {
            LogLevel::Debug => ("[DEBUG]", Style::parse("cyan").unwrap_or_default()),
            LogLevel::Info => ("[INFO]", Style::parse("green").unwrap_or_default()),
            LogLevel::Warning => ("[WARNING]", Style::parse("yellow").unwrap_or_default()),
            LogLevel::Error => ("[ERROR]", Style::parse("bold red").unwrap_or_default()),
        };

        {
            let mut file = lock_recover(&self.file);
            // Print timestamp if enabled
            if options.show_timestamp {
                let timestamp = Self::format_timestamp(options.timestamp_format.as_deref());
                let ts_style = Style::parse("dim").unwrap_or_default();
                let _ = self.print_to(
                    &mut *file,
                    &timestamp,
                    &PrintOptions::new().with_markup(false).with_style(ts_style),
                );
                let _ = write!(file, " ");
            }

            // Print file/line info if provided
            if options.file_path.is_some() || options.line_number.is_some() {
                let path_style = Style::parse("magenta").unwrap_or_default();
                let path_info = match (&options.file_path, options.line_number) {
                    (Some(path), Some(line)) => format!("{path}:{line}"),
                    (Some(path), None) => path.clone(),
                    (None, Some(line)) => format!(":{line}"),
                    (None, None) => String::new(),
                };
                if !path_info.is_empty() {
                    let _ = self.print_to(
                        &mut *file,
                        &path_info,
                        &PrintOptions::new()
                            .with_markup(false)
                            .with_style(path_style),
                    );
                    let _ = write!(file, " ");
                }
            }

            // Print level prefix if enabled
            if options.show_level {
                let _ = self.print_to(
                    &mut *file,
                    level_prefix,
                    &PrintOptions::new()
                        .with_markup(false)
                        .with_style(level_style),
                );
                let _ = write!(file, " ");
            }

            // Print the message
            let _ = self.print_to(
                &mut *file,
                message,
                &PrintOptions::new().with_markup(self.markup),
            );
        }
    }

    /// Format the current time as a timestamp string.
    fn format_timestamp(format: Option<&str>) -> String {
        // Prefer local time for parity with typical "console logger" expectations, but
        // fall back to UTC when local offset can't be determined (e.g., sandboxed envs).
        let now = OffsetDateTime::now_local().unwrap_or_else(|_| OffsetDateTime::now_utc());

        match format {
            None => format!(
                "[{:02}:{:02}:{:02}]",
                now.hour(),
                now.minute(),
                now.second()
            ),
            Some(fmt) => Self::format_timestamp_strftime_subset(&now, fmt),
        }
    }

    // Intentionally supports a small, stable subset of strftime:
    // %Y %m %d %H %M %S and %%.
    fn format_timestamp_strftime_subset(now: &OffsetDateTime, fmt: &str) -> String {
        let mut out = String::with_capacity(fmt.len().saturating_add(8));
        let mut it = fmt.chars();

        while let Some(ch) = it.next() {
            if ch != '%' {
                out.push(ch);
                continue;
            }

            let Some(code) = it.next() else {
                out.push('%');
                break;
            };

            match code {
                '%' => out.push('%'),
                'H' => {
                    let _ = write!(out, "{:02}", now.hour());
                }
                'M' => {
                    let _ = write!(out, "{:02}", now.minute());
                }
                'S' => {
                    let _ = write!(out, "{:02}", now.second());
                }
                'Y' => {
                    let _ = write!(out, "{:04}", now.year());
                }
                'm' => {
                    // time::Month implements `From<Month> for u8`.
                    let _ = write!(out, "{:02}", u8::from(now.month()));
                }
                'd' => {
                    let _ = write!(out, "{:02}", now.day());
                }
                other => {
                    // Preserve unknown tokens literally to avoid surprising callers.
                    out.push('%');
                    out.push(other);
                }
            }
        }

        out
    }
}

fn control_param(params: &[i32], index: usize, default: i32) -> i32 {
    params
        .get(index)
        .copied()
        .filter(|value| *value > 0)
        .unwrap_or(default)
}

fn erase_in_line_mode(params: &[i32]) -> i32 {
    if let Some(value) = params.first().copied()
        && (0..=2).contains(&value)
    {
        return value;
    }
    2
}

fn control_title(segment: &Segment<'_>, control: &crate::segment::ControlCode) -> String {
    let raw_title = if !segment.text.is_empty() {
        segment.text.to_string()
    } else if !control.params.is_empty() {
        let mut title = String::with_capacity(control.params.len());
        for param in &control.params {
            if let Ok(byte) = u8::try_from(*param) {
                title.push(byte as char);
            }
        }
        title
    } else {
        String::new()
    };

    // Sanitize title to prevent terminal injection:
    // Remove control characters that could break or escape the OSC sequence
    raw_title
        .chars()
        .filter(|c| {
            // Allow printable characters only, excluding control chars
            // BEL (\x07) terminates OSC, ESC (\x1b) starts new sequences
            !c.is_control()
        })
        .collect()
}

// ============================================================================
// HTML/SVG Export (Python Rich parity)
// ============================================================================

/// Default HTML export template (Rich 13.9.4).
pub const CONSOLE_HTML_FORMAT: &str = "<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"UTF-8\">\n<style>\n{stylesheet}\nbody {\n    color: {foreground};\n    background-color: {background};\n}\n</style>\n</head>\n<body>\n    <pre style=\"font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><code style=\"font-family:inherit\">{code}</code></pre>\n</body>\n</html>\n";

/// Default SVG export template (Rich 13.9.4).
pub const CONSOLE_SVG_FORMAT: &str = "<svg class=\"rich-terminal\" viewBox=\"0 0 {width} {height}\" xmlns=\"http://www.w3.org/2000/svg\">\n    <!-- Generated with Rich https://www.textualize.io -->\n    <style>\n\n    @font-face {\n        font-family: \"Fira Code\";\n        src: local(\"FiraCode-Regular\"),\n                url(\"https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Regular.woff2\") format(\"woff2\"),\n                url(\"https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Regular.woff\") format(\"woff\");\n        font-style: normal;\n        font-weight: 400;\n    }\n    @font-face {\n        font-family: \"Fira Code\";\n        src: local(\"FiraCode-Bold\"),\n                url(\"https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Bold.woff2\") format(\"woff2\"),\n                url(\"https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Bold.woff\") format(\"woff\");\n        font-style: bold;\n        font-weight: 700;\n    }\n\n    .{unique_id}-matrix {\n        font-family: Fira Code, monospace;\n        font-size: {char_height}px;\n        line-height: {line_height}px;\n        font-variant-east-asian: full-width;\n    }\n\n    .{unique_id}-title {\n        font-size: 18px;\n        font-weight: bold;\n        font-family: arial;\n    }\n\n    {styles}\n    </style>\n\n    <defs>\n    <clipPath id=\"{unique_id}-clip-terminal\">\n      <rect x=\"0\" y=\"0\" width=\"{terminal_width}\" height=\"{terminal_height}\" />\n    </clipPath>\n    {lines}\n    </defs>\n\n    {chrome}\n    <g transform=\"translate({terminal_x}, {terminal_y})\" clip-path=\"url(#{unique_id}-clip-terminal)\">\n    {backgrounds}\n    <g class=\"{unique_id}-matrix\">\n    {matrix}\n    </g>\n    </g>\n</svg>\n";

/// Options for controlling HTML export.
#[derive(Debug, Clone)]
pub struct ExportHtmlOptions {
    pub theme: TerminalTheme,
    pub clear: bool,
    /// Optional template override. If `None`, uses [`CONSOLE_HTML_FORMAT`].
    pub code_format: Option<String>,
    pub inline_styles: bool,
}

impl Default for ExportHtmlOptions {
    fn default() -> Self {
        Self {
            theme: DEFAULT_TERMINAL_THEME,
            clear: true,
            code_format: None,
            inline_styles: false,
        }
    }
}

/// Options for controlling SVG export.
#[derive(Debug, Clone)]
pub struct ExportSvgOptions {
    pub title: String,
    pub theme: TerminalTheme,
    pub clear: bool,
    /// Optional template override. If `None`, uses [`CONSOLE_SVG_FORMAT`].
    pub code_format: Option<String>,
    pub font_aspect_ratio: f64,
    pub unique_id: Option<String>,
}

impl Default for ExportSvgOptions {
    fn default() -> Self {
        Self {
            title: "Rich".to_string(),
            theme: SVG_EXPORT_THEME,
            clear: true,
            code_format: None,
            font_aspect_ratio: 0.61,
            unique_id: None,
        }
    }
}

fn export_segments_to_html_rich(segments: &[Segment<'_>], options: &ExportHtmlOptions) -> String {
    let theme = options.theme;
    let render_code_format = options
        .code_format
        .as_deref()
        .unwrap_or(CONSOLE_HTML_FORMAT);

    let simplified = crate::segment::simplify(segments.iter().cloned());

    let mut fragments: Vec<String> = Vec::new();
    let mut stylesheet = String::new();

    if options.inline_styles {
        for segment in simplified {
            if segment.is_control() {
                continue;
            }
            let mut text = escape_html_rich(segment.text.as_ref());
            if let Some(style) = &segment.style {
                let rule = style.get_html_style(theme);
                if let Some(link) = &style.link {
                    text = format!("<a href=\"{link}\">{text}</a>");
                }
                if !rule.is_empty() {
                    text = format!("<span style=\"{rule}\">{text}</span>");
                }
            }
            fragments.push(text);
        }
    } else {
        let mut rules_to_no: HashMap<String, usize> = HashMap::new();
        let mut rules_in_order: Vec<String> = Vec::new();

        let mut get_no = |rule: &str| -> usize {
            if let Some(n) = rules_to_no.get(rule) {
                *n
            } else {
                let n = rules_in_order.len() + 1;
                rules_in_order.push(rule.to_string());
                rules_to_no.insert(rule.to_string(), n);
                n
            }
        };

        for segment in simplified {
            if segment.is_control() {
                continue;
            }
            let mut text = escape_html_rich(segment.text.as_ref());
            if let Some(style) = &segment.style {
                let rule = style.get_html_style(theme);
                let style_no = get_no(&rule);
                if let Some(link) = &style.link {
                    text = format!("<a class=\"r{style_no}\" href=\"{link}\">{text}</a>");
                } else {
                    text = format!("<span class=\"r{style_no}\">{text}</span>");
                }
            }
            fragments.push(text);
        }

        let mut stylesheet_rules: Vec<String> = Vec::new();
        for (idx, rule) in rules_in_order.iter().enumerate() {
            let style_no = idx + 1;
            if !rule.is_empty() {
                stylesheet_rules.push(format!(".r{style_no} {{{rule}}}"));
            }
        }
        stylesheet = stylesheet_rules.join("\n");
    }

    let code = fragments.join("");
    let foreground = theme.foreground_color.hex();
    let background = theme.background_color.hex();
    apply_template(
        render_code_format,
        &[
            ("code", &code),
            ("stylesheet", &stylesheet),
            ("foreground", &foreground),
            ("background", &background),
        ],
    )
}

#[expect(
    clippy::cast_precision_loss,
    reason = "SVG export uses f64 coordinates; console widths/heights are small in practice"
)]
fn export_segments_to_svg_rich(
    segments: &[Segment<'_>],
    console_width: usize,
    options: &ExportSvgOptions,
) -> String {
    use crate::cells::cell_len;

    let theme = options.theme;
    let code_format = options.code_format.as_deref().unwrap_or(CONSOLE_SVG_FORMAT);

    let width = console_width;
    let char_height = 20.0_f64;
    let char_width = char_height * options.font_aspect_ratio;
    let line_height = char_height * 1.22;

    let margin_top = 1.0_f64;
    let margin_right = 1.0_f64;
    let margin_bottom = 1.0_f64;
    let margin_left = 1.0_f64;

    let padding_top = 40.0_f64;
    let padding_right = 8.0_f64;
    let padding_bottom = 8.0_f64;
    let padding_left = 8.0_f64;

    let padding_width = padding_left + padding_right;
    let padding_height = padding_top + padding_bottom;
    let margin_width = margin_left + margin_right;
    let margin_height = margin_top + margin_bottom;

    let mut style_cache: HashMap<Style, String> = HashMap::new();
    let mut get_svg_style = |style: &Style| -> String {
        if let Some(cached) = style_cache.get(style) {
            return cached.clone();
        }
        let css = style.get_svg_style(theme);
        style_cache.insert(style.clone(), css.clone());
        css
    };

    let mut text_backgrounds: Vec<String> = Vec::new();
    let mut text_group: Vec<String> = Vec::new();

    let mut classes_to_no: HashMap<String, usize> = HashMap::new();
    let mut classes_in_order: Vec<String> = Vec::new();
    let mut get_class_no = |rules: &str| -> usize {
        if let Some(n) = classes_to_no.get(rules) {
            *n
        } else {
            let n = classes_in_order.len() + 1;
            classes_in_order.push(rules.to_string());
            classes_to_no.insert(rules.to_string(), n);
            n
        }
    };

    let escape_text = |text: &str| -> String { escape_html_rich(text).replace(' ', "&#160;") };

    let segments: Vec<Segment<'static>> = segments
        .iter()
        .cloned()
        .map(Segment::into_owned)
        .filter(|seg| !seg.is_control())
        .collect();

    let unique_id = options.unique_id.clone().unwrap_or_else(|| {
        let mut repr = String::new();
        for seg in &segments {
            if seg.is_control() {
                continue;
            }
            let _ = FmtWrite::write_fmt(
                &mut repr,
                format_args!(
                    "Segment(text={:?},style={:?},control={:?})",
                    seg.text, seg.style, seg.control
                ),
            );
        }
        repr.push_str(&options.title);
        let checksum = adler32(repr.as_bytes());
        format!("terminal-{checksum}")
    });

    let mut y_last = 0usize;
    let mut lines = crate::segment::split_lines(segments.into_iter());
    lines = lines
        .into_iter()
        .map(|line| crate::segment::adjust_line_length(line, width, None, false))
        .collect();

    let default_style = Style::default();

    for (y, line) in lines.iter().enumerate() {
        y_last = y;
        let mut x_cells = 0usize;
        for segment in line {
            if segment.is_control() {
                continue;
            }

            let text = segment.text.as_ref();
            let style = segment.style.as_ref().unwrap_or(&default_style);
            let rules = get_svg_style(style);
            let class_no = get_class_no(&rules);
            let class_name = format!("r{class_no}");

            let (has_background, background_hex) = if style.attributes.contains(Attributes::REVERSE)
            {
                let bg = match &style.color {
                    None => theme.foreground_color,
                    Some(c) => c.get_truecolor_with_theme(theme, true),
                };
                (true, bg.hex())
            } else {
                let has_bg = style.bgcolor.as_ref().is_some_and(|c| !c.is_default());
                let bg = match &style.bgcolor {
                    None => theme.background_color,
                    Some(c) => c.get_truecolor_with_theme(theme, false),
                };
                (has_bg, bg.hex())
            };

            let text_length = cell_len(text);
            if has_background {
                text_backgrounds.push(format!(
                    "<rect fill=\"{background_hex}\" x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" shape-rendering=\"crispEdges\"/>",
                    (x_cells as f64) * char_width,
                    (y as f64) * line_height + 1.5,
                    char_width * (text_length as f64),
                    line_height + 0.25
                ));
            }

            let all_spaces = text.chars().all(|ch| ch == ' ');
            if !all_spaces {
                let text_len_chars = text.chars().count();
                text_group.push(format!(
                    "<text class=\"{unique_id}-{class_name}\" x=\"{}\" y=\"{}\" textLength=\"{}\" clip-path=\"url(#{unique_id}-line-{y})\">{}</text>",
                    (x_cells as f64) * char_width,
                    (y as f64) * line_height + char_height,
                    char_width * (text_len_chars as f64),
                    escape_text(text)
                ));
            }

            x_cells = x_cells.saturating_add(cell_len(text));
        }
    }

    let mut lines_defs = String::new();
    if y_last > 0 {
        for line_no in 0..y_last {
            let offset = (line_no as f64) * line_height + 1.5;
            let _ = FmtWrite::write_fmt(
                &mut lines_defs,
                format_args!(
                    "<clipPath id=\"{unique_id}-line-{line_no}\">\n    <rect x=\"0\" y=\"{offset}\" width=\"{}\" height=\"{}\"/>\n            </clipPath>",
                    char_width * (width as f64),
                    line_height + 0.25
                ),
            );
        }
    }

    let mut styles = String::new();
    for (idx, css) in classes_in_order.iter().enumerate() {
        let rule_no = idx + 1;
        let _ = FmtWrite::write_fmt(
            &mut styles,
            format_args!(".{unique_id}-r{rule_no} {{ {css} }}\n"),
        );
    }

    let backgrounds = text_backgrounds.join("");
    let matrix = text_group.join("");

    let outer_terminal_width = ((width as f64) * char_width + padding_width).ceil();
    let outer_terminal_height = ((y_last as f64) + 1.0) * line_height + padding_height;

    let mut chrome = format!(
        "<rect fill=\"{}\" stroke=\"rgba(255,255,255,0.35)\" stroke-width=\"1\" x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" rx=\"8\"/>",
        theme.background_color.hex(),
        margin_left,
        margin_top,
        outer_terminal_width,
        outer_terminal_height
    );

    if !options.title.is_empty() {
        let title_fill = theme.foreground_color.hex();
        let title_x = outer_terminal_width / 2.0;
        let title_y = margin_top + char_height + 6.0;
        let _ = FmtWrite::write_fmt(
            &mut chrome,
            format_args!(
                "<text class=\"{unique_id}-title\" fill=\"{title_fill}\" text-anchor=\"middle\" x=\"{title_x}\" y=\"{title_y}\">{}</text>",
                escape_text(&options.title)
            ),
        );
    }
    chrome.push_str(
        "\n            <g transform=\"translate(26,22)\">\n            <circle cx=\"0\" cy=\"0\" r=\"7\" fill=\"#ff5f57\"/>\n            <circle cx=\"22\" cy=\"0\" r=\"7\" fill=\"#febc2e\"/>\n            <circle cx=\"44\" cy=\"0\" r=\"7\" fill=\"#28c840\"/>\n            </g>\n        ",
    );

    let char_width_s = char_width.to_string();
    let char_height_s = char_height.to_string();
    let line_height_s = line_height.to_string();
    let terminal_width_s = (char_width * (width as f64) - 1.0).to_string();
    let terminal_height_s = (((y_last as f64) + 1.0) * line_height - 1.0).to_string();
    let width_s = (outer_terminal_width + margin_width).to_string();
    let height_s = (outer_terminal_height + margin_height).to_string();
    let terminal_translate_x = (margin_left + padding_left).to_string();
    let terminal_translate_y = (margin_top + padding_top).to_string();

    apply_template(
        code_format,
        &[
            ("unique_id", &unique_id),
            ("char_width", &char_width_s),
            ("char_height", &char_height_s),
            ("line_height", &line_height_s),
            ("terminal_width", &terminal_width_s),
            ("terminal_height", &terminal_height_s),
            ("width", &width_s),
            ("height", &height_s),
            ("terminal_x", &terminal_translate_x),
            ("terminal_y", &terminal_translate_y),
            ("styles", &styles),
            ("chrome", &chrome),
            ("backgrounds", &backgrounds),
            ("matrix", &matrix),
            ("lines", &lines_defs),
        ],
    )
}

fn apply_template(template: &str, vars: &[(&str, &str)]) -> String {
    let mut out = template.to_string();
    for (key, value) in vars {
        out = out.replace(&format!("{{{key}}}"), value);
    }
    out
}

fn escape_html_rich(text: &str) -> String {
    let mut escaped = String::with_capacity(text.len());
    for ch in text.chars() {
        match ch {
            '&' => escaped.push_str("&amp;"),
            '<' => escaped.push_str("&lt;"),
            '>' => escaped.push_str("&gt;"),
            '"' => escaped.push_str("&quot;"),
            _ => escaped.push(ch),
        }
    }
    escaped
}

fn adler32(bytes: &[u8]) -> u32 {
    const MOD_ADLER: u32 = 65521;
    let mut a: u32 = 1;
    let mut b: u32 = 0;
    for &byte in bytes {
        a = (a + u32::from(byte)) % MOD_ADLER;
        b = (b + a) % MOD_ADLER;
    }
    (b << 16) | a
}

/// Log level for `console.log()`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogLevel {
    Debug,
    Info,
    Warning,
    Error,
}

/// Options for controlling log output format.
///
/// # Examples
///
/// ```rust,ignore
/// use rich_rust::console::{Console, LogLevel, LogOptions};
///
/// let console = Console::new();
///
/// // Log with timestamp
/// let opts = LogOptions::new().with_timestamp(true);
/// console.log_with_options("Something happened", LogLevel::Info, &opts);
///
/// // Log with file/line info
/// let opts = LogOptions::new()
///     .with_timestamp(true)
///     .with_path("src/main.rs", 42);
/// console.log_with_options("Debug info", LogLevel::Debug, &opts);
/// ```
#[derive(Debug, Clone)]
pub struct LogOptions {
    /// Whether to show a timestamp.
    pub show_timestamp: bool,
    /// Custom timestamp format (strftime-like subset).
    ///
    /// Supported codes: `%Y` `%m` `%d` `%H` `%M` `%S` and `%%`.
    /// Unknown codes are preserved literally.
    ///
    /// If None, uses default format: `"[HH:MM:SS]"`.
    pub timestamp_format: Option<String>,
    /// File path (e.g., "src/main.rs").
    pub file_path: Option<String>,
    /// Line number within the file.
    pub line_number: Option<u32>,
    /// Whether to show the log level prefix.
    pub show_level: bool,
    /// Whether to highlight keywords in the message.
    pub highlight: bool,
}

impl Default for LogOptions {
    fn default() -> Self {
        Self::new()
    }
}

impl LogOptions {
    /// Create new log options with default values.
    #[must_use]
    pub fn new() -> Self {
        Self {
            show_timestamp: false,
            timestamp_format: None,
            file_path: None,
            line_number: None,
            show_level: true,
            highlight: false,
        }
    }

    /// Enable or disable timestamp display.
    #[must_use]
    pub fn with_timestamp(mut self, show: bool) -> Self {
        self.show_timestamp = show;
        self
    }

    /// Set a custom timestamp format.
    ///
    /// Simple format using: `%H` (hour), `%M` (minute), `%S` (second),
    /// `%Y` (year), `%m` (month), `%d` (day).
    #[must_use]
    pub fn with_timestamp_format(mut self, format: impl Into<String>) -> Self {
        self.timestamp_format = Some(format.into());
        self
    }

    /// Set the file path and line number for caller info.
    #[must_use]
    pub fn with_path(mut self, file: impl Into<String>, line: u32) -> Self {
        self.file_path = Some(file.into());
        self.line_number = Some(line);
        self
    }

    /// Set just the file path (without line number).
    #[must_use]
    pub fn with_file(mut self, file: impl Into<String>) -> Self {
        self.file_path = Some(file.into());
        self
    }

    /// Set just the line number.
    #[must_use]
    pub fn with_line(mut self, line: u32) -> Self {
        self.line_number = Some(line);
        self
    }

    /// Enable or disable level prefix display.
    #[must_use]
    pub fn with_level(mut self, show: bool) -> Self {
        self.show_level = show;
        self
    }

    /// Enable or disable keyword highlighting.
    #[must_use]
    pub fn with_highlight(mut self, highlight: bool) -> Self {
        self.highlight = highlight;
        self
    }
}

/// RAII guard returned by [`Console::use_theme`].
pub struct ThemeGuard<'a> {
    console: &'a Console,
}

impl Drop for ThemeGuard<'_> {
    fn drop(&mut self) {
        let _ = self.console.pop_theme();
    }
}

/// Builder for creating a Console with custom settings.
#[derive(Default)]
pub struct ConsoleBuilder {
    color_system: Option<ColorSystem>,
    force_terminal: Option<bool>,
    tab_size: Option<usize>,
    markup: Option<bool>,
    emoji: Option<bool>,
    highlight: Option<bool>,
    highlighter: Option<Arc<dyn Highlighter>>,
    width: Option<usize>,
    height: Option<usize>,
    safe_box: Option<bool>,
    theme: Option<Theme>,
    file: Option<Box<dyn Write + Send>>,
}

impl std::fmt::Debug for ConsoleBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ConsoleBuilder")
            .field("color_system", &self.color_system)
            .field("force_terminal", &self.force_terminal)
            .field("tab_size", &self.tab_size)
            .field("markup", &self.markup)
            .field("emoji", &self.emoji)
            .field("highlight", &self.highlight)
            .field(
                "highlighter",
                &self.highlighter.as_ref().map(|_| "<Highlighter>"),
            )
            .field("width", &self.width)
            .field("height", &self.height)
            .field("safe_box", &self.safe_box)
            .field("theme", &self.theme.as_ref().map(|_| "<Theme>"))
            .field("file", &self.file.as_ref().map(|_| "<dyn Write>"))
            .finish()
    }
}

impl ConsoleBuilder {
    /// Set the color system.
    #[must_use]
    pub fn color_system(mut self, system: ColorSystem) -> Self {
        self.color_system = Some(system);
        self
    }

    /// Disable colors.
    #[must_use]
    pub fn no_color(mut self) -> Self {
        self.color_system = None;
        self
    }

    /// Force terminal mode.
    #[must_use]
    pub fn force_terminal(mut self, force: bool) -> Self {
        self.force_terminal = Some(force);
        self
    }

    /// Set tab size.
    #[must_use]
    pub fn tab_size(mut self, size: usize) -> Self {
        self.tab_size = Some(size);
        self
    }

    /// Enable/disable markup parsing.
    #[must_use]
    pub fn markup(mut self, enabled: bool) -> Self {
        self.markup = Some(enabled);
        self
    }

    /// Enable/disable emoji.
    #[must_use]
    pub fn emoji(mut self, enabled: bool) -> Self {
        self.emoji = Some(enabled);
        self
    }

    /// Enable/disable highlighting.
    #[must_use]
    pub fn highlight(mut self, enabled: bool) -> Self {
        self.highlight = Some(enabled);
        self
    }

    /// Set the console's default highlighter.
    #[must_use]
    pub fn highlighter<H: Highlighter + 'static>(mut self, highlighter: H) -> Self {
        self.highlighter = Some(Arc::new(highlighter));
        self
    }

    /// Set console width.
    #[must_use]
    pub fn width(mut self, width: usize) -> Self {
        self.width = Some(width);
        self
    }

    /// Set console height.
    #[must_use]
    pub fn height(mut self, height: usize) -> Self {
        self.height = Some(height);
        self
    }

    /// Use ASCII-safe box characters.
    #[must_use]
    pub fn safe_box(mut self, safe: bool) -> Self {
        self.safe_box = Some(safe);
        self
    }

    /// Set the initial console theme.
    #[must_use]
    pub fn theme(mut self, theme: Theme) -> Self {
        self.theme = Some(theme);
        self
    }

    /// Set the output stream.
    #[must_use]
    pub fn file(mut self, writer: Box<dyn Write + Send>) -> Self {
        self.file = Some(writer);
        self
    }

    /// Build the console.
    #[must_use]
    pub fn build(self) -> Console {
        let mut console = Console::new();

        if let Some(cs) = self.color_system {
            console.color_system = Some(cs);
        }
        if let Some(ft) = self.force_terminal {
            console.force_terminal = Some(ft);
            if console.color_system.is_none() {
                console.detected_color_system = if ft {
                    terminal::detect_color_system_forced(true)
                } else {
                    None
                };
            }
        }
        if let Some(ts) = self.tab_size {
            console.tab_size = ts;
        }
        if let Some(m) = self.markup {
            console.markup = m;
        }
        if let Some(e) = self.emoji {
            console.emoji = e;
        }
        if let Some(h) = self.highlight {
            console.highlight = h;
        }
        if let Some(highlighter) = self.highlighter {
            console.highlighter = highlighter;
        }
        if let Some(w) = self.width {
            console.width = Some(w);
        }
        if let Some(h) = self.height {
            console.height = Some(h);
        }
        if let Some(sb) = self.safe_box {
            console.safe_box = sb;
        }
        if let Some(theme) = self.theme {
            console.theme_stack = Mutex::new(ThemeStack::new(theme));
        }
        if let Some(f) = self.file {
            console.file = Mutex::new(f);
        }

        console
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::highlighter::NullHighlighter;

    #[test]
    fn test_console_new() {
        let console = Console::new();
        assert!(console.width() > 0);
        assert!(console.height() > 0);
    }

    #[test]
    fn test_console_builder() {
        let console = Console::builder()
            .width(100)
            .height(50)
            .markup(false)
            .build();

        assert_eq!(console.width(), 100);
        assert_eq!(console.height(), 50);
        assert!(!console.markup);
    }

    #[test]
    fn test_console_default_highlighter_applies_when_enabled() {
        let console = Console::builder().markup(false).build();
        let opts = PrintOptions::new().with_markup(false).with_no_newline(true);
        let segments = console.render_str_segments("True", &opts);
        let expected = console.get_style("repr.bool_true");
        assert!(segments.iter().any(|s| s.style.as_ref() == Some(&expected)));
    }

    #[test]
    fn test_console_highlight_override_off_disables_highlighter() {
        let console = Console::builder().markup(false).build();
        let opts = PrintOptions::new()
            .with_markup(false)
            .with_no_newline(true)
            .with_highlight(false);
        let segments = console.render_str_segments("True", &opts);
        let expected = console.get_style("repr.bool_true");
        assert!(!segments.iter().any(|s| s.style.as_ref() == Some(&expected)));
    }

    #[test]
    fn test_console_builder_highlighter_override() {
        let console = Console::builder()
            .markup(false)
            .highlighter(NullHighlighter)
            .build();
        let opts = PrintOptions::new().with_markup(false).with_no_newline(true);
        let segments = console.render_str_segments("True", &opts);
        let expected = console.get_style("repr.bool_true");
        assert!(!segments.iter().any(|s| s.style.as_ref() == Some(&expected)));
    }

    #[test]
    fn test_console_print_options_highlighter_override() {
        let console = Console::builder().markup(false).build();
        let opts = PrintOptions::new()
            .with_markup(false)
            .with_no_newline(true)
            .with_highlight(true)
            .with_highlighter(NullHighlighter);
        let segments = console.render_str_segments("True", &opts);
        let expected = console.get_style("repr.bool_true");
        assert!(!segments.iter().any(|s| s.style.as_ref() == Some(&expected)));
    }

    #[test]
    fn test_console_options() {
        let console = Console::builder().width(80).build();
        let options = console.options();

        assert_eq!(options.max_width, 80);
        assert_eq!(options.size.width, 80);
    }

    #[test]
    fn test_print_options() {
        let options = PrintOptions::new()
            .with_markup(true)
            .with_style(Style::new().bold());

        assert_eq!(options.markup, Some(true));
        assert!(options.style.is_some());
    }

    #[test]
    fn test_capture() {
        let console = Console::new();
        console.begin_capture();

        console.print_plain("capture test");
        let segments = console.end_capture();
        let captured: String = segments.iter().map(|s| s.text.as_ref()).collect();
        assert!(captured.contains("capture test"));
    }

    #[test]
    fn test_capture_collects_segments() {
        use std::sync::{Arc, Mutex};

        #[derive(Clone)]
        struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

        impl Write for SharedBuffer {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().write(buf)
            }
            fn flush(&mut self) -> io::Result<()> {
                self.0.lock().unwrap().flush()
            }
        }

        let buffer = SharedBuffer(Arc::new(Mutex::new(Vec::new())));
        let console = Console::builder()
            .width(40)
            .markup(false)
            .file(Box::new(buffer))
            .build();

        console.begin_capture();
        console.print_plain("Hello");
        let segments = console.end_capture();

        let captured: String = segments.iter().map(|s| s.text.as_ref()).collect();
        assert!(captured.contains("Hello"));
    }

    #[test]
    fn test_print_exception_renders_traceback() {
        use crate::renderables::{Traceback, TracebackFrame};

        let console = Console::builder().width(60).markup(false).build();
        console.begin_capture();

        let traceback = Traceback::new(
            vec![
                TracebackFrame::new("<module>", 14),
                TracebackFrame::new("level1", 11),
            ],
            "ErrorType",
            "boom",
        );

        console.print_exception(&traceback);
        let segments = console.end_capture();
        let captured: String = segments.iter().map(|s| s.text.as_ref()).collect();

        assert!(captured.contains("Traceback (most recent call last)"));
        assert!(captured.contains("in <module>:14"));
        assert!(captured.contains("ErrorType: boom"));
    }

    #[test]
    fn test_dimensions() {
        let dims = ConsoleDimensions::default();
        assert_eq!(dims.width, 80);
        assert_eq!(dims.height, 24);
    }

    #[test]
    fn test_custom_output_stream() {
        use std::sync::{Arc, Mutex};

        // Thread-safe buffer that implements Write + Send
        #[derive(Clone)]
        struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

        impl Write for SharedBuffer {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().write(buf)
            }
            fn flush(&mut self) -> io::Result<()> {
                self.0.lock().unwrap().flush()
            }
        }

        let buffer = SharedBuffer(Arc::new(Mutex::new(Vec::new())));
        let console = Console::builder()
            .width(80)
            .markup(false)
            .file(Box::new(buffer.clone()))
            .build();

        console.print_plain("Hello, World!");

        let output = buffer.0.lock().unwrap();
        let text = String::from_utf8_lossy(&output);
        assert!(
            text.contains("Hello, World!"),
            "Expected 'Hello, World!' in output, got: {text}"
        );
    }

    #[test]
    fn test_print_plain_disables_markup() {
        use std::sync::{Arc, Mutex};

        #[derive(Clone)]
        struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

        impl Write for SharedBuffer {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().write(buf)
            }
            fn flush(&mut self) -> io::Result<()> {
                self.0.lock().unwrap().flush()
            }
        }

        let buffer = SharedBuffer(Arc::new(Mutex::new(Vec::new())));
        let console = Console::builder()
            .markup(true)
            .file(Box::new(buffer.clone()))
            .build();

        console.print_plain("[bold]Hello[/]");

        let output = buffer.0.lock().unwrap();
        let text = String::from_utf8_lossy(&output);
        assert!(
            text.contains("[bold]Hello[/]"),
            "Expected literal markup in output, got: {text}"
        );
        assert!(
            !text.contains("\x1b["),
            "Did not expect ANSI sequences in output, got: {text}"
        );
    }

    #[test]
    fn test_export_text_defaults() {
        let console = Console::builder().markup(true).build();
        let output = console.export_text("[bold]Hello[/]");
        assert_eq!(output, "Hello\n");
    }

    #[test]
    fn test_export_text_respects_markup_setting() {
        let console = Console::builder().markup(false).build();
        let output = console.export_text("[bold]Hello[/]");
        assert_eq!(output, "[bold]Hello[/]\n");
    }

    #[test]
    fn test_export_text_replaces_emoji_codes_by_default() {
        let console = Console::builder().markup(false).build();
        let output = console.export_text("hi :smile:");
        assert_eq!(output, "hi πŸ˜„\n");
    }

    #[test]
    fn test_export_text_does_not_replace_emoji_codes_when_disabled() {
        let console = Console::builder().markup(false).emoji(false).build();
        let output = console.export_text("hi :smile:");
        assert_eq!(output, "hi :smile:\n");
    }

    #[test]
    fn test_export_text_with_options_no_newline() {
        let console = Console::new();
        let mut options = PrintOptions::new().with_markup(false);
        options.no_newline = true;
        let output = console.export_text_with_options("Hello", &options);
        assert_eq!(output, "Hello");
    }

    #[test]
    fn test_export_renderable_text() {
        use crate::renderables::Rule;

        let console = Console::builder().width(20).build();
        let rule = Rule::with_title("Title");
        let output = console.export_renderable_text(&rule);
        assert!(output.contains("Title"));
        assert!(output.ends_with('\n'));
    }

    #[test]
    fn test_export_html_svg_capture() {
        use std::sync::{Arc, Mutex};

        #[derive(Clone)]
        struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

        impl Write for SharedBuffer {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().write(buf)
            }
            fn flush(&mut self) -> io::Result<()> {
                self.0.lock().unwrap().flush()
            }
        }

        let buffer = SharedBuffer(Arc::new(Mutex::new(Vec::new())));
        let console = Console::builder()
            .markup(false)
            .file(Box::new(buffer))
            .build();

        console.begin_capture();
        console.print_plain("Hello");

        let html = console.export_html(false);
        assert!(html.contains("<pre"));
        assert!(html.contains("Hello"));

        let svg = console.export_svg(true);
        assert!(svg.contains("<svg"));
        assert!(svg.contains("Hello"));

        let cleared = console.export_html(false);
        assert!(!cleared.contains("Hello"));
    }

    #[test]
    fn test_escape_html_entities() {
        let escaped = escape_html_rich("<>&\"'");
        assert_eq!(escaped, "&lt;&gt;&amp;&quot;'");
    }

    #[test]
    fn test_style_html_rule_basic_attributes() {
        use crate::color::Color;

        let style = Style::new()
            .color(Color::from_rgb(255, 0, 0))
            .bgcolor(Color::from_rgb(0, 0, 255))
            .bold()
            .italic()
            .underline()
            .strike();
        let css = style.get_html_style(DEFAULT_TERMINAL_THEME);

        assert!(css.contains("color: #ff0000"));
        assert!(css.contains("background-color: #0000ff"));
        assert!(css.contains("font-weight: bold"));
        assert!(css.contains("font-style: italic"));
        assert!(css.contains("text-decoration: underline"));
        assert!(css.contains("text-decoration: line-through"));
    }

    #[test]
    fn test_style_html_rule_reverse_swaps_colors() {
        use crate::color::Color;

        let style = Style::new()
            .color(Color::from_rgb(10, 20, 30))
            .bgcolor(Color::from_rgb(200, 210, 220))
            .reverse();
        let css = style.get_html_style(DEFAULT_TERMINAL_THEME);

        assert!(css.contains("color: #c8d2dc"));
        assert!(css.contains("background-color: #0a141e"));
    }

    #[test]
    fn test_export_html_body_links_and_spans() {
        let link_style = Style::new().link("https://example.com").bold();
        let segments = vec![
            Segment::new("Link", Some(link_style)),
            Segment::new(" ", None),
            Segment::new("Plain", None),
        ];

        let opts = ExportHtmlOptions {
            inline_styles: true,
            code_format: Some("{code}".to_string()),
            ..ExportHtmlOptions::default()
        };
        let html = export_segments_to_html_rich(&segments, &opts);
        assert!(html.contains("href=\"https://example.com\""));
        assert!(html.contains("font-weight: bold"));
        assert!(html.contains("Plain"));
    }

    #[test]
    fn test_export_html_escapes_text() {
        let segments = vec![Segment::plain("<tag> & \"quote\"")];
        let opts = ExportHtmlOptions {
            inline_styles: true,
            code_format: Some("{code}".to_string()),
            ..ExportHtmlOptions::default()
        };
        let html = export_segments_to_html_rich(&segments, &opts);
        assert!(html.contains("&lt;tag&gt;"));
        assert!(html.contains("&amp;"));
        assert!(html.contains("&quot;"));
    }

    #[test]
    fn test_export_html_skips_control_segments() {
        use crate::segment::{ControlCode, ControlType};

        let segments = vec![
            Segment::control(vec![ControlCode::new(ControlType::Bell)]),
            Segment::new("Hi", None),
        ];
        let opts = ExportHtmlOptions {
            inline_styles: true,
            code_format: Some("{code}".to_string()),
            ..ExportHtmlOptions::default()
        };
        let html = export_segments_to_html_rich(&segments, &opts);
        assert!(html.contains("Hi"));
        assert!(!html.contains("Bell"));
    }

    #[test]
    fn test_export_svg_dimensions() {
        let segments = vec![Segment::plain("AB"), Segment::line(), Segment::plain("C")];
        let opts = ExportSvgOptions {
            code_format: Some("{width}x{height}".to_string()),
            ..ExportSvgOptions::default()
        };
        let svg = export_segments_to_svg_rich(&segments, 2, &opts);
        assert!(svg.contains('x'));
    }

    #[test]
    fn test_export_svg_includes_text() {
        let segments = vec![Segment::plain("Hello")];
        let opts = ExportSvgOptions {
            code_format: Some("{matrix}".to_string()),
            ..ExportSvgOptions::default()
        };
        let svg = export_segments_to_svg_rich(&segments, 10, &opts);
        assert!(svg.contains("Hello"));
    }

    #[test]
    fn test_export_html_document_structure() {
        let segments = vec![Segment::plain("Hello")];
        let opts = ExportHtmlOptions::default();
        let html = export_segments_to_html_rich(&segments, &opts);
        assert!(html.starts_with("<!DOCTYPE html>"));
        assert!(html.contains("<meta charset=\"UTF-8\">"));
        assert!(html.contains("<body>"));
        assert!(html.contains("</html>"));
    }

    #[test]
    fn test_export_html_includes_renderable_content() {
        use crate::renderables::{Column, Panel, Table, Tree, TreeNode};

        let console = Console::builder().width(30).build();
        console.begin_capture();

        let mut table = Table::new().with_column(Column::new("Col"));
        table.add_row_cells(["Cell"]);
        console.print_renderable(&table);

        let panel = Panel::from_text("Panel").width(10);
        console.print_renderable(&panel);

        let root = TreeNode::new("Root").child(TreeNode::new("Leaf"));
        let tree = Tree::new(root);
        console.print_renderable(&tree);

        let html = console.export_html(true);
        assert!(html.contains("Col"));
        assert!(html.contains("Cell"));
        assert!(html.contains("Panel"));
        assert!(html.contains("Root"));
        assert!(html.contains("Leaf"));
    }

    #[test]
    fn test_print_options_justify_uses_console_width() {
        let console = Console::builder().width(10).markup(false).build();
        let mut output = Vec::new();
        let mut options = PrintOptions::new().with_justify(JustifyMethod::Center);
        options.no_newline = true;

        console
            .print_to(&mut output, "Hi", &options)
            .expect("failed to render");

        let text = String::from_utf8(output).expect("invalid utf8");
        assert_eq!(text, "    Hi    ");
    }

    #[test]
    fn test_print_options_width_wraps() {
        let console = Console::builder().width(80).markup(false).build();
        let mut output = Vec::new();
        let mut options = PrintOptions::new();
        options.width = Some(4);

        console
            .print_to(&mut output, "Hello", &options)
            .expect("failed to render");

        let text = String::from_utf8(output).expect("invalid utf8");
        assert_eq!(text, "Hell\no\n");
    }

    #[test]
    fn test_print_options_no_wrap_ellipsis() {
        let console = Console::builder().width(80).markup(false).build();
        let mut output = Vec::new();
        let mut options = PrintOptions::new()
            .with_no_wrap(true)
            .with_overflow(OverflowMethod::Ellipsis);
        options.width = Some(4);
        options.no_newline = true;

        console
            .print_to(&mut output, "Hello", &options)
            .expect("failed to render");

        let text = String::from_utf8(output).expect("invalid utf8");
        assert_eq!(text, "H...");
    }

    #[test]
    fn test_custom_output_stream_line() {
        use std::sync::{Arc, Mutex};

        #[derive(Clone)]
        struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

        impl Write for SharedBuffer {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().write(buf)
            }
            fn flush(&mut self) -> io::Result<()> {
                self.0.lock().unwrap().flush()
            }
        }

        let buffer = SharedBuffer(Arc::new(Mutex::new(Vec::new())));
        let console = Console::builder()
            .width(80)
            .file(Box::new(buffer.clone()))
            .build();

        console.line();

        let output = buffer.0.lock().unwrap();
        let text = String::from_utf8_lossy(&output);
        assert_eq!(text, "\n", "Expected single newline, got: {text:?}");
    }

    // ========== ConsoleBuilder Tests ==========

    #[test]
    fn test_console_builder_color_system() {
        let console = Console::builder()
            .color_system(ColorSystem::TrueColor)
            .build();
        assert_eq!(console.color_system(), Some(ColorSystem::TrueColor));
    }

    #[test]
    fn test_console_builder_no_color() {
        let console = Console::builder().no_color().build();
        assert_eq!(console.color_system, None);
    }

    #[test]
    fn test_console_builder_force_terminal() {
        let console = Console::builder().force_terminal(true).build();
        assert!(console.is_terminal());
    }

    #[test]
    fn test_console_builder_tab_size() {
        let console = Console::builder().tab_size(4).build();
        assert_eq!(console.tab_size(), 4);
    }

    #[test]
    fn test_console_builder_emoji() {
        let console = Console::builder().emoji(false).build();
        assert!(!console.emoji);
    }

    #[test]
    fn test_console_builder_highlight() {
        let console = Console::builder().highlight(false).build();
        assert!(!console.highlight);
    }

    #[test]
    fn test_console_builder_safe_box() {
        let console = Console::builder().safe_box(true).build();
        assert!(console.safe_box);
    }

    #[test]
    fn test_console_builder_all_options() {
        let console = Console::builder()
            .color_system(ColorSystem::EightBit)
            .force_terminal(true)
            .tab_size(2)
            .markup(false)
            .emoji(false)
            .highlight(false)
            .width(120)
            .height(40)
            .safe_box(true)
            .build();

        assert_eq!(console.color_system(), Some(ColorSystem::EightBit));
        assert!(console.is_terminal());
        assert_eq!(console.tab_size(), 2);
        assert!(!console.markup);
        assert!(!console.emoji);
        assert!(!console.highlight);
        assert_eq!(console.width(), 120);
        assert_eq!(console.height(), 40);
        assert!(console.safe_box);
    }

    // ========== Console Size Tests ==========

    #[test]
    fn test_console_size_returns_dimensions() {
        let console = Console::builder().width(100).height(50).build();
        let size = console.size();
        assert_eq!(size.width, 100);
        assert_eq!(size.height, 50);
    }

    #[test]
    fn test_console_default_dimensions() {
        let console = Console::new();
        // Default should be reasonable terminal size
        assert!(console.width() >= 40);
        assert!(console.height() >= 10);
    }

    // ========== PrintOptions Tests ==========

    #[test]
    fn test_print_options_default() {
        let options = PrintOptions::new();
        assert_eq!(options.markup, None);
        assert!(options.style.is_none());
        assert_eq!(options.sep, " ");
        assert_eq!(options.end, "\n");
        assert_eq!(options.no_wrap, None);
        assert!(!options.no_newline);
        assert_eq!(options.highlight, None);
    }

    #[test]
    fn test_print_options_with_sep() {
        let options = PrintOptions::new().with_sep(", ");
        assert_eq!(options.sep, ", ");
    }

    #[test]
    fn test_print_options_with_end() {
        let options = PrintOptions::new().with_end("\r\n");
        assert_eq!(options.end, "\r\n");
    }

    #[test]
    fn test_print_options_with_overflow() {
        let options = PrintOptions::new().with_overflow(OverflowMethod::Crop);
        assert_eq!(options.overflow, Some(OverflowMethod::Crop));
    }

    #[test]
    fn test_print_options_with_crop() {
        let options = PrintOptions::new().with_crop(true);
        assert!(options.crop);
    }

    #[test]
    fn test_print_options_with_soft_wrap() {
        let options = PrintOptions::new().with_soft_wrap(true);
        assert!(options.soft_wrap);
    }

    #[test]
    fn test_print_options_chained() {
        let style = Style::new().bold().italic();
        let options = PrintOptions::new()
            .with_markup(false)
            .with_style(style.clone())
            .with_sep(" | ")
            .with_end("")
            .with_justify(JustifyMethod::Right)
            .with_overflow(OverflowMethod::Ellipsis)
            .with_no_wrap(true)
            .with_no_newline(true)
            .with_highlight(true)
            .with_width(40)
            .with_crop(true)
            .with_soft_wrap(true);

        assert_eq!(options.markup, Some(false));
        assert!(options.style.is_some());
        assert_eq!(options.sep, " | ");
        assert_eq!(options.end, "");
        assert_eq!(options.justify, Some(JustifyMethod::Right));
        assert_eq!(options.overflow, Some(OverflowMethod::Ellipsis));
        assert_eq!(options.no_wrap, Some(true));
        assert!(options.no_newline);
        assert_eq!(options.highlight, Some(true));
        assert_eq!(options.width, Some(40));
        assert!(options.crop);
        assert!(options.soft_wrap);
    }

    // ========== ConsoleOptions Tests ==========

    #[test]
    fn test_console_options_update_width() {
        let console = Console::builder().width(100).build();
        let options = console.options();
        // update_width clamps to the new width (min of current and new)
        let updated = options.update_width(80);
        assert_eq!(updated.max_width, 80);
    }

    #[test]
    fn test_console_options_update_height() {
        let console = Console::builder().height(24).build();
        let options = console.options();
        // update_height sets the height in the options
        let updated = options.update_height(50);
        assert_eq!(updated.height, Some(50));
    }

    // ========== Color System Tests ==========

    #[test]
    fn test_console_is_color_enabled_with_system() {
        let console = Console::builder()
            .color_system(ColorSystem::Standard)
            .build();
        assert!(console.is_color_enabled());
    }

    #[test]
    fn test_console_is_color_enabled_no_color() {
        let console = Console::builder().no_color().build();
        assert!(!console.is_color_enabled());
    }

    // ========== Capture Mode Tests ==========

    #[test]
    fn test_capture_empty() {
        let console = Console::new();
        console.begin_capture();
        let segments = console.end_capture();
        assert!(segments.is_empty());
    }

    #[test]
    fn test_capture_with_styled_text() {
        use std::sync::{Arc, Mutex};

        #[derive(Clone)]
        struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

        impl Write for SharedBuffer {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().write(buf)
            }
            fn flush(&mut self) -> io::Result<()> {
                self.0.lock().unwrap().flush()
            }
        }

        let buffer = SharedBuffer(Arc::new(Mutex::new(Vec::new())));
        let console = Console::builder()
            .width(80)
            .markup(true)
            .color_system(ColorSystem::TrueColor)
            .file(Box::new(buffer))
            .build();

        console.begin_capture();
        console.print("[bold]Test[/]");
        let segments = console.end_capture();

        // Should have captured at least one segment
        assert!(!segments.is_empty());
    }

    #[test]
    fn test_capture_multiple_prints() {
        use std::sync::{Arc, Mutex};

        #[derive(Clone)]
        struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

        impl Write for SharedBuffer {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().write(buf)
            }
            fn flush(&mut self) -> io::Result<()> {
                self.0.lock().unwrap().flush()
            }
        }

        let buffer = SharedBuffer(Arc::new(Mutex::new(Vec::new())));
        let console = Console::builder()
            .width(80)
            .markup(false)
            .file(Box::new(buffer))
            .build();

        console.begin_capture();
        console.print_plain("First");
        console.print_plain("Second");
        let segments = console.end_capture();

        let text: String = segments.iter().map(|s| s.text.as_ref()).collect();
        assert!(text.contains("First"));
        assert!(text.contains("Second"));
    }

    // ========== Print Method Tests ==========

    #[test]
    fn test_print_text_direct() {
        use std::sync::{Arc, Mutex};

        #[derive(Clone)]
        struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

        impl Write for SharedBuffer {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().write(buf)
            }
            fn flush(&mut self) -> io::Result<()> {
                self.0.lock().unwrap().flush()
            }
        }

        let buffer = SharedBuffer(Arc::new(Mutex::new(Vec::new())));
        let console = Console::builder()
            .width(80)
            .markup(false)
            .file(Box::new(buffer.clone()))
            .build();

        let text = Text::new("Direct text");
        console.print_text(&text);

        let output = buffer.0.lock().unwrap();
        let result = String::from_utf8_lossy(&output);
        assert!(result.contains("Direct text"));
    }

    #[test]
    fn test_print_styled() {
        use std::sync::{Arc, Mutex};

        #[derive(Clone)]
        struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

        impl Write for SharedBuffer {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().write(buf)
            }
            fn flush(&mut self) -> io::Result<()> {
                self.0.lock().unwrap().flush()
            }
        }

        let buffer = SharedBuffer(Arc::new(Mutex::new(Vec::new())));
        let console = Console::builder()
            .width(80)
            .color_system(ColorSystem::TrueColor)
            .file(Box::new(buffer.clone()))
            .build();

        console.print_styled("Styled", Style::new().bold());

        let output = buffer.0.lock().unwrap();
        let result = String::from_utf8_lossy(&output);
        assert!(result.contains("Styled"));
        // Should contain ANSI codes for bold
        assert!(result.contains("\x1b["));
    }

    #[test]
    fn test_print_to_writer() {
        let console = Console::builder().width(80).markup(false).build();
        let mut output = Vec::new();
        let options = PrintOptions::new();

        console
            .print_to(&mut output, "Writer test", &options)
            .expect("failed to print");

        let text = String::from_utf8(output).expect("invalid utf8");
        assert!(text.contains("Writer test"));
    }

    #[test]
    fn test_print_segments() {
        use std::sync::{Arc, Mutex};

        #[derive(Clone)]
        struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

        impl Write for SharedBuffer {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().write(buf)
            }
            fn flush(&mut self) -> io::Result<()> {
                self.0.lock().unwrap().flush()
            }
        }

        let buffer = SharedBuffer(Arc::new(Mutex::new(Vec::new())));
        let console = Console::builder()
            .width(80)
            .file(Box::new(buffer.clone()))
            .build();

        let segments = vec![Segment::plain("Hello "), Segment::plain("World")];
        console.print_segments(&segments);

        let output = buffer.0.lock().unwrap();
        let result = String::from_utf8_lossy(&output);
        assert!(result.contains("Hello "));
        assert!(result.contains("World"));
    }

    // ========== Rule Method Tests ==========

    #[test]
    fn test_rule_without_title() {
        use std::sync::{Arc, Mutex};

        #[derive(Clone)]
        struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

        impl Write for SharedBuffer {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().write(buf)
            }
            fn flush(&mut self) -> io::Result<()> {
                self.0.lock().unwrap().flush()
            }
        }

        let buffer = SharedBuffer(Arc::new(Mutex::new(Vec::new())));
        let console = Console::builder()
            .width(20)
            .file(Box::new(buffer.clone()))
            .build();

        console.rule(None);

        let output = buffer.0.lock().unwrap();
        let result = String::from_utf8_lossy(&output);
        // Rule should contain horizontal line characters
        assert!(result.contains('─') || result.contains('-'));
    }

    #[test]
    fn test_rule_with_title() {
        use std::sync::{Arc, Mutex};

        #[derive(Clone)]
        struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

        impl Write for SharedBuffer {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().write(buf)
            }
            fn flush(&mut self) -> io::Result<()> {
                self.0.lock().unwrap().flush()
            }
        }

        let buffer = SharedBuffer(Arc::new(Mutex::new(Vec::new())));
        let console = Console::builder()
            .width(40)
            .file(Box::new(buffer.clone()))
            .build();

        console.rule(Some("Section"));

        let output = buffer.0.lock().unwrap();
        let result = String::from_utf8_lossy(&output);
        assert!(result.contains("Section"));
    }

    // ========== Log Method Tests ==========

    #[test]
    fn test_log_debug() {
        use std::sync::{Arc, Mutex};

        #[derive(Clone)]
        struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

        impl Write for SharedBuffer {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().write(buf)
            }
            fn flush(&mut self) -> io::Result<()> {
                self.0.lock().unwrap().flush()
            }
        }

        let buffer = SharedBuffer(Arc::new(Mutex::new(Vec::new())));
        let console = Console::builder()
            .width(80)
            .file(Box::new(buffer.clone()))
            .build();

        console.log("Debug message", LogLevel::Debug);

        let output = buffer.0.lock().unwrap();
        let result = String::from_utf8_lossy(&output);
        assert!(result.contains("Debug message"));
    }

    #[test]
    fn test_log_info() {
        use std::sync::{Arc, Mutex};

        #[derive(Clone)]
        struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

        impl Write for SharedBuffer {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().write(buf)
            }
            fn flush(&mut self) -> io::Result<()> {
                self.0.lock().unwrap().flush()
            }
        }

        let buffer = SharedBuffer(Arc::new(Mutex::new(Vec::new())));
        let console = Console::builder()
            .width(80)
            .file(Box::new(buffer.clone()))
            .build();

        console.log("Info message", LogLevel::Info);

        let output = buffer.0.lock().unwrap();
        let result = String::from_utf8_lossy(&output);
        assert!(result.contains("Info message"));
    }

    #[test]
    fn test_log_warning() {
        use std::sync::{Arc, Mutex};

        #[derive(Clone)]
        struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

        impl Write for SharedBuffer {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().write(buf)
            }
            fn flush(&mut self) -> io::Result<()> {
                self.0.lock().unwrap().flush()
            }
        }

        let buffer = SharedBuffer(Arc::new(Mutex::new(Vec::new())));
        let console = Console::builder()
            .width(80)
            .file(Box::new(buffer.clone()))
            .build();

        console.log("Warning message", LogLevel::Warning);

        let output = buffer.0.lock().unwrap();
        let result = String::from_utf8_lossy(&output);
        assert!(result.contains("Warning message"));
    }

    #[test]
    fn test_log_error() {
        use std::sync::{Arc, Mutex};

        #[derive(Clone)]
        struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

        impl Write for SharedBuffer {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().write(buf)
            }
            fn flush(&mut self) -> io::Result<()> {
                self.0.lock().unwrap().flush()
            }
        }

        let buffer = SharedBuffer(Arc::new(Mutex::new(Vec::new())));
        let console = Console::builder()
            .width(80)
            .file(Box::new(buffer.clone()))
            .build();

        console.log("Error message", LogLevel::Error);

        let output = buffer.0.lock().unwrap();
        let result = String::from_utf8_lossy(&output);
        assert!(result.contains("Error message"));
    }

    // ========== Log with Options Tests ==========

    #[test]
    fn test_log_with_timestamp() {
        use std::sync::{Arc, Mutex};

        #[derive(Clone)]
        struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

        impl Write for SharedBuffer {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().write(buf)
            }
            fn flush(&mut self) -> io::Result<()> {
                self.0.lock().unwrap().flush()
            }
        }

        let buffer = SharedBuffer(Arc::new(Mutex::new(Vec::new())));
        let console = Console::builder()
            .width(80)
            .file(Box::new(buffer.clone()))
            .build();

        let opts = LogOptions::new().with_timestamp(true);
        console.log_with_options("Test message", LogLevel::Info, &opts);

        let output = buffer.0.lock().unwrap();
        let result = String::from_utf8_lossy(&output);
        // Should contain timestamp format [HH:MM:SS]
        assert!(result.contains('['));
        assert!(result.contains(']'));
        assert!(result.contains(':'));
        assert!(result.contains("Test message"));
    }

    #[test]
    fn test_log_with_file_path() {
        use std::sync::{Arc, Mutex};

        #[derive(Clone)]
        struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

        impl Write for SharedBuffer {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().write(buf)
            }
            fn flush(&mut self) -> io::Result<()> {
                self.0.lock().unwrap().flush()
            }
        }

        let buffer = SharedBuffer(Arc::new(Mutex::new(Vec::new())));
        let console = Console::builder()
            .width(80)
            .file(Box::new(buffer.clone()))
            .build();

        let opts = LogOptions::new().with_path("src/main.rs", 42);
        console.log_with_options("Debug info", LogLevel::Debug, &opts);

        let output = buffer.0.lock().unwrap();
        let result = String::from_utf8_lossy(&output);
        assert!(result.contains("src/main.rs"));
        assert!(result.contains("42"));
        assert!(result.contains("Debug info"));
    }

    #[test]
    fn test_log_with_timestamp_and_path() {
        use std::sync::{Arc, Mutex};

        #[derive(Clone)]
        struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

        impl Write for SharedBuffer {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().write(buf)
            }
            fn flush(&mut self) -> io::Result<()> {
                self.0.lock().unwrap().flush()
            }
        }

        let buffer = SharedBuffer(Arc::new(Mutex::new(Vec::new())));
        let console = Console::builder()
            .width(80)
            .file(Box::new(buffer.clone()))
            .build();

        let opts = LogOptions::new()
            .with_timestamp(true)
            .with_path("test.rs", 100);
        console.log_with_options("Combined test", LogLevel::Warning, &opts);

        let output = buffer.0.lock().unwrap();
        let result = String::from_utf8_lossy(&output);
        assert!(result.contains('[')); // timestamp bracket
        assert!(result.contains("test.rs"));
        assert!(result.contains("100"));
        assert!(result.contains("Combined test"));
    }

    #[test]
    fn test_log_without_level() {
        use std::sync::{Arc, Mutex};

        #[derive(Clone)]
        struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

        impl Write for SharedBuffer {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().write(buf)
            }
            fn flush(&mut self) -> io::Result<()> {
                self.0.lock().unwrap().flush()
            }
        }

        let buffer = SharedBuffer(Arc::new(Mutex::new(Vec::new())));
        let console = Console::builder()
            .width(80)
            .file(Box::new(buffer.clone()))
            .build();

        let opts = LogOptions::new().with_level(false);
        console.log_with_options("No level prefix", LogLevel::Info, &opts);

        let output = buffer.0.lock().unwrap();
        let result = String::from_utf8_lossy(&output);
        assert!(!result.contains("[INFO]"));
        assert!(result.contains("No level prefix"));
    }

    #[test]
    fn test_log_options_default() {
        let opts = LogOptions::default();
        assert!(!opts.show_timestamp);
        assert!(opts.timestamp_format.is_none());
        assert!(opts.file_path.is_none());
        assert!(opts.line_number.is_none());
        assert!(opts.show_level);
        assert!(!opts.highlight);
    }

    #[test]
    fn test_log_options_builder() {
        let opts = LogOptions::new()
            .with_timestamp(true)
            .with_timestamp_format("%Y-%m-%d %H:%M:%S")
            .with_file("test.rs")
            .with_line(123)
            .with_level(false)
            .with_highlight(true);

        assert!(opts.show_timestamp);
        assert_eq!(opts.timestamp_format, Some("%Y-%m-%d %H:%M:%S".to_string()));
        assert_eq!(opts.file_path, Some("test.rs".to_string()));
        assert_eq!(opts.line_number, Some(123));
        assert!(!opts.show_level);
        assert!(opts.highlight);
    }

    #[test]
    fn test_format_timestamp_default() {
        let ts = Console::format_timestamp(None);
        // Default format: [HH:MM:SS]
        assert!(ts.starts_with('['));
        assert!(ts.ends_with(']'));
        assert_eq!(ts.matches(':').count(), 2);
    }

    #[test]
    fn test_format_timestamp_custom() {
        let ts = Console::format_timestamp(Some("%H-%M-%S"));
        // Custom format: HH-MM-SS
        assert_eq!(ts.matches('-').count(), 2);
        assert!(!ts.contains(':'));
    }

    #[test]
    fn test_format_timestamp_custom_with_date_tokens() {
        let ts = Console::format_timestamp(Some("%Y-%m-%d %H:%M:%S"));
        // We don't assert wall-clock values; we only assert the substitutions happened.
        assert_eq!(ts.len(), "0000-00-00 00:00:00".len());
        assert_eq!(ts.matches('-').count(), 2);
        assert_eq!(ts.matches(':').count(), 2);
    }

    // ========== Markup Integration Tests ==========

    #[test]
    fn test_markup_enabled() {
        use std::sync::{Arc, Mutex};

        #[derive(Clone)]
        struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

        impl Write for SharedBuffer {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().write(buf)
            }
            fn flush(&mut self) -> io::Result<()> {
                self.0.lock().unwrap().flush()
            }
        }

        let buffer = SharedBuffer(Arc::new(Mutex::new(Vec::new())));
        let console = Console::builder()
            .width(80)
            .markup(true)
            .color_system(ColorSystem::TrueColor)
            .file(Box::new(buffer.clone()))
            .build();

        console.print("[bold]Bold text[/]");

        let output = buffer.0.lock().unwrap();
        let result = String::from_utf8_lossy(&output);
        // Should contain ANSI codes, not literal [bold]
        assert!(!result.contains("[bold]"));
        assert!(result.contains("\x1b["));
    }

    #[test]
    fn test_markup_disabled() {
        use std::sync::{Arc, Mutex};

        #[derive(Clone)]
        struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

        impl Write for SharedBuffer {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().write(buf)
            }
            fn flush(&mut self) -> io::Result<()> {
                self.0.lock().unwrap().flush()
            }
        }

        let buffer = SharedBuffer(Arc::new(Mutex::new(Vec::new())));
        let console = Console::builder()
            .width(80)
            .markup(false)
            .file(Box::new(buffer.clone()))
            .build();

        console.print("[bold]Literal markup[/]");

        let output = buffer.0.lock().unwrap();
        let result = String::from_utf8_lossy(&output);
        // Should contain literal markup tags
        assert!(result.contains("[bold]"));
    }

    // ========== Width Constraint Tests ==========

    #[test]
    fn test_print_with_width_constraint() {
        let console = Console::builder().width(80).markup(false).build();
        let mut output = Vec::new();
        let mut options = PrintOptions::new();
        options.width = Some(10);

        console
            .print_to(
                &mut output,
                "This is a long text that should wrap",
                &options,
            )
            .expect("failed to print");

        let text = String::from_utf8(output).expect("invalid utf8");
        // Text should be wrapped at width 10
        let lines: Vec<&str> = text.lines().collect();
        assert!(lines.len() > 1);
    }

    #[test]
    fn test_justify_left() {
        let console = Console::builder().width(20).markup(false).build();
        let mut output = Vec::new();
        let mut options = PrintOptions::new().with_justify(JustifyMethod::Left);
        options.no_newline = true;

        console
            .print_to(&mut output, "Left", &options)
            .expect("failed to print");

        let text = String::from_utf8(output).expect("invalid utf8");
        assert!(text.starts_with("Left"));
    }

    #[test]
    fn test_justify_right() {
        let console = Console::builder().width(20).markup(false).build();
        let mut output = Vec::new();
        let mut options = PrintOptions::new().with_justify(JustifyMethod::Right);
        options.no_newline = true;

        console
            .print_to(&mut output, "Right", &options)
            .expect("failed to print");

        let text = String::from_utf8(output).expect("invalid utf8");
        assert!(text.ends_with("Right"));
        assert!(text.len() == 20);
    }

    // ========== ConsoleDimensions Tests ==========

    #[test]
    fn test_console_dimensions_default() {
        let dims = ConsoleDimensions::default();
        assert_eq!(dims.width, 80);
        assert_eq!(dims.height, 24);
    }

    #[test]
    fn test_console_dimensions_custom() {
        let dims = ConsoleDimensions {
            width: 120,
            height: 40,
        };
        assert_eq!(dims.width, 120);
        assert_eq!(dims.height, 40);
    }

    // ========== PrintOptions Default Trait ==========

    #[test]
    fn test_print_options_implements_default() {
        // Default::default() uses derived defaults (empty strings)
        // PrintOptions::new() sets explicit defaults (sep=" ", end="\n")
        let default_options = PrintOptions::default();
        assert_eq!(default_options.sep, "");
        assert_eq!(default_options.end, "");

        // new() provides the typical defaults
        let new_options = PrintOptions::new();
        assert_eq!(new_options.sep, " ");
        assert_eq!(new_options.end, "\n");
    }

    // ========== Edge Case Tests ==========

    #[test]
    fn test_print_empty_string() {
        use std::sync::{Arc, Mutex};

        #[derive(Clone)]
        struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

        impl Write for SharedBuffer {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().write(buf)
            }
            fn flush(&mut self) -> io::Result<()> {
                self.0.lock().unwrap().flush()
            }
        }

        let buffer = SharedBuffer(Arc::new(Mutex::new(Vec::new())));
        let console = Console::builder()
            .width(80)
            .file(Box::new(buffer.clone()))
            .build();

        console.print_plain("");

        let output = buffer.0.lock().unwrap();
        let result = String::from_utf8_lossy(&output);
        // Should only have newline
        assert_eq!(result.trim(), "");
    }

    #[test]
    fn test_print_unicode() {
        use std::sync::{Arc, Mutex};

        #[derive(Clone)]
        struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

        impl Write for SharedBuffer {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().write(buf)
            }
            fn flush(&mut self) -> io::Result<()> {
                self.0.lock().unwrap().flush()
            }
        }

        let buffer = SharedBuffer(Arc::new(Mutex::new(Vec::new())));
        let console = Console::builder()
            .width(80)
            .file(Box::new(buffer.clone()))
            .build();

        console.print_plain("Hello δΈ–η•Œ 🌍");

        let output = buffer.0.lock().unwrap();
        let result = String::from_utf8_lossy(&output);
        assert!(result.contains("δΈ–η•Œ"));
        assert!(result.contains("🌍"));
    }

    #[test]
    fn test_print_with_newlines() {
        use std::sync::{Arc, Mutex};

        #[derive(Clone)]
        struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

        impl Write for SharedBuffer {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().write(buf)
            }
            fn flush(&mut self) -> io::Result<()> {
                self.0.lock().unwrap().flush()
            }
        }

        let buffer = SharedBuffer(Arc::new(Mutex::new(Vec::new())));
        let console = Console::builder()
            .width(80)
            .file(Box::new(buffer.clone()))
            .build();

        console.print_plain("Line 1\nLine 2\nLine 3");

        let output = buffer.0.lock().unwrap();
        let result = String::from_utf8_lossy(&output);
        let lines: Vec<&str> = result.lines().collect();
        assert!(lines.len() >= 3);
    }

    #[test]
    fn test_overflow_crop() {
        let console = Console::builder().width(80).markup(false).build();
        let mut output = Vec::new();
        let mut options = PrintOptions::new()
            .with_no_wrap(true)
            .with_overflow(OverflowMethod::Crop);
        options.width = Some(5);
        options.no_newline = true;

        console
            .print_to(&mut output, "Hello World", &options)
            .expect("failed to print");

        let text = String::from_utf8(output).expect("invalid utf8");
        assert_eq!(text, "Hello");
    }

    // ========================================================================
    // Console I/O Error Path Tests (bd-3761)
    // ========================================================================

    /// A writer that always fails on write
    struct FailingWriter;

    impl Write for FailingWriter {
        fn write(&mut self, _buf: &[u8]) -> io::Result<usize> {
            Err(io::Error::new(io::ErrorKind::BrokenPipe, "write failed"))
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    /// A writer that fails on flush
    struct FlushFailingWriter {
        buffer: Vec<u8>,
    }

    impl FlushFailingWriter {
        fn new() -> Self {
            Self { buffer: Vec::new() }
        }
    }

    impl Write for FlushFailingWriter {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.buffer.extend_from_slice(buf);
            Ok(buf.len())
        }

        fn flush(&mut self) -> io::Result<()> {
            Err(io::Error::other("flush failed: disk full"))
        }
    }

    /// A writer that fails after N bytes
    struct LimitedWriter {
        limit: usize,
        written: usize,
    }

    impl LimitedWriter {
        fn new(limit: usize) -> Self {
            Self { limit, written: 0 }
        }
    }

    impl Write for LimitedWriter {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            if self.written >= self.limit {
                return Err(io::Error::new(io::ErrorKind::WriteZero, "buffer full"));
            }
            let available = self.limit - self.written;
            let to_write = buf.len().min(available);
            self.written += to_write;
            Ok(to_write)
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    /// A writer that tracks operations for verification
    struct TrackingWriter {
        writes: Arc<Mutex<Vec<usize>>>,
        flushes: Arc<Mutex<usize>>,
    }

    impl TrackingWriter {
        fn new() -> Self {
            Self {
                writes: Arc::new(Mutex::new(Vec::new())),
                flushes: Arc::new(Mutex::new(0)),
            }
        }

        fn write_count(&self) -> usize {
            self.writes.lock().unwrap().len()
        }

        #[allow(dead_code)]
        fn flush_count(&self) -> usize {
            *self.flushes.lock().unwrap()
        }

        fn total_bytes(&self) -> usize {
            self.writes.lock().unwrap().iter().sum()
        }
    }

    impl Clone for TrackingWriter {
        fn clone(&self) -> Self {
            Self {
                writes: Arc::clone(&self.writes),
                flushes: Arc::clone(&self.flushes),
            }
        }
    }

    impl Write for TrackingWriter {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.writes.lock().unwrap().push(buf.len());
            Ok(buf.len())
        }

        fn flush(&mut self) -> io::Result<()> {
            *self.flushes.lock().unwrap() += 1;
            Ok(())
        }
    }

    #[test]
    fn test_io_write_failure() {
        // Test that write errors are properly propagated via print_to
        let console = Console::builder().width(80).markup(false).build();

        let mut failing_writer = FailingWriter;
        let result = console.print_to(&mut failing_writer, "Hello", &PrintOptions::new());

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::BrokenPipe);
    }

    #[test]
    fn test_io_write_partial() {
        // Test writer that accepts only partial writes
        let console = Console::builder().width(80).markup(false).build();

        let mut limited = LimitedWriter::new(5);
        let _result = console.print_to(&mut limited, "Hello World!", &PrintOptions::new());

        // May succeed partially or fail depending on implementation
        // The writer should have accepted at least some bytes
        assert!(limited.written > 0);
    }

    #[test]
    fn test_io_flush_failure() {
        // Test that flush errors are handled
        let mut writer = FlushFailingWriter::new();

        // Write should succeed
        let write_result = writer.write(b"Hello");
        assert!(write_result.is_ok());
        assert_eq!(write_result.unwrap(), 5);

        // Flush should fail
        let flush_result = writer.flush();
        assert!(flush_result.is_err());
        let err = flush_result.unwrap_err();
        assert!(err.to_string().contains("flush failed"));
    }

    #[test]
    fn test_io_write_segments_to_failing() {
        let console = Console::builder().width(80).markup(false).build();

        // Create segments
        let segments = vec![
            Segment::plain("Hello "),
            Segment::styled("World", Style::new().bold()),
        ];

        let mut failing_writer = FailingWriter;
        let result = console.print_segments_to(&mut failing_writer, &segments);

        assert!(result.is_err());
    }

    #[test]
    fn test_io_print_text_to_failing() {
        let console = Console::builder().width(80).markup(false).build();

        let text = Text::new("Hello World");
        let mut failing_writer = FailingWriter;
        let result = console.print_text_to(&mut failing_writer, &text);

        assert!(result.is_err());
    }

    #[test]
    fn test_io_write_tracking() {
        // Verify writes are actually occurring
        let tracking = TrackingWriter::new();
        let console = Console::builder()
            .width(80)
            .markup(false)
            .file(Box::new(tracking.clone()))
            .build();

        console.print_plain("Line 1");
        console.print_plain("Line 2");

        // Should have multiple writes
        assert!(tracking.write_count() >= 2, "Expected writes to occur");
        assert!(tracking.total_bytes() > 0, "Expected bytes written");
    }

    #[test]
    fn test_io_empty_write() {
        // Writing empty content should not cause errors
        let console = Console::builder().width(80).markup(false).build();

        let mut output = Vec::new();
        let result = console.print_to(&mut output, "", &PrintOptions::new().with_no_newline(true));

        assert!(result.is_ok());
        // Empty string with no_newline should produce empty output
        assert!(output.is_empty() || output == b"\n");
    }

    #[test]
    fn test_io_large_write() {
        // Test with a large string to ensure no buffer issues
        let console = Console::builder().width(1000).markup(false).build();

        let large_content = "x".repeat(10000);
        let mut output = Vec::new();
        let result = console.print_to(&mut output, &large_content, &PrintOptions::new());

        assert!(result.is_ok());
        // Should contain all the content plus newline
        assert!(output.len() >= 10000);
    }

    #[test]
    fn test_io_control_code_write_failure() {
        // Test that control code writes handle errors
        // Note: This tests internal behavior, so we use print_segments_to
        let console = Console::builder().width(80).markup(false).build();

        // Create a segment with control codes
        let segments = vec![Segment {
            text: std::borrow::Cow::Borrowed(""),
            style: None,
            control: Some(vec![ControlCode::new(ControlType::Home)]),
        }];

        let mut failing_writer = FailingWriter;
        let result = console.print_segments_to(&mut failing_writer, &segments);

        // Should handle the error (either succeed because control codes are skipped
        // in non-terminal mode, or fail gracefully)
        // The important thing is no panic
        let _ = result;
    }

    #[test]
    fn test_control_cursor_move_to_column_is_zero_based() {
        let console = Console::builder()
            .width(80)
            .markup(false)
            .force_terminal(true)
            .build();
        let segments = vec![Segment::control(vec![ControlCode::with_params_vec(
            ControlType::CursorMoveToColumn,
            vec![0],
        )])];
        let mut output = Vec::new();
        console
            .print_segments_to(&mut output, &segments)
            .expect("print_segments_to");

        assert_eq!(String::from_utf8(output).expect("utf8 output"), "\x1b[1G");
    }

    #[test]
    fn test_control_cursor_move_to_is_zero_based_xy() {
        let console = Console::builder()
            .width(80)
            .markup(false)
            .force_terminal(true)
            .build();
        let segments = vec![Segment::control(vec![ControlCode::with_params_vec(
            ControlType::CursorMoveTo,
            vec![3, 4],
        )])];
        let mut output = Vec::new();
        console
            .print_segments_to(&mut output, &segments)
            .expect("print_segments_to");

        assert_eq!(String::from_utf8(output).expect("utf8 output"), "\x1b[5;4H");
    }

    #[test]
    fn test_control_set_window_title_emits_empty_title_sequence() {
        let console = Console::builder()
            .width(80)
            .markup(false)
            .force_terminal(true)
            .build();
        let segments = vec![Segment {
            text: std::borrow::Cow::Borrowed(""),
            style: None,
            control: Some(vec![ControlCode::new(ControlType::SetWindowTitle)]),
        }];
        let mut output = Vec::new();
        console
            .print_segments_to(&mut output, &segments)
            .expect("print_segments_to");

        assert_eq!(
            String::from_utf8(output).expect("utf8 output"),
            "\x1b]0;\x07"
        );
    }

    #[test]
    fn test_io_error_types() {
        // Create writers with different error types
        struct NotFoundWriter;
        impl Write for NotFoundWriter {
            fn write(&mut self, _buf: &[u8]) -> io::Result<usize> {
                Err(io::Error::new(io::ErrorKind::NotFound, "file not found"))
            }
            fn flush(&mut self) -> io::Result<()> {
                Ok(())
            }
        }

        struct PermissionWriter;
        impl Write for PermissionWriter {
            fn write(&mut self, _buf: &[u8]) -> io::Result<usize> {
                Err(io::Error::new(
                    io::ErrorKind::PermissionDenied,
                    "access denied",
                ))
            }
            fn flush(&mut self) -> io::Result<()> {
                Ok(())
            }
        }

        // Verify different error types are preserved
        let console = Console::builder().width(80).markup(false).build();
        let mut not_found = NotFoundWriter;
        let result1 = console.print_to(&mut not_found, "test", &PrintOptions::new());
        assert!(matches!(
            result1.as_ref().map_err(std::io::Error::kind),
            Err(io::ErrorKind::NotFound)
        ));

        let mut permission = PermissionWriter;
        let result2 = console.print_to(&mut permission, "test", &PrintOptions::new());
        assert!(matches!(
            result2.as_ref().map_err(std::io::Error::kind),
            Err(io::ErrorKind::PermissionDenied)
        ));
    }

    #[test]
    fn test_io_concurrent_writes() {
        use std::thread;

        struct SharedBuffer(Arc<Mutex<Vec<u8>>>);

        impl Clone for SharedBuffer {
            fn clone(&self) -> Self {
                Self(Arc::clone(&self.0))
            }
        }

        impl Write for SharedBuffer {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.lock().unwrap().extend_from_slice(buf);
                Ok(buf.len())
            }
            fn flush(&mut self) -> io::Result<()> {
                Ok(())
            }
        }

        // Test thread-safe writes to shared buffer
        let buffer = Arc::new(Mutex::new(Vec::new()));
        let shared = SharedBuffer(Arc::clone(&buffer));
        let console = Console::builder()
            .width(80)
            .markup(false)
            .file(Box::new(shared))
            .build()
            .shared();

        // Spawn multiple threads writing concurrently
        let mut handles = vec![];
        for i in 0..4 {
            let console_clone = Arc::clone(&console);
            let handle = thread::spawn(move || {
                console_clone.print_plain(&format!("Thread {i}"));
            });
            handles.push(handle);
        }

        for handle in handles {
            handle.join().expect("thread panicked");
        }

        // Verify all writes completed
        let output = buffer.lock().unwrap();
        let text = String::from_utf8_lossy(&output);
        // All 4 threads should have written something
        assert!(text.contains("Thread"), "Expected thread output");
    }

    #[test]
    fn test_io_interrupted_write() {
        // Test handling of interrupted writes (EINTR-like scenario)
        struct InterruptedWriter {
            attempts: Arc<Mutex<usize>>,
            succeed_after: usize,
        }

        impl Write for InterruptedWriter {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                let mut attempts = self.attempts.lock().unwrap();
                *attempts += 1;
                if *attempts <= self.succeed_after {
                    Err(io::Error::new(io::ErrorKind::Interrupted, "interrupted"))
                } else {
                    Ok(buf.len())
                }
            }
            fn flush(&mut self) -> io::Result<()> {
                Ok(())
            }
        }

        let console = Console::builder().width(80).markup(false).build();

        // Writer that returns Interrupted initially
        let attempts = Arc::new(Mutex::new(0));
        let mut writer = InterruptedWriter {
            attempts: Arc::clone(&attempts),
            succeed_after: 0, // Succeed on first try
        };

        let result = console.print_to(&mut writer, "test", &PrintOptions::new());
        assert!(
            result.is_ok()
                || result.as_ref().map_err(std::io::Error::kind) == Err(io::ErrorKind::Interrupted)
        );
    }
}