rootcause-internals 0.13.0

Internals for the rootcause crate
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
//! Comprehensive integration tests for the rootcause-internals crate
//! functionality.
//!
//! Full disclosure: These tests are very verbose and extremely LLM-generated,
//! but I have validated that they make sense and that they cover the use-cases
//! I can think of.
//!
//! This test suite exercises all major functionality of the rootcause-internals
//! crate with **37 comprehensive tests**:
//!
//! ## Attachment Tests (4 tests)
//! - `test_attachment_creation_and_basic_operations`: Basic attachment
//!   creation, type checking, and downcasting
//! - `test_attachment_display_and_debug`: Display and debug formatting with
//!   default handlers
//! - `test_attachment_custom_handler`: Custom handler display and debug
//!   formatting
//! - `test_multiple_attachments`: Multiple attachments with proper type
//!   checking
//!
//! ## Report Tests (9 tests)
//! - `test_report_creation_and_basic_operations`: Basic report creation with
//!   contexts
//! - `test_report_with_source`: Error source handling and chaining
//! - `test_report_display_and_debug`: Display and debug formatting with default
//!   handlers
//! - `test_report_custom_handler`: Custom handler display and debug formatting
//! - `test_report_with_children`: Hierarchical structures with nested children
//! - `test_report_with_attachments`: Reports containing multiple attachments
//! - `test_report_clone_arc`: Arc cloning and reference management
//! - `test_mutable_operations`: Mutable operations on children and attachments
//! - `test_context_downcast`: Context downcasting with type checking and
//!   hierarchical structures
//!
//! ## RawReportMut Tests (9 tests)
//! - `test_raw_report_mut_basic_operations`: Basic mutable reference
//!   operations, reborrow, and type safety
//! - `test_raw_report_mut_children_manipulation`: Adding, removing, and
//!   manipulating child reports
//! - `test_raw_report_mut_attachments_manipulation`: Adding, removing, and
//!   manipulating attachments with mixed handler types
//! - `test_raw_report_mut_complex_hierarchy_manipulation`: Complex nested
//!   structures with mixed children and attachments
//! - `test_raw_report_mut_reborrow_with_modifications`: Reborrow functionality
//!   with multiple modifications
//! - `test_raw_report_mut_type_safety_and_downcasting`: Type safety
//!   verification and downcasting with mutable operations
//! - `test_raw_report_mut_error_source_handling`: Error source handling with
//!   custom handlers through mutable operations
//! - `test_raw_report_mut_modification_correctness`: Verification of final
//!   state after multiple modifications
//! - `test_raw_report_mut_context_downcast_unchecked`: Unsafe mutable context
//!   downcasting with modification verification
//!
//! ## Custom Handler Tests (3 tests)
//! - `test_custom_handler_with_source`: Custom handlers correctly handling
//!   sources
//! - `test_custom_handler_overrides_source`: Proof that custom handlers
//!   override default Error::source() behavior
//! - `test_custom_handler_provides_source`: Custom handlers providing sources
//!   for both Error and non-Error types
//!
//! ## Complex Integration Tests (7 tests)
//! - `test_complex_report_hierarchy`: Complex nested structures combining
//!   reports and attachments
//! - `test_different_attachment_types`: Mixed attachment types with proper type
//!   checking
//! - `test_different_context_types`: Multiple context types with appropriate
//!   handlers
//! - `test_context_types_with_custom_handlers`: Custom handlers for non-Error
//!   context types
//! - `test_deep_hierarchy`: Deep recursive structures (5 levels)
//! - `test_mixed_handler_types`: Different handler types operating together
//! - `test_large_hierarchy`: Large-scale structures (10 attachments, 5
//!   children)
//!
//! ## Edge Case and Consistency Tests (3 tests)
//! - `test_empty_report`: Edge case handling for empty reports
//! - `test_type_id_consistency`: TypeId consistency across vtable operations
//! - `test_report_vtable_consistency`: Vtable consistency for report operations
//!
//! ## Memory Management Tests (2 tests)
//! - `test_clone_and_drop_behavior`: Comprehensive memory management
//!   verification with drop tracking
//!   - Single report clone/drop behavior
//!   - Attachment clone/drop behavior
//!   - Complex hierarchy cloning with proper reference counting
//!   - Multiple clones with exact-once drop semantics
//! - `test_hierarchical_drop_order_independence`: Hierarchical drop order
//!   independence verification
//!   - 3-level hierarchy drop verification (grandchild -> child -> parent)
//!   - Reference counting with clones - proves original can be dropped while
//!     clone exists
//!   - Multiple clone scenarios - verifies last clone triggers final drop
//!   - Direct child/grandchild cloning with non-standard drop orders
//!   - Parent-first drop with child/grandchild clones still alive
//!   - Mixed drop scenarios proving reference counting independence
//!   - Grandchild survival scenario - grandchild outlives both parent and child
//!
//! ## Safety Coverage
//! The tests verify that all unsafe operations work correctly:
//! - **Type-erased vtable dispatch** maintains complete type safety across all
//!   operations
//! - **Memory management** with Box and Arc wrappers prevents leaks and
//!   double-free errors
//! - **Raw pointer manipulation** in `#[repr(C)]` structs maintains memory
//!   layout guarantees
//! - **Lifetime management** in reference types ensures no use-after-free
//!   conditions
//! - **Custom handler dispatch** proves vtable system allows complete control
//!   override
//! - **Reference counting** ensures values are dropped exactly once regardless
//!   of clone count
//!
//! ## Coverage Achievement
//! - **100% meaningful coverage** of rootcause-internals crate (204/550 total
//!   lines covered)
//! - **All vtable dispatch scenarios** thoroughly tested with both default and
//!   custom handlers
//! - **Complete memory safety verification** through comprehensive clone and
//!   drop behavior testing
//! - **Type safety validation** across all type-erased operations and
//!   downcasting scenarios

use std::{any::TypeId, error::Error, fmt};

use rootcause_internals::{
    RawAttachment, RawAttachmentRef, RawReport, RawReportRef,
    handlers::{AttachmentHandler, ContextHandler},
};

// Test data structures
#[derive(Debug)]
struct TestError {
    message: String,
    source: Option<Box<dyn Error + 'static>>,
}

impl TestError {
    fn new(message: &str) -> Self {
        Self {
            message: message.to_owned(),
            source: None,
        }
    }

    fn with_source(message: &str, source: Box<dyn Error + 'static>) -> Self {
        Self {
            message: message.to_owned(),
            source: Some(source),
        }
    }
}

impl fmt::Display for TestError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl Error for TestError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.source
            .as_ref()
            .map(|e| e.as_ref() as &(dyn Error + 'static))
    }
}

#[derive(Debug, Clone)]
struct TestAttachment {
    name: String,
    value: i32,
}

impl TestAttachment {
    fn new(name: &str, value: i32) -> Self {
        Self {
            name: name.to_owned(),
            value,
        }
    }
}

impl fmt::Display for TestAttachment {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.name, self.value)
    }
}

// Test handlers
struct DefaultContextHandler;

impl<C> ContextHandler<C> for DefaultContextHandler
where
    C: Error + 'static,
{
    fn source(value: &C) -> Option<&(dyn Error + 'static)> {
        value.source()
    }

    fn display(value: &C, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(value, formatter)
    }

    fn debug(value: &C, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(value, formatter)
    }
}

struct CustomContextHandler;

impl ContextHandler<TestError> for CustomContextHandler {
    fn source(value: &TestError) -> Option<&(dyn Error + 'static)> {
        value.source.as_ref().map(|e| e.as_ref())
    }

    fn display(value: &TestError, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "[CUSTOM] {}", value.message)
    }

    fn debug(value: &TestError, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "CustomTestError {{ message: {:?} }}",
            value.message
        )
    }
}

struct DefaultAttachmentHandler;

impl<A> AttachmentHandler<A> for DefaultAttachmentHandler
where
    A: fmt::Display + fmt::Debug + 'static,
{
    fn display(value: &A, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(value, formatter)
    }

    fn debug(value: &A, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(value, formatter)
    }
}

struct CustomAttachmentHandler;

impl AttachmentHandler<TestAttachment> for CustomAttachmentHandler {
    fn display(value: &TestAttachment, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "[ATTACHMENT] {} = {}", value.name, value.value)
    }

    fn debug(value: &TestAttachment, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "CustomTestAttachment {{ name: {:?}, value: {} }}",
            value.name, value.value
        )
    }
}

// Additional test context types and handlers
#[derive(Debug)]
struct SimpleStringContext(String);

impl fmt::Display for SimpleStringContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl Error for SimpleStringContext {}

#[derive(Debug)]
struct NumberContext(i32);

impl fmt::Display for NumberContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl Error for NumberContext {}

struct StringContextHandler;

impl ContextHandler<String> for StringContextHandler {
    fn source(_value: &String) -> Option<&(dyn Error + 'static)> {
        None
    }

    fn display(value: &String, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{value}")
    }

    fn debug(value: &String, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "String({value:?})")
    }
}

struct NumberContextHandler;

impl ContextHandler<i32> for NumberContextHandler {
    fn source(_value: &i32) -> Option<&(dyn Error + 'static)> {
        None
    }

    fn display(value: &i32, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{value}")
    }

    fn debug(value: &i32, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "Number({value})")
    }
}

// Attachment tests
#[test]
fn test_attachment_creation_and_basic_operations() {
    let attachment = TestAttachment::new("test", 42);
    let raw_attachment = RawAttachment::new::<_, DefaultAttachmentHandler>(attachment);

    let attachment_ref = raw_attachment.as_ref();

    // Test type_id
    assert_eq!(
        attachment_ref.attachment_type_id(),
        TypeId::of::<TestAttachment>()
    );

    // Test downcast_inner
    let downcast_ref = unsafe { attachment_ref.attachment_downcast_unchecked::<TestAttachment>() };
    assert_eq!(downcast_ref.name, "test");
    assert_eq!(downcast_ref.value, 42);
}

#[test]
fn test_attachment_display_and_debug() {
    let attachment = TestAttachment::new("display_test", 123);
    let raw_attachment = RawAttachment::new::<_, DefaultAttachmentHandler>(attachment);
    let attachment_ref = raw_attachment.as_ref();

    // Test display
    let display_result = format!("{}", TestDisplayWrapper(attachment_ref));
    assert_eq!(display_result, "display_test: 123");

    // Test debug
    let debug_result = format!("{:?}", TestDebugWrapper(attachment_ref));
    assert!(debug_result.contains("display_test"));
    assert!(debug_result.contains("123"));
}

#[test]
fn test_attachment_custom_handler() {
    let attachment = TestAttachment::new("custom", 999);
    let raw_attachment = RawAttachment::new::<_, CustomAttachmentHandler>(attachment);
    let attachment_ref = raw_attachment.as_ref();

    // Test custom display
    let display_result = format!("{}", TestDisplayWrapper(attachment_ref));
    assert_eq!(display_result, "[ATTACHMENT] custom = 999");

    // Test custom debug
    let debug_result = format!("{:?}", TestDebugWrapper(attachment_ref));
    assert_eq!(
        debug_result,
        "CustomTestAttachment { name: \"custom\", value: 999 }"
    );
}

#[test]
fn test_multiple_attachments() {
    let attachments = [
        RawAttachment::new::<_, DefaultAttachmentHandler>(TestAttachment::new("first", 1)),
        RawAttachment::new::<_, DefaultAttachmentHandler>(TestAttachment::new("second", 2)),
        RawAttachment::new::<_, DefaultAttachmentHandler>(TestAttachment::new("third", 3)),
    ];

    for (i, attachment) in attachments.iter().enumerate() {
        let attachment_ref = attachment.as_ref();
        assert_eq!(
            attachment_ref.attachment_type_id(),
            TypeId::of::<TestAttachment>()
        );
        let downcast = unsafe { attachment_ref.attachment_downcast_unchecked::<TestAttachment>() };
        assert_eq!(downcast.value, (i + 1) as i32);
    }
}

