whereat 0.1.5

Lightweight error location tracking with small sizeof and no_std support
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
//! Unit tests for whereat.
//!
//! These tests are in a separate file for organization but remain in the `src/`
//! directory to retain access to `pub(crate)` items like `AtContext`.

use crate::context::AtContext;
use crate::trace::AtTrace;
use crate::{At, ErrorAtExt, ResultAtExt, at};
use alloc::boxed::Box;
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;

#[derive(Debug, PartialEq, Eq, Hash)]
enum TestError {
    NotFound,
    InvalidInput,
}

impl fmt::Display for TestError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TestError::NotFound => write!(f, "not found"),
            TestError::InvalidInput => write!(f, "invalid input"),
        }
    }
}

impl core::error::Error for TestError {}

#[test]
fn test_sizeof() {
    use core::mem::size_of;

    let ptr = size_of::<usize>();

    // At<E> should be sizeof(E) + pointer (pointer to boxed trace)
    assert_eq!(size_of::<Option<Box<AtTrace>>>(), ptr);

    let traced_size = size_of::<At<TestError>>();
    let error_size = size_of::<TestError>();
    let pointer_size = size_of::<Option<Box<AtTrace>>>();

    // Should be error + pointer, with possible padding
    assert!(traced_size <= error_size + pointer_size + ptr); // Allow for alignment
    assert!(traced_size >= error_size + pointer_size);

    // For a 1-byte enum: 1 + padding + pointer = 2*pointer
    // (1 + 7 padding + 8 pointer = 16 on 64-bit, 1 + 3 padding + 4 pointer = 8 on 32-bit)
    assert_eq!(traced_size, 2 * ptr);
}

#[test]
fn test_sizeof_trace() {
    use core::mem::size_of;

    let trace_size = size_of::<AtTrace>();

    // AtTrace size depends on feature flags (sizes shown for 64-bit):
    // - Without tinyvec/smallvec: 112 bytes (InlineVec<4> + crate_info + contexts)
    // - tinyvec-64-bytes: 64 bytes (TinyVec<4 slots> 48 + crate_info 8 + contexts 8)
    // - tinyvec-128-bytes / smallvec-128-bytes: 128 bytes (12 slots)
    // - tinyvec-256-bytes / smallvec-256-bytes: 256 bytes (28 slots)
    // - tinyvec-512-bytes: 512 bytes (60 slots)
    //
    // On 32-bit platforms, all sizes are smaller due to 4-byte pointers.
    // Exact sizes are only asserted on 64-bit; 32-bit asserts the size is
    // at most the 64-bit budget (feature name).

    #[cfg(target_pointer_width = "64")]
    {
        #[cfg(not(any(
            feature = "_tinyvec-64-bytes",
            feature = "_tinyvec-128-bytes",
            feature = "_tinyvec-256-bytes",
            feature = "_tinyvec-512-bytes",
            feature = "_smallvec-128-bytes",
            feature = "_smallvec-256-bytes"
        )))]
        // InlineVec<LocationElem, 4> with 4 inline slots:
        // - len: u8 (1 byte, padded to 8)
        // - inline: [Option<Option<&Location>>; 4] = 64 bytes
        // - heap: Vec<T> = 24 bytes (ptr + len + capacity)
        // Plus crate_info (8) + contexts (8) = 112 bytes total
        assert_eq!(
            trace_size, 112,
            "AtTrace should be 112 bytes with 4 inline slots"
        );

        #[cfg(all(
            feature = "_tinyvec-64-bytes",
            not(any(
                feature = "_tinyvec-128-bytes",
                feature = "_tinyvec-256-bytes",
                feature = "_smallvec-128-bytes",
                feature = "_smallvec-256-bytes"
            ))
        ))]
        assert_eq!(
            trace_size, 64,
            "AtTrace with tinyvec-64-bytes should be exactly 64 bytes"
        );

        #[cfg(all(
            any(feature = "_tinyvec-128-bytes", feature = "_smallvec-128-bytes"),
            not(any(feature = "_tinyvec-256-bytes", feature = "_smallvec-256-bytes"))
        ))]
        assert_eq!(
            trace_size, 128,
            "AtTrace with 128-bytes feature should be exactly 128 bytes"
        );

        // smallvec-256-bytes takes precedence over everything
        #[cfg(feature = "_smallvec-256-bytes")]
        assert_eq!(
            trace_size, 256,
            "AtTrace with smallvec-256-bytes should be exactly 256 bytes"
        );

        // tinyvec-256-bytes only if no smallvec and no tinyvec-512
        #[cfg(all(
            feature = "_tinyvec-256-bytes",
            not(any(
                feature = "_smallvec-128-bytes",
                feature = "_smallvec-256-bytes",
                feature = "_tinyvec-512-bytes"
            ))
        ))]
        assert_eq!(
            trace_size, 256,
            "AtTrace with tinyvec-256-bytes should be exactly 256 bytes"
        );

        // tinyvec-512-bytes only if no smallvec features
        #[cfg(all(
            feature = "_tinyvec-512-bytes",
            not(any(feature = "_smallvec-128-bytes", feature = "_smallvec-256-bytes"))
        ))]
        assert_eq!(
            trace_size, 512,
            "AtTrace with tinyvec-512-bytes should be exactly 512 bytes"
        );
    }

    // On 32-bit, just verify the size is at most the 64-bit budget
    #[cfg(target_pointer_width = "32")]
    {
        #[cfg(not(any(
            feature = "_tinyvec-64-bytes",
            feature = "_tinyvec-128-bytes",
            feature = "_tinyvec-256-bytes",
            feature = "_tinyvec-512-bytes",
            feature = "_smallvec-128-bytes",
            feature = "_smallvec-256-bytes"
        )))]
        assert!(
            trace_size <= 112,
            "AtTrace should be <= 112 bytes on 32-bit. Got: {trace_size}"
        );

        #[cfg(all(
            feature = "_tinyvec-64-bytes",
            not(any(
                feature = "_tinyvec-128-bytes",
                feature = "_tinyvec-256-bytes",
                feature = "_smallvec-128-bytes",
                feature = "_smallvec-256-bytes"
            ))
        ))]
        assert!(
            trace_size <= 64,
            "AtTrace with tinyvec-64-bytes should be <= 64 bytes on 32-bit. Got: {trace_size}"
        );

        #[cfg(all(
            any(feature = "_tinyvec-128-bytes", feature = "_smallvec-128-bytes"),
            not(any(feature = "_tinyvec-256-bytes", feature = "_smallvec-256-bytes"))
        ))]
        assert!(
            trace_size <= 128,
            "AtTrace with 128-bytes feature should be <= 128 bytes on 32-bit. Got: {trace_size}"
        );

        #[cfg(feature = "_smallvec-256-bytes")]
        assert!(
            trace_size <= 256,
            "AtTrace with smallvec-256-bytes should be <= 256 bytes on 32-bit. Got: {trace_size}"
        );

        #[cfg(all(
            feature = "_tinyvec-256-bytes",
            not(any(
                feature = "_smallvec-128-bytes",
                feature = "_smallvec-256-bytes",
                feature = "_tinyvec-512-bytes"
            ))
        ))]
        assert!(
            trace_size <= 256,
            "AtTrace with tinyvec-256-bytes should be <= 256 bytes on 32-bit. Got: {trace_size}"
        );

        #[cfg(all(
            feature = "_tinyvec-512-bytes",
            not(any(feature = "_smallvec-128-bytes", feature = "_smallvec-256-bytes"))
        ))]
        assert!(
            trace_size <= 512,
            "AtTrace with tinyvec-512-bytes should be <= 512 bytes on 32-bit. Got: {trace_size}"
        );
    }
}

#[test]
fn test_basic_trace() {
    let err = TestError::NotFound.start_at();
    assert_eq!(*err.error(), TestError::NotFound);
    assert_eq!(err.frame_count(), 1);
    assert!(!err.is_empty());
}

#[test]
fn test_propagation() {
    fn inner() -> Result<(), At<TestError>> {
        Err(TestError::NotFound.start_at())
    }

    fn middle() -> Result<(), At<TestError>> {
        inner().at()
    }

    fn outer() -> Result<(), At<TestError>> {
        middle().at()
    }

    let err = outer().unwrap_err();
    assert_eq!(err.frame_count(), 3);

    // Verify locations are captured
    let locations: Vec<_> = err.locations().collect();
    assert_eq!(locations.len(), 3);

    // All locations should be in this file
    for loc in &locations {
        assert!(loc.file().contains("tests.rs"));
    }
}

#[test]
fn test_result_map_err_at() {
    fn fallible() -> Result<(), &'static str> {
        Err("oops")
    }

    fn wrapper() -> Result<(), At<&'static str>> {
        fallible().map_err(at)?;
        Ok(())
    }

    let err = wrapper().unwrap_err();
    assert_eq!(*err.error(), "oops");
    assert_eq!(err.frame_count(), 1);
}

#[test]
fn test_decompose() {
    let err = TestError::InvalidInput.start_at();
    let (inner, trace) = err.decompose();
    assert_eq!(inner, TestError::InvalidInput);
    assert!(trace.is_some());
}

#[test]
#[allow(deprecated)]
fn test_into_inner_deprecated() {
    let err = TestError::InvalidInput.start_at();
    let inner = err.into_inner();
    assert_eq!(inner, TestError::InvalidInput);
}

#[test]
#[allow(deprecated)]
fn test_at_error_deprecated_still_works() {
    let err = at(TestError::NotFound).at_error(core::fmt::Error);
    let output = alloc::format!("{:?}", err);
    assert!(output.contains("caused by"));
}

#[test]
fn test_first_last_location() {
    fn level1() -> Result<(), At<TestError>> {
        Err(TestError::NotFound.start_at())
    }

    fn level2() -> Result<(), At<TestError>> {
        level1().at()
    }

    fn level3() -> Result<(), At<TestError>> {
        level2().at()
    }

    let err = level3().unwrap_err();

    let first = err.first_location().unwrap();
    let last = err.last_location().unwrap();

    // First should be from level1, last from level3
    assert!(first.line() < last.line());
}

#[test]
fn test_display_debug() {
    let err = TestError::NotFound.start_at();

    // Display should just show the error
    let display = alloc::format!("{}", err);
    assert_eq!(display, "not found");

    // Debug should include trace
    let debug = alloc::format!("{:?}", err);
    assert!(debug.contains("NotFound"));
    assert!(debug.contains("at"));
    assert!(debug.contains("tests.rs"));
}

#[test]
fn test_no_trace() {
    let err: At<TestError> = At::wrap(TestError::NotFound);
    assert_eq!(err.frame_count(), 0);
    assert!(err.is_empty());
    assert!(err.first_location().is_none());
    assert!(err.last_location().is_none());
}

#[test]
fn test_from_impl() {
    let err: At<TestError> = TestError::NotFound.into();
    assert_eq!(*err.error(), TestError::NotFound);
    assert!(err.is_empty()); // From doesn't add trace
}

#[test]
fn test_error_mut() {
    #[derive(Debug)]
    struct MutableError {
        count: u32,
    }

    let mut err = at(MutableError { count: 0 });
    err.error_mut().count = 42;
    assert_eq!(err.error().count, 42);
}

#[test]
fn test_larger_error_type() {
    #[derive(Debug)]
    #[allow(dead_code)]
    struct LargeError {
        message: String,
        code: u64,
        data: [u8; 32],
    }

    let err = at(LargeError {
        message: String::from("test"),
        code: 42,
        data: [0; 32],
    });

    assert_eq!(err.frame_count(), 1);
    assert_eq!(err.error().code, 42);
}

#[test]
fn test_at_str() {
    let err = TestError::NotFound.start_at().at_str("while fetching user");
    assert_eq!(err.frame_count(), 1); // same line = one location with context
    // Use contexts() to find text context
    let text = err.contexts().find_map(|c| c.as_text());
    assert_eq!(text, Some("while fetching user"));
}

#[test]
fn test_at_fn_captures_function_name() {
    fn my_function_name() -> At<TestError> {
        // at() creates first frame, at_fn() creates second with function name
        at(TestError::NotFound).at_fn(|| {})
    }

    let err = my_function_name();
    assert_eq!(err.frame_count(), 2); // at() + at_fn() = 2 frames

    // The function name should appear in the debug output
    let debug = alloc::format!("{:?}", err);
    assert!(
        debug.contains("my_function_name"),
        "Debug output should contain function name: {}",
        debug
    );
}

#[test]
fn test_at_fn_adds_frame() {
    fn inner() -> Result<(), At<TestError>> {
        Err(at(TestError::NotFound))
    }

    fn outer() -> Result<(), At<TestError>> {
        inner().at_fn(|| {})
    }

    let err = outer().unwrap_err();
    assert_eq!(err.frame_count(), 2); // at() + at_fn() = 2 frames

    let debug = alloc::format!("{:?}", err);
    assert!(
        debug.contains("outer"),
        "Should capture outer function name"
    );
}

#[test]
fn test_at_named_adds_frame_with_label() {
    fn inner() -> Result<(), At<TestError>> {
        Err(at(TestError::NotFound))
    }

    fn outer() -> Result<(), At<TestError>> {
        inner().at_named("validation_phase")?;
        Ok(())
    }

    let err = outer().unwrap_err();
    assert_eq!(err.frame_count(), 2); // at() + at_named() = 2 frames

    let debug = alloc::format!("{:?}", err);
    assert!(
        debug.contains("validation_phase"),
        "Should contain custom label: {}",
        debug
    );
}

#[test]
fn test_str_propagation() {
    fn inner() -> Result<(), At<TestError>> {
        Err(TestError::NotFound.start_at())
    }

    fn outer() -> Result<(), At<TestError>> {
        // at_str adds context to last frame, use .at() first if you want a new frame
        inner().at_str("during initialization")?;
        Ok(())
    }

    let err = outer().unwrap_err();
    assert_eq!(err.frame_count(), 1); // at_str doesn't add new frame
    let text = err.contexts().find_map(|c| c.as_text());
    assert_eq!(text, Some("during initialization"));
}

#[test]
fn test_map_err_at_with_context() {
    fn fallible() -> Result<(), &'static str> {
        Err("oops")
    }

    fn wrapper() -> Result<(), At<&'static str>> {
        fallible().map_err(at).at_str("while doing something")?;
        Ok(())
    }

    let err = wrapper().unwrap_err();
    assert_eq!(*err.error(), "oops");
    let text = err.contexts().find_map(|c| c.as_text());
    assert_eq!(text, Some("while doing something"));
}

#[test]
fn test_debug_with_message() {
    let err = TestError::NotFound.start_at().at_str("context info");
    let debug = alloc::format!("{:?}", err);
    assert!(debug.contains("NotFound"));
    assert!(debug.contains("╰─ context info"));
    assert!(debug.contains("tests.rs"));
}

#[test]
fn test_dbg_ctx_typed() {
    #[derive(Debug)]
    struct RequestInfo {
        user_id: u64,
    }

    let err = TestError::NotFound
        .start_at()
        .at_debug(|| RequestInfo { user_id: 42 });

    assert_eq!(err.frame_count(), 1); // at_debug adds context to existing frame

    // Retrieve typed context
    let mut found = false;
    for ctx in err.contexts() {
        if let Some(req) = ctx.downcast_ref::<RequestInfo>() {
            assert_eq!(req.user_id, 42);
            found = true;
        }
    }
    assert!(found, "should find RequestInfo context");
}

#[test]
fn test_multiple_contexts() {
    fn level1() -> Result<(), At<TestError>> {
        Err(TestError::NotFound.start_at())
    }

    fn level2() -> Result<(), At<TestError>> {
        level1().at_str("in level2")?;
        Ok(())
    }

    fn level3() -> Result<(), At<TestError>> {
        level2().at_str("in level3")?;
        Ok(())
    }

    let err = level3().unwrap_err();

    // at_str adds context to last frame, doesn't create new frames
    assert_eq!(err.frame_count(), 1);

    // Should have 2 context messages (level2 and level3)
    let contexts: Vec<_> = err.contexts().collect();
    assert_eq!(contexts.len(), 2);

    // Most recent first
    assert_eq!(contexts[0].as_text(), Some("in level3"));
    assert_eq!(contexts[1].as_text(), Some("in level2"));
}

#[test]
fn test_context_enum() {
    let text_ctx = AtContext::Text(String::from("hello").into());
    assert_eq!(text_ctx.as_text(), Some("hello"));
    assert!(text_ctx.downcast_ref::<u32>().is_none());

    // Debug context - requires Debug (u32 implements Debug)
    let debug_ctx = AtContext::Debug(Box::new(42u32));
    assert_eq!(debug_ctx.as_text(), None);
    assert_eq!(debug_ctx.downcast_ref::<u32>(), Some(&42));

    // Verify Debug output works
    let debug_str = alloc::format!("{:?}", debug_ctx);
    assert!(debug_str.contains("42"));

    // Display context - requires Display (u32 implements Display)
    let display_ctx = AtContext::Display(Box::new(99u32));
    assert_eq!(display_ctx.as_text(), None);
    assert_eq!(display_ctx.downcast_ref::<u32>(), Some(&99));

    // Verify Display output works
    let display_str = alloc::format!("{}", display_ctx);
    assert!(display_str.contains("99"));

    // is_display should be true for Text and Display
    assert!(text_ctx.is_display());
    assert!(!debug_ctx.is_display());
    assert!(display_ctx.is_display());
}

#[test]
fn test_typed_context_debug_output() {
    #[derive(Debug)]
    #[allow(dead_code)]
    struct MyContext {
        id: u64,
        name: &'static str,
    }

    let err = TestError::NotFound.start_at().at_debug(|| MyContext {
        id: 123,
        name: "test",
    });

    let debug = alloc::format!("{:?}", err);
    // Should contain the Debug output of MyContext
    assert!(debug.contains("MyContext"));
    assert!(debug.contains("123"));
    assert!(debug.contains("test"));
}

#[test]
fn test_ctx_data() {
    // Use a type that has both Display and Debug but we want Display formatting
    let err = TestError::NotFound
        .start_at()
        .at_data(|| "user-friendly message");

    assert_eq!(err.frame_count(), 1); // at_data adds context to existing frame

    // Check that Display formatting is used in output
    let debug = alloc::format!("{:?}", err);
    assert!(debug.contains("╰─ user-friendly message"));

    // Downcast should still work
    let mut found = false;
    for ctx in err.contexts() {
        if ctx.downcast_ref::<&str>().is_some() {
            found = true;
            assert!(ctx.is_display());
        }
    }
    assert!(found, "should find string context");
}

#[test]
fn test_mixed_context_types() {
    #[derive(Debug)]
    #[allow(dead_code)]
    struct DebugInfo {
        code: u32,
    }

    let err = TestError::NotFound
        .start_at()
        .at_str("text message")
        .at_debug(|| DebugInfo { code: 42 })
        .at_data(|| "display message");

    // All context methods add to the existing frame, not new ones
    assert_eq!(err.frame_count(), 1);

    // Should have 3 contexts
    let contexts: Vec<_> = err.contexts().collect();
    assert_eq!(contexts.len(), 3);

    // Most recent first (display, debug, text)
    assert!(contexts[0].is_display()); // display message
    assert!(!contexts[1].is_display()); // DebugInfo (Debug)
    assert!(contexts[2].is_display()); // text message
}

#[test]
fn test_trace_format_structure() {
    // Test that trace format shows locations oldest-first with contexts
    fn level1() -> Result<(), At<TestError>> {
        Err(TestError::NotFound.start_at())
    }

    fn level2() -> Result<(), At<TestError>> {
        level1().at_str("in level2")?;
        Ok(())
    }

    fn level3() -> Result<(), At<TestError>> {
        level2().at_str("in level3")?;
        Ok(())
    }

    let err = level3().unwrap_err();
    let debug = alloc::format!("{:?}", err);

    // Verify structure:
    // - Error header
    assert!(debug.contains("Error: NotFound"));

    // - Locations with contexts
    assert!(debug.contains("╰─ in level2"));
    assert!(debug.contains("╰─ in level3"));

    // - Location lines present (path separator varies by platform)
    assert!(
        debug.contains("at src/tests.rs:") || debug.contains("at src\\tests.rs:"),
        "Debug output should contain location: {}",
        debug
    );

    // Verify order: level2 context before level3 context (oldest first)
    let level2_pos = debug.find("in level2").unwrap();
    let level3_pos = debug.find("in level3").unwrap();
    assert!(
        level2_pos < level3_pos,
        "level2 should appear before level3 (oldest first)"
    );
}

#[test]
fn test_trace_origin_comes_first() {
    fn origin() -> Result<(), At<TestError>> {
        Err(TestError::NotFound.start_at())
    }

    fn wrapper() -> Result<(), At<TestError>> {
        origin().at_str("wrapping")?;
        Ok(())
    }

    let err = wrapper().unwrap_err();
    let debug = alloc::format!("{:?}", err);

    // The first "at" line should be from origin (lower line number)
    // and the context "wrapping" should come after
    let lines: Vec<&str> = debug.lines().collect();

    // Find first "at" line (path separator varies by platform)
    let first_at = lines
        .iter()
        .find(|l| l.contains("at src/tests.rs:") || l.contains("at src\\tests.rs:"))
        .expect("should find location line in debug output");

    // It should be the origin location (before the wrapper's context)
    // The origin .start_at() call will be at a lower line than wrapper's .at_str()
    assert!(
        !first_at.contains("╰─"),
        "First location should be origin without context"
    );
}

#[test]
fn test_partial_eq_compares_error_only() {
    // Same error, different traces
    fn location1() -> At<TestError> {
        TestError::NotFound.start_at()
    }
    fn location2() -> At<TestError> {
        TestError::NotFound.start_at()
    }

    let err1 = location1();
    let err2 = location2();

    // Different traces (different source locations)
    assert!(err1.first_location() != err2.first_location());

    // But errors should be equal because the inner E is equal
    assert_eq!(err1, err2);

    // Different errors should not be equal
    let err3 = at(TestError::InvalidInput);
    assert_ne!(err1, err3);
}

#[test]
fn test_as_ref() {
    let err = at(TestError::NotFound);

    // AsRef gives us &E
    let inner: &TestError = err.as_ref();
    assert_eq!(*inner, TestError::NotFound);

    // Should be same as .error()
    assert!(core::ptr::eq(err.as_ref(), err.error()));
}

#[test]
fn test_map_err_at() {
    #[derive(Debug, PartialEq)]
    struct Error1;
    #[derive(Debug, PartialEq)]
    struct Error2;

    fn inner() -> Result<(), At<Error1>> {
        Err(at(Error1).at_str("inner context"))
    }

    fn outer() -> Result<(), At<Error2>> {
        // map_err_at converts Error1 -> Error2 while preserving trace
        inner().map_err_at(|_| Error2)?;
        Ok(())
    }

    let err = outer().unwrap_err();
    assert_eq!(*err.error(), Error2);
    assert_eq!(err.frame_count(), 1); // Trace preserved
    let text = err.contexts().find_map(|c| c.as_text());
    assert_eq!(text, Some("inner context")); // Context preserved
}