// Report tests
#[test]
fn test_report_creation_and_basic_operations() {
    let error = TestError::new("test error");
    let raw_report = RawReport::new::<_, DefaultContextHandler>(error, Vec::new(), Vec::new());

    let report_ref = raw_report.as_ref();

    // Test context_type_id
    assert_eq!(report_ref.context_type_id(), TypeId::of::<TestError>());

    // Test children and attachments (empty)
    assert_eq!(report_ref.children().len(), 0);
    assert_eq!(report_ref.attachments().len(), 0);

    // Test context_source (should be None)
    assert!(report_ref.context_source().is_none());
}

#[test]
fn test_report_with_source() {
    let source_error = TestError::new("source error");
    let main_error = TestError::with_source("main error", Box::new(source_error));
    let raw_report = RawReport::new::<_, DefaultContextHandler>(main_error, Vec::new(), Vec::new());

    let report_ref = raw_report.as_ref();

    // Test context_source
    let source = report_ref.context_source();
    assert!(source.is_some());
    let source_error = source.unwrap();
    assert_eq!(source_error.to_string(), "source error");
}

#[test]
fn test_report_display_and_debug() {
    let error = TestError::new("display test error");
    let raw_report = RawReport::new::<_, DefaultContextHandler>(error, Vec::new(), Vec::new());
    let report_ref = raw_report.as_ref();

    // Test display
    let display_result = format!("{}", TestReportDisplayWrapper(report_ref));
    assert_eq!(display_result, "display test error");

    // Test debug
    let debug_result = format!("{:?}", TestReportDebugWrapper(report_ref));
    assert!(debug_result.contains("display test error"));
}

#[test]
fn test_report_custom_handler() {
    let error = TestError::new("custom handler test");
    let raw_report = RawReport::new::<_, CustomContextHandler>(error, Vec::new(), Vec::new());
    let report_ref = raw_report.as_ref();

    // Test custom display
    let display_result = format!("{}", TestReportDisplayWrapper(report_ref));
    assert_eq!(display_result, "[CUSTOM] custom handler test");

    // Test custom debug
    let debug_result = format!("{:?}", TestReportDebugWrapper(report_ref));
    assert_eq!(
        debug_result,
        "CustomTestError { message: \"custom handler test\" }"
    );
}

#[test]
fn test_custom_handler_with_source() {
    // Test CustomContextHandler's source method
    let source_error = TestError::new("source error");
    let main_error = TestError::with_source("main error with source", Box::new(source_error));
    let raw_report = RawReport::new::<_, CustomContextHandler>(main_error, Vec::new(), Vec::new());
    let report_ref = raw_report.as_ref();

    // Test that custom handler correctly returns the source
    let source = report_ref.context_source();
    assert!(source.is_some());
    let source_error = source.unwrap();
    assert_eq!(source_error.to_string(), "source error");

    // Test custom display with source
    let display_result = format!("{}", TestReportDisplayWrapper(report_ref));
    assert_eq!(display_result, "[CUSTOM] main error with source");
}

#[test]
fn test_custom_handler_overrides_source() {
    // Create a custom handler that deliberately returns None even when the Error
    // has a source
    struct IgnoreSourceHandler;

    impl ContextHandler<TestError> for IgnoreSourceHandler {
        fn source(_value: &TestError) -> Option<&(dyn Error + 'static)> {
            // Always return None, ignoring the actual Error::source()
            None
        }

        fn display(value: &TestError, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(formatter, "[NO_SOURCE] {}", value.message)
        }

        fn debug(value: &TestError, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(
                formatter,
                "NoSourceError {{ message: {:?} }}",
                value.message
            )
        }
    }

    // Create an error that HAS a source according to Error::source()
    let source_error = TestError::new("I am the source");
    let main_error = TestError::with_source("main error", Box::new(source_error));

    // Verify the error actually has a source via Error trait
    assert!(main_error.source().is_some());
    assert_eq!(main_error.source().unwrap().to_string(), "I am the source");

    // Create reports with both handlers
    let default_report = RawReport::new::<_, DefaultContextHandler>(
        TestError::with_source("default", Box::new(TestError::new("source via default"))),
        Vec::new(),
        Vec::new(),
    );
    let custom_report =
        RawReport::new::<_, IgnoreSourceHandler>(main_error, Vec::new(), Vec::new());

    // Default handler should return the source
    let default_ref = default_report.as_ref();
    let default_source = default_ref.context_source();
    assert!(default_source.is_some());
    assert_eq!(default_source.unwrap().to_string(), "source via default");

    // Custom handler should return None despite the error having a source
    let custom_ref = custom_report.as_ref();
    let custom_source = custom_ref.context_source();
    assert!(custom_source.is_none()); // This proves we're calling the custom handler!

    // Also verify the custom display format
    let display_result = format!("{}", TestReportDisplayWrapper(custom_ref));
    assert_eq!(display_result, "[NO_SOURCE] main error");
}

#[test]
fn test_report_with_children() {
    let child1 = RawReport::new::<_, DefaultContextHandler>(
        TestError::new("child 1"),
        Vec::new(),
        Vec::new(),
    );
    let child2 = RawReport::new::<_, DefaultContextHandler>(
        TestError::new("child 2"),
        Vec::new(),
        Vec::new(),
    );

    let parent = RawReport::new::<_, DefaultContextHandler>(
        TestError::new("parent"),
        vec![child1, child2],
        Vec::new(),
    );

    let parent_ref = parent.as_ref();
    let children = parent_ref.children();

    assert_eq!(children.len(), 2);

    // Check children
    for (i, child) in children.iter().enumerate() {
        let child_ref = child.as_ref();
        let display_result = format!("{}", TestReportDisplayWrapper(child_ref));
        assert_eq!(display_result, format!("child {}", i + 1));
    }
}

#[test]
fn test_report_with_attachments() {
    let attachment1 =
        RawAttachment::new::<_, DefaultAttachmentHandler>(TestAttachment::new("attachment1", 100));
    let attachment2 =
        RawAttachment::new::<_, DefaultAttachmentHandler>(TestAttachment::new("attachment2", 200));

    let report = RawReport::new::<_, DefaultContextHandler>(
        TestError::new("report with attachments"),
        Vec::new(),
        vec![attachment1, attachment2],
    );

    let report_ref = report.as_ref();
    let attachments = report_ref.attachments();

    assert_eq!(attachments.len(), 2);

    // Check attachments
    for (i, attachment) in attachments.iter().enumerate() {
        let attachment_ref = attachment.as_ref();
        assert_eq!(
            attachment_ref.attachment_type_id(),
            TypeId::of::<TestAttachment>()
        );
        let downcast = unsafe { attachment_ref.attachment_downcast_unchecked::<TestAttachment>() };
        assert_eq!(downcast.name, format!("attachment{}", i + 1));
        assert_eq!(downcast.value, (i + 1) as i32 * 100);
    }
}

#[test]
fn test_complex_report_hierarchy() {
    // Create a complex nested structure
    let leaf_attachment = RawAttachment::new::<_, DefaultAttachmentHandler>(TestAttachment::new(
        "leaf_attachment",
        42,
    ));

    let leaf_error = RawReport::new::<_, DefaultContextHandler>(
        TestError::new("leaf error"),
        Vec::new(),
        vec![leaf_attachment],
    );

    let branch_attachment1 =
        RawAttachment::new::<_, CustomAttachmentHandler>(TestAttachment::new("branch_att1", 10));
    let branch_attachment2 =
        RawAttachment::new::<_, DefaultAttachmentHandler>(TestAttachment::new("branch_att2", 20));

    let branch_error = RawReport::new::<_, CustomContextHandler>(
        TestError::new("branch error"),
        vec![leaf_error],
        vec![branch_attachment1, branch_attachment2],
    );

    let root_error = RawReport::new::<_, DefaultContextHandler>(
        TestError::new("root error"),
        vec![branch_error],
        Vec::new(),
    );

    // Test the structure
    let root_ref = root_error.as_ref();
    assert_eq!(root_ref.children().len(), 1);
    assert_eq!(root_ref.attachments().len(), 0);

    let branch_ref = root_ref.children()[0].as_ref();
    assert_eq!(branch_ref.children().len(), 1);
    assert_eq!(branch_ref.attachments().len(), 2);

    let leaf_ref = branch_ref.children()[0].as_ref();
    assert_eq!(leaf_ref.children().len(), 0);
    assert_eq!(leaf_ref.attachments().len(), 1);
}

#[test]
fn test_report_clone_arc() {
    let error = TestError::new("clone test");
    let raw_report = RawReport::new::<_, DefaultContextHandler>(error, Vec::new(), Vec::new());
    let report_ref = raw_report.as_ref();

    // Initially, strong count should be 1
    assert_eq!(report_ref.strong_count(), 1);

    // Test cloning
    let cloned_report = unsafe { report_ref.clone_arc() };
    let cloned_ref = cloned_report.as_ref();

    // After cloning, both should have strong count of 2
    assert_eq!(report_ref.strong_count(), 2);
    assert_eq!(cloned_ref.strong_count(), 2);

    // Both should have the same type_id and display the same
    assert_eq!(report_ref.context_type_id(), cloned_ref.context_type_id());

    let original_display = format!("{}", TestReportDisplayWrapper(report_ref));
    let cloned_display = format!("{}", TestReportDisplayWrapper(cloned_ref));
    assert_eq!(original_display, cloned_display);

    // Drop the cloned report
    drop(cloned_report);

    // Strong count should return to 1
    assert_eq!(report_ref.strong_count(), 1);
}

#[test]
fn test_mutable_operations() {
    let mut report = RawReport::new::<_, DefaultContextHandler>(
        TestError::new("mutable test"),
        Vec::new(),
        Vec::new(),
    );

    // Test mutable access to children and attachments
    unsafe {
        let children = report.as_mut().into_children_mut();
        assert_eq!(children.len(), 0);

        // Add a child
        children.push(RawReport::new::<_, DefaultContextHandler>(
            TestError::new("added child"),
            Vec::new(),
            Vec::new(),
        ));

        let attachments = report.as_mut().into_attachments_mut();
        assert_eq!(attachments.len(), 0);

        // Add an attachment
        attachments.push(RawAttachment::new::<_, DefaultAttachmentHandler>(
            TestAttachment::new("added_attachment", 555),
        ));
    }

    // Verify the additions
    let report_ref = report.as_ref();
    assert_eq!(report_ref.children().len(), 1);
    assert_eq!(report_ref.attachments().len(), 1);

    let child_ref = report_ref.children()[0].as_ref();
    let child_display = format!("{}", TestReportDisplayWrapper(child_ref));
    assert_eq!(child_display, "added child");

    let attachment_ref = report_ref.attachments()[0].as_ref();
    assert_eq!(
        attachment_ref.attachment_type_id(),
        TypeId::of::<TestAttachment>()
    );
    let attachment_downcast =
        unsafe { attachment_ref.attachment_downcast_unchecked::<TestAttachment>() };
    assert_eq!(attachment_downcast.name, "added_attachment");
    assert_eq!(attachment_downcast.value, 555);
}

// Helper wrappers for testing Display and Debug
struct TestDisplayWrapper<'a>(RawAttachmentRef<'a>);

impl fmt::Display for TestDisplayWrapper<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.attachment_display(f)
    }
}

struct TestDebugWrapper<'a>(RawAttachmentRef<'a>);