#[test]
fn test_hash_ignores_trace() {
    use core::hash::{Hash, Hasher};

    // Simple hasher for testing
    struct TestHasher(u64);
    impl Hasher for TestHasher {
        fn finish(&self) -> u64 {
            self.0
        }
        fn write(&mut self, bytes: &[u8]) {
            for &b in bytes {
                self.0 = self.0.wrapping_mul(31).wrapping_add(b as u64);
            }
        }
    }

    fn hash_one<T: Hash>(val: &T) -> u64 {
        let mut h = TestHasher(0);
        val.hash(&mut h);
        h.finish()
    }

    // Same error, different traces (different locations)
    fn loc1() -> At<TestError> {
        TestError::NotFound.start_at()
    }
    fn loc2() -> At<TestError> {
        TestError::NotFound.start_at()
    }

    let err1 = loc1();
    let err2 = loc2();

    // Different traces
    assert!(err1.first_location() != err2.first_location());

    // But same hash (because E is the same)
    assert_eq!(hash_one(&err1), hash_one(&err2));

    // Different error = different hash
    let err3 = at(TestError::InvalidInput);
    assert_ne!(hash_one(&err1), hash_one(&err3));
}

// ============================================================================
// Pretty Formatter Tests
// ============================================================================

#[cfg(feature = "_termcolor")]
#[test]
fn test_termcolor_display_contains_error() {
    let err = at(TestError::NotFound).at_str("context");
    let output = alloc::format!("{}", err.display_color());

    // Should contain the error type
    assert!(output.contains("NotFound"), "Output: {}", output);
    // Should contain the context
    assert!(output.contains("context"), "Output: {}", output);
    // Should contain location info
    assert!(output.contains("tests.rs"), "Output: {}", output);
}

#[cfg(feature = "_termcolor")]
#[test]
fn test_termcolor_meta_display_contains_crate_info() {
    let err = crate::at!(TestError::NotFound);
    let output = alloc::format!("{}", err.display_color_meta());

    // Should contain crate info
    assert!(output.contains("whereat"), "Output: {}", output);
}

#[cfg(feature = "_html")]
#[test]
fn test_html_display_contains_markup() {
    let err = at(TestError::NotFound).at_str("context");
    let output = alloc::format!("{}", err.display_html());

    // Should have the wrapper div
    assert!(
        output.contains("class=\"whereat-error\""),
        "Output: {}",
        output
    );
    // Should have error header
    assert!(
        output.contains("class=\"error-header\""),
        "Output: {}",
        output
    );
    // Should contain the error
    assert!(output.contains("NotFound"), "Output: {}", output);
    // Should contain context
    assert!(output.contains("context"), "Output: {}", output);
}

#[cfg(feature = "_html")]
#[test]
fn test_html_styled_includes_css() {
    let err = at(TestError::NotFound);
    let output = alloc::format!("{}", err.display_html_styled());

    // Should include style tag
    assert!(output.contains("<style>"), "Output: {}", output);
    assert!(output.contains(".whereat-error"), "Output: {}", output);
}

#[cfg(feature = "_html")]
#[test]
fn test_html_escapes_special_chars() {
    let err = at(TestError::NotFound)
        .at_string(|| alloc::string::String::from("<script>alert('xss')</script>"));
    let output = alloc::format!("{}", err.display_html());

    // Should escape angle brackets
    assert!(output.contains("&lt;script&gt;"), "Output: {}", output);
    assert!(output.contains("&#39;"), "Output: {}", output);
    // Should NOT contain unescaped script tag
    assert!(!output.contains("<script>"), "Output: {}", output);
}

// ============================================================================
// Depth Limit Tests
// ============================================================================

#[test]
fn test_max_trace_frames_limit() {
    use crate::trace::AT_MAX_FRAMES;

    // Recursive function that adds many frames
    fn add_frames(err: At<TestError>, depth: usize) -> At<TestError> {
        if depth == 0 {
            err
        } else {
            add_frames(err.at(), depth - 1)
        }
    }

    let err = at(TestError::NotFound);
    let err = add_frames(err, AT_MAX_FRAMES + 50);

    // Should be capped at AT_MAX_FRAMES
    assert_eq!(
        err.frame_count(),
        AT_MAX_FRAMES,
        "Frame count should be capped at AT_MAX_FRAMES ({})",
        AT_MAX_FRAMES
    );
}

#[test]
fn test_max_trace_contexts_limit() {
    use crate::trace::AT_MAX_CONTEXTS;

    let mut err = at(TestError::NotFound);

    // Add more contexts than the limit
    for i in 0..(AT_MAX_CONTEXTS + 50) {
        err = err.at_string(|| alloc::format!("context {}", i));
    }

    // Count contexts
    let context_count = err.contexts().count();

    // Should be capped at AT_MAX_CONTEXTS
    assert_eq!(
        context_count, AT_MAX_CONTEXTS,
        "Context count should be capped at AT_MAX_CONTEXTS ({})",
        AT_MAX_CONTEXTS
    );
}

#[test]
fn test_limits_constants_are_128() {
    use crate::trace::{AT_MAX_CONTEXTS, AT_MAX_FRAMES};

    assert_eq!(AT_MAX_FRAMES, 128);
    assert_eq!(AT_MAX_CONTEXTS, 128);
}

// ============================================================================
// Additional Coverage Tests
// ============================================================================

#[test]
fn test_from_parts() {
    use crate::trace::AtTrace;

    let mut trace = AtTrace::new();
    let _ = trace.try_push(core::panic::Location::caller());
    let err = At::<TestError>::from_parts(TestError::NotFound, trace);
    assert_eq!(err.frame_count(), 1);
    assert_eq!(*err.error(), TestError::NotFound);
}

#[test]
fn test_take_trace_and_set_trace() {
    let mut err = at(TestError::NotFound).at_str("context");
    assert_eq!(err.frame_count(), 1);

    let trace = err.take_trace();
    assert!(trace.is_some());
    assert_eq!(err.frame_count(), 0);

    err.set_trace(trace.unwrap());
    assert_eq!(err.frame_count(), 1);
}

#[test]
fn test_at_string_on_at() {
    let err = at(TestError::NotFound).at_string(|| alloc::format!("dynamic {}", 42));
    let text = err.contexts().find_map(|c| c.as_text());
    assert_eq!(text, Some("dynamic 42"));
}

#[test]
fn test_full_trace_display() {
    let err = at(TestError::NotFound)
        .at_str("loading config")
        .at()
        .at_str("initializing");

    let output = alloc::format!("{}", err.full_trace());
    assert!(output.contains("not found"));
    assert!(output.contains("loading config"));
    assert!(output.contains("initializing"));
    assert!(output.contains("at "));
}

#[test]
fn test_full_trace_with_skipped() {
    let err = at(TestError::NotFound).at_skipped_frames().at();
    let output = alloc::format!("{}", err.full_trace());
    assert!(output.contains("[...]"));
}

#[test]
fn test_full_trace_with_fn_name() {
    fn my_function() -> At<TestError> {
        at(TestError::NotFound).at_fn(|| {})
    }
    let err = my_function();
    let output = alloc::format!("{}", err.full_trace());
    assert!(output.contains("in "));
    assert!(output.contains("my_function"));
}

#[test]
fn test_full_trace_with_error_context() {
    #[derive(Debug)]
    struct Inner(&'static str);
    impl fmt::Display for Inner {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "inner: {}", self.0)
        }
    }
    impl core::error::Error for Inner {}

    let err = at(TestError::NotFound).at_aside_error(Inner("root cause"));
    let output = alloc::format!("{}", err.full_trace());
    assert!(output.contains("caused by: inner: root cause"));
}

#[test]
fn test_full_trace_with_debug_and_display_data() {
    #[derive(Debug)]
    struct DbgData(#[allow(dead_code)] u32);

    struct DispData(u32);
    impl fmt::Display for DispData {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "val={}", self.0)
        }
    }

    let err = at(TestError::NotFound)
        .at_debug(|| DbgData(42))
        .at_data(|| DispData(99));

    let output = alloc::format!("{}", err.full_trace());
    assert!(output.contains("DbgData"));
    assert!(output.contains("42"));
    assert!(output.contains("val=99"));
}

#[test]
fn test_last_error_trace_display() {
    let err = at(TestError::NotFound)
        .at_str("this should not appear")
        .at();

    let output = alloc::format!("{}", err.last_error_trace());
    assert!(output.contains("not found"));
    assert!(output.contains("at "));
    assert!(!output.contains("this should not appear"));
}

#[test]
fn test_last_error_trace_with_skipped() {
    let err = at(TestError::NotFound).at_skipped_frames();
    let output = alloc::format!("{}", err.last_error_trace());
    assert!(output.contains("[...]"));
}

#[test]
fn test_last_error_display() {
    let err = at(TestError::NotFound).at_str("context");
    let output = alloc::format!("{}", err.last_error());
    assert_eq!(output, "not found");
}

#[test]
fn test_display_with_meta_no_trace() {
    let err: At<TestError> = At::wrap(TestError::NotFound);
    let output = alloc::format!("{}", err.display_with_meta());
    assert!(output.contains("NotFound"));
}

#[test]
fn test_display_with_meta_skipped() {
    let err = at(TestError::NotFound)
        .set_crate_info(crate::at_crate_info())
        .at_skipped_frames()
        .at();
    let output = alloc::format!("{}", err.display_with_meta());
    assert!(output.contains("[...]"));
}

#[test]
fn test_display_with_meta_contexts() {
    let err = at(TestError::NotFound)
        .set_crate_info(crate::at_crate_info())
        .at_str("text ctx")
        .at_fn(|| {})
        .at_debug(|| 42u32)
        .at_data(|| "display data")
        .at_aside_error(core::fmt::Error);

    let output = alloc::format!("{}", err.display_with_meta());
    assert!(output.contains("text ctx"));
    assert!(output.contains("in "));
    assert!(output.contains("42"));
    assert!(output.contains("display data"));
    assert!(output.contains("caused by"));
}

#[test]
fn test_into_traceable() {
    use crate::trace::{AtTrace, AtTraceable};

    struct MyErr {
        trace: AtTrace,
    }
    impl AtTraceable for MyErr {
        fn trace_mut(&mut self) -> &mut AtTrace {
            &mut self.trace
        }
        fn trace(&self) -> Option<&AtTrace> {
            Some(&self.trace)
        }
        fn fmt_message(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "my error")
        }
    }

    let at_err = at(TestError::NotFound).at_str("context");
    let my_err: MyErr = at_err.into_traceable(|_| MyErr {
        trace: AtTrace::new(),
    });
    assert!(my_err.trace().unwrap().frame_count() >= 1);
}

#[test]
fn test_into_traceable_no_trace() {
    use crate::trace::{AtTrace, AtTraceable};

    struct MyErr {
        trace: AtTrace,
    }
    impl AtTraceable for MyErr {
        fn trace_mut(&mut self) -> &mut AtTrace {
            &mut self.trace
        }
        fn trace(&self) -> Option<&AtTrace> {
            Some(&self.trace)
        }
        fn fmt_message(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "my error")
        }
    }

    let at_err: At<TestError> = At::wrap(TestError::NotFound);
    let my_err: MyErr = at_err.into_traceable(|_| MyErr {
        trace: AtTrace::new(),
    });
    assert_eq!(my_err.trace().unwrap().frame_count(), 0);
}

#[test]
fn test_debug_with_skipped_frames() {
    let err = at(TestError::NotFound).at_skipped_frames().at();
    let debug = alloc::format!("{:?}", err);
    assert!(debug.contains("[...]"));
}

#[test]
fn test_context_type_name() {
    let ctx = AtContext::Debug(Box::new(42u32));
    assert!(ctx.type_name().unwrap().contains("u32"));

    let ctx = AtContext::Display(Box::new(42u32));
    assert!(ctx.type_name().unwrap().contains("u32"));

    let text = AtContext::Text("hello".into());
    assert!(text.type_name().is_none());
}

#[test]
fn test_context_function_name() {
    let ctx = AtContext::FunctionName("my_func");
    assert_eq!(ctx.as_function_name(), Some("my_func"));
    assert!(ctx.is_function_name());
    assert!(ctx.as_text().is_none());
}

#[test]
fn test_context_crate_info() {
    let info = crate::at_crate_info();
    let ctx = AtContext::Crate(info);
    assert!(ctx.as_crate_info().is_some());
    assert!(core::ptr::eq(ctx.as_crate_info().unwrap(), info));
    assert!(ctx.is_crate_boundary());
    assert!(ctx.as_text().is_none());
}

#[test]
fn test_context_error() {
    let ctx = AtContext::Error(Box::new(core::fmt::Error));
    assert!(ctx.is_error());
    assert!(ctx.as_error().is_some());
    assert!(ctx.is_display());

    // Verify it's not function name or crate boundary
    assert!(!ctx.is_function_name());
    assert!(!ctx.is_crate_boundary());
}

#[test]
fn test_context_debug_display_fmt() {
    let fn_ctx = AtContext::FunctionName("foo");
    assert_eq!(alloc::format!("{:?}", fn_ctx), "in foo");
    assert_eq!(alloc::format!("{}", fn_ctx), "in foo");

    let crate_ctx = AtContext::Crate(crate::at_crate_info());
    let debug = alloc::format!("{:?}", crate_ctx);
    assert!(debug.contains("[crate:"));
    let display = alloc::format!("{}", crate_ctx);
    assert!(display.contains("[crate:"));

    let err_ctx = AtContext::Error(Box::new(core::fmt::Error));
    let debug = alloc::format!("{:?}", err_ctx);
    assert!(debug.contains("caused by"));
    let display = alloc::format!("{}", err_ctx);
    assert!(display.contains("caused by"));
}

#[test]
fn test_context_ref_display_debug() {
    use crate::context::AtContextRef;

    let ctx = AtContext::Text("hello".into());
    let ctx_ref = AtContextRef { inner: &ctx };
    assert_eq!(alloc::format!("{}", ctx_ref), "hello");
    assert_eq!(alloc::format!("{:?}", ctx_ref), "\"hello\"");
}

#[test]
fn test_context_ref_is_methods() {
    use crate::context::AtContextRef;

    let fn_ctx = AtContext::FunctionName("foo");
    let ref1 = AtContextRef { inner: &fn_ctx };
    assert!(ref1.is_function_name());
    assert_eq!(ref1.as_function_name(), Some("foo"));

    let crate_ctx = AtContext::Crate(crate::at_crate_info());
    let ref2 = AtContextRef { inner: &crate_ctx };
    assert!(ref2.is_crate_boundary());
    assert!(ref2.as_crate_info().is_some());

    let err_ctx = AtContext::Error(Box::new(core::fmt::Error));
    let ref3 = AtContextRef { inner: &err_ctx };
    assert!(ref3.is_error());
    assert!(ref3.as_error().is_some());
}

#[test]
fn test_context_ref_type_name() {
    use crate::context::AtContextRef;

    let dbg_ctx = AtContext::Debug(Box::new(42u32));
    let ref1 = AtContextRef { inner: &dbg_ctx };
    assert!(ref1.type_name().unwrap().contains("u32"));

    let text_ctx = AtContext::Text("hello".into());
    let ref2 = AtContextRef { inner: &text_ctx };
    assert!(ref2.type_name().is_none());
}

#[test]
fn test_trace_default() {
    use crate::trace::AtTrace;

    let trace: AtTrace = Default::default();
    assert!(trace.is_empty());
    assert_eq!(trace.frame_count(), 0);
}

#[test]
fn test_trace_take() {
    use crate::trace::AtTrace;

    let mut trace = AtTrace::capture();
    assert_eq!(trace.frame_count(), 1);

    let taken = trace.take();
    assert_eq!(taken.frame_count(), 1);
    assert_eq!(trace.frame_count(), 0);
}

#[test]
fn test_trace_append() {
    use crate::trace::AtTrace;

    let mut trace1 = AtTrace::capture();
    let trace2 = AtTrace::capture();
    trace1.append(trace2);
    assert_eq!(trace1.frame_count(), 2);
}

#[test]
fn test_trace_prepend() {
    use crate::trace::AtTrace;

    let mut trace1 = AtTrace::capture();
    let trace2 = AtTrace::capture();
    trace1.prepend(trace2);
    assert_eq!(trace1.frame_count(), 2);
}

#[test]
fn test_trace_boxed_from_trace() {
    use crate::trace::{AtTrace, AtTraceBoxed};

    let trace = AtTrace::capture();
    let boxed = AtTraceBoxed::from(trace);
    assert!(!boxed.is_empty());
    assert_eq!(boxed.frame_count(), 1);

    let empty = AtTrace::new();
    let boxed_empty = AtTraceBoxed::from(empty);
    assert!(boxed_empty.is_empty());
}

#[test]
fn test_trace_boxed_into_option() {
    use crate::trace::{AtTrace, AtTraceBoxed};

    let boxed = AtTraceBoxed::from(AtTrace::capture());
    let opt: Option<AtTrace> = boxed.into();
    assert!(opt.is_some());

    let empty = AtTraceBoxed::new();
    let opt: Option<AtTrace> = empty.into();
    assert!(opt.is_none());
}

#[test]
fn test_trace_boxed_debug() {
    use crate::trace::{AtTrace, AtTraceBoxed};

    let empty = AtTraceBoxed::new();
    let debug = alloc::format!("{:?}", empty);
    assert!(debug.contains("empty"));

    let boxed = AtTraceBoxed::from(AtTrace::capture());
    let debug = alloc::format!("{:?}", boxed);
    assert!(!debug.contains("empty"));
}

#[test]
fn test_trace_boxed_set_empty() {
    use crate::trace::{AtTrace, AtTraceBoxed};

    let mut boxed = AtTraceBoxed::from(AtTrace::capture());
    assert!(!boxed.is_empty());

    // Setting an empty trace should clear
    boxed.set(AtTrace::new());
    assert!(boxed.is_empty());
}

#[test]
fn test_trace_boxed_crate_info() {
    use crate::trace::{AtTrace, AtTraceBoxed};

    let mut trace = AtTrace::capture();
    trace.set_crate_info(crate::at_crate_info());
    let boxed = AtTraceBoxed::from(trace);
    assert!(boxed.crate_info().is_some());

    let empty = AtTraceBoxed::new();
    assert!(empty.crate_info().is_none());
}

#[test]
fn test_at_frame_has_contexts() {
    let err = at(TestError::NotFound).at_str("ctx").at();
    let frames: alloc::vec::Vec<_> = err.frames().collect();
    assert!(frames[0].has_contexts());
    assert!(!frames[1].has_contexts());
}

#[test]
fn test_at_frame_debug() {
    let err = at(TestError::NotFound).at_str("ctx").at_skipped_frames();
    let frames: alloc::vec::Vec<_> = err.frames().collect();

    let debug0 = alloc::format!("{:?}", frames[0]);
    assert!(debug0.contains("at "));

    let debug1 = alloc::format!("{:?}", frames[1]);
    assert_eq!(debug1, "[...]");
}

#[test]
fn test_crate_info_builder_all_methods() {
    use crate::AtCrateInfo;

    let info = AtCrateInfo::builder()
        .name("test")
        .repo(Some("https://github.com/org/repo"))
        .commit(Some("abc123"))
        .path(Some("crates/lib/"))
        .module("test_mod")
        .meta(&[("key", "value")])
        .link_format(crate::GITHUB_LINK_FORMAT)
        .build();

    assert_eq!(info.name(), "test");
    assert_eq!(info.repo(), Some("https://github.com/org/repo"));
    assert_eq!(info.commit(), Some("abc123"));
    assert_eq!(info.crate_path(), Some("crates/lib/"));
    assert_eq!(info.module(), "test_mod");
    assert_eq!(info.meta(), &[("key", "value")]);
    assert_eq!(info.link_format(), crate::GITHUB_LINK_FORMAT);
    assert_eq!(info.get_meta("key"), Some("value"));
    assert_eq!(info.get_meta("missing"), None);
}

#[test]
fn test_crate_info_builder_default() {
    use crate::crate_info::AtCrateInfoBuilder;

    let builder: AtCrateInfoBuilder = Default::default();
    let info = builder.build();
    assert_eq!(info.name(), "");
    assert!(info.repo().is_none());
}

#[test]
fn test_crate_info_owned_methods() {
    use crate::AtCrateInfo;

    let info = AtCrateInfo::builder()
        .name_owned("owned-name".into())
        .repo_owned(Some("https://example.com".into()))
        .commit_owned(Some("abc123".into()))
        .path_owned(Some("crates/lib/".into()))
        .module_owned("my_mod".into())
        .meta_owned(alloc::vec![("k".into(), "v".into())])
        .link_format_owned("{repo}/{file}".into())
        .build();

    assert_eq!(info.name(), "owned-name");
    assert_eq!(info.repo(), Some("https://example.com"));
    assert_eq!(info.commit(), Some("abc123"));
    assert_eq!(info.crate_path(), Some("crates/lib/"));
    assert_eq!(info.module(), "my_mod");
    assert_eq!(info.get_meta("k"), Some("v"));
    assert_eq!(info.link_format(), "{repo}/{file}");
}

#[test]
fn test_crate_info_owned_none_variants() {
    use crate::AtCrateInfo;

    let info = AtCrateInfo::builder()
        .repo_owned(None)
        .commit_owned(None)
        .path_owned(None)
        .build();

    assert!(info.repo().is_none());
    assert!(info.commit().is_none());
    assert!(info.crate_path().is_none());
}

#[test]
fn test_link_format_auto_detect() {
    use crate::AtCrateInfo;

    let github = AtCrateInfo::builder()
        .repo(Some("https://github.com/org/repo"))
        .link_format_auto()
        .build();
    assert_eq!(github.link_format(), crate::GITHUB_LINK_FORMAT);

    let gitlab = AtCrateInfo::builder()
        .repo(Some("https://gitlab.com/org/repo"))
        .link_format_auto()
        .build();
    assert_eq!(gitlab.link_format(), crate::GITLAB_LINK_FORMAT);

    let gitea = AtCrateInfo::builder()
        .repo(Some("https://gitea.example.com/org/repo"))
        .link_format_auto()
        .build();
    assert_eq!(gitea.link_format(), crate::GITEA_LINK_FORMAT);

    let forgejo = AtCrateInfo::builder()
        .repo(Some("https://forgejo.example.com/org/repo"))
        .link_format_auto()
        .build();
    assert_eq!(forgejo.link_format(), crate::GITEA_LINK_FORMAT);

    let codeberg = AtCrateInfo::builder()
        .repo(Some("https://codeberg.org/org/repo"))
        .link_format_auto()
        .build();
    assert_eq!(codeberg.link_format(), crate::GITEA_LINK_FORMAT);

    let bitbucket = AtCrateInfo::builder()
        .repo(Some("https://bitbucket.org/org/repo"))
        .link_format_auto()
        .build();
    assert_eq!(bitbucket.link_format(), crate::BITBUCKET_LINK_FORMAT);

    let unknown = AtCrateInfo::builder()
        .repo(Some("https://example.com/repo"))
        .link_format_auto()
        .build();
    assert_eq!(unknown.link_format(), crate::GITHUB_LINK_FORMAT);

    let no_repo = AtCrateInfo::builder().link_format_auto().build();
    assert_eq!(no_repo.link_format(), crate::GITHUB_LINK_FORMAT);
}