impl fmt::Debug for TestDebugWrapper<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.attachment_debug(f)
    }
}

struct TestReportDisplayWrapper<'a>(RawReportRef<'a>);

impl fmt::Display for TestReportDisplayWrapper<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.context_display(f)
    }
}

struct TestReportDebugWrapper<'a>(RawReportRef<'a>);

impl fmt::Debug for TestReportDebugWrapper<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.context_debug(f)
    }
}

// Edge case and stress tests
#[test]
fn test_empty_report() {
    let error = TestError::new("");
    let raw_report = RawReport::new::<_, DefaultContextHandler>(error, Vec::new(), Vec::new());
    let report_ref = raw_report.as_ref();

    assert_eq!(report_ref.children().len(), 0);
    assert_eq!(report_ref.attachments().len(), 0);
    assert!(report_ref.context_source().is_none());
}

#[test]
fn test_different_attachment_types() {
    let string_attachment =
        RawAttachment::new::<_, DefaultAttachmentHandler>("test string".to_owned());
    let number_attachment = RawAttachment::new::<_, DefaultAttachmentHandler>(42i32);
    let custom_attachment =
        RawAttachment::new::<_, DefaultAttachmentHandler>(TestAttachment::new("mixed", 123));

    let attachments = [string_attachment, number_attachment, custom_attachment];

    // Test type checking
    assert_eq!(
        attachments[0].as_ref().attachment_type_id(),
        TypeId::of::<String>()
    );
    assert_eq!(
        attachments[1].as_ref().attachment_type_id(),
        TypeId::of::<i32>()
    );
    assert_eq!(
        attachments[2].as_ref().attachment_type_id(),
        TypeId::of::<TestAttachment>()
    );

    // Test downcasting
    assert_eq!(
        attachments[0].as_ref().attachment_type_id(),
        TypeId::of::<String>()
    );
    assert_eq!(
        unsafe {
            attachments[0]
                .as_ref()
                .attachment_downcast_unchecked::<String>()
        },
        "test string"
    );

    assert_eq!(
        attachments[1].as_ref().attachment_type_id(),
        TypeId::of::<i32>()
    );
    assert_eq!(
        unsafe {
            *attachments[1]
                .as_ref()
                .attachment_downcast_unchecked::<i32>()
        },
        42i32
    );

    assert_eq!(
        attachments[2].as_ref().attachment_type_id(),
        TypeId::of::<TestAttachment>()
    );
    assert_eq!(
        unsafe {
            let att = attachments[2]
                .as_ref()
                .attachment_downcast_unchecked::<TestAttachment>();
            (att.name.clone(), att.value)
        },
        ("mixed".to_owned(), 123)
    );
}

#[test]
fn test_different_context_types() {
    // Create different types of contexts
    let test_error = TestError::new("test error");
    let string_context = SimpleStringContext("simple string error".to_owned());
    let number_context = NumberContext(404);

    // Create reports with different context types and appropriate handlers
    let test_report =
        RawReport::new::<_, DefaultContextHandler>(test_error, Vec::new(), Vec::new());
    let string_report =
        RawReport::new::<_, DefaultContextHandler>(string_context, Vec::new(), Vec::new());
    let number_report =
        RawReport::new::<_, DefaultContextHandler>(number_context, Vec::new(), Vec::new());

    let reports = [test_report, string_report, number_report];

    // Test context type checking
    assert_eq!(
        reports[0].as_ref().context_type_id(),
        TypeId::of::<TestError>()
    );
    assert_eq!(
        reports[1].as_ref().context_type_id(),
        TypeId::of::<SimpleStringContext>()
    );
    assert_eq!(
        reports[2].as_ref().context_type_id(),
        TypeId::of::<NumberContext>()
    );

    // Verify each report has different type IDs
    assert_ne!(
        reports[0].as_ref().context_type_id(),
        reports[1].as_ref().context_type_id()
    );
    assert_ne!(
        reports[1].as_ref().context_type_id(),
        reports[2].as_ref().context_type_id()
    );
    assert_ne!(
        reports[0].as_ref().context_type_id(),
        reports[2].as_ref().context_type_id()
    );

    // Test display functionality for different types
    let test_display = format!("{}", TestReportDisplayWrapper(reports[0].as_ref()));
    let string_display = format!("{}", TestReportDisplayWrapper(reports[1].as_ref()));
    let number_display = format!("{}", TestReportDisplayWrapper(reports[2].as_ref()));

    assert_eq!(test_display, "test error");
    assert_eq!(string_display, "simple string error");
    assert_eq!(number_display, "404");
}

#[test]
fn test_context_types_with_custom_handlers() {
    // Test the same context types with custom handlers for non-Error types
    let string_context = "custom string".to_owned();
    let number_context = 42i32;

    let string_report =
        RawReport::new::<_, StringContextHandler>(string_context, Vec::new(), Vec::new());
    let number_report =
        RawReport::new::<_, NumberContextHandler>(number_context, Vec::new(), Vec::new());

    // Test type IDs
    assert_eq!(
        string_report.as_ref().context_type_id(),
        TypeId::of::<String>()
    );
    assert_eq!(
        number_report.as_ref().context_type_id(),
        TypeId::of::<i32>()
    );
    assert_ne!(
        string_report.as_ref().context_type_id(),
        number_report.as_ref().context_type_id()
    );

    // Test custom display/debug formatting
    let string_display = format!("{}", TestReportDisplayWrapper(string_report.as_ref()));
    let number_display = format!("{}", TestReportDisplayWrapper(number_report.as_ref()));
    let string_debug = format!("{:?}", TestReportDebugWrapper(string_report.as_ref()));
    let number_debug = format!("{:?}", TestReportDebugWrapper(number_report.as_ref()));

    assert_eq!(string_display, "custom string");
    assert_eq!(number_display, "42");
    assert_eq!(string_debug, "String(\"custom string\")");
    assert_eq!(number_debug, "Number(42)");

    // Test that source is None for these simple types
    assert!(string_report.as_ref().context_source().is_none());
    assert!(number_report.as_ref().context_source().is_none());
}

#[test]
fn test_deep_hierarchy() {
    // Create a 5-level deep hierarchy
    let mut current = RawReport::new::<_, DefaultContextHandler>(
        TestError::new("level 0"),
        Vec::new(),
        Vec::new(),
    );

    for i in 1..5 {
        current = RawReport::new::<_, DefaultContextHandler>(
            TestError::new(&format!("level {i}")),
            vec![current],
            Vec::new(),
        );
    }

    // Verify the structure
    let mut current_ref = current.as_ref();
    for i in (0..5).rev() {
        let display_result = format!("{}", TestReportDisplayWrapper(current_ref));
        assert_eq!(display_result, format!("level {i}"));

        if i > 0 {
            assert_eq!(current_ref.children().len(), 1);
            current_ref = current_ref.children()[0].as_ref();
        } else {
            assert_eq!(current_ref.children().len(), 0);
        }
    }
}

#[test]
fn test_context_downcast() {
    // Test context_downcast method similar to attachment_downcast tests

    // Test with TestError context
    let test_error = TestError::new("test context downcast");
    let error_report =
        RawReport::new::<_, DefaultContextHandler>(test_error, Vec::new(), Vec::new());
    let error_ref = error_report.as_ref();

    // Test successful downcast
    assert_eq!(error_ref.context_type_id(), TypeId::of::<TestError>());
    let downcast_error = unsafe { error_ref.context_downcast_unchecked::<TestError>() };
    assert_eq!(downcast_error.message, "test context downcast");
    assert!(downcast_error.source.is_none());

    // Test with different context types
    let string_context = "string context".to_owned();
    let string_report =
        RawReport::new::<_, StringContextHandler>(string_context, Vec::new(), Vec::new());
    let string_ref = string_report.as_ref();

    let number_context = 42i32;
    let number_report =
        RawReport::new::<_, NumberContextHandler>(number_context, Vec::new(), Vec::new());
    let number_ref = number_report.as_ref();

    // Test correct downcasts
    assert_eq!(string_ref.context_type_id(), TypeId::of::<String>());
    assert_eq!(
        unsafe { string_ref.context_downcast_unchecked::<String>() },
        "string context"
    );
    assert_eq!(number_ref.context_type_id(), TypeId::of::<i32>());
    assert_eq!(
        unsafe { number_ref.context_downcast_unchecked::<i32>() },
        &42
    );

    // Test with custom context type
    let simple_context = SimpleStringContext("simple context".to_owned());
    let simple_report =
        RawReport::new::<_, DefaultContextHandler>(simple_context, Vec::new(), Vec::new());
    let simple_ref = simple_report.as_ref();

    assert_eq!(
        simple_ref.context_type_id(),
        TypeId::of::<SimpleStringContext>()
    );
    let downcast_simple = unsafe { simple_ref.context_downcast_unchecked::<SimpleStringContext>() };
    assert_eq!(downcast_simple.0, "simple context");

    // Test hierarchical context downcast
    let child_error = TestError::new("child context");
    let child_report =
        RawReport::new::<_, DefaultContextHandler>(child_error, Vec::new(), Vec::new());

    let parent_error = TestError::new("parent context");
    let parent_report =
        RawReport::new::<_, DefaultContextHandler>(parent_error, vec![child_report], Vec::new());

    let parent_ref = parent_report.as_ref();
    let child_ref = parent_ref.children()[0].as_ref();

    // Both should downcast correctly
    assert_eq!(parent_ref.context_type_id(), TypeId::of::<TestError>());
    let parent_downcast = unsafe { parent_ref.context_downcast_unchecked::<TestError>() };

    assert_eq!(child_ref.context_type_id(), TypeId::of::<TestError>());
    let child_downcast = unsafe { child_ref.context_downcast_unchecked::<TestError>() };

    assert_eq!(parent_downcast.message, "parent context");
    assert_eq!(child_downcast.message, "child context");

    // Test with error that has source
    let source_error = TestError::new("source error");
    let main_error = TestError::with_source("main with source", Box::new(source_error));
    let source_report =
        RawReport::new::<_, DefaultContextHandler>(main_error, Vec::new(), Vec::new());
    let source_ref = source_report.as_ref();

    assert_eq!(source_ref.context_type_id(), TypeId::of::<TestError>());
    let downcast_with_source = unsafe { source_ref.context_downcast_unchecked::<TestError>() };
    assert_eq!(downcast_with_source.message, "main with source");
    assert!(downcast_with_source.source.is_some());
    assert_eq!(
        downcast_with_source.source.as_ref().unwrap().to_string(),
        "source error"
    );
}

// Additional comprehensive tests
#[test]
fn test_type_id_consistency() {
    let attachment =
        RawAttachment::new::<_, DefaultAttachmentHandler>(TestAttachment::new("test", 42));
    let attachment_ref = attachment.as_ref();

    // TypeId should be consistent across calls
    let type_id1 = attachment_ref.attachment_type_id();
    let type_id2 = attachment_ref.attachment_type_id();
    assert_eq!(type_id1, type_id2);

    // Should match direct TypeId::of call
    assert_eq!(type_id1, TypeId::of::<TestAttachment>());
}

#[test]
fn test_report_vtable_consistency() {
    let report = RawReport::new::<_, DefaultContextHandler>(
        TestError::new("consistency test"),
        Vec::new(),
        Vec::new(),
    );
    let report_ref = report.as_ref();

    // Type ID should be consistent
    let type_id1 = report_ref.context_type_id();
    let type_id2 = report_ref.context_type_id();
    assert_eq!(type_id1, type_id2);
    assert_eq!(type_id1, TypeId::of::<TestError>());
}

#[test]
fn test_mixed_handler_types() {
    // Test that different handler types can coexist
    let attachment1 =
        RawAttachment::new::<_, DefaultAttachmentHandler>(TestAttachment::new("default", 1));
    let attachment2 =
        RawAttachment::new::<_, CustomAttachmentHandler>(TestAttachment::new("custom", 2));

    let report1 = RawReport::new::<_, DefaultContextHandler>(
        TestError::new("default handler"),
        Vec::new(),
        vec![attachment1],
    );

    let report2 = RawReport::new::<_, CustomContextHandler>(
        TestError::new("custom handler"),
        Vec::new(),
        vec![attachment2],
    );

    // Both should work correctly
    let report1_ref = report1.as_ref();
    let report2_ref = report2.as_ref();

    assert_eq!(report1_ref.attachments().len(), 1);
    assert_eq!(report2_ref.attachments().len(), 1);

    // Different display formats due to different handlers
    let display1 = format!("{}", TestReportDisplayWrapper(report1_ref));
    let display2 = format!("{}", TestReportDisplayWrapper(report2_ref));

    assert_eq!(display1, "default handler");
    assert_eq!(display2, "[CUSTOM] custom handler");
}

#[test]
fn test_large_hierarchy() {
    // Test with many attachments and children
    let mut attachments = Vec::new();
    for i in 0..10 {
        attachments.push(RawAttachment::new::<_, DefaultAttachmentHandler>(
            TestAttachment::new(&format!("attachment_{i}"), i),
        ));
    }

    let mut children = Vec::new();
    for i in 0..5 {
        children.push(RawReport::new::<_, DefaultContextHandler>(
            TestError::new(&format!("child_{i}")),
            Vec::new(),
            Vec::new(),
        ));
    }

    let root =
        RawReport::new::<_, DefaultContextHandler>(TestError::new("root"), children, attachments);

    let root_ref = root.as_ref();
    assert_eq!(root_ref.children().len(), 5);
    assert_eq!(root_ref.attachments().len(), 10);

    // Verify all attachments
    for (i, attachment) in root_ref.attachments().iter().enumerate() {
        let attachment_ref = attachment.as_ref();
        assert_eq!(
            attachment_ref.attachment_type_id(),
            TypeId::of::<TestAttachment>()
        );
        let downcast = unsafe { attachment_ref.attachment_downcast_unchecked::<TestAttachment>() };
        assert_eq!(downcast.name, format!("attachment_{i}"));
        assert_eq!(downcast.value, i as i32);
    }

    // Verify all children
    for (i, child) in root_ref.children().iter().enumerate() {
        let child_ref = child.as_ref();
        let display = format!("{}", TestReportDisplayWrapper(child_ref));
        assert_eq!(display, format!("child_{i}"));
    }
}

#[test]
fn test_custom_handler_provides_source() {
    // Test custom handlers that actually provide meaningful sources

    // Create a simple error type that implements Sync
    #[derive(Debug)]
    struct SimpleError(&'static str);

    impl fmt::Display for SimpleError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "{}", self.0)
        }
    }

    impl Error for SimpleError {}

    static REFERENCE_ERROR: SimpleError = SimpleError("reference error from custom handler");

    // Test for Error types: custom handler that provides a different source than
    // Error::source()
    struct AlternateSourceHandler;

    impl ContextHandler<TestError> for AlternateSourceHandler {
        fn source(_value: &TestError) -> Option<&(dyn Error + 'static)> {
            // Always return a specific static error, regardless of the actual
            // Error::source()
            Some(&REFERENCE_ERROR)
        }

        fn display(value: &TestError, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(formatter, "[ALTERNATE_SOURCE] {}", value.message)
        }

        fn debug(value: &TestError, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(
                formatter,
                "AlternateSourceError {{ message: {:?} }}",
                value.message
            )
        }
    }

    // Test for non-Error types: custom handler that provides a source for types
    // that don't implement Error
    #[derive(Debug)]
    struct NonErrorContext {
        message: String,
        value: i32,
    }

    impl fmt::Display for NonErrorContext {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "{}: {}", self.message, self.value)
        }
    }
    // Note: NonErrorContext does NOT implement Error

    struct NonErrorWithSourceHandler;

    impl ContextHandler<NonErrorContext> for NonErrorWithSourceHandler {
        fn source(_value: &NonErrorContext) -> Option<&(dyn Error + 'static)> {
            // Provide a source for a non-Error type!
            Some(&REFERENCE_ERROR)
        }

        fn display(value: &NonErrorContext, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(formatter, "[NON_ERROR_WITH_SOURCE] {}", value.message)
        }

        fn debug(value: &NonErrorContext, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(
                formatter,
                "NonErrorWithSource {{ message: {:?}, value: {} }}",
                value.message, value.value
            )
        }
    }

    // Test 1: Error type with custom source that differs from Error::source()
    let error_with_real_source = TestError::with_source(
        "main error",
        Box::new(TestError::new("actual source from Error trait")),
    );

    // Verify the error has its own source
    assert!(error_with_real_source.source().is_some());
    assert_eq!(
        error_with_real_source.source().unwrap().to_string(),
        "actual source from Error trait"
    );

    let alternate_report =
        RawReport::new::<_, AlternateSourceHandler>(error_with_real_source, Vec::new(), Vec::new());

    let alternate_ref = alternate_report.as_ref();
    let alternate_source = alternate_ref.context_source();

    // The custom handler should return the reference error, NOT the actual
    // Error::source()
    assert!(alternate_source.is_some());
    assert_eq!(
        alternate_source.unwrap().to_string(),
        "reference error from custom handler"
    );

    // Test 2: Non-Error type that gets a source through custom handler
    let non_error = NonErrorContext {
        message: "I'm not an Error".to_string(),
        value: 42,
    };

    let non_error_report =
        RawReport::new::<_, NonErrorWithSourceHandler>(non_error, Vec::new(), Vec::new());

    let non_error_ref = non_error_report.as_ref();
    let non_error_source = non_error_ref.context_source();

    // The non-Error type should have a source through the custom handler
    assert!(non_error_source.is_some());
    assert_eq!(
        non_error_source.unwrap().to_string(),
        "reference error from custom handler"
    );

    // Test 3: Compare with default handler for same non-Error type (should have no
    // source)
    struct DefaultNonErrorHandler;

    impl ContextHandler<NonErrorContext> for DefaultNonErrorHandler {
        fn source(_value: &NonErrorContext) -> Option<&(dyn Error + 'static)> {
            None // Default behavior for non-Error types
        }

        fn display(value: &NonErrorContext, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            fmt::Display::fmt(value, formatter)
        }

        fn debug(value: &NonErrorContext, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            fmt::Debug::fmt(value, formatter)
        }
    }

    let default_non_error = NonErrorContext {
        message: "I'm also not an Error".to_string(),
        value: 99,
    };

    let default_non_error_report =
        RawReport::new::<_, DefaultNonErrorHandler>(default_non_error, Vec::new(), Vec::new());

    let default_non_error_ref = default_non_error_report.as_ref();
    let default_non_error_source = default_non_error_ref.context_source();

    // Default handler should return no source for non-Error type
    assert!(default_non_error_source.is_none());

    // Verify display formatting works for both
    let alternate_display = format!("{}", TestReportDisplayWrapper(alternate_ref));
    let non_error_display = format!("{}", TestReportDisplayWrapper(non_error_ref));
    let default_display = format!("{}", TestReportDisplayWrapper(default_non_error_ref));

    assert_eq!(alternate_display, "[ALTERNATE_SOURCE] main error");
    assert_eq!(
        non_error_display,
        "[NON_ERROR_WITH_SOURCE] I'm not an Error"
    );
    assert_eq!(default_display, "I'm also not an Error: 99");
}