#[test]
fn test_build_auto_detects_link_format() {
    use crate::AtCrateInfo;

    // build() auto-detects without explicit link_format_auto() call
    let gitlab = AtCrateInfo::builder()
        .repo(Some("https://gitlab.com/org/repo"))
        .build();
    assert_eq!(gitlab.link_format(), crate::GITLAB_LINK_FORMAT);

    let bitbucket = AtCrateInfo::builder()
        .repo(Some("https://bitbucket.org/org/repo"))
        .build();
    assert_eq!(bitbucket.link_format(), crate::BITBUCKET_LINK_FORMAT);

    let codeberg = AtCrateInfo::builder()
        .repo(Some("https://codeberg.org/org/repo"))
        .build();
    assert_eq!(codeberg.link_format(), crate::GITEA_LINK_FORMAT);

    // Explicit link_format() overrides auto-detection
    let explicit = AtCrateInfo::builder()
        .repo(Some("https://gitlab.com/org/repo"))
        .link_format(crate::GITHUB_LINK_FORMAT)
        .build();
    assert_eq!(explicit.link_format(), crate::GITHUB_LINK_FORMAT);
}

#[test]
fn test_traceable_at_string() {
    use crate::trace::{AtTrace, AtTraceable};

    struct MyErr {
        trace: AtTrace,
    }
    impl AtTraceable for MyErr {
        fn trace_mut(&mut self) -> &mut AtTrace {
            &mut self.trace
        }
        fn trace(&self) -> Option<&AtTrace> {
            Some(&self.trace)
        }
        fn fmt_message(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "err")
        }
    }

    let err = MyErr {
        trace: AtTrace::capture(),
    }
    .at_string(|| alloc::format!("dyn {}", 1));
    let ctx: alloc::vec::Vec<_> = err
        .trace()
        .unwrap()
        .contexts()
        .filter_map(|c| c.as_text().map(alloc::string::ToString::to_string))
        .collect();
    assert!(ctx.iter().any(|s| s == "dyn 1"));
}

#[test]
fn test_traceable_at_data_and_debug() {
    use crate::trace::{AtTrace, AtTraceable};

    struct MyErr {
        trace: AtTrace,
    }
    impl AtTraceable for MyErr {
        fn trace_mut(&mut self) -> &mut AtTrace {
            &mut self.trace
        }
        fn trace(&self) -> Option<&AtTrace> {
            Some(&self.trace)
        }
        fn fmt_message(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "err")
        }
    }

    let err = MyErr {
        trace: AtTrace::capture(),
    }
    .at_data(|| 42u32)
    .at_debug(|| "dbg_val");

    assert_eq!(err.trace().unwrap().contexts().count(), 2);
}

#[test]
fn test_traceable_at_error() {
    use crate::trace::{AtTrace, AtTraceable};

    struct MyErr {
        trace: AtTrace,
    }
    impl AtTraceable for MyErr {
        fn trace_mut(&mut self) -> &mut AtTrace {
            &mut self.trace
        }
        fn trace(&self) -> Option<&AtTrace> {
            Some(&self.trace)
        }
        fn fmt_message(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "err")
        }
    }

    let err = MyErr {
        trace: AtTrace::capture(),
    }
    .at_aside_error(core::fmt::Error);

    let has_error = err.trace().unwrap().contexts().any(|c| c.is_error());
    assert!(has_error);
}

#[test]
fn test_traceable_at_crate() {
    use crate::trace::{AtTrace, AtTraceable};

    struct MyErr {
        trace: AtTrace,
    }
    impl AtTraceable for MyErr {
        fn trace_mut(&mut self) -> &mut AtTrace {
            &mut self.trace
        }
        fn trace(&self) -> Option<&AtTrace> {
            Some(&self.trace)
        }
        fn fmt_message(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "err")
        }
    }

    let err = MyErr {
        trace: AtTrace::capture(),
    }
    .at_crate(crate::at_crate_info());

    assert!(err.trace().unwrap().crate_info().is_some());
}

#[test]
fn test_traceable_at_fn_and_named() {
    use crate::trace::{AtTrace, AtTraceable};

    struct MyErr {
        trace: AtTrace,
    }
    impl AtTraceable for MyErr {
        fn trace_mut(&mut self) -> &mut AtTrace {
            &mut self.trace
        }
        fn trace(&self) -> Option<&AtTrace> {
            Some(&self.trace)
        }
        fn fmt_message(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "err")
        }
    }

    let err = MyErr {
        trace: AtTrace::capture(),
    }
    .at_fn(|| {});
    assert_eq!(err.trace().unwrap().frame_count(), 2);

    let err2 = MyErr {
        trace: AtTrace::capture(),
    }
    .at_named("step1");
    assert_eq!(err2.trace().unwrap().frame_count(), 2);
}

#[test]
fn test_traceable_at_skipped() {
    use crate::trace::{AtTrace, AtTraceable};

    struct MyErr {
        trace: AtTrace,
    }
    impl AtTraceable for MyErr {
        fn trace_mut(&mut self) -> &mut AtTrace {
            &mut self.trace
        }
        fn trace(&self) -> Option<&AtTrace> {
            Some(&self.trace)
        }
        fn fmt_message(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "err")
        }
    }

    let err = MyErr {
        trace: AtTrace::capture(),
    }
    .at_skipped_frames();
    assert_eq!(err.trace().unwrap().frame_count(), 2);
}

#[test]
fn test_traceable_map_traceable() {
    use crate::trace::{AtTrace, AtTraceable};

    struct ErrA {
        trace: AtTrace,
    }
    impl AtTraceable for ErrA {
        fn trace_mut(&mut self) -> &mut AtTrace {
            &mut self.trace
        }
        fn trace(&self) -> Option<&AtTrace> {
            Some(&self.trace)
        }
        fn fmt_message(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "A")
        }
    }
    struct ErrB {
        trace: AtTrace,
    }
    impl AtTraceable for ErrB {
        fn trace_mut(&mut self) -> &mut AtTrace {
            &mut self.trace
        }
        fn trace(&self) -> Option<&AtTrace> {
            Some(&self.trace)
        }
        fn fmt_message(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "B")
        }
    }

    let a = ErrA {
        trace: AtTrace::capture(),
    }
    .at_str("context");
    let b: ErrB = a.map_traceable(|_| ErrB {
        trace: AtTrace::new(),
    });
    assert!(b.trace().unwrap().frame_count() >= 1);
}

#[test]
fn test_traceable_into_at() {
    use crate::trace::{AtTrace, AtTraceable};

    struct MyErr {
        trace: AtTrace,
    }
    impl AtTraceable for MyErr {
        fn trace_mut(&mut self) -> &mut AtTrace {
            &mut self.trace
        }
        fn trace(&self) -> Option<&AtTrace> {
            Some(&self.trace)
        }
        fn fmt_message(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "err")
        }
    }

    let err = MyErr {
        trace: AtTrace::capture(),
    }
    .at_str("context");
    let at_err: At<&str> = err.into_at(|_| "converted");
    assert_eq!(*at_err.error(), "converted");
    assert!(at_err.frame_count() >= 1);
}

#[test]
fn test_traceable_full_trace_format() {
    use crate::trace::{AtTrace, AtTraceable};

    struct MyErr {
        trace: AtTrace,
    }
    impl AtTraceable for MyErr {
        fn trace_mut(&mut self) -> &mut AtTrace {
            &mut self.trace
        }
        fn trace(&self) -> Option<&AtTrace> {
            Some(&self.trace)
        }
        fn fmt_message(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "my error")
        }
    }

    let err = MyErr {
        trace: AtTrace::capture(),
    }
    .at_str("context msg")
    .at_fn(|| {})
    .at_debug(|| 42u32)
    .at_data(|| "disp data")
    .at_aside_error(core::fmt::Error);

    let output = alloc::format!("{}", err.full_trace());
    assert!(output.contains("my error"));
    assert!(output.contains("context msg"));
    assert!(output.contains("in "));
}

#[test]
fn test_traceable_last_error_trace_format() {
    use crate::trace::{AtTrace, AtTraceable};

    struct MyErr {
        trace: AtTrace,
    }
    impl AtTraceable for MyErr {
        fn trace_mut(&mut self) -> &mut AtTrace {
            &mut self.trace
        }
        fn trace(&self) -> Option<&AtTrace> {
            Some(&self.trace)
        }
        fn fmt_message(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "my error")
        }
    }

    let err = MyErr {
        trace: AtTrace::capture(),
    }
    .at_str("should not appear")
    .at_skipped_frames();

    let output = alloc::format!("{}", err.last_error_trace());
    assert!(output.contains("my error"));
    assert!(output.contains("[...]"));
    assert!(!output.contains("should not appear"));
}

#[test]
fn test_traceable_last_error_format() {
    use crate::trace::{AtTrace, AtTraceable};

    struct MyErr {
        trace: AtTrace,
    }
    impl AtTraceable for MyErr {
        fn trace_mut(&mut self) -> &mut AtTrace {
            &mut self.trace
        }
        fn trace(&self) -> Option<&AtTrace> {
            Some(&self.trace)
        }
        fn fmt_message(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "just the message")
        }
    }

    let err = MyErr {
        trace: AtTrace::capture(),
    };
    let output = alloc::format!("{}", err.last_error());
    assert_eq!(output, "just the message");
}

#[test]
fn test_result_at_ext_ok_paths() {
    type R = Result<i32, At<TestError>>;
    assert_eq!(R::Ok(42).at().unwrap(), 42);
    assert_eq!(R::Ok(42).at_str("msg").unwrap(), 42);
    assert_eq!(
        R::Ok(42)
            .at_string(|| alloc::string::String::from("dyn"))
            .unwrap(),
        42
    );
    assert_eq!(R::Ok(42).at_data(|| 1u32).unwrap(), 42);
    assert_eq!(R::Ok(42).at_debug(|| 1u32).unwrap(), 42);
    assert_eq!(R::Ok(42).at_aside_error(core::fmt::Error).unwrap(), 42);
    assert_eq!(R::Ok(42).at_crate(crate::at_crate_info()).unwrap(), 42);
    assert_eq!(R::Ok(42).at_fn(|| {}).unwrap(), 42);
    assert_eq!(R::Ok(42).at_named("step").unwrap(), 42);
    assert_eq!(R::Ok(42).map_err_at(|_| ()).unwrap(), 42);
}

#[test]
fn test_result_at_ext_err_paths() {
    fn make_err() -> Result<(), At<TestError>> {
        Err(at(TestError::NotFound))
    }

    // Test error paths for methods not already covered
    let _ = make_err().at_data(|| 42u32).unwrap_err();
    let _ = make_err().at_debug(|| 42u32).unwrap_err();
    let _ = make_err().at_aside_error(core::fmt::Error).unwrap_err();
    let _ = make_err().at_crate(crate::at_crate_info()).unwrap_err();
    let _ = make_err().at_fn(|| {}).unwrap_err();
    let _ = make_err().at_named("step").unwrap_err();
}

#[test]
fn test_result_at_traceable_ext_all() {
    use crate::ResultAtTraceableExt;
    use crate::trace::{AtTrace, AtTraceable};

    #[derive(Debug)]
    struct MyErr {
        trace: AtTrace,
    }
    impl AtTraceable for MyErr {
        fn trace_mut(&mut self) -> &mut AtTrace {
            &mut self.trace
        }
        fn trace(&self) -> Option<&AtTrace> {
            Some(&self.trace)
        }
        fn fmt_message(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "err")
        }
    }

    #[allow(clippy::result_large_err)]
    fn make_err() -> Result<i32, MyErr> {
        Err(MyErr {
            trace: AtTrace::capture(),
        })
    }

    #[allow(clippy::result_large_err)]
    fn make_ok() -> Result<i32, MyErr> {
        Ok(42)
    }

    // Ok paths
    assert_eq!(make_ok().at().unwrap(), 42);
    assert_eq!(make_ok().at_str("msg").unwrap(), 42);
    assert_eq!(
        make_ok()
            .at_string(|| alloc::string::String::from("x"))
            .unwrap(),
        42
    );
    assert_eq!(make_ok().at_data(|| 1u32).unwrap(), 42);
    assert_eq!(make_ok().at_debug(|| 1u32).unwrap(), 42);
    assert_eq!(make_ok().at_aside_error(core::fmt::Error).unwrap(), 42);
    assert_eq!(make_ok().at_crate(crate::at_crate_info()).unwrap(), 42);
    assert_eq!(make_ok().at_fn(|| {}).unwrap(), 42);
    assert_eq!(make_ok().at_named("step").unwrap(), 42);

    // Err paths
    let _ = make_err().at().unwrap_err();
    let _ = make_err().at_str("msg").unwrap_err();
    let _ = make_err()
        .at_string(|| alloc::string::String::from("x"))
        .unwrap_err();
    let _ = make_err().at_data(|| 1u32).unwrap_err();
    let _ = make_err().at_debug(|| 1u32).unwrap_err();
    let _ = make_err().at_aside_error(core::fmt::Error).unwrap_err();
    let _ = make_err().at_crate(crate::at_crate_info()).unwrap_err();
    let _ = make_err().at_fn(|| {}).unwrap_err();
    let _ = make_err().at_named("step").unwrap_err();
}