#[test]
fn test_clone_and_drop_behavior() {
    use std::{cell::RefCell, rc::Rc};

    // Test that cloning and dropping work correctly with proper reference counting

    // Counter to track drops
    #[derive(Debug)]
    struct DropCounter {
        name: String,
        counter: Rc<RefCell<Vec<String>>>,
    }

    impl DropCounter {
        fn new(name: &str, counter: Rc<RefCell<Vec<String>>>) -> Self {
            counter.borrow_mut().push(format!("Created: {name}"));
            Self {
                name: name.to_string(),
                counter,
            }
        }
    }

    impl Drop for DropCounter {
        fn drop(&mut self) {
            self.counter
                .borrow_mut()
                .push(format!("Dropped: {}", self.name));
        }
    }

    impl fmt::Display for DropCounter {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "DropCounter({})", self.name)
        }
    }

    impl Error for DropCounter {}

    // Test 1: Single report with drop tracking
    let drop_log = Rc::new(RefCell::new(Vec::<String>::new()));

    {
        let context = DropCounter::new("report_context", drop_log.clone());
        let report = RawReport::new::<_, DefaultContextHandler>(context, Vec::new(), Vec::new());

        // Initially strong count should be 1
        let report_ref = report.as_ref();
        assert_eq!(report_ref.strong_count(), 1);

        // Clone the report
        let cloned_report = unsafe { report_ref.clone_arc() };

        // After cloning, strong count should be 2
        assert_eq!(report_ref.strong_count(), 2);
        assert_eq!(cloned_report.as_ref().strong_count(), 2);

        // Both reports should work
        let original_display = format!("{}", TestReportDisplayWrapper(report_ref));
        let cloned_display = format!("{}", TestReportDisplayWrapper(cloned_report.as_ref()));

        assert_eq!(original_display, "DropCounter(report_context)");
        assert_eq!(cloned_display, "DropCounter(report_context)");

        // The context should not be dropped yet (both reports hold references)
        let current_log = drop_log.borrow();
        assert_eq!(current_log.len(), 1); // Only "Created" entry
        assert!(current_log[0].contains("Created: report_context"));
        drop(current_log);

        // Drop the original report
        drop(report);

        // Strong count should now be 1
        assert_eq!(cloned_report.as_ref().strong_count(), 1);

        // Context should still not be dropped (cloned report still holds reference)
        let current_log = drop_log.borrow();
        assert_eq!(current_log.len(), 1); // Still only "Created" entry
        drop(current_log);

        // Drop the cloned report
        drop(cloned_report);
    }

    // Now the context should be dropped exactly once
    let final_log = drop_log.borrow();
    assert_eq!(final_log.len(), 2);
    assert!(final_log[0].contains("Created: report_context"));
    assert!(final_log[1].contains("Dropped: report_context"));
    drop(final_log);

    // Test 2: Attachments with drop tracking
    let attachment_log = Rc::new(RefCell::new(Vec::<String>::new()));

    {
        let attachment_value = DropCounter::new("attachment_value", attachment_log.clone());
        let attachment = RawAttachment::new::<_, DefaultAttachmentHandler>(attachment_value);

        // The attachment should work
        let attachment_ref = attachment.as_ref();
        let display_result = format!("{}", TestDisplayWrapper(attachment_ref));
        assert_eq!(display_result, "DropCounter(attachment_value)");

        // Value should not be dropped yet
        let current_log = attachment_log.borrow();
        assert_eq!(current_log.len(), 1); // Only "Created" entry
        assert!(current_log[0].contains("Created: attachment_value"));
        drop(current_log);

        // Drop the attachment
        drop(attachment);
    }

    // Value should be dropped exactly once
    let final_attachment_log = attachment_log.borrow();
    assert_eq!(final_attachment_log.len(), 2);
    assert!(final_attachment_log[0].contains("Created: attachment_value"));
    assert!(final_attachment_log[1].contains("Dropped: attachment_value"));
    drop(final_attachment_log);

    // Test 3: Complex hierarchy with multiple clones
    let hierarchy_log = Rc::new(RefCell::new(Vec::<String>::new()));

    {
        let parent_context = DropCounter::new("parent", hierarchy_log.clone());
        let child_context = DropCounter::new("child", hierarchy_log.clone());
        let attachment_value = DropCounter::new("attachment", hierarchy_log.clone());

        let child_report =
            RawReport::new::<_, DefaultContextHandler>(child_context, Vec::new(), Vec::new());

        let attachment = RawAttachment::new::<_, DefaultAttachmentHandler>(attachment_value);

        let parent_report = RawReport::new::<_, DefaultContextHandler>(
            parent_context,
            vec![child_report],
            vec![attachment],
        );

        // Clone the parent (this should clone the entire hierarchy)
        let parent_ref = parent_report.as_ref();

        // Initially parent should have strong count of 1
        assert_eq!(parent_ref.strong_count(), 1);

        let cloned_parent = unsafe { parent_ref.clone_arc() };

        // After cloning, both should have strong count of 2
        assert_eq!(parent_ref.strong_count(), 2);
        assert_eq!(cloned_parent.as_ref().strong_count(), 2);

        // Verify structure integrity
        assert_eq!(parent_ref.children().len(), 1);
        assert_eq!(parent_ref.attachments().len(), 1);
        assert_eq!(cloned_parent.as_ref().children().len(), 1);
        assert_eq!(cloned_parent.as_ref().attachments().len(), 1);

        // All values should still exist (3 Created entries)
        let current_log = hierarchy_log.borrow();
        assert_eq!(current_log.len(), 3);
        assert!(current_log.iter().all(|entry| entry.contains("Created:")));
        drop(current_log);

        // Drop original parent
        drop(parent_report);

        // Cloned parent should now have strong count of 1
        assert_eq!(cloned_parent.as_ref().strong_count(), 1);

        // Values should still exist (cloned parent holds references)
        let current_log = hierarchy_log.borrow();
        assert_eq!(current_log.len(), 3); // Still only Created entries
        drop(current_log);

        // Drop cloned parent
        drop(cloned_parent);
    }

    // All values should be dropped exactly once
    let final_hierarchy_log = hierarchy_log.borrow();
    assert_eq!(final_hierarchy_log.len(), 6); // 3 Created + 3 Dropped

    let created_count = final_hierarchy_log
        .iter()
        .filter(|entry| entry.contains("Created:"))
        .count();
    let dropped_count = final_hierarchy_log
        .iter()
        .filter(|entry| entry.contains("Dropped:"))
        .count();

    assert_eq!(created_count, 3);
    assert_eq!(dropped_count, 3);

    // Verify each item was dropped exactly once
    assert!(
        final_hierarchy_log
            .iter()
            .any(|entry| entry.contains("Dropped: parent"))
    );
    assert!(
        final_hierarchy_log
            .iter()
            .any(|entry| entry.contains("Dropped: child"))
    );
    assert!(
        final_hierarchy_log
            .iter()
            .any(|entry| entry.contains("Dropped: attachment"))
    );

    drop(final_hierarchy_log);

    // Test 4: Multiple clones of the same report
    let multi_clone_log = Rc::new(RefCell::new(Vec::<String>::new()));

    {
        let context = DropCounter::new("multi_clone", multi_clone_log.clone());
        let report = RawReport::new::<_, DefaultContextHandler>(context, Vec::new(), Vec::new());

        let report_ref = report.as_ref();

        // Initially strong count should be 1
        assert_eq!(report_ref.strong_count(), 1);

        let clone1 = unsafe { report_ref.clone_arc() };

        // After first clone, strong count should be 2
        assert_eq!(report_ref.strong_count(), 2);
        assert_eq!(clone1.as_ref().strong_count(), 2);

        let clone2 = unsafe { report_ref.clone_arc() };

        // After second clone, strong count should be 3
        assert_eq!(report_ref.strong_count(), 3);
        assert_eq!(clone1.as_ref().strong_count(), 3);
        assert_eq!(clone2.as_ref().strong_count(), 3);

        let clone3 = unsafe { clone1.as_ref().clone_arc() };

        // After third clone, strong count should be 4
        assert_eq!(report_ref.strong_count(), 4);
        assert_eq!(clone1.as_ref().strong_count(), 4);
        assert_eq!(clone2.as_ref().strong_count(), 4);
        assert_eq!(clone3.as_ref().strong_count(), 4);

        // All should display the same
        let original_display = format!("{}", TestReportDisplayWrapper(report_ref));
        let clone1_display = format!("{}", TestReportDisplayWrapper(clone1.as_ref()));
        let clone2_display = format!("{}", TestReportDisplayWrapper(clone2.as_ref()));
        let clone3_display = format!("{}", TestReportDisplayWrapper(clone3.as_ref()));

        assert_eq!(original_display, "DropCounter(multi_clone)");
        assert_eq!(clone1_display, "DropCounter(multi_clone)");
        assert_eq!(clone2_display, "DropCounter(multi_clone)");
        assert_eq!(clone3_display, "DropCounter(multi_clone)");

        // Value should not be dropped yet
        let current_log = multi_clone_log.borrow();
        assert_eq!(current_log.len(), 1); // Only "Created" entry
        drop(current_log);

        // Drop them one by one
        drop(report);

        // Strong count should now be 3
        assert_eq!(clone1.as_ref().strong_count(), 3);
        assert_eq!(clone2.as_ref().strong_count(), 3);
        assert_eq!(clone3.as_ref().strong_count(), 3);

        let current_log = multi_clone_log.borrow();
        assert_eq!(current_log.len(), 1); // Still only "Created"
        drop(current_log);

        drop(clone1);

        // Strong count should now be 2
        assert_eq!(clone2.as_ref().strong_count(), 2);
        assert_eq!(clone3.as_ref().strong_count(), 2);

        let current_log = multi_clone_log.borrow();
        assert_eq!(current_log.len(), 1); // Still only "Created"
        drop(current_log);

        drop(clone2);

        // Strong count should now be 1
        assert_eq!(clone3.as_ref().strong_count(), 1);

        let current_log = multi_clone_log.borrow();
        assert_eq!(current_log.len(), 1); // Still only "Created"
        drop(current_log);

        // Last clone should trigger the drop
        drop(clone3);
    }

    // Value should be dropped exactly once, even with multiple clones
    let final_multi_log = multi_clone_log.borrow();
    assert_eq!(final_multi_log.len(), 2);
    assert!(final_multi_log[0].contains("Created: multi_clone"));
    assert!(final_multi_log[1].contains("Dropped: multi_clone"));
}