#[test]
fn test_crate_info_get_meta_const() {
    use crate::AtCrateInfo;

    static INFO: AtCrateInfo = AtCrateInfo::builder()
        .name("test")
        .meta(&[("team", "platform"), ("env", "prod")])
        .build();

    assert_eq!(INFO.get_meta("team"), Some("platform"));
    assert_eq!(INFO.get_meta("env"), Some("prod"));
    assert_eq!(INFO.get_meta("missing"), None);
    assert_eq!(INFO.get_meta("tea"), None); // Different length
}

#[test]
fn test_traceable_full_trace_with_crate_boundary() {
    use crate::AtCrateInfo;
    use crate::trace::{AtTrace, AtTraceable};

    struct MyErr {
        trace: AtTrace,
    }
    impl AtTraceable for MyErr {
        fn trace_mut(&mut self) -> &mut AtTrace {
            &mut self.trace
        }
        fn trace(&self) -> Option<&AtTrace> {
            Some(&self.trace)
        }
        fn fmt_message(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "err")
        }
    }

    static C1: AtCrateInfo = AtCrateInfo::builder().name("crate-a").build();
    static C2: AtCrateInfo = AtCrateInfo::builder().name("crate-b").build();

    let mut trace = AtTrace::capture();
    trace.set_crate_info(&C1);
    let err = MyErr { trace }.at_crate(&C2).at();

    let output = alloc::format!("{}", err.full_trace());
    assert!(output.contains("crate-a"));
    assert!(output.contains("crate-b"));
}

#[test]
fn test_traceable_full_trace_no_trace() {
    use crate::trace::{AtTrace, AtTraceable};

    struct MyErr;
    impl AtTraceable for MyErr {
        fn trace_mut(&mut self) -> &mut AtTrace {
            panic!("should not be called");
        }
        fn trace(&self) -> Option<&AtTrace> {
            None
        }
        fn fmt_message(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "err")
        }
    }

    let err = MyErr;
    let output = alloc::format!("{}", err.full_trace());
    assert_eq!(output, "err");

    let output2 = alloc::format!("{}", err.last_error_trace());
    assert_eq!(output2, "err");
}

// ============================================================================
// Additional coverage tests — format.rs, at.rs, context.rs, trace.rs, ext.rs
// ============================================================================

#[test]
fn test_at_locations_iterator() {
    let err = at(TestError::NotFound).at_str("msg").at();
    let locs: alloc::vec::Vec<_> = err.locations().collect();
    assert!(locs.len() >= 2);
    for loc in &locs {
        assert!(loc.file().contains("tests.rs"));
    }
}

#[test]
fn test_at_debug_with_skipped_frames() {
    // At<E> Debug impl with a skipped frame marker (None location)
    let mut err = at(TestError::NotFound).at_str("ctx");
    err = err.at_skipped_frames();
    let output = alloc::format!("{:?}", err);
    assert!(output.contains("[...]"));
    assert!(output.contains("NotFound"));
    assert!(output.contains("ctx"));
}

#[test]
fn test_full_trace_display_with_nested_error_chain() {
    // Exercise lines 1101-1110 in at.rs (nested error source chain)
    use core::error::Error;

    #[derive(Debug)]
    struct Inner;
    impl fmt::Display for Inner {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "inner error")
        }
    }
    impl Error for Inner {}

    #[derive(Debug)]
    struct Outer(Inner);
    impl fmt::Display for Outer {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "outer error")
        }
    }
    impl Error for Outer {
        fn source(&self) -> Option<&(dyn Error + 'static)> {
            Some(&self.0)
        }
    }

    let err = at(TestError::NotFound).at_aside_error(Outer(Inner));
    let output = alloc::format!("{}", err.full_trace());
    assert!(output.contains("caused by: outer error"));
    assert!(output.contains("caused by: inner error"));
}

#[test]
fn test_full_trace_display_with_debug_and_display_ctx() {
    // Exercise lines 1112-1113 (the else branch: non-text, non-fn, non-error contexts)
    let err = at(TestError::NotFound)
        .at_data(|| "display_val")
        .at_debug(|| 99u32);
    let output = alloc::format!("{}", err.full_trace());
    // Display contexts fall through to the else branch, which calls ctx Display
    assert!(output.contains("display_val") || output.contains("99"));
}

#[test]
fn test_display_with_meta_skipped_frames() {
    // Exercise line 910 (display_with_meta None branch)
    let err = at(TestError::NotFound).at_skipped_frames();
    let output = alloc::format!("{}", err.display_with_meta());
    assert!(output.contains("[...]"));
}

#[test]
fn test_display_with_meta_with_link_template() {
    // Exercise line 988 (write_location_meta with link_template)
    use crate::AtCrateInfo;

    static INFO: AtCrateInfo = AtCrateInfo::builder()
        .name("test-crate")
        .repo(Some("https://github.com/user/repo"))
        .commit(Some("abc123"))
        .path(Some("src"))
        .build();

    let err = At::wrap(TestError::NotFound).set_crate_info(&INFO).at();
    let output = alloc::format!("{}", err.display_with_meta());
    // Should contain a link with file/line substituted
    assert!(output.contains("github.com"), "Output: {}", output);
}

#[test]
fn test_context_downcast_ref() {
    use crate::context::AtContext;

    // Debug variant — downcast succeeds
    let ctx = AtContext::Debug(Box::new(42u32));
    assert_eq!(ctx.downcast_ref::<u32>(), Some(&42u32));
    assert_eq!(ctx.downcast_ref::<i32>(), None);

    // Display variant — downcast succeeds
    let ctx = AtContext::Display(Box::new(alloc::string::String::from("hello")));
    assert_eq!(
        ctx.downcast_ref::<alloc::string::String>(),
        Some(&alloc::string::String::from("hello"))
    );

    // Text — always None
    let ctx = AtContext::Text(alloc::borrow::Cow::Borrowed("hi"));
    assert_eq!(ctx.downcast_ref::<alloc::string::String>(), None);

    // FunctionName — always None
    let ctx = AtContext::FunctionName("fn_name");
    assert_eq!(ctx.downcast_ref::<&str>(), None);

    // Error — always None
    let ctx = AtContext::Error(Box::new(core::fmt::Error));
    assert_eq!(ctx.downcast_ref::<core::fmt::Error>(), None);
}

#[test]
fn test_context_type_name_all_variants() {
    use crate::context::AtContext;

    // Debug — has type_name
    let ctx = AtContext::Debug(Box::new(42u32));
    assert!(ctx.type_name().is_some());

    // Display — has type_name
    let ctx = AtContext::Display(Box::new(alloc::string::String::from("x")));
    assert!(ctx.type_name().is_some());

    // Text — None
    let ctx = AtContext::Text(alloc::borrow::Cow::Borrowed("hi"));
    assert!(ctx.type_name().is_none());
}

#[test]
fn test_context_display_fmt_all_variants() {
    use crate::context::AtContext;

    // Display variant in Debug fmt
    let ctx = AtContext::Display(Box::new(42u32));
    let dbg_output = alloc::format!("{:?}", ctx);
    assert!(dbg_output.contains("42"), "Output: {}", dbg_output);

    // Display variant in Display fmt
    let disp_output = alloc::format!("{}", ctx);
    assert!(disp_output.contains("42"), "Output: {}", disp_output);

    // Crate variant
    use crate::AtCrateInfo;
    static INFO: AtCrateInfo = AtCrateInfo::builder().name("my-crate").build();
    let ctx = AtContext::Crate(&INFO);
    let dbg_output = alloc::format!("{:?}", ctx);
    assert!(dbg_output.contains("my-crate"), "Output: {}", dbg_output);
    let disp_output = alloc::format!("{}", ctx);
    assert!(disp_output.contains("my-crate"), "Output: {}", disp_output);

    // Error variant
    let ctx = AtContext::Error(Box::new(core::fmt::Error));
    let dbg_output = alloc::format!("{:?}", ctx);
    assert!(dbg_output.contains("caused by:"), "Output: {}", dbg_output);
    let disp_output = alloc::format!("{}", ctx);
    assert!(
        disp_output.contains("caused by:"),
        "Output: {}",
        disp_output
    );
}

#[test]
fn test_trace_try_add_crate_boundary_same_crate() {
    // Exercise line 296/300 — same crate info ptr → no-op
    use crate::AtCrateInfo;
    use crate::trace::AtTrace;

    static INFO: AtCrateInfo = AtCrateInfo::builder().name("same").build();

    let mut trace = AtTrace::capture();
    trace.set_crate_info(&INFO);
    let frames_before = trace.frame_count();
    // Add same crate info again — should be a no-op (no new context)
    trace.try_add_crate_boundary(core::panic::Location::caller(), &INFO);
    assert_eq!(trace.frame_count(), frames_before);
}

#[test]
fn test_trace_try_add_crate_boundary_different_crate() {
    // Exercise line 303 — different crate info → adds context
    use crate::AtCrateInfo;
    use crate::trace::AtTrace;

    static C1: AtCrateInfo = AtCrateInfo::builder().name("crate-a").build();
    static C2: AtCrateInfo = AtCrateInfo::builder().name("crate-b").build();

    let mut trace = AtTrace::capture();
    trace.set_crate_info(&C1);
    trace.try_add_crate_boundary(core::panic::Location::caller(), &C2);
    // Should have a crate boundary context now
    let _output = alloc::format!("{:?}", trace);
    // The boundary context is stored — visible when formatting At
    assert!(trace.crate_info().is_some());
}

#[test]
fn test_trace_pop_first_with_contexts() {
    // Exercise lines 455-465 (pop_first draining contexts)
    use crate::trace::AtTrace;

    let mut trace = AtTrace::capture();
    trace.try_add_context(
        core::panic::Location::caller(),
        crate::context::AtContext::Text(alloc::borrow::Cow::Borrowed("ctx1")),
    );
    // Add a second frame
    trace.try_push(core::panic::Location::caller());
    trace.try_add_context(
        core::panic::Location::caller(),
        crate::context::AtContext::Text(alloc::borrow::Cow::Borrowed("ctx2")),
    );

    let first = trace.pop_first();
    assert!(first.is_some());
    let frame = first.unwrap();
    assert!(frame.context_count() > 0);
}

#[test]
fn test_trace_push_with_contexts() {
    // Exercise line 475 (push with contexts on AtFrameOwned)
    use crate::trace::AtTrace;

    let mut trace = AtTrace::capture();
    trace.try_add_context(
        core::panic::Location::caller(),
        crate::context::AtContext::Text(alloc::borrow::Cow::Borrowed("existing")),
    );

    // Pop first, then push it back
    let frame = trace.pop_first().unwrap();
    let count_before = trace.frame_count();
    trace.push(frame);
    assert_eq!(trace.frame_count(), count_before + 1);
}