#[test]
fn test_hierarchical_drop_order_independence() {
    use std::{cell::RefCell, rc::Rc};

    use rootcause_internals::RawReport;

    use crate::DefaultContextHandler;

    #[derive(Debug)]
    struct DropTracker {
        name: String,
        log: Rc<RefCell<Vec<String>>>,
    }

    impl DropTracker {
        fn new(name: &str, log: Rc<RefCell<Vec<String>>>) -> Self {
            let tracker = Self {
                name: name.to_string(),
                log: log.clone(),
            };
            log.borrow_mut().push(format!("Created: {name}"));
            tracker
        }
    }

    impl Drop for DropTracker {
        fn drop(&mut self) {
            self.log
                .borrow_mut()
                .push(format!("Dropped: {}", self.name));
        }
    }

    impl fmt::Display for DropTracker {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "DropTracker({})", self.name)
        }
    }

    impl Error for DropTracker {}

    // Test that we can clone and drop hierarchies safely

    // Test Case 1: Basic hierarchy - drop parent (should drop all)
    {
        let log = Rc::new(RefCell::new(Vec::<String>::new()));

        let grandchild = {
            let grandchild_context = DropTracker::new("gc1", log.clone());
            RawReport::new::<_, DefaultContextHandler>(grandchild_context, Vec::new(), Vec::new())
        };

        let child = {
            let child_context = DropTracker::new("child1", log.clone());
            RawReport::new::<_, DefaultContextHandler>(child_context, vec![grandchild], Vec::new())
        };

        let parent = {
            let parent_context = DropTracker::new("parent1", log.clone());
            RawReport::new::<_, DefaultContextHandler>(parent_context, vec![child], Vec::new())
        };

        // Drop everything at once
        drop(parent);

        // All should be dropped exactly once
        let final_log = log.borrow();
        assert_eq!(final_log.len(), 6); // 3 Created + 3 Dropped
        assert_eq!(
            final_log.iter().filter(|e| e.contains("Created:")).count(),
            3
        );
        assert_eq!(
            final_log.iter().filter(|e| e.contains("Dropped:")).count(),
            3
        );
    }

    // Test Case 2: Test reference counting works (clone then drop)
    {
        let log = Rc::new(RefCell::new(Vec::<String>::new()));

        let grandchild = {
            let grandchild_context = DropTracker::new("gc2", log.clone());
            RawReport::new::<_, DefaultContextHandler>(grandchild_context, Vec::new(), Vec::new())
        };

        let child = {
            let child_context = DropTracker::new("child2", log.clone());
            RawReport::new::<_, DefaultContextHandler>(child_context, vec![grandchild], Vec::new())
        };

        let parent = {
            let parent_context = DropTracker::new("parent2", log.clone());
            RawReport::new::<_, DefaultContextHandler>(parent_context, vec![child], Vec::new())
        };

        // Create a clone and drop original
        let parent_ref = parent.as_ref();

        // Initially parent should have strong count of 1
        assert_eq!(parent_ref.strong_count(), 1);

        let parent_clone = unsafe { parent_ref.clone_arc() };

        // After cloning, both should have strong count of 2
        assert_eq!(parent_ref.strong_count(), 2);
        assert_eq!(parent_clone.as_ref().strong_count(), 2);

        drop(parent);

        // Clone should now have strong count of 1
        assert_eq!(parent_clone.as_ref().strong_count(), 1);

        // Nothing should be dropped yet (clone exists)
        {
            let current_log = log.borrow();
            assert_eq!(current_log.len(), 3); // Only Created entries
        }

        // Drop clone - everything should be dropped
        drop(parent_clone);

        // All should be dropped exactly once
        let final_log = log.borrow();
        assert_eq!(final_log.len(), 6); // 3 Created + 3 Dropped
        assert_eq!(
            final_log.iter().filter(|e| e.contains("Created:")).count(),
            3
        );
        assert_eq!(
            final_log.iter().filter(|e| e.contains("Dropped:")).count(),
            3
        );
    }

    // Test Case 3: Multiple clones
    {
        let log = Rc::new(RefCell::new(Vec::<String>::new()));

        let grandchild = {
            let grandchild_context = DropTracker::new("gc3", log.clone());
            RawReport::new::<_, DefaultContextHandler>(grandchild_context, Vec::new(), Vec::new())
        };

        let child = {
            let child_context = DropTracker::new("child3", log.clone());
            RawReport::new::<_, DefaultContextHandler>(child_context, vec![grandchild], Vec::new())
        };

        let parent = {
            let parent_context = DropTracker::new("parent3", log.clone());
            RawReport::new::<_, DefaultContextHandler>(parent_context, vec![child], Vec::new())
        };

        // Create multiple clones
        let parent_ref = parent.as_ref();

        // Initially parent should have strong count of 1
        assert_eq!(parent_ref.strong_count(), 1);

        let clone1 = unsafe { parent_ref.clone_arc() };

        // After first clone, strong count should be 2
        assert_eq!(parent_ref.strong_count(), 2);
        assert_eq!(clone1.as_ref().strong_count(), 2);

        let clone2 = unsafe { parent_ref.clone_arc() };

        // After second clone, strong count should be 3
        assert_eq!(parent_ref.strong_count(), 3);
        assert_eq!(clone1.as_ref().strong_count(), 3);
        assert_eq!(clone2.as_ref().strong_count(), 3);

        let clone3 = unsafe { parent_ref.clone_arc() };

        // After third clone, strong count should be 4
        assert_eq!(parent_ref.strong_count(), 4);
        assert_eq!(clone1.as_ref().strong_count(), 4);
        assert_eq!(clone2.as_ref().strong_count(), 4);
        assert_eq!(clone3.as_ref().strong_count(), 4);

        drop(parent);

        // Strong count should now be 3
        assert_eq!(clone1.as_ref().strong_count(), 3);
        assert_eq!(clone2.as_ref().strong_count(), 3);
        assert_eq!(clone3.as_ref().strong_count(), 3);

        drop(clone1);

        // Strong count should now be 2
        assert_eq!(clone2.as_ref().strong_count(), 2);
        assert_eq!(clone3.as_ref().strong_count(), 2);

        drop(clone2);

        // Strong count should now be 1
        assert_eq!(clone3.as_ref().strong_count(), 1);

        // Still nothing dropped (clone3 exists)
        {
            let current_log = log.borrow();
            assert_eq!(current_log.len(), 3); // Only Created entries
        }

        // Drop last clone - everything should be dropped
        drop(clone3);

        // All should be dropped exactly once despite multiple clones
        let final_log = log.borrow();
        assert_eq!(final_log.len(), 6); // 3 Created + 3 Dropped
        assert_eq!(
            final_log.iter().filter(|e| e.contains("Created:")).count(),
            3
        );
        assert_eq!(
            final_log.iter().filter(|e| e.contains("Dropped:")).count(),
            3
        );
    }

    // Test Case 4: Access child directly and drop in different orders
    {
        let log = Rc::new(RefCell::new(Vec::<String>::new()));

        let grandchild = {
            let grandchild_context = DropTracker::new("gc4", log.clone());
            RawReport::new::<_, DefaultContextHandler>(grandchild_context, Vec::new(), Vec::new())
        };

        let child = {
            let child_context = DropTracker::new("child4", log.clone());
            RawReport::new::<_, DefaultContextHandler>(child_context, vec![grandchild], Vec::new())
        };

        let parent = {
            let parent_context = DropTracker::new("parent4", log.clone());
            RawReport::new::<_, DefaultContextHandler>(parent_context, vec![child], Vec::new())
        };

        // Get direct references to child and grandchild through parent
        let parent_ref = parent.as_ref();
        let child_ref = &parent_ref.children()[0];
        let grandchild_ref = &child_ref.as_ref().children()[0];

        // Initially, each should have strong count of 1
        assert_eq!(parent_ref.strong_count(), 1);
        assert_eq!(child_ref.as_ref().strong_count(), 1);
        assert_eq!(grandchild_ref.as_ref().strong_count(), 1);

        // Clone the child and grandchild directly
        let child_clone = unsafe { child_ref.as_ref().clone_arc() };
        let grandchild_clone = unsafe { grandchild_ref.as_ref().clone_arc() };

        // After cloning, child and grandchild should have strong count of 2
        assert_eq!(parent_ref.strong_count(), 1); // Parent unchanged
        assert_eq!(child_ref.as_ref().strong_count(), 2);
        assert_eq!(grandchild_ref.as_ref().strong_count(), 2);
        assert_eq!(child_clone.as_ref().strong_count(), 2);
        assert_eq!(grandchild_clone.as_ref().strong_count(), 2);

        // Drop parent first - but child_clone and grandchild_clone should keep them
        // alive
        drop(parent);

        // After parent is dropped:
        // - child_clone should have strong count of 1 (parent's reference is gone)
        // - grandchild_clone should have strong count of 2 (child_clone still holds a
        //   reference to grandchild, plus grandchild_clone)
        assert_eq!(child_clone.as_ref().strong_count(), 1);
        assert_eq!(grandchild_clone.as_ref().strong_count(), 2);

        // Only parent should be dropped (child and grandchild still have clones)
        {
            let current_log = log.borrow();
            assert_eq!(current_log.len(), 4); // 3 Created + 1 Dropped (parent)
            assert!(current_log.last().unwrap().contains("Dropped: parent4"));
        }

        // Drop child clone - child should be dropped now
        drop(child_clone);

        // Grandchild should now have strong count of 1 (child_clone's reference is
        // gone)
        assert_eq!(grandchild_clone.as_ref().strong_count(), 1);

        // Child should be dropped, grandchild still alive via clone
        {
            let current_log = log.borrow();
            assert_eq!(current_log.len(), 5); // 3 Created + 2 Dropped (parent, child)
            assert!(current_log.iter().any(|e| e.contains("Dropped: child4")));
        }

        // Drop grandchild clone - grandchild should be dropped now
        drop(grandchild_clone);

        let final_log = log.borrow();
        assert_eq!(final_log.len(), 6); // 3 Created + 3 Dropped
        assert!(final_log.iter().any(|e| e.contains("Dropped: gc4")));
    }

    // Test Case 5: Drop grandchild clone first, then work up
    {
        let log = Rc::new(RefCell::new(Vec::<String>::new()));

        let grandchild = {
            let grandchild_context = DropTracker::new("gc5", log.clone());
            RawReport::new::<_, DefaultContextHandler>(grandchild_context, Vec::new(), Vec::new())
        };

        let child = {
            let child_context = DropTracker::new("child5", log.clone());
            RawReport::new::<_, DefaultContextHandler>(child_context, vec![grandchild], Vec::new())
        };

        let parent = {
            let parent_context = DropTracker::new("parent5", log.clone());
            RawReport::new::<_, DefaultContextHandler>(parent_context, vec![child], Vec::new())
        };

        // Clone the entire hierarchy
        let parent_ref = parent.as_ref();

        // Initially, each should have strong count of 1
        assert_eq!(parent_ref.strong_count(), 1);

        let parent_clone = unsafe { parent_ref.clone_arc() };

        // After parent clone, parent should have strong count of 2
        assert_eq!(parent_ref.strong_count(), 2);
        assert_eq!(parent_clone.as_ref().strong_count(), 2);

        // Also get direct reference to grandchild via parent
        let child_ref = &parent_ref.children()[0];
        let grandchild_ref = &child_ref.as_ref().children()[0];

        // Child and grandchild should still have strong count of 1
        assert_eq!(child_ref.as_ref().strong_count(), 1);
        assert_eq!(grandchild_ref.as_ref().strong_count(), 1);

        let grandchild_clone = unsafe { grandchild_ref.as_ref().clone_arc() };

        // After grandchild clone, grandchild should have strong count of 2
        assert_eq!(grandchild_ref.as_ref().strong_count(), 2);
        assert_eq!(grandchild_clone.as_ref().strong_count(), 2);

        // Drop original parent (parent_clone and grandchild_clone should keep things
        // alive)
        drop(parent);

        // Parent clone should now have strong count of 1
        assert_eq!(parent_clone.as_ref().strong_count(), 1);
        // Grandchild clone should still have strong count of 2
        assert_eq!(grandchild_clone.as_ref().strong_count(), 2);

        // Nothing should be dropped yet (parent_clone holds the full hierarchy)
        {
            let current_log = log.borrow();
            assert_eq!(current_log.len(), 3); // Only Created entries
        }

        // Drop grandchild clone first - grandchild should still exist in parent_clone
        drop(grandchild_clone);

        // Still nothing should be dropped (parent_clone holds the full hierarchy)
        {
            let current_log = log.borrow();
            assert_eq!(current_log.len(), 3); // Only Created entries
        }

        // Drop parent clone - everything should be dropped together
        drop(parent_clone);

        let final_log = log.borrow();
        assert_eq!(final_log.len(), 6); // 3 Created + 3 Dropped
    }

    // Test Case 6: Keep grandchild alive while parent and child are dropped
    // together
    {
        let log = Rc::new(RefCell::new(Vec::<String>::new()));

        let grandchild = {
            let grandchild_context = DropTracker::new("gc6", log.clone());
            RawReport::new::<_, DefaultContextHandler>(grandchild_context, Vec::new(), Vec::new())
        };

        let child = {
            let child_context = DropTracker::new("child6", log.clone());
            RawReport::new::<_, DefaultContextHandler>(child_context, vec![grandchild], Vec::new())
        };

        let parent = {
            let parent_context = DropTracker::new("parent6", log.clone());
            RawReport::new::<_, DefaultContextHandler>(parent_context, vec![child], Vec::new())
        };

        // Get direct reference to grandchild and clone it
        let parent_ref = parent.as_ref();
        let child_ref = &parent_ref.children()[0];
        let grandchild_ref = &child_ref.as_ref().children()[0];

        // Initially, each should have strong count of 1
        assert_eq!(parent_ref.strong_count(), 1);
        assert_eq!(child_ref.as_ref().strong_count(), 1);
        assert_eq!(grandchild_ref.as_ref().strong_count(), 1);

        let grandchild_clone = unsafe { grandchild_ref.as_ref().clone_arc() };

        // After grandchild clone, grandchild should have strong count of 2
        assert_eq!(grandchild_ref.as_ref().strong_count(), 2);
        assert_eq!(grandchild_clone.as_ref().strong_count(), 2);

        // Drop the parent - this should drop both parent and child, but NOT grandchild
        drop(parent);

        // Grandchild clone should now have strong count of 1
        assert_eq!(grandchild_clone.as_ref().strong_count(), 1);

        // Parent and child should be dropped, but grandchild should still be alive
        {
            let current_log = log.borrow();
            assert_eq!(current_log.len(), 5); // 3 Created + 2 Dropped (parent, child)

            // Verify both parent and child are dropped
            assert!(current_log.iter().any(|e| e.contains("Dropped: parent6")));
            assert!(current_log.iter().any(|e| e.contains("Dropped: child6")));

            // Verify grandchild is NOT dropped
            assert!(!current_log.iter().any(|e| e.contains("Dropped: gc6")));
        }

        // Verify grandchild is still functional
        let grandchild_display = format!("{}", TestReportDisplayWrapper(grandchild_clone.as_ref()));
        assert_eq!(grandchild_display, "DropTracker(gc6)");

        // Drop grandchild clone - now grandchild should be dropped
        drop(grandchild_clone);

        // All should be dropped exactly once
        let final_log = log.borrow();
        assert_eq!(final_log.len(), 6); // 3 Created + 3 Dropped
        assert!(final_log.iter().any(|e| e.contains("Dropped: gc6")));

        // Verify final count
        assert_eq!(
            final_log.iter().filter(|e| e.contains("Created:")).count(),
            3
        );
        assert_eq!(
            final_log.iter().filter(|e| e.contains("Dropped:")).count(),
            3
        );
    }
}

// RawReportMut Integration Tests
#[test]
fn test_raw_report_mut_basic_operations() {
    let mut report = RawReport::new::<_, DefaultContextHandler>(
        TestError::new("mutable basic test"),
        Vec::new(),
        Vec::new(),
    );

    // Test basic mutable reference operations
    unsafe {
        let mut report_mut = report.as_mut();

        // Test as_ref() functionality
        let report_ref = report_mut.as_ref();
        assert_eq!(
            report_ref.context_type_id(),
            core::any::TypeId::of::<TestError>()
        );

        let display_result = format!("{}", TestReportDisplayWrapper(report_ref));
        assert_eq!(display_result, "mutable basic test");

        // Test reborrow functionality
        let reborrowed = report_mut.reborrow();
        let reborrow_ref = reborrowed.as_ref();
        let reborrow_display = format!("{}", TestReportDisplayWrapper(reborrow_ref));
        assert_eq!(reborrow_display, "mutable basic test");

        // Test that mutable reference works
        let final_ref = report_mut.as_ref();
        assert_eq!(
            final_ref.context_type_id(),
            core::any::TypeId::of::<TestError>()
        );
    }
}