#[test]
fn test_trace_push_first_with_contexts() {
    // Exercise lines 534, 541 (push_first with contexts)
    use crate::trace::AtTrace;

    let mut trace = AtTrace::capture();
    trace.try_push(core::panic::Location::caller()); // Add a second frame

    // Pop from the end, add context via builder, then push_first
    let frame = trace.pop_first().unwrap().with_str("prepended");
    trace.push_first(frame);
    assert!(trace.frame_count() >= 2);
}

#[test]
fn test_traceable_at_first_pop_and_insert() {
    // Exercise lines 1208-1209 (at_first_pop, at_first_insert)
    use crate::trace::{AtTrace, AtTraceable};

    struct MyErr {
        trace: AtTrace,
    }
    impl AtTraceable for MyErr {
        fn trace_mut(&mut self) -> &mut AtTrace {
            &mut self.trace
        }
        fn trace(&self) -> Option<&AtTrace> {
            Some(&self.trace)
        }
        fn fmt_message(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "err")
        }
    }

    let mut err = MyErr {
        trace: AtTrace::capture(),
    }
    .at_str("ctx");

    let count_before = err.trace().unwrap().frame_count();
    let frame = err.at_first_pop().unwrap();
    assert_eq!(err.trace().unwrap().frame_count(), count_before - 1);
    err.at_first_insert(frame);
    assert_eq!(err.trace().unwrap().frame_count(), count_before);
}

#[test]
fn test_traceable_full_trace_with_nested_error_chain() {
    // Exercise lines 1393-1402 in trace.rs (nested error source chain in FullTraceDisplay)
    use crate::trace::{AtTrace, AtTraceable};
    use core::error::Error;

    #[derive(Debug)]
    struct Inner;
    impl fmt::Display for Inner {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "inner")
        }
    }
    impl Error for Inner {}

    #[derive(Debug)]
    struct Outer(Inner);
    impl fmt::Display for Outer {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "outer")
        }
    }
    impl Error for Outer {
        fn source(&self) -> Option<&(dyn Error + 'static)> {
            Some(&self.0)
        }
    }

    struct MyErr {
        trace: AtTrace,
    }
    impl AtTraceable for MyErr {
        fn trace_mut(&mut self) -> &mut AtTrace {
            &mut self.trace
        }
        fn trace(&self) -> Option<&AtTrace> {
            Some(&self.trace)
        }
        fn fmt_message(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "my error")
        }
    }

    let err = MyErr {
        trace: AtTrace::capture(),
    }
    .at_aside_error(Outer(Inner));

    let output = alloc::format!("{}", err.full_trace());
    assert!(output.contains("caused by: outer"), "Output: {}", output);
    assert!(output.contains("caused by: inner"), "Output: {}", output);
}

#[test]
fn test_traceable_full_trace_with_skipped_frames_display() {
    // Exercise line 1381 (FullTraceDisplay skipped frame marker)
    use crate::trace::{AtTrace, AtTraceable};

    struct MyErr {
        trace: AtTrace,
    }
    impl AtTraceable for MyErr {
        fn trace_mut(&mut self) -> &mut AtTrace {
            &mut self.trace
        }
        fn trace(&self) -> Option<&AtTrace> {
            Some(&self.trace)
        }
        fn fmt_message(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "err")
        }
    }

    let err = MyErr {
        trace: AtTrace::capture(),
    }
    .at_skipped_frames()
    .at();

    let output = alloc::format!("{}", err.full_trace());
    assert!(output.contains("[...]"), "Output: {}", output);
}

#[test]
fn test_ext_at_string_err_path() {
    // Exercise line 201 in ext.rs
    fn make_err() -> Result<(), At<TestError>> {
        Err(at(TestError::NotFound))
    }
    let result = make_err().at_string(|| alloc::string::String::from("dynamic context"));
    let err = result.unwrap_err();
    let output = alloc::format!("{:?}", err);
    assert!(output.contains("dynamic context"), "Output: {}", output);
}

#[test]
fn test_crate_info_owned_with_some_values() {
    // Exercise lines 338, 348, 358 in crate_info.rs
    use crate::crate_info::AtCrateInfoBuilder;

    let info = AtCrateInfoBuilder::new()
        .name("test")
        .repo_owned(Some(alloc::string::String::from(
            "https://github.com/test/test",
        )))
        .commit_owned(Some(alloc::string::String::from("abc123")))
        .path_owned(Some(alloc::string::String::from("crates/test")))
        .build();

    assert_eq!(info.repo(), Some("https://github.com/test/test"));
    assert_eq!(info.commit(), Some("abc123"));
    assert_eq!(info.crate_path(), Some("crates/test"));
}

// ============================================================================
// Format.rs coverage — termcolor and HTML formatters
// ============================================================================

#[cfg(feature = "_termcolor")]
#[test]
fn test_termcolor_display_with_all_context_types() {
    use crate::AtCrateInfo;

    static C1: AtCrateInfo = AtCrateInfo::builder().name("crate-a").build();
    static C2: AtCrateInfo = AtCrateInfo::builder().name("crate-b").build();

    let err = At::wrap(TestError::NotFound)
        .set_crate_info(&C1)
        .at()
        .at_str("text context")
        .at_fn(|| {})
        .at_debug(|| 42u32)
        .at_data(|| "display data")
        .at_aside_error(core::fmt::Error)
        .at_crate(&C2)
        .at();

    let output = alloc::format!("{}", err.display_color());
    assert!(output.contains("NotFound"), "Output: {}", output);
    assert!(output.contains("text context"), "Output: {}", output);
    assert!(output.contains("42"), "Output: {}", output);
    assert!(output.contains("display data"), "Output: {}", output);
    assert!(output.contains("caused by"), "Output: {}", output);
}

#[cfg(feature = "_termcolor")]
#[test]
fn test_termcolor_display_with_skipped_frames() {
    let err = at(TestError::NotFound).at_skipped_frames();
    let output = alloc::format!("{}", err.display_color());
    assert!(output.contains("[...]"), "Output: {}", output);
}

#[cfg(feature = "_termcolor")]
#[test]
fn test_termcolor_display_no_trace() {
    let err = At::wrap(TestError::NotFound);
    let output = alloc::format!("{}", err.display_color());
    assert!(output.contains("NotFound"), "Output: {}", output);
}

#[cfg(feature = "_termcolor")]
#[test]
fn test_termcolor_meta_with_crate_boundaries() {
    use crate::AtCrateInfo;

    static C1: AtCrateInfo = AtCrateInfo::builder()
        .name("crate-a")
        .repo(Some("https://github.com/user/repo"))
        .commit(Some("abc123"))
        .build();
    static C2: AtCrateInfo = AtCrateInfo::builder()
        .name("crate-b")
        .repo(Some("https://github.com/user/repo2"))
        .commit(Some("def456"))
        .build();

    let err = At::wrap(TestError::NotFound)
        .set_crate_info(&C1)
        .at()
        .at_str("context")
        .at_fn(|| {})
        .at_debug(|| 42u32)
        .at_data(|| "disp")
        .at_aside_error(core::fmt::Error)
        .at_crate(&C2)
        .at();

    let output = alloc::format!("{}", err.display_color_meta());
    assert!(output.contains("crate-a"), "Output: {}", output);
    assert!(output.contains("crate-b"), "Output: {}", output);
    // Link URL should be present
    assert!(output.contains("github.com"), "Output: {}", output);
}

#[cfg(feature = "_termcolor")]
#[test]
fn test_termcolor_meta_with_skipped_frames() {
    let err = at(TestError::NotFound).at_skipped_frames();
    let output = alloc::format!("{}", err.display_color_meta());
    assert!(output.contains("[...]"), "Output: {}", output);
}

#[cfg(feature = "_termcolor")]
#[test]
fn test_termcolor_meta_no_trace() {
    let err = At::wrap(TestError::NotFound);
    let output = alloc::format!("{}", err.display_color_meta());
    assert!(output.contains("NotFound"), "Output: {}", output);
}

#[cfg(feature = "_html")]
#[test]
fn test_html_display_with_all_context_types() {
    use crate::AtCrateInfo;

    static C1: AtCrateInfo = AtCrateInfo::builder().name("crate-a").build();
    static C2: AtCrateInfo = AtCrateInfo::builder().name("crate-b").build();

    let err = At::wrap(TestError::NotFound)
        .set_crate_info(&C1)
        .at()
        .at_str("text context")
        .at_fn(|| {})
        .at_debug(|| 42u32)
        .at_data(|| "display data")
        .at_aside_error(core::fmt::Error)
        .at_crate(&C2)
        .at();

    let output = alloc::format!("{}", err.display_html());
    assert!(output.contains("context-text"), "Output: {}", output);
    assert!(output.contains("context-fn"), "Output: {}", output);
    assert!(output.contains("context-data"), "Output: {}", output);
    assert!(output.contains("context-error"), "Output: {}", output);
    assert!(output.contains("crate-boundary"), "Output: {}", output);
    assert!(output.contains("crate-a"), "Output: {}", output);
    assert!(output.contains("crate-b"), "Output: {}", output);
}

#[cfg(feature = "_html")]
#[test]
fn test_html_display_with_skipped_frames() {
    let err = at(TestError::NotFound).at_skipped_frames();
    let output = alloc::format!("{}", err.display_html());
    assert!(output.contains("skip-marker"), "Output: {}", output);
    assert!(output.contains("[...]"), "Output: {}", output);
}

#[cfg(feature = "_html")]
#[test]
fn test_html_display_no_trace() {
    let err = At::wrap(TestError::NotFound);
    let output = alloc::format!("{}", err.display_html());
    assert!(output.contains("NotFound"), "Output: {}", output);
    // Should close div immediately since no trace
    assert!(output.contains("</div>"), "Output: {}", output);
}

#[cfg(feature = "_html")]
#[test]
fn test_html_display_with_link_template() {
    use crate::AtCrateInfo;

    static INFO: AtCrateInfo = AtCrateInfo::builder()
        .name("test-crate")
        .repo(Some("https://github.com/user/repo"))
        .commit(Some("abc123"))
        .path(Some("crates/test"))
        .build();

    let err = At::wrap(TestError::NotFound).set_crate_info(&INFO).at();
    let output = alloc::format!("{}", err.display_html());
    // Should have <a href=...> with link
    assert!(output.contains("<a href="), "Output: {}", output);
    assert!(output.contains("github.com"), "Output: {}", output);
}

#[cfg(feature = "_html")]
#[test]
fn test_html_display_with_crate_boundary_and_links() {
    use crate::AtCrateInfo;

    static C1: AtCrateInfo = AtCrateInfo::builder()
        .name("crate-a")
        .repo(Some("https://github.com/user/repo"))
        .commit(Some("abc123"))
        .build();
    static C2: AtCrateInfo = AtCrateInfo::builder()
        .name("crate-b")
        .repo(Some("https://github.com/user/repo2"))
        .commit(Some("def456"))
        .build();

    let err = At::wrap(TestError::NotFound)
        .set_crate_info(&C1)
        .at()
        .at_str("msg")
        .at_crate(&C2)
        .at();

    let output = alloc::format!("{}", err.display_html());
    assert!(output.contains("crate-boundary"), "Output: {}", output);
    assert!(output.contains("crate-a"), "Output: {}", output);
    assert!(output.contains("crate-b"), "Output: {}", output);
    assert!(output.contains("crate-info"), "Output: {}", output);
}