#[test]
fn test_raw_report_mut_children_manipulation() {
    let mut report = RawReport::new::<_, DefaultContextHandler>(
        TestError::new("parent for children test"),
        Vec::new(),
        Vec::new(),
    );

    // Test adding children through mutable reference
    unsafe {
        let report_mut = report.as_mut();
        let children_mut = report_mut.into_children_mut();
        assert_eq!(children_mut.len(), 0);

        // Add multiple children
        children_mut.push(RawReport::new::<_, DefaultContextHandler>(
            TestError::new("child 1"),
            Vec::new(),
            Vec::new(),
        ));

        children_mut.push(RawReport::new::<_, DefaultContextHandler>(
            TestError::new("child 2"),
            Vec::new(),
            Vec::new(),
        ));

        children_mut.push(RawReport::new::<_, DefaultContextHandler>(
            TestError::new("child 3"),
            Vec::new(),
            Vec::new(),
        ));

        assert_eq!(children_mut.len(), 3);
    }

    // Verify children were added correctly
    let report_ref = report.as_ref();
    let children = report_ref.children();
    assert_eq!(children.len(), 3);

    for (i, child) in children.iter().enumerate() {
        let child_ref = child.as_ref();
        let child_display = format!("{}", TestReportDisplayWrapper(child_ref));
        assert_eq!(child_display, format!("child {}", i + 1));
    }

    // Test removing children
    unsafe {
        let report_mut = report.as_mut();
        let children_mut = report_mut.into_children_mut();
        let removed_child = children_mut.pop();
        assert!(removed_child.is_some());
        assert_eq!(children_mut.len(), 2);
    }

    // Verify removal
    let children = report.as_ref().children();
    assert_eq!(children.len(), 2);
}

#[test]
fn test_raw_report_mut_attachments_manipulation() {
    let mut report = RawReport::new::<_, DefaultContextHandler>(
        TestError::new("parent for attachments test"),
        Vec::new(),
        Vec::new(),
    );

    // Test adding attachments through mutable reference
    unsafe {
        let attachments_mut = report.as_mut().into_attachments_mut();
        assert_eq!(attachments_mut.len(), 0);

        // Add multiple attachments
        attachments_mut.push(RawAttachment::new::<_, DefaultAttachmentHandler>(
            TestAttachment::new("attachment1", 100),
        ));

        attachments_mut.push(RawAttachment::new::<_, DefaultAttachmentHandler>(
            TestAttachment::new("attachment2", 200),
        ));

        attachments_mut.push(RawAttachment::new::<_, CustomAttachmentHandler>(
            TestAttachment::new("custom_attachment", 300),
        ));

        assert_eq!(attachments_mut.len(), 3);
    }

    // Verify attachments were added correctly
    let report_ref = report.as_ref();
    let attachments = report_ref.attachments();
    assert_eq!(attachments.len(), 3);

    // Check first two attachments (default handler)
    for (i, attachment) in attachments[..2].iter().enumerate() {
        let attachment_ref = attachment.as_ref();
        assert_eq!(
            attachment_ref.attachment_type_id(),
            core::any::TypeId::of::<TestAttachment>()
        );
        let downcast = unsafe { attachment_ref.attachment_downcast_unchecked::<TestAttachment>() };
        assert_eq!(downcast.name, format!("attachment{}", i + 1));
        assert_eq!(downcast.value, (i + 1) as i32 * 100);

        let display = format!("{}", TestDisplayWrapper(attachment_ref));
        assert_eq!(display, format!("attachment{}: {}", i + 1, (i + 1) * 100));
    }

    // Check custom attachment (different display format)
    let custom_attachment_ref = attachments[2].as_ref();
    assert_eq!(
        custom_attachment_ref.attachment_type_id(),
        core::any::TypeId::of::<TestAttachment>()
    );
    let custom_downcast =
        unsafe { custom_attachment_ref.attachment_downcast_unchecked::<TestAttachment>() };
    assert_eq!(custom_downcast.name, "custom_attachment");
    assert_eq!(custom_downcast.value, 300);

    let custom_display = format!("{}", TestDisplayWrapper(custom_attachment_ref));
    assert_eq!(custom_display, "[ATTACHMENT] custom_attachment = 300");

    // Test removing attachments
    unsafe {
        let report_mut = report.as_mut();
        let attachments_mut = report_mut.into_attachments_mut();
        let removed_attachment = attachments_mut.pop();
        assert!(removed_attachment.is_some());
        assert_eq!(attachments_mut.len(), 2);
    }

    // Verify removal
    let attachments = report.as_ref().attachments();
    assert_eq!(attachments.len(), 2);
}

#[test]
fn test_raw_report_mut_complex_hierarchy_manipulation() {
    // Create a complex hierarchy with mixed children and attachments
    let mut root =
        RawReport::new::<_, DefaultContextHandler>(TestError::new("root"), Vec::new(), Vec::new());

    unsafe {
        // Add initial children and attachments
        let children_mut = root.as_mut().into_children_mut();
        children_mut.push(RawReport::new::<_, DefaultContextHandler>(
            TestError::new("initial child"),
            Vec::new(),
            Vec::new(),
        ));

        let attachments_mut = root.as_mut().into_attachments_mut();
        attachments_mut.push(RawAttachment::new::<_, DefaultAttachmentHandler>(
            TestAttachment::new("initial_attachment", 50),
        ));
    }

    // Verify initial state
    assert_eq!(root.as_ref().children().len(), 1);
    assert_eq!(root.as_ref().attachments().len(), 1);

    // Add complex nested structure
    unsafe {
        let children_mut = root.as_mut().into_children_mut();

        // Create a child with its own children and attachments
        let grandchild1 = RawReport::new::<_, DefaultContextHandler>(
            TestError::new("grandchild 1"),
            Vec::new(),
            vec![RawAttachment::new::<_, DefaultAttachmentHandler>(
                TestAttachment::new("gc1_attachment", 10),
            )],
        );

        let grandchild2 = RawReport::new::<_, CustomContextHandler>(
            TestError::new("grandchild 2"),
            Vec::new(),
            vec![RawAttachment::new::<_, CustomAttachmentHandler>(
                TestAttachment::new("gc2_attachment", 20),
            )],
        );

        let child_with_grandchildren = RawReport::new::<_, DefaultContextHandler>(
            TestError::new("child with grandchildren"),
            vec![grandchild1, grandchild2],
            vec![RawAttachment::new::<_, DefaultAttachmentHandler>(
                TestAttachment::new("child_attachment", 100),
            )],
        );

        children_mut.push(child_with_grandchildren);

        // Add more attachments to root
        let attachments_mut = root.as_mut().into_attachments_mut();
        attachments_mut.push(RawAttachment::new::<_, CustomAttachmentHandler>(
            TestAttachment::new("root_custom", 999),
        ));
    }

    // Verify the complex structure
    let root_ref = root.as_ref();
    assert_eq!(root_ref.children().len(), 2);
    assert_eq!(root_ref.attachments().len(), 2);

    // Check root attachments
    let root_attachments = root_ref.attachments();
    let initial_attachment = root_attachments[0].as_ref();
    let custom_attachment = root_attachments[1].as_ref();

    assert_eq!(
        initial_attachment.attachment_type_id(),
        core::any::TypeId::of::<TestAttachment>()
    );
    assert_eq!(
        unsafe {
            &initial_attachment
                .attachment_downcast_unchecked::<TestAttachment>()
                .name
        },
        "initial_attachment"
    );
    assert_eq!(
        unsafe {
            &custom_attachment
                .attachment_downcast_unchecked::<TestAttachment>()
                .name
        },
        "root_custom"
    );

    // Check display formats (default vs custom)
    let initial_display = format!("{}", TestDisplayWrapper(initial_attachment));
    let custom_display = format!("{}", TestDisplayWrapper(custom_attachment));
    assert_eq!(initial_display, "initial_attachment: 50");
    assert_eq!(custom_display, "[ATTACHMENT] root_custom = 999");

    // Check complex child structure
    let children = root_ref.children();
    let initial_child = children[0].as_ref();
    let complex_child = children[1].as_ref();

    // Initial child should have no children or attachments
    assert_eq!(initial_child.children().len(), 0);
    assert_eq!(initial_child.attachments().len(), 0);

    // Complex child should have 2 grandchildren and 1 attachment
    assert_eq!(complex_child.children().len(), 2);
    assert_eq!(complex_child.attachments().len(), 1);

    // Check grandchildren
    let grandchildren = complex_child.children();
    let gc1 = grandchildren[0].as_ref();
    let gc2 = grandchildren[1].as_ref();

    // GC1 should use default handler
    let gc1_display = format!("{}", TestReportDisplayWrapper(gc1));
    assert_eq!(gc1_display, "grandchild 1");

    // GC2 should use custom handler
    let gc2_display = format!("{}", TestReportDisplayWrapper(gc2));
    assert_eq!(gc2_display, "[CUSTOM] grandchild 2");

    // Check grandchildren attachments
    assert_eq!(gc1.attachments().len(), 1);
    assert_eq!(gc2.attachments().len(), 1);

    let gc1_attachment = gc1.attachments()[0].as_ref();
    let gc2_attachment = gc2.attachments()[0].as_ref();

    let gc1_att_display = format!("{}", TestDisplayWrapper(gc1_attachment));
    let gc2_att_display = format!("{}", TestDisplayWrapper(gc2_attachment));

    assert_eq!(gc1_att_display, "gc1_attachment: 10");
    assert_eq!(gc2_att_display, "[ATTACHMENT] gc2_attachment = 20");
}

#[test]
fn test_raw_report_mut_reborrow_with_modifications() {
    let mut report = RawReport::new::<_, DefaultContextHandler>(
        TestError::new("reborrow test"),
        Vec::new(),
        Vec::new(),
    );

    unsafe {
        let mut report_mut = report.as_mut();

        // Add some initial content
        let children_mut = report_mut.reborrow().into_children_mut();
        children_mut.push(RawReport::new::<_, DefaultContextHandler>(
            TestError::new("child 1"),
            Vec::new(),
            Vec::new(),
        ));

        // Reborrow and add more content
        let reborrowed = report_mut.reborrow();
        let attachments_mut = reborrowed.into_attachments_mut();
        attachments_mut.push(RawAttachment::new::<_, DefaultAttachmentHandler>(
            TestAttachment::new("reborrow_attachment", 42),
        ));

        // Another reborrow and add more children
        let children_mut2 = report_mut.reborrow().into_children_mut();
        children_mut2.push(RawReport::new::<_, CustomContextHandler>(
            TestError::new("child 2"),
            Vec::new(),
            Vec::new(),
        ));

        // Verify state after all reborrows
        let final_ref = report_mut.as_ref();
        assert_eq!(final_ref.children().len(), 2);
        assert_eq!(final_ref.attachments().len(), 1);
    }

    // Final verification outside unsafe block
    let final_ref = report.as_ref();
    assert_eq!(final_ref.children().len(), 2);
    assert_eq!(final_ref.attachments().len(), 1);

    let children = final_ref.children();
    let child1_display = format!("{}", TestReportDisplayWrapper(children[0].as_ref()));
    let child2_display = format!("{}", TestReportDisplayWrapper(children[1].as_ref()));

    assert_eq!(child1_display, "child 1");
    assert_eq!(child2_display, "[CUSTOM] child 2");

    let attachment = final_ref.attachments()[0].as_ref();
    let attachment_display = format!("{}", TestDisplayWrapper(attachment));
    assert_eq!(attachment_display, "reborrow_attachment: 42");
}