#[test]
fn test_at_debug_with_all_context_types() {
    // Exercise all branches in At Debug impl (lines 800-810)
    use crate::AtCrateInfo;

    static INFO: AtCrateInfo = AtCrateInfo::builder().name("test").build();

    let err = at(TestError::NotFound)
        .at_str("text msg")
        .at_fn(|| {})
        .at_debug(|| 42u32)
        .at_data(|| "display val")
        .at_aside_error(core::fmt::Error)
        .at_crate(&INFO);

    let output = alloc::format!("{:?}", err);
    assert!(output.contains("text msg"), "Output: {}", output);
    assert!(output.contains("in "), "Output: {}", output);
    assert!(output.contains("42"), "Output: {}", output);
    assert!(output.contains("display val"), "Output: {}", output);
    assert!(output.contains("caused by"), "Output: {}", output);
    // Crate boundary should NOT show in basic Debug
    assert!(!output.contains("[crate:"), "Output: {}", output);
}

#[test]
fn test_display_with_meta_all_context_types() {
    // Exercise all branches in display_with_meta (lines 900-910)
    use crate::AtCrateInfo;

    static C1: AtCrateInfo = AtCrateInfo::builder()
        .name("crate-a")
        .repo(Some("https://github.com/user/repo"))
        .commit(Some("abc123"))
        .build();
    static C2: AtCrateInfo = AtCrateInfo::builder().name("crate-b").build();

    let err = At::wrap(TestError::NotFound)
        .set_crate_info(&C1)
        .at()
        .at_str("text")
        .at_fn(|| {})
        .at_debug(|| 42u32)
        .at_data(|| "disp")
        .at_aside_error(core::fmt::Error)
        .at_crate(&C2);

    let output = alloc::format!("{}", err.display_with_meta());
    assert!(output.contains("text"), "Output: {}", output);
    assert!(output.contains("42"), "Output: {}", output);
    assert!(output.contains("disp"), "Output: {}", output);
    assert!(output.contains("caused by"), "Output: {}", output);
}

#[cfg(feature = "_html")]
#[test]
fn test_html_escape_ampersand_and_quotes() {
    // Exercise lines 445, 446 in format.rs (& and " escaping)
    let err = at(TestError::NotFound).at_string(|| alloc::string::String::from("x&y \"quoted\""));
    let output = alloc::format!("{}", err.display_html());
    assert!(output.contains("&amp;"), "Output: {}", output);
    assert!(output.contains("&quot;"), "Output: {}", output);
}

#[cfg(feature = "_termcolor")]
#[test]
fn test_termcolor_display_crate_boundary_with_other_contexts() {
    // Exercise line 70 (continue on Crate context in TermColorDisplay)
    // Need a frame that has BOTH a crate boundary AND other contexts
    use crate::AtCrateInfo;

    static C1: AtCrateInfo = AtCrateInfo::builder().name("a").build();
    static C2: AtCrateInfo = AtCrateInfo::builder().name("b").build();

    // Build error with crate boundary and text context on same frame
    let err = At::wrap(TestError::NotFound)
        .set_crate_info(&C1)
        .at()
        .at_str("before boundary")
        .at_crate(&C2);

    let output = alloc::format!("{}", err.display_color());
    assert!(output.contains("before boundary"), "Output: {}", output);
}

#[cfg(feature = "_termcolor")]
#[test]
fn test_termcolor_meta_link_url_substitution() {
    // Exercise lines 155-163 and 217 (link template in TermColorMetaDisplay)
    use crate::AtCrateInfo;

    static INFO: AtCrateInfo = AtCrateInfo::builder()
        .name("test-crate")
        .repo(Some("https://github.com/user/repo"))
        .commit(Some("abc123"))
        .path(Some("crates/test"))
        .build();

    let err = At::wrap(TestError::NotFound)
        .set_crate_info(&INFO)
        .at()
        .at_str("msg");

    let output = alloc::format!("{}", err.display_color_meta());
    // Should contain a URL from the link template
    assert!(output.contains("github.com"), "Output: {}", output);
}

#[cfg(feature = "_termcolor")]
#[test]
fn test_termcolor_meta_crate_boundary_with_contexts() {
    // Exercise line 173 (continue on Crate context in TermColorMetaDisplay)
    use crate::AtCrateInfo;

    static C1: AtCrateInfo = AtCrateInfo::builder()
        .name("a")
        .repo(Some("https://github.com/user/a"))
        .commit(Some("abc"))
        .build();
    static C2: AtCrateInfo = AtCrateInfo::builder()
        .name("b")
        .repo(Some("https://github.com/user/b"))
        .commit(Some("def"))
        .build();

    let err = At::wrap(TestError::NotFound)
        .set_crate_info(&C1)
        .at()
        .at_str("context text")
        .at_crate(&C2);

    let output = alloc::format!("{}", err.display_color_meta());
    assert!(output.contains("context text"), "Output: {}", output);
}

#[cfg(feature = "_html")]
#[test]
fn test_html_display_link_and_crate_skip_in_contexts() {
    // Exercise lines 374 (link URL), 396 (continue crate), 464 (build_link_base)
    use crate::AtCrateInfo;

    static C1: AtCrateInfo = AtCrateInfo::builder()
        .name("crate-a")
        .repo(Some("https://github.com/user/repo"))
        .commit(Some("abc123"))
        .path(Some("src"))
        .build();
    static C2: AtCrateInfo = AtCrateInfo::builder()
        .name("crate-b")
        .repo(Some("https://github.com/user/repo2"))
        .commit(Some("def456"))
        .build();

    let err = At::wrap(TestError::NotFound)
        .set_crate_info(&C1)
        .at()
        .at_str("context msg")
        .at_fn(|| {})
        .at_debug(|| 42u32)
        .at_data(|| "disp")
        .at_aside_error(core::fmt::Error)
        .at_crate(&C2)
        .at();

    let output = alloc::format!("{}", err.display_html());
    // Should have link from C1
    assert!(
        output.contains("<a href="),
        "Should have link. Output: {}",
        output
    );
    // Should have context-text, context-fn etc.
    assert!(output.contains("context-text"), "Output: {}", output);
    assert!(output.contains("context-fn"), "Output: {}", output);
    // Should have crate boundary
    assert!(output.contains("crate-boundary"), "Output: {}", output);
}

#[cfg(feature = "_html")]
#[test]
fn test_html_display_skipped_frames_with_link() {
    // Exercise line 429 (None/skip-marker in HTML) with link context
    use crate::AtCrateInfo;

    static INFO: AtCrateInfo = AtCrateInfo::builder()
        .name("test")
        .repo(Some("https://github.com/user/repo"))
        .commit(Some("abc"))
        .build();

    let err = At::wrap(TestError::NotFound)
        .set_crate_info(&INFO)
        .at()
        .at_skipped_frames();

    let output = alloc::format!("{}", err.display_html());
    assert!(output.contains("skip-marker"), "Output: {}", output);
}

#[test]
fn test_at_trace_boxed_new_const() {
    // Exercise lines 777-778 (AtTraceBoxed::new)
    use crate::trace::AtTraceBoxed;

    let boxed = AtTraceBoxed::new();
    assert!(boxed.as_ref().is_none());
    let dbg = alloc::format!("{:?}", boxed);
    assert!(dbg.contains("None") || dbg.contains("AtTraceBoxed"));
}

#[test]
fn test_context_vec_new_path() {
    // Exercise lines 154-155 (context_vec_new — only called via try_add_context when no contexts exist)
    use crate::trace::AtTrace;

    // Create a fresh trace with no contexts, then add one
    let mut trace = AtTrace::new();
    trace.try_push(core::panic::Location::caller());
    trace.try_add_context(
        core::panic::Location::caller(),
        crate::context::AtContext::Text(alloc::borrow::Cow::Borrowed("first")),
    );
    assert_eq!(trace.contexts().count(), 1);
}

#[test]
fn test_context_vec_limit() {
    // Exercise line 167 (try_push_context limit check)
    use crate::trace::AtTrace;

    let mut trace = AtTrace::new();
    trace.try_push(core::panic::Location::caller());
    // Push many contexts to hit the limit
    for i in 0..200 {
        trace.try_add_context(
            core::panic::Location::caller(),
            crate::context::AtContext::Text(alloc::borrow::Cow::Owned(alloc::format!("ctx{}", i))),
        );
    }
    // Should have been capped at AT_MAX_CONTEXTS
    assert!(trace.contexts().count() <= 128);
}

#[test]
fn test_trace_pop_last_with_contexts_break() {
    // Exercise line 459 (break in pop() when contexts span multiple frames)
    use crate::trace::AtTrace;

    let mut trace = AtTrace::capture();
    trace.try_add_context(
        core::panic::Location::caller(),
        crate::context::AtContext::Text(alloc::borrow::Cow::Borrowed("first-ctx")),
    );
    // Add second frame with a different context
    trace.try_push(core::panic::Location::caller());
    trace.try_add_context(
        core::panic::Location::caller(),
        crate::context::AtContext::Text(alloc::borrow::Cow::Borrowed("second-ctx")),
    );

    // Pop the last frame — the while loop should break when it encounters
    // contexts belonging to the first frame
    let popped = trace.pop();
    assert!(popped.is_some());
    let frame = popped.unwrap();
    assert!(frame.context_count() > 0);
    // First frame's context should still be in the trace
    assert!(trace.contexts().count() > 0);
}

#[test]
fn test_at_locations_covers_iterator() {
    // Exercise line 563 (At::locations())
    // Using a longer chain to ensure the iterator body gets instrumented
    let err = at(TestError::NotFound).at_str("a").at_str("b").at_str("c");
    let locs: alloc::vec::Vec<_> = err.locations().collect();
    assert!(!locs.is_empty());
    // Verify locations are from this file
    assert!(locs.iter().all(|l| l.file().contains("tests.rs")));
}

#[test]
fn test_at_frames_iterator() {
    // Exercise lines 400, 402 (AtTrace::frames() iterator)
    use crate::trace::AtTrace;

    let mut trace = AtTrace::capture();
    trace.try_push(core::panic::Location::caller());
    trace.try_push(core::panic::Location::caller());

    let frames: alloc::vec::Vec<_> = trace.frames().collect();
    assert_eq!(frames.len(), 3);
    for frame in &frames {
        assert!(frame.location().is_some());
    }
}

#[test]
fn test_context_debug_any_type_name() {
    // Exercise lines 31, 57 (AtDebugAny::type_name, AtDisplayAny::type_name)
    use crate::context::AtContext;

    let ctx = AtContext::Debug(Box::new(42u32));
    let tn = ctx.type_name().unwrap();
    assert!(tn.contains("u32"), "type_name: {}", tn);

    let ctx = AtContext::Display(Box::new(42u32));
    let tn = ctx.type_name().unwrap();
    assert!(tn.contains("u32"), "type_name: {}", tn);
}

#[test]
fn test_context_display_fmt_for_display_variant() {
    // Exercise line 181 (AtContext Display impl for Display variant)
    use crate::context::AtContext;

    let ctx = AtContext::Display(Box::new(alloc::string::String::from("hello")));
    let disp = alloc::format!("{}", ctx);
    assert_eq!(disp, "hello");

    // FunctionName in Display
    let ctx = AtContext::FunctionName("my_fn");
    let disp = alloc::format!("{}", ctx);
    assert!(disp.contains("my_fn"));
}

#[test]
fn test_context_downcast_ref_all_none_arms() {
    // Exercise lines 127, 128, 129 individually
    use crate::context::AtContext;

    // Text — always None
    let ctx = AtContext::Text(alloc::borrow::Cow::Borrowed("hi"));
    assert!(ctx.downcast_ref::<u32>().is_none());

    // FunctionName — always None
    let ctx = AtContext::FunctionName("fn");
    assert!(ctx.downcast_ref::<u32>().is_none());

    // Crate — always None
    use crate::AtCrateInfo;
    static INFO: AtCrateInfo = AtCrateInfo::builder().name("x").build();
    let ctx = AtContext::Crate(&INFO);
    assert!(ctx.downcast_ref::<u32>().is_none());

    // Error — always None
    let ctx = AtContext::Error(Box::new(core::fmt::Error));
    assert!(ctx.downcast_ref::<u32>().is_none());
}