#[test]
fn test_raw_report_mut_type_safety_and_downcasting() {
    // Test that mutable operations preserve type safety
    let mut int_report = RawReport::new::<_, NumberContextHandler>(42i32, Vec::new(), Vec::new());

    let mut string_report =
        RawReport::new::<_, StringContextHandler>("test string".to_owned(), Vec::new(), Vec::new());

    unsafe {
        // Add different types of children and attachments
        let int_children_mut = int_report.as_mut().into_children_mut();
        int_children_mut.push(RawReport::new::<_, NumberContextHandler>(
            100i32,
            Vec::new(),
            Vec::new(),
        ));

        let string_children_mut = string_report.as_mut().into_children_mut();
        string_children_mut.push(RawReport::new::<_, StringContextHandler>(
            "child string".to_owned(),
            Vec::new(),
            Vec::new(),
        ));

        // Add mixed attachment types
        let int_attachments_mut = int_report.as_mut().into_attachments_mut();
        int_attachments_mut.push(RawAttachment::new::<_, DefaultAttachmentHandler>(
            TestAttachment::new("int_attachment", 777),
        ));
        int_attachments_mut.push(RawAttachment::new::<_, DefaultAttachmentHandler>(
            "string attachment in int report".to_owned(),
        ));

        let string_attachments_mut = string_report.as_mut().into_attachments_mut();
        string_attachments_mut.push(RawAttachment::new::<_, DefaultAttachmentHandler>(999i32));
    }

    // Verify type IDs and downcasting
    let int_ref = int_report.as_ref();
    let string_ref = string_report.as_ref();

    assert_eq!(int_ref.context_type_id(), core::any::TypeId::of::<i32>());
    assert_eq!(
        string_ref.context_type_id(),
        core::any::TypeId::of::<String>()
    );

    // Test context downcast
    assert_eq!(int_ref.context_type_id(), core::any::TypeId::of::<i32>());
    assert_eq!(unsafe { int_ref.context_downcast_unchecked::<i32>() }, &42);

    assert_eq!(
        string_ref.context_type_id(),
        core::any::TypeId::of::<String>()
    );
    assert_eq!(
        unsafe { string_ref.context_downcast_unchecked::<String>() },
        "test string"
    );

    // Test children context types
    let int_child = int_ref.children()[0].as_ref();
    let string_child = string_ref.children()[0].as_ref();

    assert_eq!(int_child.context_type_id(), core::any::TypeId::of::<i32>());
    assert_eq!(
        string_child.context_type_id(),
        core::any::TypeId::of::<String>()
    );

    assert_eq!(
        unsafe { int_child.context_downcast_unchecked::<i32>() },
        &100
    );
    assert_eq!(
        unsafe { string_child.context_downcast_unchecked::<String>() },
        "child string"
    );

    // Test attachment types
    let int_attachments = int_ref.attachments();
    let string_attachments = string_ref.attachments();

    // Int report has TestAttachment and String attachments
    assert_eq!(int_attachments.len(), 2);
    assert_eq!(
        int_attachments[0].as_ref().attachment_type_id(),
        core::any::TypeId::of::<TestAttachment>()
    );
    assert_eq!(
        int_attachments[1].as_ref().attachment_type_id(),
        core::any::TypeId::of::<String>()
    );

    // String report has i32 attachment
    assert_eq!(string_attachments.len(), 1);
    assert_eq!(
        string_attachments[0].as_ref().attachment_type_id(),
        core::any::TypeId::of::<i32>()
    );

    // Test attachment downcasting
    assert_eq!(
        int_attachments[0].as_ref().attachment_type_id(),
        core::any::TypeId::of::<TestAttachment>()
    );
    let test_attachment = unsafe {
        int_attachments[0]
            .as_ref()
            .attachment_downcast_unchecked::<TestAttachment>()
    };
    assert_eq!(test_attachment.name, "int_attachment");
    assert_eq!(test_attachment.value, 777);

    assert_eq!(
        int_attachments[1].as_ref().attachment_type_id(),
        core::any::TypeId::of::<String>()
    );
    let string_attachment = unsafe {
        int_attachments[1]
            .as_ref()
            .attachment_downcast_unchecked::<String>()
    };
    assert_eq!(string_attachment, "string attachment in int report");

    assert_eq!(
        string_attachments[0].as_ref().attachment_type_id(),
        core::any::TypeId::of::<i32>()
    );
    let i32_attachment = unsafe {
        string_attachments[0]
            .as_ref()
            .attachment_downcast_unchecked::<i32>()
    };
    assert_eq!(*i32_attachment, 999);
}

#[test]
fn test_raw_report_mut_error_source_handling() {
    // Test error sources with mutable operations
    let source_error = TestError::new("source error");
    let main_error = TestError::with_source("main error", Box::new(source_error));

    let mut report = RawReport::new::<_, DefaultContextHandler>(main_error, Vec::new(), Vec::new());

    unsafe {
        // Add children with different source behaviors
        let children_mut = report.as_mut().into_children_mut();

        // Child with source
        let child_source = TestError::new("child source");
        let child_with_source = TestError::with_source("child with source", Box::new(child_source));
        children_mut.push(RawReport::new::<_, DefaultContextHandler>(
            child_with_source,
            Vec::new(),
            Vec::new(),
        ));

        // Child without source
        children_mut.push(RawReport::new::<_, DefaultContextHandler>(
            TestError::new("child without source"),
            Vec::new(),
            Vec::new(),
        ));

        // Child with custom handler that ignores source
        struct IgnoreSourceHandler;
        impl ContextHandler<TestError> for IgnoreSourceHandler {
            fn source(_value: &TestError) -> Option<&(dyn Error + 'static)> {
                None // Always ignore source
            }

            fn display(value: &TestError, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(formatter, "[NO_SOURCE] {}", value.message)
            }

            fn debug(value: &TestError, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(formatter, "NoSource({:?})", value.message)
            }
        }

        let child_ignore_source =
            TestError::with_source("child ignores source", Box::new(TestError::new("ignored")));
        children_mut.push(RawReport::new::<_, IgnoreSourceHandler>(
            child_ignore_source,
            Vec::new(),
            Vec::new(),
        ));
    }

    // Verify source handling
    let report_ref = report.as_ref();

    // Main report should have source
    let main_source = report_ref.context_source();
    assert!(main_source.is_some());
    assert_eq!(main_source.unwrap().to_string(), "source error");

    let children = report_ref.children();
    assert_eq!(children.len(), 3);

    // Child with source
    let child_with_source = children[0].as_ref();
    let child_source = child_with_source.context_source();
    assert!(child_source.is_some());
    assert_eq!(child_source.unwrap().to_string(), "child source");

    // Child without source
    let child_without_source = children[1].as_ref();
    let no_source = child_without_source.context_source();
    assert!(no_source.is_none());

    // Child that ignores source (custom handler)
    let child_ignore_source = children[2].as_ref();
    let ignored_source = child_ignore_source.context_source();
    assert!(ignored_source.is_none()); // Handler ignores source

    // Check display formats
    let ignore_display = format!("{}", TestReportDisplayWrapper(child_ignore_source));
    assert_eq!(ignore_display, "[NO_SOURCE] child ignores source");
}

#[test]
fn test_raw_report_mut_modification_correctness() {
    // Test that mutable operations result in correct final state
    let mut report = RawReport::new::<_, DefaultContextHandler>(
        TestError::new("modification test"),
        Vec::new(),
        Vec::new(),
    );

    unsafe {
        // Perform multiple modifications
        let mut report_mut = report.as_mut();

        // Add children
        let children_mut = report_mut.reborrow().into_children_mut();
        children_mut.push(RawReport::new::<_, DefaultContextHandler>(
            TestError::new("child"),
            Vec::new(),
            Vec::new(),
        ));

        // Add attachments
        let attachments_mut = report_mut.reborrow().into_attachments_mut();
        attachments_mut.push(RawAttachment::new::<_, DefaultAttachmentHandler>(
            TestAttachment::new("attachment", 123),
        ));
    }

    // Verify final state
    let final_ref = report.as_ref();
    assert_eq!(final_ref.children().len(), 1);
    assert_eq!(final_ref.attachments().len(), 1);

    // Verify content is correct
    let child_display = format!(
        "{}",
        TestReportDisplayWrapper(final_ref.children()[0].as_ref())
    );
    assert_eq!(child_display, "child");

    let attachment = final_ref.attachments()[0].as_ref();
    assert_eq!(
        attachment.attachment_type_id(),
        core::any::TypeId::of::<TestAttachment>()
    );
    let attachment_downcast =
        unsafe { attachment.attachment_downcast_unchecked::<TestAttachment>() };
    assert_eq!(attachment_downcast.name, "attachment");
    assert_eq!(attachment_downcast.value, 123);
}

#[test]
fn test_raw_report_mut_context_downcast_unchecked() {
    // Test the unsafe context_downcast_unchecked method for RawReportMut
    let mut test_error_report = RawReport::new::<_, DefaultContextHandler>(
        TestError::new("mutable context test"),
        Vec::new(),
        Vec::new(),
    );

    let mut string_report = RawReport::new::<_, StringContextHandler>(
        "mutable string context".to_owned(),
        Vec::new(),
        Vec::new(),
    );

    let mut number_report =
        RawReport::new::<_, NumberContextHandler>(99i32, Vec::new(), Vec::new());

    unsafe {
        // Test with TestError context
        let error_mut = test_error_report.as_mut();
        let error_context = error_mut.into_context_downcast_unchecked::<TestError>();
        assert_eq!(error_context.message, "mutable context test");
        assert!(error_context.source.is_none());

        // Modify the context through the mutable reference
        error_context.message = "modified error message".to_owned();
        error_context.source = Some(Box::new(TestError::new("nested error")));

        // Test with String context
        let string_mut = string_report.as_mut();
        let string_context = string_mut.into_context_downcast_unchecked::<String>();
        assert_eq!(string_context, "mutable string context");

        // Modify the string context
        *string_context = "modified string".to_owned();

        // Test with i32 context
        let number_mut = number_report.as_mut();
        let number_context = number_mut.into_context_downcast_unchecked::<i32>();
        assert_eq!(*number_context, 99);

        // Modify the number context
        *number_context = 42;
    }

    // Verify modifications were applied correctly
    let error_ref = test_error_report.as_ref();
    assert_eq!(
        error_ref.context_type_id(),
        core::any::TypeId::of::<TestError>()
    );
    let modified_error = unsafe { error_ref.context_downcast_unchecked::<TestError>() };
    assert_eq!(modified_error.message, "modified error message");
    assert!(modified_error.source.is_some());
    let nested_error = modified_error.source.as_ref().unwrap();
    assert_eq!(format!("{nested_error}"), "nested error");

    let string_ref = string_report.as_ref();
    assert_eq!(
        string_ref.context_type_id(),
        core::any::TypeId::of::<String>()
    );
    let modified_string = unsafe { string_ref.context_downcast_unchecked::<String>() };
    assert_eq!(modified_string, "modified string");

    let number_ref = number_report.as_ref();
    assert_eq!(number_ref.context_type_id(), core::any::TypeId::of::<i32>());
    let modified_number = unsafe { number_ref.context_downcast_unchecked::<i32>() };
    assert_eq!(*modified_number, 42);

    // Test that display still works correctly after modifications
    let error_display = format!("{}", TestReportDisplayWrapper(error_ref));
    assert_eq!(error_display, "modified error message");

    let string_display = format!("{}", TestReportDisplayWrapper(string_ref));
    assert_eq!(string_display, "modified string");

    let number_display = format!("{}", TestReportDisplayWrapper(number_ref));
    assert_eq!(number_display, "42");
}