aprender-test-lib 0.31.1

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

use std::collections::VecDeque;
use std::fmt;
use std::time::{Duration, Instant};

// =============================================================================
// VU Meter Configuration (Section 2.4)
// =============================================================================

/// VU meter validation parameters
///
/// # Example
/// ```
/// use jugar_probar::validators::VuMeterConfig;
///
/// let config = VuMeterConfig::default()
///     .with_min_level(0.1)
///     .with_update_rate_hz(30.0);
/// ```
#[derive(Debug, Clone)]
pub struct VuMeterConfig {
    /// Minimum expected level (0.0-1.0)
    pub min_level: f32,
    /// Maximum expected level (0.0-1.0)
    pub max_level: f32,
    /// Update frequency (Hz)
    pub update_rate_hz: f32,
    /// Smoothing factor validation tolerance
    pub smoothing_tolerance: f32,
    /// Maximum time without updates (staleness)
    pub max_stale_ms: u64,
}

impl Default for VuMeterConfig {
    fn default() -> Self {
        Self {
            min_level: 0.0,
            max_level: 1.0,
            update_rate_hz: 30.0,
            smoothing_tolerance: 0.1,
            max_stale_ms: 100,
        }
    }
}

impl VuMeterConfig {
    /// Set minimum expected level
    #[must_use]
    pub fn with_min_level(mut self, level: f32) -> Self {
        self.min_level = level.clamp(0.0, 1.0);
        self
    }

    /// Set maximum expected level
    #[must_use]
    pub fn with_max_level(mut self, level: f32) -> Self {
        self.max_level = level.clamp(0.0, 1.0);
        self
    }

    /// Set expected update rate in Hz
    #[must_use]
    pub fn with_update_rate_hz(mut self, rate: f32) -> Self {
        self.update_rate_hz = rate.max(1.0);
        self
    }

    /// Set staleness threshold
    #[must_use]
    pub fn with_max_stale_ms(mut self, ms: u64) -> Self {
        self.max_stale_ms = ms;
        self
    }

    /// Validate a VU meter sample
    pub fn validate_sample(&self, level: f32) -> Result<(), VuMeterError> {
        if level < 0.0 {
            return Err(VuMeterError::NegativeLevel(level));
        }
        if level > self.max_level + self.smoothing_tolerance {
            return Err(VuMeterError::Clipping(level));
        }
        Ok(())
    }
}

/// VU meter validation error
#[derive(Debug, Clone)]
pub enum VuMeterError {
    /// Level is negative
    NegativeLevel(f32),
    /// Level exceeds maximum (clipping)
    Clipping(f32),
    /// Updates are stale
    Stale {
        /// Last update timestamp
        last_update_ms: u64,
        /// Current timestamp
        current_ms: u64,
    },
    /// Update rate too slow
    SlowUpdateRate {
        /// Measured rate
        measured_hz: f32,
        /// Expected rate
        expected_hz: f32,
    },
    /// Constant value detected (not animating)
    NotAnimating {
        /// Number of samples
        sample_count: usize,
        /// Constant value
        value: f32,
    },
}

impl fmt::Display for VuMeterError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NegativeLevel(v) => write!(f, "VU meter level is negative: {v}"),
            Self::Clipping(v) => write!(f, "VU meter clipping at: {v}"),
            Self::Stale {
                last_update_ms,
                current_ms,
            } => {
                write!(
                    f,
                    "VU meter stale: last update {}ms ago",
                    current_ms - last_update_ms
                )
            }
            Self::SlowUpdateRate {
                measured_hz,
                expected_hz,
            } => {
                write!(
                    f,
                    "VU meter update rate too slow: {measured_hz:.1}Hz < {expected_hz:.1}Hz"
                )
            }
            Self::NotAnimating {
                sample_count,
                value,
            } => {
                write!(
                    f,
                    "VU meter not animating: {sample_count} samples all at {value}"
                )
            }
        }
    }
}

impl std::error::Error for VuMeterError {}

// =============================================================================
// State Transition Tracking (Section 2.4)
// =============================================================================

/// State transition event with timing
#[derive(Debug, Clone)]
pub struct StateTransition {
    /// Previous state
    pub from: String,
    /// New state
    pub to: String,
    /// Timestamp of transition (ms since start)
    pub timestamp_ms: f64,
    /// Duration in previous state (ms)
    pub duration_ms: f64,
}

/// Partial transcription result
#[derive(Debug, Clone)]
pub struct PartialResult {
    /// Timestamp (ms since start)
    pub timestamp_ms: f64,
    /// Partial text content
    pub text: String,
    /// Whether this is the final result
    pub is_final: bool,
}

/// VU meter sample
#[derive(Debug, Clone)]
pub struct VuMeterSample {
    /// Timestamp (ms since start)
    pub timestamp_ms: f64,
    /// Level (0.0-1.0)
    pub level: f32,
}

// =============================================================================
// Test Execution Stats (Section 5.1 - trueno-zram integration)
// =============================================================================

/// Test execution statistics with compression metrics
///
/// Tracks game state capture efficiency during test runs.
/// Based on trueno-zram compression statistics patterns.
///
/// # Example
/// ```
/// use jugar_probar::validators::TestExecutionStats;
///
/// let mut stats = TestExecutionStats::new();
/// stats.record_state_capture(4096, 1024);
/// stats.record_state_capture(4096, 512); // Same-fill page
///
/// assert!(stats.efficiency() > 0.5);
/// ```
#[derive(Debug, Clone, Default)]
pub struct TestExecutionStats {
    /// Total game states captured
    pub states_captured: u64,
    /// Bytes before compression
    pub bytes_raw: u64,
    /// Bytes after compression
    pub bytes_compressed: u64,
    /// Same-fill pages detected (high compression)
    pub same_fill_pages: u64,
    /// Start time (for throughput calculation)
    start_time: Option<Instant>,
    /// End time (for throughput calculation)
    end_time: Option<Instant>,
}

impl TestExecutionStats {
    /// Create new stats tracker
    #[must_use]
    pub fn new() -> Self {
        Self {
            states_captured: 0,
            bytes_raw: 0,
            bytes_compressed: 0,
            same_fill_pages: 0,
            start_time: None,
            end_time: None,
        }
    }

    /// Start tracking
    pub fn start(&mut self) {
        self.start_time = Some(Instant::now());
    }

    /// Stop tracking
    pub fn stop(&mut self) {
        self.end_time = Some(Instant::now());
    }

    /// Record a state capture
    pub fn record_state_capture(&mut self, raw_bytes: u64, compressed_bytes: u64) {
        self.states_captured += 1;
        self.bytes_raw += raw_bytes;
        self.bytes_compressed += compressed_bytes;

        // Detect same-fill pages (>90% compression = likely uniform data)
        if raw_bytes > 0 && (compressed_bytes as f64 / raw_bytes as f64) < 0.1 {
            self.same_fill_pages += 1;
        }
    }

    /// Calculate compression ratio (raw / compressed)
    #[must_use]
    pub fn compression_ratio(&self) -> f64 {
        if self.bytes_compressed == 0 {
            return 0.0;
        }
        self.bytes_raw as f64 / self.bytes_compressed as f64
    }

    /// Calculate compression efficiency (1 - compressed/raw)
    #[must_use]
    pub fn efficiency(&self) -> f64 {
        if self.bytes_raw == 0 {
            return 0.0;
        }
        1.0 - (self.bytes_compressed as f64 / self.bytes_raw as f64)
    }

    /// Estimate storage savings in MB
    #[must_use]
    pub fn storage_savings_mb(&self) -> f64 {
        (self.bytes_raw.saturating_sub(self.bytes_compressed)) as f64 / 1_000_000.0
    }

    /// Calculate compression throughput (bytes/sec)
    #[must_use]
    pub fn compress_throughput(&self) -> f64 {
        match (self.start_time, self.end_time) {
            (Some(start), Some(end)) => {
                let duration_secs = end.duration_since(start).as_secs_f64();
                if duration_secs > 0.0 {
                    self.bytes_raw as f64 / duration_secs
                } else {
                    0.0
                }
            }
            _ => 0.0,
        }
    }

    /// Get same-fill page ratio
    #[must_use]
    pub fn same_fill_ratio(&self) -> f64 {
        if self.states_captured == 0 {
            return 0.0;
        }
        self.same_fill_pages as f64 / self.states_captured as f64
    }

    /// Reset statistics
    pub fn reset(&mut self) {
        self.states_captured = 0;
        self.bytes_raw = 0;
        self.bytes_compressed = 0;
        self.same_fill_pages = 0;
        self.start_time = None;
        self.end_time = None;
    }
}

// =============================================================================
// Screenshot Content Classifier (Section 5.2)
// =============================================================================

/// Compression algorithm recommendation
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompressionAlgorithm {
    /// LZ4 for speed (UI-heavy content)
    Lz4,
    /// Zstd for balanced speed/ratio
    Zstd,
    /// PNG for lossless images
    Png,
    /// RLE for uniform content
    Rle,
}

/// Screenshot content classification for optimal compression
///
/// Based on entropy analysis to determine best compression strategy.
///
/// # Example
/// ```
/// use jugar_probar::validators::ScreenshotContent;
///
/// // Simulate UI-heavy screenshot (low entropy)
/// let pixels: Vec<u8> = vec![255; 1000]; // Uniform white
/// let content = ScreenshotContent::classify(&pixels);
///
/// assert!(matches!(content, ScreenshotContent::Uniform { .. }));
/// ```
#[derive(Debug, Clone)]
pub enum ScreenshotContent {
    /// UI-heavy (text, buttons) - high compressibility
    UiDominated {
        /// Shannon entropy (0.0-8.0 for bytes)
        entropy: f32,
    },
    /// Physics/game world - medium compressibility
    GameWorld {
        /// Shannon entropy
        entropy: f32,
    },
    /// Random/noise - low compressibility
    HighEntropy {
        /// Shannon entropy
        entropy: f32,
    },
    /// Mostly uniform - very high compressibility (same-fill)
    Uniform {
        /// Dominant fill value
        fill_value: u8,
    },
}

impl ScreenshotContent {
    /// Classify screenshot by entropy analysis
    ///
    /// Uses Shannon entropy to determine content type.
    #[must_use]
    pub fn classify(pixels: &[u8]) -> Self {
        if pixels.is_empty() {
            return Self::Uniform { fill_value: 0 };
        }

        // Count byte frequencies
        let mut frequencies = [0u64; 256];
        for &byte in pixels {
            frequencies[byte as usize] += 1;
        }

        // Check for uniform content (>95% same value)
        let total = pixels.len() as f64;
        let (max_idx, max_count) = frequencies
            .iter()
            .enumerate()
            .max_by_key(|(_, &count)| count)
            .map(|(idx, &count)| (idx, count))
            .unwrap_or((0, 0));

        if max_count as f64 / total > 0.95 {
            return Self::Uniform {
                fill_value: max_idx as u8,
            };
        }

        // Calculate Shannon entropy
        let entropy: f32 = frequencies
            .iter()
            .filter(|&&count| count > 0)
            .map(|&count| {
                let p = count as f64 / total;
                -(p * p.log2()) as f32
            })
            .sum();

        // Classify based on entropy thresholds
        if entropy < 3.0 {
            Self::UiDominated { entropy }
        } else if entropy < 6.0 {
            Self::GameWorld { entropy }
        } else {
            Self::HighEntropy { entropy }
        }
    }

    /// Get entropy value
    #[must_use]
    pub fn entropy(&self) -> f32 {
        match self {
            Self::UiDominated { entropy }
            | Self::GameWorld { entropy }
            | Self::HighEntropy { entropy } => *entropy,
            Self::Uniform { .. } => 0.0,
        }
    }

    /// Recommended compression algorithm based on content type
    #[must_use]
    pub fn recommended_algorithm(&self) -> CompressionAlgorithm {
        match self {
            Self::Uniform { .. } => CompressionAlgorithm::Rle,
            Self::UiDominated { .. } => CompressionAlgorithm::Png,
            Self::GameWorld { .. } => CompressionAlgorithm::Zstd,
            Self::HighEntropy { .. } => CompressionAlgorithm::Lz4,
        }
    }

    /// Expected compression ratio hint
    #[must_use]
    pub fn expected_ratio_hint(&self) -> &'static str {
        match self {
            Self::Uniform { .. } => "excellent (>100:1)",
            Self::UiDominated { .. } => "good (5:1 - 20:1)",
            Self::GameWorld { .. } => "moderate (2:1 - 5:1)",
            Self::HighEntropy { .. } => "poor (<2:1)",
        }
    }
}

/// Streaming UX validator for real-time audio/video interfaces
///
/// # Example
/// ```
/// use std::time::Duration;
/// use jugar_probar::validators::{StreamingUxValidator, StreamingMetric};
///
/// let mut validator = StreamingUxValidator::new()
///     .with_max_latency(Duration::from_millis(100))
///     .with_buffer_underrun_threshold(3);
///
/// // Simulate streaming metrics
/// validator.record_metric(StreamingMetric::Latency(Duration::from_millis(50)));
/// validator.record_metric(StreamingMetric::FrameRendered { timestamp: 1000 });
///
/// assert!(validator.validate().is_ok());
/// ```
#[derive(Debug, Clone)]
pub struct StreamingUxValidator {
    /// Maximum acceptable latency
    max_latency: Duration,
    /// Maximum buffer underrun count threshold
    buffer_underrun_threshold: usize,
    /// Maximum consecutive dropped frames
    max_dropped_frames: usize,
    /// Minimum frames per second
    min_fps: f64,
    /// Time-to-first-byte timeout
    ttfb_timeout: Duration,
    /// Recorded metrics
    metrics: Vec<StreamingMetricRecord>,
    /// Buffer underrun count
    buffer_underruns: usize,
    /// Dropped frame count
    dropped_frames: usize,
    /// Frame timestamps for FPS calculation
    frame_times: VecDeque<u64>,
    /// First byte received time
    first_byte_time: Option<Instant>,
    /// Start time
    start_time: Option<Instant>,
    /// State machine state
    state: StreamingState,
    /// State transition history
    state_history: Vec<(StreamingState, Instant)>,
}

/// Streaming metric record with timestamp
#[derive(Debug, Clone)]
pub struct StreamingMetricRecord {
    /// The metric
    pub metric: StreamingMetric,
    /// When recorded
    pub timestamp: Instant,
}

/// Streaming metrics to record
#[derive(Debug, Clone)]
pub enum StreamingMetric {
    /// Latency measurement
    Latency(Duration),
    /// Frame rendered with timestamp
    FrameRendered {
        /// Frame timestamp in milliseconds
        timestamp: u64,
    },
    /// Frame dropped
    FrameDropped,
    /// Buffer underrun occurred
    BufferUnderrun,
    /// First byte received
    FirstByteReceived,
    /// Buffer level percentage
    BufferLevel(f32),
    /// Audio chunk processed
    AudioChunk {
        /// Sample count
        samples: usize,
        /// Sample rate
        sample_rate: u32,
    },
}

/// Streaming state machine states
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum StreamingState {
    /// Initial state
    Idle,
    /// Loading/buffering
    Buffering,
    /// Actively streaming
    Streaming,
    /// Stalled (buffer underrun)
    Stalled,
    /// Error state
    Error,
    /// Completed
    Completed,
}

impl Default for StreamingState {
    fn default() -> Self {
        Self::Idle
    }
}

impl fmt::Display for StreamingState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Idle => write!(f, "Idle"),
            Self::Buffering => write!(f, "Buffering"),
            Self::Streaming => write!(f, "Streaming"),
            Self::Stalled => write!(f, "Stalled"),
            Self::Error => write!(f, "Error"),
            Self::Completed => write!(f, "Completed"),
        }
    }
}

/// Streaming validation error
#[derive(Debug, Clone)]
pub enum StreamingValidationError {
    /// Latency exceeded threshold
    LatencyExceeded {
        /// Measured latency
        measured: Duration,
        /// Maximum allowed
        max: Duration,
    },
    /// Too many buffer underruns
    BufferUnderrunThreshold {
        /// Number of underruns
        count: usize,
        /// Threshold
        threshold: usize,
    },
    /// Too many dropped frames
    DroppedFrameThreshold {
        /// Number of dropped frames
        count: usize,
        /// Maximum allowed
        max: usize,
    },
    /// FPS below minimum
    FpsBelowMinimum {
        /// Measured FPS
        measured: f64,
        /// Minimum required
        min: f64,
    },
    /// Time to first byte exceeded
    TtfbExceeded {
        /// Measured TTFB
        measured: Duration,
        /// Maximum allowed
        max: Duration,
    },
    /// Invalid state transition
    InvalidStateTransition {
        /// From state
        from: StreamingState,
        /// To state
        to: StreamingState,
    },
    /// State machine ended in error state
    EndedInError,
}

impl fmt::Display for StreamingValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::LatencyExceeded { measured, max } => {
                write!(f, "Latency exceeded: {measured:?} > {max:?} (max allowed)")
            }
            Self::BufferUnderrunThreshold { count, threshold } => {
                write!(
                    f,
                    "Buffer underruns exceeded threshold: {count} > {threshold}"
                )
            }
            Self::DroppedFrameThreshold { count, max } => {
                write!(f, "Dropped frames exceeded: {count} > {max} (max allowed)")
            }
            Self::FpsBelowMinimum { measured, min } => {
                write!(f, "FPS below minimum: {measured:.1} < {min:.1} (required)")
            }
            Self::TtfbExceeded { measured, max } => {
                write!(
                    f,
                    "Time to first byte exceeded: {measured:?} > {max:?} (max allowed)"
                )
            }
            Self::InvalidStateTransition { from, to } => {
                write!(f, "Invalid state transition: {from} -> {to}")
            }
            Self::EndedInError => write!(f, "Streaming ended in error state"),
        }
    }
}

impl std::error::Error for StreamingValidationError {}

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

impl StreamingUxValidator {
    /// Create a new streaming UX validator with sensible defaults
    #[must_use]
    pub fn new() -> Self {
        Self {
            max_latency: Duration::from_millis(200),
            buffer_underrun_threshold: 5,
            max_dropped_frames: 10,
            min_fps: 24.0,
            ttfb_timeout: Duration::from_secs(3),
            metrics: Vec::new(),
            buffer_underruns: 0,
            dropped_frames: 0,
            frame_times: VecDeque::with_capacity(120),
            first_byte_time: None,
            start_time: None,
            state: StreamingState::Idle,
            state_history: Vec::new(),
        }
    }

    /// Create validator for real-time audio streaming
    #[must_use]
    pub fn for_audio() -> Self {
        Self::new()
            .with_max_latency(Duration::from_millis(100))
            .with_buffer_underrun_threshold(3)
            .with_ttfb_timeout(Duration::from_secs(2))
    }

    /// Create validator for video streaming
    #[must_use]
    pub fn for_video() -> Self {
        Self::new()
            .with_max_latency(Duration::from_millis(500))
            .with_min_fps(30.0)
            .with_max_dropped_frames(5)
    }

    /// Set maximum acceptable latency
    #[must_use]
    pub fn with_max_latency(mut self, latency: Duration) -> Self {
        self.max_latency = latency;
        self
    }

    /// Set buffer underrun threshold
    #[must_use]
    pub fn with_buffer_underrun_threshold(mut self, threshold: usize) -> Self {
        self.buffer_underrun_threshold = threshold;
        self
    }

    /// Set maximum dropped frames
    #[must_use]
    pub fn with_max_dropped_frames(mut self, max: usize) -> Self {
        self.max_dropped_frames = max;
        self
    }

    /// Set minimum FPS
    #[must_use]
    pub fn with_min_fps(mut self, fps: f64) -> Self {
        self.min_fps = fps;
        self
    }

    /// Set time-to-first-byte timeout
    #[must_use]
    pub fn with_ttfb_timeout(mut self, timeout: Duration) -> Self {
        self.ttfb_timeout = timeout;
        self
    }

    /// Start streaming validation
    pub fn start(&mut self) {
        self.start_time = Some(Instant::now());
        self.transition_to(StreamingState::Buffering);
    }

    /// Record a streaming metric
    pub fn record_metric(&mut self, metric: StreamingMetric) {
        let now = Instant::now();

        match &metric {
            StreamingMetric::Latency(latency) => {
                // Latency recorded - check if streaming
                if self.state == StreamingState::Buffering && *latency < self.max_latency {
                    self.transition_to(StreamingState::Streaming);
                }
            }
            StreamingMetric::FrameRendered { timestamp } => {
                self.frame_times.push_back(*timestamp);
                // Keep only last 120 frames (4 seconds at 30fps)
                while self.frame_times.len() > 120 {
                    self.frame_times.pop_front();
                }
                // If streaming, we're healthy
                if self.state == StreamingState::Stalled {
                    self.transition_to(StreamingState::Streaming);
                }
            }
            StreamingMetric::FrameDropped => {
                self.dropped_frames += 1;
            }
            StreamingMetric::BufferUnderrun => {
                self.buffer_underruns += 1;
                if self.state == StreamingState::Streaming {
                    self.transition_to(StreamingState::Stalled);
                }
            }
            StreamingMetric::FirstByteReceived => {
                self.first_byte_time = Some(now);
                if self.state == StreamingState::Idle {
                    self.transition_to(StreamingState::Buffering);
                }
            }
            StreamingMetric::BufferLevel(level) => {
                // Low buffer level indicates potential stall
                if *level < 0.1 && self.state == StreamingState::Streaming {
                    self.transition_to(StreamingState::Stalled);
                } else if *level > 0.3 && self.state == StreamingState::Stalled {
                    self.transition_to(StreamingState::Streaming);
                }
            }
            StreamingMetric::AudioChunk { .. } => {
                // Audio chunk received - mark streaming active
                if self.state == StreamingState::Buffering {
                    self.transition_to(StreamingState::Streaming);
                }
            }
        }

        self.metrics.push(StreamingMetricRecord {
            metric,
            timestamp: now,
        });
    }

    /// Transition to a new state
    fn transition_to(&mut self, new_state: StreamingState) {
        if self.state != new_state {
            self.state_history.push((self.state, Instant::now()));
            self.state = new_state;
        }
    }

    /// Mark streaming as completed
    pub fn complete(&mut self) {
        self.transition_to(StreamingState::Completed);
    }

    /// Mark streaming as errored
    pub fn error(&mut self) {
        self.transition_to(StreamingState::Error);
    }

    /// Get current state
    #[must_use]
    pub fn state(&self) -> StreamingState {
        self.state
    }

    /// Get buffer underrun count
    #[must_use]
    pub fn buffer_underruns(&self) -> usize {
        self.buffer_underruns
    }

    /// Get dropped frame count
    #[must_use]
    pub fn dropped_frames(&self) -> usize {
        self.dropped_frames
    }

    /// Calculate average FPS from recorded frames
    #[must_use]
    pub fn average_fps(&self) -> f64 {
        if self.frame_times.len() < 2 {
            return 0.0;
        }

        let first = *self.frame_times.front().unwrap_or(&0);
        let last = *self.frame_times.back().unwrap_or(&0);
        let duration_ms = last.saturating_sub(first);

        if duration_ms == 0 {
            return 0.0;
        }

        let frame_count = self.frame_times.len() - 1;
        (frame_count as f64 * 1000.0) / duration_ms as f64
    }

    /// Validate all recorded metrics
    ///
    /// # Errors
    /// Returns validation error if any threshold is exceeded.
    pub fn validate(&self) -> Result<StreamingValidationResult, StreamingValidationError> {
        let mut errors = Vec::new();

        // Check latency metrics
        for record in &self.metrics {
            if let StreamingMetric::Latency(latency) = &record.metric {
                if *latency > self.max_latency {
                    errors.push(StreamingValidationError::LatencyExceeded {
                        measured: *latency,
                        max: self.max_latency,
                    });
                }
            }
        }

        // Check buffer underruns
        if self.buffer_underruns > self.buffer_underrun_threshold {
            errors.push(StreamingValidationError::BufferUnderrunThreshold {
                count: self.buffer_underruns,
                threshold: self.buffer_underrun_threshold,
            });
        }

        // Check dropped frames
        if self.dropped_frames > self.max_dropped_frames {
            errors.push(StreamingValidationError::DroppedFrameThreshold {
                count: self.dropped_frames,
                max: self.max_dropped_frames,
            });
        }

        // Check FPS
        let fps = self.average_fps();
        if fps > 0.0 && fps < self.min_fps {
            errors.push(StreamingValidationError::FpsBelowMinimum {
                measured: fps,
                min: self.min_fps,
            });
        }

        // Check TTFB
        if let (Some(start), Some(first_byte)) = (self.start_time, self.first_byte_time) {
            let ttfb = first_byte.duration_since(start);
            if ttfb > self.ttfb_timeout {
                errors.push(StreamingValidationError::TtfbExceeded {
                    measured: ttfb,
                    max: self.ttfb_timeout,
                });
            }
        }

        // Check final state
        if self.state == StreamingState::Error {
            errors.push(StreamingValidationError::EndedInError);
        }

        if errors.is_empty() {
            Ok(StreamingValidationResult {
                buffer_underruns: self.buffer_underruns,
                dropped_frames: self.dropped_frames,
                average_fps: fps,
                max_latency_recorded: self.max_recorded_latency(),
                total_frames: self.frame_times.len(),
            })
        } else {
            Err(errors.remove(0))
        }
    }

    /// Get all validation errors (for comprehensive reporting)
    #[must_use]
    pub fn validate_all(&self) -> Vec<StreamingValidationError> {
        let mut errors = Vec::new();

        for record in &self.metrics {
            if let StreamingMetric::Latency(latency) = &record.metric {
                if *latency > self.max_latency {
                    errors.push(StreamingValidationError::LatencyExceeded {
                        measured: *latency,
                        max: self.max_latency,
                    });
                }
            }
        }

        if self.buffer_underruns > self.buffer_underrun_threshold {
            errors.push(StreamingValidationError::BufferUnderrunThreshold {
                count: self.buffer_underruns,
                threshold: self.buffer_underrun_threshold,
            });
        }

        if self.dropped_frames > self.max_dropped_frames {
            errors.push(StreamingValidationError::DroppedFrameThreshold {
                count: self.dropped_frames,
                max: self.max_dropped_frames,
            });
        }

        let fps = self.average_fps();
        if fps > 0.0 && fps < self.min_fps {
            errors.push(StreamingValidationError::FpsBelowMinimum {
                measured: fps,
                min: self.min_fps,
            });
        }

        if self.state == StreamingState::Error {
            errors.push(StreamingValidationError::EndedInError);
        }

        errors
    }

    /// Get maximum recorded latency
    fn max_recorded_latency(&self) -> Duration {
        self.metrics
            .iter()
            .filter_map(|r| {
                if let StreamingMetric::Latency(l) = &r.metric {
                    Some(*l)
                } else {
                    None
                }
            })
            .max()
            .unwrap_or(Duration::ZERO)
    }

    /// Get state history for debugging
    #[must_use]
    pub fn state_history(&self) -> &[(StreamingState, Instant)] {
        &self.state_history
    }

    /// Reset validator for reuse
    pub fn reset(&mut self) {
        self.metrics.clear();
        self.buffer_underruns = 0;
        self.dropped_frames = 0;
        self.frame_times.clear();
        self.first_byte_time = None;
        self.start_time = None;
        self.state = StreamingState::Idle;
        self.state_history.clear();
    }
}

/// Successful validation result
#[derive(Debug, Clone)]
pub struct StreamingValidationResult {
    /// Number of buffer underruns
    pub buffer_underruns: usize,
    /// Number of dropped frames
    pub dropped_frames: usize,
    /// Average FPS
    pub average_fps: f64,
    /// Maximum latency recorded
    pub max_latency_recorded: Duration,
    /// Total frames processed
    pub total_frames: usize,
}

// CDP-based streaming UX tracking (PROBAR-SPEC-011)
#[cfg(feature = "browser")]
impl StreamingUxValidator {
    /// Track state changes on element via CDP
    ///
    /// Sets up a MutationObserver to watch for text content changes
    /// on the specified element and records state transitions.
    ///
    /// # Errors
    /// Returns error if CDP injection fails or element not found.
    pub async fn track_state_cdp(
        page: &chromiumoxide::Page,
        selector: &str,
    ) -> Result<Self, StreamingValidationError> {
        // Inject MutationObserver to track text changes
        let js = format!(
            r#"
            (function() {{
                window.__probar_state_history = [];
                window.__probar_start_time = performance.now();
                window.__probar_last_state = '';

                const el = document.querySelector('{}');
                if (!el) {{
                    return {{ error: 'Element not found: {}' }};
                }}

                const observer = new MutationObserver((mutations) => {{
                    const newState = el.textContent || el.innerText || '';
                    if (newState !== window.__probar_last_state) {{
                        const now = performance.now();
                        const elapsed = now - window.__probar_start_time;
                        window.__probar_state_history.push({{
                            from: window.__probar_last_state,
                            to: newState,
                            timestamp: elapsed,
                        }});
                        window.__probar_last_state = newState;
                    }}
                }});

                observer.observe(el, {{
                    characterData: true,
                    childList: true,
                    subtree: true
                }});

                window.__probar_state_observer = observer;
                return {{ success: true }};
            }})()
            "#,
            selector, selector
        );

        let _: serde_json::Value = page
            .evaluate(js)
            .await
            .map_err(|_e| StreamingValidationError::InvalidStateTransition {
                from: StreamingState::Idle,
                to: StreamingState::Error,
            })?
            .into_value()
            .map_err(|_| StreamingValidationError::InvalidStateTransition {
                from: StreamingState::Idle,
                to: StreamingState::Error,
            })?;

        Ok(Self::new())
    }

    /// Track VU meter levels via CDP
    ///
    /// Sets up an animation frame loop to sample VU meter values
    /// from the specified element's width, height, or data attribute.
    ///
    /// # Errors
    /// Returns error if CDP injection fails.
    pub async fn track_vu_meter_cdp(
        &mut self,
        page: &chromiumoxide::Page,
        selector: &str,
    ) -> Result<(), StreamingValidationError> {
        let js = format!(
            r#"
            (function() {{
                window.__probar_vu_samples = [];
                window.__probar_vu_start_time = performance.now();

                const el = document.querySelector('{}');
                if (!el) {{
                    return {{ error: 'VU meter element not found: {}' }};
                }}

                function sampleVu() {{
                    const elapsed = performance.now() - window.__probar_vu_start_time;
                    // Try to get level from data attribute, width, or computed style
                    let level = parseFloat(el.dataset.level) || 0;
                    if (!level) {{
                        const style = getComputedStyle(el);
                        const widthPct = parseFloat(style.width) / parseFloat(style.maxWidth || 100);
                        level = isNaN(widthPct) ? 0 : widthPct;
                    }}
                    window.__probar_vu_samples.push([elapsed, level]);

                    if (window.__probar_vu_running) {{
                        requestAnimationFrame(sampleVu);
                    }}
                }}

                window.__probar_vu_running = true;
                requestAnimationFrame(sampleVu);
                return {{ success: true }};
            }})()
            "#,
            selector, selector
        );

        let _: serde_json::Value = page
            .evaluate(js)
            .await
            .map_err(|_| StreamingValidationError::EndedInError)?
            .into_value()
            .map_err(|_| StreamingValidationError::EndedInError)?;

        Ok(())
    }

    /// Track partial transcription results via CDP
    ///
    /// Watches for text content changes on the specified element
    /// and records partial results with timestamps.
    ///
    /// # Errors
    /// Returns error if CDP injection fails.
    pub async fn track_partials_cdp(
        &mut self,
        page: &chromiumoxide::Page,
        selector: &str,
    ) -> Result<(), StreamingValidationError> {
        let js = format!(
            r#"
            (function() {{
                window.__probar_partials = [];
                window.__probar_partials_start = performance.now();
                window.__probar_last_partial = '';

                const el = document.querySelector('{}');
                if (!el) {{
                    return {{ error: 'Partial results element not found: {}' }};
                }}

                const observer = new MutationObserver((mutations) => {{
                    const text = el.textContent || el.innerText || '';
                    if (text !== window.__probar_last_partial) {{
                        const elapsed = performance.now() - window.__probar_partials_start;
                        window.__probar_partials.push([elapsed, text]);
                        window.__probar_last_partial = text;
                    }}
                }});

                observer.observe(el, {{
                    characterData: true,
                    childList: true,
                    subtree: true
                }});

                window.__probar_partials_observer = observer;
                return {{ success: true }};
            }})()
            "#,
            selector, selector
        );

        let _: serde_json::Value = page
            .evaluate(js)
            .await
            .map_err(|_| StreamingValidationError::EndedInError)?
            .into_value()
            .map_err(|_| StreamingValidationError::EndedInError)?;

        Ok(())
    }

    /// Collect state history from browser
    ///
    /// # Errors
    /// Returns error if CDP call fails.
    pub async fn collect_state_history_cdp(
        &self,
        page: &chromiumoxide::Page,
    ) -> Result<Vec<StateTransition>, StreamingValidationError> {
        let js = r#"
            (function() {
                const history = window.__probar_state_history || [];
                return history.map((h, i, arr) => ({
                    from: h.from,
                    to: h.to,
                    timestamp: h.timestamp,
                    duration_ms: i < arr.length - 1 ? arr[i + 1].timestamp - h.timestamp : 0
                }));
            })()
        "#;

        let result: Vec<serde_json::Value> = page
            .evaluate(js)
            .await
            .map_err(|_| StreamingValidationError::EndedInError)?
            .into_value()
            .map_err(|_| StreamingValidationError::EndedInError)?;

        Ok(result
            .into_iter()
            .map(|v| StateTransition {
                from: v["from"].as_str().unwrap_or("").to_string(),
                to: v["to"].as_str().unwrap_or("").to_string(),
                timestamp_ms: v["timestamp"].as_f64().unwrap_or(0.0),
                duration_ms: v["duration_ms"].as_f64().unwrap_or(0.0),
            })
            .collect())
    }

    /// Collect VU meter samples from browser
    ///
    /// # Errors
    /// Returns error if CDP call fails.
    pub async fn collect_vu_samples_cdp(
        &self,
        page: &chromiumoxide::Page,
    ) -> Result<Vec<VuMeterSample>, StreamingValidationError> {
        // Stop sampling
        let _: serde_json::Value = page
            .evaluate("window.__probar_vu_running = false; true")
            .await
            .map_err(|_| StreamingValidationError::EndedInError)?
            .into_value()
            .map_err(|_| StreamingValidationError::EndedInError)?;

        let js = "window.__probar_vu_samples || []";
        let result: Vec<Vec<f64>> = page
            .evaluate(js)
            .await
            .map_err(|_| StreamingValidationError::EndedInError)?
            .into_value()
            .map_err(|_| StreamingValidationError::EndedInError)?;

        Ok(result
            .into_iter()
            .map(|arr| VuMeterSample {
                timestamp_ms: arr.first().copied().unwrap_or(0.0),
                level: arr.get(1).copied().unwrap_or(0.0) as f32,
            })
            .collect())
    }

    /// Collect partial results from browser
    ///
    /// # Errors
    /// Returns error if CDP call fails.
    pub async fn collect_partials_cdp(
        &self,
        page: &chromiumoxide::Page,
    ) -> Result<Vec<PartialResult>, StreamingValidationError> {
        let js = "window.__probar_partials || []";
        let result: Vec<Vec<serde_json::Value>> = page
            .evaluate(js)
            .await
            .map_err(|_| StreamingValidationError::EndedInError)?
            .into_value()
            .map_err(|_| StreamingValidationError::EndedInError)?;

        let partials: Vec<PartialResult> = result
            .into_iter()
            .filter_map(|arr| {
                let ts = arr.first()?.as_f64()?;
                let text = arr.get(1)?.as_str()?.to_string();
                Some(PartialResult {
                    timestamp_ms: ts,
                    text,
                    is_final: false,
                })
            })
            .collect();

        // Mark the last one as final if present
        if partials.is_empty() {
            return Ok(partials);
        }

        let mut result = partials;
        if let Some(last) = result.last_mut() {
            last.is_final = true;
        }
        Ok(result)
    }

    /// Assert state sequence occurred in order
    ///
    /// # Errors
    /// Returns error if sequence was not observed.
    pub async fn assert_state_sequence_cdp(
        &self,
        page: &chromiumoxide::Page,
        expected: &[&str],
    ) -> Result<(), StreamingValidationError> {
        let history = self.collect_state_history_cdp(page).await?;
        let states: Vec<&str> = history.iter().map(|t| t.to.as_str()).collect();

        let mut expected_iter = expected.iter();
        let mut current_expected = expected_iter.next();

        for state in &states {
            if let Some(exp) = current_expected {
                if state == exp {
                    current_expected = expected_iter.next();
                }
            }
        }

        if current_expected.is_some() {
            return Err(StreamingValidationError::InvalidStateTransition {
                from: StreamingState::Idle,
                to: StreamingState::Error,
            });
        }

        Ok(())
    }

    /// Assert VU meter was active during period
    ///
    /// # Errors
    /// Returns error if VU meter was not active for required duration.
    pub async fn assert_vu_meter_active_cdp(
        &self,
        page: &chromiumoxide::Page,
        min_level: f32,
        duration_ms: u64,
    ) -> Result<(), StreamingValidationError> {
        let samples = self.collect_vu_samples_cdp(page).await?;

        let mut active_duration: f64 = 0.0;
        let mut last_ts: Option<f64> = None;

        for sample in &samples {
            if sample.level >= min_level {
                if let Some(prev_ts) = last_ts {
                    active_duration += sample.timestamp_ms - prev_ts;
                }
            }
            last_ts = Some(sample.timestamp_ms);
        }

        if active_duration < duration_ms as f64 {
            return Err(StreamingValidationError::TtfbExceeded {
                measured: Duration::from_millis(active_duration as u64),
                max: Duration::from_millis(duration_ms),
            });
        }

        Ok(())
    }

    /// Assert no UI jank (state updates within threshold)
    ///
    /// # Errors
    /// Returns error if gap between updates exceeds threshold.
    pub async fn assert_no_jank_cdp(
        &self,
        page: &chromiumoxide::Page,
        max_gap_ms: f64,
    ) -> Result<(), StreamingValidationError> {
        let history = self.collect_state_history_cdp(page).await?;

        for transition in &history {
            if transition.duration_ms > max_gap_ms {
                return Err(StreamingValidationError::LatencyExceeded {
                    measured: Duration::from_millis(transition.duration_ms as u64),
                    max: Duration::from_millis(max_gap_ms as u64),
                });
            }
        }

        Ok(())
    }

    /// Assert partial results appeared before final result
    ///
    /// # Errors
    /// Returns error if no partials appeared before final.
    pub async fn assert_partials_before_final_cdp(
        &self,
        page: &chromiumoxide::Page,
    ) -> Result<(), StreamingValidationError> {
        let partials = self.collect_partials_cdp(page).await?;

        // Need at least 2 results (one partial, one final)
        if partials.len() < 2 {
            return Err(StreamingValidationError::EndedInError);
        }

        // Verify there's at least one non-final result before the final
        let non_final_count = partials.iter().filter(|p| !p.is_final).count();
        if non_final_count == 0 {
            return Err(StreamingValidationError::EndedInError);
        }

        Ok(())
    }

    /// Get average state transition time in milliseconds
    ///
    /// # Errors
    /// Returns error if CDP call fails.
    pub async fn avg_transition_time_ms_cdp(
        &self,
        page: &chromiumoxide::Page,
    ) -> Result<f64, StreamingValidationError> {
        let history = self.collect_state_history_cdp(page).await?;

        if history.is_empty() {
            return Ok(0.0);
        }

        let total: f64 = history.iter().map(|t| t.duration_ms).sum();
        Ok(total / history.len() as f64)
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    // ========================================================================
    // H7: Streaming latency monitoring is accurate - Falsification tests
    // ========================================================================

    #[test]
    fn f029_latency_exceeded() {
        // Falsification: Latency above threshold should fail validation
        let mut validator =
            StreamingUxValidator::new().with_max_latency(Duration::from_millis(100));

        validator.record_metric(StreamingMetric::Latency(Duration::from_millis(150)));

        let result = validator.validate();
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(matches!(
            err,
            StreamingValidationError::LatencyExceeded { .. }
        ));
    }

    #[test]
    fn f030_latency_acceptable() {
        // Falsification: Latency below threshold should pass
        let mut validator =
            StreamingUxValidator::new().with_max_latency(Duration::from_millis(100));

        validator.record_metric(StreamingMetric::Latency(Duration::from_millis(50)));

        assert!(validator.validate().is_ok());
    }

    #[test]
    fn f031_buffer_underrun_threshold() {
        // Falsification: Too many buffer underruns should fail
        let mut validator = StreamingUxValidator::new().with_buffer_underrun_threshold(2);

        validator.record_metric(StreamingMetric::BufferUnderrun);
        validator.record_metric(StreamingMetric::BufferUnderrun);
        validator.record_metric(StreamingMetric::BufferUnderrun);

        let result = validator.validate();
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            StreamingValidationError::BufferUnderrunThreshold { .. }
        ));
    }

    #[test]
    fn f032_dropped_frames_threshold() {
        // Falsification: Too many dropped frames should fail
        let mut validator = StreamingUxValidator::new().with_max_dropped_frames(2);

        for _ in 0..5 {
            validator.record_metric(StreamingMetric::FrameDropped);
        }

        let result = validator.validate();
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            StreamingValidationError::DroppedFrameThreshold { .. }
        ));
    }

    // ========================================================================
    // H8: State machine transitions are valid - Falsification tests
    // ========================================================================

    #[test]
    fn f033_state_idle_to_buffering() {
        // Falsification: FirstByteReceived should transition Idle -> Buffering
        let mut validator = StreamingUxValidator::new();
        assert_eq!(validator.state(), StreamingState::Idle);

        validator.record_metric(StreamingMetric::FirstByteReceived);
        assert_eq!(validator.state(), StreamingState::Buffering);
    }

    #[test]
    fn f034_state_buffering_to_streaming() {
        // Falsification: Audio chunk should transition Buffering -> Streaming
        let mut validator = StreamingUxValidator::new();
        validator.start();
        assert_eq!(validator.state(), StreamingState::Buffering);

        validator.record_metric(StreamingMetric::AudioChunk {
            samples: 1024,
            sample_rate: 16000,
        });
        assert_eq!(validator.state(), StreamingState::Streaming);
    }

    #[test]
    fn f035_state_streaming_to_stalled() {
        // Falsification: Buffer underrun should transition Streaming -> Stalled
        let mut validator = StreamingUxValidator::new();
        validator.start();
        validator.record_metric(StreamingMetric::AudioChunk {
            samples: 1024,
            sample_rate: 16000,
        });
        assert_eq!(validator.state(), StreamingState::Streaming);

        validator.record_metric(StreamingMetric::BufferUnderrun);
        assert_eq!(validator.state(), StreamingState::Stalled);
    }

    #[test]
    fn f036_state_recovery_from_stalled() {
        // Falsification: Frame rendered should recover Stalled -> Streaming
        let mut validator = StreamingUxValidator::new();
        validator.start();
        validator.record_metric(StreamingMetric::AudioChunk {
            samples: 1024,
            sample_rate: 16000,
        });
        validator.record_metric(StreamingMetric::BufferUnderrun);
        assert_eq!(validator.state(), StreamingState::Stalled);

        validator.record_metric(StreamingMetric::FrameRendered { timestamp: 1000 });
        assert_eq!(validator.state(), StreamingState::Streaming);
    }

    // ========================================================================
    // H9: FPS calculation is accurate - Falsification tests
    // ========================================================================

    #[test]
    fn f037_fps_calculation() {
        // Falsification: FPS should be calculated correctly
        let mut validator = StreamingUxValidator::new();

        // Simulate 30fps for 1 second
        for i in 0..31 {
            validator.record_metric(StreamingMetric::FrameRendered {
                timestamp: i * 33, // ~30fps
            });
        }

        let fps = validator.average_fps();
        // Should be approximately 30fps
        assert!((fps - 30.0).abs() < 1.0, "FPS was {fps}, expected ~30");
    }

    #[test]
    fn f038_fps_below_minimum() {
        // Falsification: Low FPS should fail validation
        let mut validator = StreamingUxValidator::new().with_min_fps(30.0);

        // Simulate 15fps for 1 second
        for i in 0..16 {
            validator.record_metric(StreamingMetric::FrameRendered {
                timestamp: i * 66, // ~15fps
            });
        }

        let result = validator.validate();
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            StreamingValidationError::FpsBelowMinimum { .. }
        ));
    }

    // ========================================================================
    // Unit tests for core functionality
    // ========================================================================

    #[test]
    fn test_default_validator() {
        let validator = StreamingUxValidator::new();
        assert_eq!(validator.state(), StreamingState::Idle);
        assert_eq!(validator.buffer_underruns(), 0);
        assert_eq!(validator.dropped_frames(), 0);
    }

    #[test]
    fn test_audio_preset() {
        let validator = StreamingUxValidator::for_audio();
        assert_eq!(validator.max_latency, Duration::from_millis(100));
        assert_eq!(validator.buffer_underrun_threshold, 3);
    }

    #[test]
    fn test_video_preset() {
        let validator = StreamingUxValidator::for_video();
        assert_eq!(validator.max_latency, Duration::from_millis(500));
        assert!((validator.min_fps - 30.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_complete_transition() {
        let mut validator = StreamingUxValidator::new();
        validator.complete();
        assert_eq!(validator.state(), StreamingState::Completed);
    }

    #[test]
    fn test_error_transition() {
        let mut validator = StreamingUxValidator::new();
        validator.error();
        assert_eq!(validator.state(), StreamingState::Error);
        assert!(validator.validate().is_err());
    }

    #[test]
    fn test_reset() {
        let mut validator = StreamingUxValidator::new();
        validator.start();
        validator.record_metric(StreamingMetric::BufferUnderrun);
        validator.record_metric(StreamingMetric::FrameDropped);

        validator.reset();
        assert_eq!(validator.state(), StreamingState::Idle);
        assert_eq!(validator.buffer_underruns(), 0);
        assert_eq!(validator.dropped_frames(), 0);
    }

    #[test]
    fn test_validate_all_errors() {
        let mut validator = StreamingUxValidator::new()
            .with_max_latency(Duration::from_millis(50))
            .with_buffer_underrun_threshold(1);

        validator.record_metric(StreamingMetric::Latency(Duration::from_millis(100)));
        validator.record_metric(StreamingMetric::BufferUnderrun);
        validator.record_metric(StreamingMetric::BufferUnderrun);

        let errors = validator.validate_all();
        assert!(errors.len() >= 2);
    }

    #[test]
    fn test_state_history() {
        let mut validator = StreamingUxValidator::new();
        validator.start();
        validator.record_metric(StreamingMetric::AudioChunk {
            samples: 1024,
            sample_rate: 16000,
        });

        let history = validator.state_history();
        assert!(!history.is_empty());
        assert_eq!(history[0].0, StreamingState::Idle);
    }

    #[test]
    fn test_buffer_level_transitions() {
        let mut validator = StreamingUxValidator::new();
        validator.start();
        validator.record_metric(StreamingMetric::AudioChunk {
            samples: 1024,
            sample_rate: 16000,
        });
        assert_eq!(validator.state(), StreamingState::Streaming);

        // Low buffer level should stall
        validator.record_metric(StreamingMetric::BufferLevel(0.05));
        assert_eq!(validator.state(), StreamingState::Stalled);

        // Buffer recovery should resume streaming
        validator.record_metric(StreamingMetric::BufferLevel(0.5));
        assert_eq!(validator.state(), StreamingState::Streaming);
    }

    #[test]
    fn test_streaming_state_display() {
        assert_eq!(format!("{}", StreamingState::Idle), "Idle");
        assert_eq!(format!("{}", StreamingState::Streaming), "Streaming");
        assert_eq!(format!("{}", StreamingState::Stalled), "Stalled");
    }

    // ========================================================================
    // H10: VU Meter validation is accurate - Falsification tests
    // ========================================================================

    #[test]
    fn f039_vu_meter_negative_level_rejected() {
        // Falsification: Negative levels should be rejected
        let config = VuMeterConfig::default();
        let result = config.validate_sample(-0.5);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            VuMeterError::NegativeLevel(_)
        ));
    }

    #[test]
    fn f040_vu_meter_clipping_detected() {
        // Falsification: Level above max (with tolerance) should be clipping
        let config = VuMeterConfig::default().with_max_level(1.0);
        // Level 1.5 exceeds 1.0 + 0.1 tolerance
        let result = config.validate_sample(1.5);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), VuMeterError::Clipping(_)));
    }

    #[test]
    fn f041_vu_meter_valid_level_accepted() {
        // Falsification: Valid level should pass
        let config = VuMeterConfig::default();
        assert!(config.validate_sample(0.5).is_ok());
        assert!(config.validate_sample(0.0).is_ok());
        assert!(config.validate_sample(1.0).is_ok());
    }

    #[test]
    fn f042_vu_meter_config_builder() {
        // Falsification: Builder methods should work correctly
        let config = VuMeterConfig::default()
            .with_min_level(0.1)
            .with_max_level(0.9)
            .with_update_rate_hz(60.0)
            .with_max_stale_ms(50);

        assert!((config.min_level - 0.1).abs() < f32::EPSILON);
        assert!((config.max_level - 0.9).abs() < f32::EPSILON);
        assert!((config.update_rate_hz - 60.0).abs() < f32::EPSILON);
        assert_eq!(config.max_stale_ms, 50);
    }

    #[test]
    fn f043_vu_meter_level_clamping() {
        // Falsification: Out-of-range levels should be clamped in config
        let config = VuMeterConfig::default()
            .with_min_level(-5.0)
            .with_max_level(10.0);

        // Clamped to 0.0-1.0 range
        assert!((config.min_level - 0.0).abs() < f32::EPSILON);
        assert!((config.max_level - 1.0).abs() < f32::EPSILON);
    }

    #[test]
    fn f044_vu_meter_min_update_rate() {
        // Falsification: Update rate should have minimum of 1.0 Hz
        let config = VuMeterConfig::default().with_update_rate_hz(0.1);

        assert!((config.update_rate_hz - 1.0).abs() < f32::EPSILON);
    }

    #[test]
    fn f045_vu_meter_error_display() {
        // Falsification: Error messages should be informative
        let negative = VuMeterError::NegativeLevel(-0.5);
        assert!(negative.to_string().contains("negative"));

        let clipping = VuMeterError::Clipping(1.5);
        assert!(clipping.to_string().contains("clipping"));

        let stale = VuMeterError::Stale {
            last_update_ms: 100,
            current_ms: 300,
        };
        assert!(stale.to_string().contains("stale"));

        let slow = VuMeterError::SlowUpdateRate {
            measured_hz: 10.0,
            expected_hz: 30.0,
        };
        assert!(slow.to_string().contains("slow"));

        let not_animating = VuMeterError::NotAnimating {
            sample_count: 10,
            value: 0.5,
        };
        assert!(not_animating.to_string().contains("not animating"));
    }

    #[test]
    fn f046_state_transition_tracking() {
        // Falsification: State transitions should be properly structured
        let transition = StateTransition {
            from: "Idle".to_string(),
            to: "Recording".to_string(),
            timestamp_ms: 1000.0,
            duration_ms: 500.0,
        };

        assert_eq!(transition.from, "Idle");
        assert_eq!(transition.to, "Recording");
        assert!((transition.timestamp_ms - 1000.0).abs() < f64::EPSILON);
        assert!((transition.duration_ms - 500.0).abs() < f64::EPSILON);
    }

    #[test]
    fn f047_partial_result_tracking() {
        // Falsification: Partial results should track interim transcriptions
        let partial = PartialResult {
            timestamp_ms: 1500.0,
            text: "Hello wo".to_string(),
            is_final: false,
        };

        assert!(!partial.is_final);
        assert_eq!(partial.text, "Hello wo");

        let final_result = PartialResult {
            timestamp_ms: 2000.0,
            text: "Hello world".to_string(),
            is_final: true,
        };

        assert!(final_result.is_final);
    }

    #[test]
    fn f048_vu_meter_sample_tracking() {
        // Falsification: VU meter samples should track level over time
        let samples = vec![
            VuMeterSample {
                timestamp_ms: 0.0,
                level: 0.1,
            },
            VuMeterSample {
                timestamp_ms: 33.3,
                level: 0.3,
            },
            VuMeterSample {
                timestamp_ms: 66.6,
                level: 0.5,
            },
            VuMeterSample {
                timestamp_ms: 100.0,
                level: 0.4,
            },
        ];

        // Calculate average level
        let avg: f32 = samples.iter().map(|s| s.level).sum::<f32>() / samples.len() as f32;
        assert!((avg - 0.325).abs() < 0.01);

        // Check time span
        let duration = samples.last().unwrap().timestamp_ms - samples.first().unwrap().timestamp_ms;
        assert!((duration - 100.0).abs() < f64::EPSILON);
    }

    // ========================================================================
    // H11: Test Execution Stats are accurate - Falsification tests (Section 5.1)
    // ========================================================================

    #[test]
    fn f049_test_execution_stats_creation() {
        // Falsification: New stats should be zero-initialized
        let stats = TestExecutionStats::new();
        assert_eq!(stats.states_captured, 0);
        assert_eq!(stats.bytes_raw, 0);
        assert_eq!(stats.bytes_compressed, 0);
        assert_eq!(stats.same_fill_pages, 0);
    }

    #[test]
    fn f050_test_execution_stats_recording() {
        // Falsification: Stats should correctly record captures
        let mut stats = TestExecutionStats::new();
        stats.record_state_capture(4096, 1024);
        stats.record_state_capture(4096, 2048);

        assert_eq!(stats.states_captured, 2);
        assert_eq!(stats.bytes_raw, 8192);
        assert_eq!(stats.bytes_compressed, 3072);
    }

    #[test]
    fn f051_test_execution_stats_compression_ratio() {
        // Falsification: Compression ratio should be raw/compressed
        let mut stats = TestExecutionStats::new();
        stats.record_state_capture(4000, 1000);

        let ratio = stats.compression_ratio();
        assert!((ratio - 4.0).abs() < 0.01);
    }

    #[test]
    fn f052_test_execution_stats_efficiency() {
        // Falsification: Efficiency should be 1 - (compressed/raw)
        let mut stats = TestExecutionStats::new();
        stats.record_state_capture(1000, 250); // 75% efficiency

        let efficiency = stats.efficiency();
        assert!((efficiency - 0.75).abs() < 0.01);
    }

    #[test]
    fn f053_test_execution_stats_storage_savings() {
        // Falsification: Storage savings should be in MB
        let mut stats = TestExecutionStats::new();
        stats.record_state_capture(5_000_000, 1_000_000); // 4MB saved

        let savings = stats.storage_savings_mb();
        assert!((savings - 4.0).abs() < 0.01);
    }

    #[test]
    fn f054_test_execution_stats_same_fill_detection() {
        // Falsification: >90% compression should be detected as same-fill
        let mut stats = TestExecutionStats::new();
        stats.record_state_capture(4096, 100); // 97.5% compression - same-fill
        stats.record_state_capture(4096, 1024); // 75% compression - not same-fill

        assert_eq!(stats.same_fill_pages, 1);
        assert!((stats.same_fill_ratio() - 0.5).abs() < 0.01);
    }

    #[test]
    fn f055_test_execution_stats_reset() {
        // Falsification: Reset should clear all stats
        let mut stats = TestExecutionStats::new();
        stats.record_state_capture(4096, 1024);
        stats.reset();

        assert_eq!(stats.states_captured, 0);
        assert_eq!(stats.bytes_raw, 0);
        assert_eq!(stats.bytes_compressed, 0);
    }

    #[test]
    fn f056_test_execution_stats_edge_cases() {
        // Falsification: Edge cases should not panic
        let mut stats = TestExecutionStats::new();

        // Zero bytes
        assert!((stats.compression_ratio() - 0.0).abs() < f64::EPSILON);
        assert!((stats.efficiency() - 0.0).abs() < f64::EPSILON);
        assert!((stats.same_fill_ratio() - 0.0).abs() < f64::EPSILON);

        // Record with zero compressed
        stats.record_state_capture(1000, 0);
        assert!((stats.compression_ratio() - 0.0).abs() < f64::EPSILON); // Avoid division by zero
    }

    // ========================================================================
    // H12: Screenshot content classification is accurate - Falsification tests (Section 5.2)
    // ========================================================================

    #[test]
    fn f057_screenshot_content_uniform_detection() {
        // Falsification: >95% same value should be classified as Uniform
        let pixels: Vec<u8> = vec![255; 1000];
        let content = ScreenshotContent::classify(&pixels);

        assert!(matches!(
            content,
            ScreenshotContent::Uniform { fill_value: 255 }
        ));
        assert!((content.entropy() - 0.0).abs() < f32::EPSILON);
    }

    #[test]
    fn f058_screenshot_content_ui_dominated() {
        // Falsification: Low entropy (<3.0) should be UI-dominated
        // Simulate mostly uniform with some variation (like UI text)
        let mut pixels = vec![255u8; 900]; // 90% white
        pixels.extend(vec![0u8; 50]); // 5% black
        pixels.extend(vec![128u8; 50]); // 5% gray

        let content = ScreenshotContent::classify(&pixels);
        // This should not be Uniform since it's <95% same value
        // And should have low entropy
        assert!(matches!(
            content,
            ScreenshotContent::UiDominated { .. } | ScreenshotContent::Uniform { .. }
        ));
    }

    #[test]
    fn f059_screenshot_content_high_entropy() {
        // Falsification: Random data should be classified as HighEntropy
        // Create pseudo-random looking data
        let pixels: Vec<u8> = (0..1000).map(|i| ((i * 127 + 37) % 256) as u8).collect();
        let content = ScreenshotContent::classify(&pixels);

        // Should be GameWorld or HighEntropy depending on actual entropy
        assert!(matches!(
            content,
            ScreenshotContent::GameWorld { .. } | ScreenshotContent::HighEntropy { .. }
        ));
    }

    #[test]
    fn f060_screenshot_content_compression_algorithm() {
        // Falsification: Compression algorithm should match content type
        let uniform = ScreenshotContent::Uniform { fill_value: 0 };
        assert_eq!(uniform.recommended_algorithm(), CompressionAlgorithm::Rle);

        let ui = ScreenshotContent::UiDominated { entropy: 2.0 };
        assert_eq!(ui.recommended_algorithm(), CompressionAlgorithm::Png);

        let game = ScreenshotContent::GameWorld { entropy: 4.5 };
        assert_eq!(game.recommended_algorithm(), CompressionAlgorithm::Zstd);

        let high = ScreenshotContent::HighEntropy { entropy: 7.0 };
        assert_eq!(high.recommended_algorithm(), CompressionAlgorithm::Lz4);
    }

    #[test]
    fn f061_screenshot_content_ratio_hints() {
        // Falsification: Ratio hints should describe compression expectations
        let uniform = ScreenshotContent::Uniform { fill_value: 0 };
        assert!(uniform.expected_ratio_hint().contains("excellent"));

        let ui = ScreenshotContent::UiDominated { entropy: 2.0 };
        assert!(ui.expected_ratio_hint().contains("good"));

        let game = ScreenshotContent::GameWorld { entropy: 4.5 };
        assert!(game.expected_ratio_hint().contains("moderate"));

        let high = ScreenshotContent::HighEntropy { entropy: 7.0 };
        assert!(high.expected_ratio_hint().contains("poor"));
    }

    #[test]
    fn f062_screenshot_content_empty_input() {
        // Falsification: Empty input should be handled gracefully
        let content = ScreenshotContent::classify(&[]);
        assert!(matches!(
            content,
            ScreenshotContent::Uniform { fill_value: 0 }
        ));
    }

    #[test]
    fn f063_screenshot_content_entropy_extraction() {
        // Falsification: Entropy should be extractable from all variants
        let variants = [
            ScreenshotContent::UiDominated { entropy: 1.5 },
            ScreenshotContent::GameWorld { entropy: 4.0 },
            ScreenshotContent::HighEntropy { entropy: 7.5 },
            ScreenshotContent::Uniform { fill_value: 128 },
        ];

        let entropies: Vec<f32> = variants.iter().map(|v| v.entropy()).collect();
        assert!((entropies[0] - 1.5).abs() < f32::EPSILON);
        assert!((entropies[1] - 4.0).abs() < f32::EPSILON);
        assert!((entropies[2] - 7.5).abs() < f32::EPSILON);
        assert!((entropies[3] - 0.0).abs() < f32::EPSILON); // Uniform has 0 entropy
    }

    // ========================================================================
    // Additional coverage tests for validators.rs
    // ========================================================================

    #[test]
    fn test_execution_stats_start_stop_throughput() {
        // Test start/stop timing and throughput calculation
        let mut stats = TestExecutionStats::new();
        stats.start();

        // Record some captures
        stats.record_state_capture(1_000_000, 100_000);
        stats.record_state_capture(1_000_000, 100_000);

        stats.stop();

        // Throughput should be > 0 after recording data
        let throughput = stats.compress_throughput();
        // May be 0 if test runs too fast, but shouldn't panic
        assert!(throughput >= 0.0);
    }

    #[test]
    fn test_execution_stats_throughput_no_timing() {
        // Test throughput without start/stop
        let mut stats = TestExecutionStats::new();
        stats.record_state_capture(1000, 100);

        // Should return 0 when no timing is set
        assert!((stats.compress_throughput() - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_execution_stats_throughput_start_only() {
        // Test throughput with only start (no stop)
        let mut stats = TestExecutionStats::new();
        stats.start();
        stats.record_state_capture(1000, 100);

        // Should return 0 when end time not set
        assert!((stats.compress_throughput() - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_streaming_validation_error_display() {
        // Test Display implementations for all error variants
        let latency_err = StreamingValidationError::LatencyExceeded {
            measured: Duration::from_millis(500),
            max: Duration::from_millis(100),
        };
        assert!(latency_err.to_string().contains("exceeded"));

        let underrun_err = StreamingValidationError::BufferUnderrunThreshold {
            count: 10,
            threshold: 5,
        };
        assert!(underrun_err.to_string().contains("Buffer underruns"));

        let dropped_err = StreamingValidationError::DroppedFrameThreshold { count: 20, max: 10 };
        assert!(dropped_err.to_string().contains("Dropped frames"));

        let fps_err = StreamingValidationError::FpsBelowMinimum {
            measured: 15.0,
            min: 30.0,
        };
        assert!(fps_err.to_string().contains("FPS below"));

        let ttfb_err = StreamingValidationError::TtfbExceeded {
            measured: Duration::from_secs(5),
            max: Duration::from_secs(2),
        };
        assert!(ttfb_err.to_string().contains("first byte"));

        let transition_err = StreamingValidationError::InvalidStateTransition {
            from: StreamingState::Idle,
            to: StreamingState::Completed,
        };
        assert!(transition_err.to_string().contains("Invalid state"));

        let error_err = StreamingValidationError::EndedInError;
        assert!(error_err.to_string().contains("error state"));
    }

    #[test]
    fn test_streaming_state_default() {
        let state: StreamingState = Default::default();
        assert_eq!(state, StreamingState::Idle);
    }

    #[test]
    fn test_streaming_state_display_all_variants() {
        assert_eq!(format!("{}", StreamingState::Idle), "Idle");
        assert_eq!(format!("{}", StreamingState::Buffering), "Buffering");
        assert_eq!(format!("{}", StreamingState::Streaming), "Streaming");
        assert_eq!(format!("{}", StreamingState::Stalled), "Stalled");
        assert_eq!(format!("{}", StreamingState::Error), "Error");
        assert_eq!(format!("{}", StreamingState::Completed), "Completed");
    }

    #[test]
    fn test_streaming_metric_record_creation() {
        let record = StreamingMetricRecord {
            metric: StreamingMetric::BufferUnderrun,
            timestamp: Instant::now(),
        };
        assert!(matches!(record.metric, StreamingMetric::BufferUnderrun));
    }

    #[test]
    fn test_streaming_ux_validator_default() {
        let validator: StreamingUxValidator = Default::default();
        assert_eq!(validator.state(), StreamingState::Idle);
    }

    #[test]
    fn test_ttfb_validation() {
        let mut validator =
            StreamingUxValidator::new().with_ttfb_timeout(Duration::from_millis(100));

        // Start and wait for first byte
        validator.start();

        // Simulate waiting too long before first byte
        std::thread::sleep(Duration::from_millis(150));

        // Record first byte
        validator.record_metric(StreamingMetric::FirstByteReceived);

        let result = validator.validate();
        // TTFB should be exceeded
        assert!(result.is_err());
        if let Err(err) = result {
            assert!(matches!(err, StreamingValidationError::TtfbExceeded { .. }));
        }
    }

    #[test]
    fn test_ttfb_validation_success() {
        let mut validator = StreamingUxValidator::new().with_ttfb_timeout(Duration::from_secs(5));

        // Start and immediately receive first byte
        validator.start();
        validator.record_metric(StreamingMetric::FirstByteReceived);

        // Other metrics to make it valid
        validator.record_metric(StreamingMetric::AudioChunk {
            samples: 1024,
            sample_rate: 16000,
        });

        let result = validator.validate();
        assert!(result.is_ok());
    }

    #[test]
    fn test_compression_algorithm_enum() {
        // Ensure all variants are distinct
        assert_ne!(CompressionAlgorithm::Lz4, CompressionAlgorithm::Zstd);
        assert_ne!(CompressionAlgorithm::Zstd, CompressionAlgorithm::Png);
        assert_ne!(CompressionAlgorithm::Png, CompressionAlgorithm::Rle);
    }

    #[test]
    fn test_vu_meter_config_debug() {
        let config = VuMeterConfig::default();
        let debug_str = format!("{:?}", config);
        assert!(debug_str.contains("VuMeterConfig"));
    }

    #[test]
    fn test_state_transition_debug() {
        let transition = StateTransition {
            from: "Idle".to_string(),
            to: "Recording".to_string(),
            timestamp_ms: 1000.0,
            duration_ms: 500.0,
        };
        let debug_str = format!("{:?}", transition);
        assert!(debug_str.contains("StateTransition"));
    }

    #[test]
    fn test_partial_result_debug() {
        let partial = PartialResult {
            timestamp_ms: 1500.0,
            text: "Hello".to_string(),
            is_final: false,
        };
        let debug_str = format!("{:?}", partial);
        assert!(debug_str.contains("PartialResult"));
    }

    #[test]
    fn test_vu_meter_sample_debug() {
        let sample = VuMeterSample {
            timestamp_ms: 100.0,
            level: 0.5,
        };
        let debug_str = format!("{:?}", sample);
        assert!(debug_str.contains("VuMeterSample"));
    }

    #[test]
    fn test_test_execution_stats_debug() {
        let stats = TestExecutionStats::new();
        let debug_str = format!("{:?}", stats);
        assert!(debug_str.contains("TestExecutionStats"));
    }

    #[test]
    fn test_screenshot_content_debug() {
        let content = ScreenshotContent::UiDominated { entropy: 2.0 };
        let debug_str = format!("{:?}", content);
        assert!(debug_str.contains("UiDominated"));
    }

    #[test]
    fn test_streaming_metric_debug() {
        let metric = StreamingMetric::Latency(Duration::from_millis(50));
        let debug_str = format!("{:?}", metric);
        assert!(debug_str.contains("Latency"));
    }

    #[test]
    fn test_streaming_validation_error_as_error() {
        // Test std::error::Error implementation
        let err = StreamingValidationError::EndedInError;
        let _: &dyn std::error::Error = &err;
    }

    #[test]
    fn test_vu_meter_error_as_error() {
        // Test std::error::Error implementation
        let err = VuMeterError::NegativeLevel(-0.5);
        let _: &dyn std::error::Error = &err;
    }

    #[test]
    fn test_streaming_metric_all_variants() {
        // Ensure all variants can be created
        let metrics = vec![
            StreamingMetric::Latency(Duration::from_millis(50)),
            StreamingMetric::FrameRendered { timestamp: 1000 },
            StreamingMetric::FrameDropped,
            StreamingMetric::BufferUnderrun,
            StreamingMetric::FirstByteReceived,
            StreamingMetric::BufferLevel(0.5),
            StreamingMetric::AudioChunk {
                samples: 1024,
                sample_rate: 16000,
            },
        ];

        assert_eq!(metrics.len(), 7);
    }

    #[test]
    fn test_streaming_ux_validator_clone() {
        let validator = StreamingUxValidator::new()
            .with_max_latency(Duration::from_millis(100))
            .with_buffer_underrun_threshold(3);

        let cloned = validator;
        assert_eq!(cloned.state(), StreamingState::Idle);
    }

    #[test]
    fn test_test_execution_stats_clone() {
        let mut stats = TestExecutionStats::new();
        stats.record_state_capture(1000, 100);

        let cloned = stats.clone();
        assert_eq!(cloned.states_captured, 1);
    }

    #[test]
    fn test_vu_meter_config_clone() {
        let config = VuMeterConfig::default().with_min_level(0.2);
        let cloned = config;
        assert!((cloned.min_level - 0.2).abs() < f32::EPSILON);
    }

    #[test]
    fn test_state_transition_clone() {
        let transition = StateTransition {
            from: "Idle".to_string(),
            to: "Recording".to_string(),
            timestamp_ms: 1000.0,
            duration_ms: 500.0,
        };
        let cloned = transition;
        assert_eq!(cloned.from, "Idle");
    }

    // Additional coverage tests

    #[test]
    fn test_vu_meter_stale_error_display() {
        let err = VuMeterError::Stale {
            last_update_ms: 100,
            current_ms: 300,
        };
        let display = format!("{}", err);
        assert!(display.contains("stale"));
        assert!(display.contains("200ms"));
    }

    #[test]
    fn test_vu_meter_slow_update_rate_error_display() {
        let err = VuMeterError::SlowUpdateRate {
            measured_hz: 15.0,
            expected_hz: 30.0,
        };
        let display = format!("{}", err);
        assert!(display.contains("15.0Hz"));
        assert!(display.contains("30.0Hz"));
    }

    #[test]
    fn test_vu_meter_not_animating_error_display() {
        let err = VuMeterError::NotAnimating {
            sample_count: 100,
            value: 0.5,
        };
        let display = format!("{}", err);
        assert!(display.contains("100 samples"));
        assert!(display.contains("0.5"));
    }

    #[test]
    fn test_screenshot_content_game_world() {
        // Create medium entropy data
        let mut pixels = Vec::with_capacity(1000);
        for i in 0..1000 {
            pixels.push((i % 64) as u8); // Moderate variation
        }
        let content = ScreenshotContent::classify(&pixels);
        // With 64 unique values, entropy should be ~6 bits
        match content {
            ScreenshotContent::GameWorld { entropy } => {
                assert!((3.0..6.0).contains(&entropy));
            }
            ScreenshotContent::HighEntropy { entropy } => {
                // Also acceptable for this pattern
                assert!(entropy >= 6.0);
            }
            _ => {}
        }
    }

    #[test]
    fn test_streaming_validation_error_invalid_transition() {
        let err = StreamingValidationError::InvalidStateTransition {
            from: StreamingState::Idle,
            to: StreamingState::Streaming,
        };
        let display = format!("{}", err);
        assert!(display.contains("Invalid state transition"));
        assert!(display.contains("Idle"));
        assert!(display.contains("Streaming"));
    }

    #[test]
    fn test_streaming_latency_transition() {
        let mut validator = StreamingUxValidator::new();
        validator.start();
        assert_eq!(validator.state(), StreamingState::Buffering);

        // Record good latency - should transition to Streaming
        validator.record_metric(StreamingMetric::Latency(Duration::from_millis(10)));
        assert_eq!(validator.state(), StreamingState::Streaming);
    }

    #[test]
    fn test_streaming_buffer_level() {
        let mut validator = StreamingUxValidator::new();
        validator.start();

        // Buffer level should be recorded
        validator.record_metric(StreamingMetric::BufferLevel(0.75));
        assert_eq!(validator.state(), StreamingState::Buffering);
    }

    #[test]
    fn test_streaming_frame_times_overflow() {
        let mut validator = StreamingUxValidator::new();
        validator.start();
        validator.record_metric(StreamingMetric::AudioChunk {
            samples: 1024,
            sample_rate: 16000,
        });

        // Add more than 120 frames to test the overflow handling
        for i in 0..150 {
            validator.record_metric(StreamingMetric::FrameRendered { timestamp: i * 33 });
        }

        // Should have capped at 120 frames
        let fps = validator.average_fps();
        assert!(fps > 0.0);
    }

    #[test]
    fn test_streaming_metrics_all_variants_coverage() {
        let mut validator = StreamingUxValidator::new();
        validator.start();

        // Cover all metric variants
        validator.record_metric(StreamingMetric::Latency(Duration::from_millis(50)));
        validator.record_metric(StreamingMetric::FrameRendered { timestamp: 0 });
        validator.record_metric(StreamingMetric::FrameDropped);
        validator.record_metric(StreamingMetric::BufferUnderrun);
        validator.record_metric(StreamingMetric::FirstByteReceived);
        validator.record_metric(StreamingMetric::BufferLevel(0.5));
        validator.record_metric(StreamingMetric::AudioChunk {
            samples: 1024,
            sample_rate: 16000,
        });

        assert!(validator.dropped_frames() >= 1);
        assert!(validator.buffer_underruns() >= 1);
    }

    #[test]
    fn test_max_recorded_latency() {
        let mut validator = StreamingUxValidator::new();
        validator.record_metric(StreamingMetric::Latency(Duration::from_millis(50)));
        validator.record_metric(StreamingMetric::Latency(Duration::from_millis(100)));
        validator.record_metric(StreamingMetric::Latency(Duration::from_millis(75)));

        // Access the validate method which uses max_recorded_latency
        let result = validator.validate();
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_all_with_fps_error() {
        let mut validator = StreamingUxValidator::new()
            .with_min_fps(60.0)
            .with_max_dropped_frames(0);

        // Add some slow frames
        for i in 0..10 {
            validator.record_metric(StreamingMetric::FrameRendered {
                timestamp: i * 100, // 10fps
            });
        }
        validator.record_metric(StreamingMetric::FrameDropped);

        let errors = validator.validate_all();
        assert!(!errors.is_empty());
    }

    #[test]
    fn test_screenshot_content_entropy_boundaries() {
        // Test UI-dominated (entropy < 3.0)
        let mut pixels = Vec::with_capacity(1000);
        for i in 0..1000 {
            pixels.push((i % 4) as u8); // Only 4 unique values = low entropy
        }
        let content = ScreenshotContent::classify(&pixels);
        match content {
            ScreenshotContent::UiDominated { entropy } => {
                assert!(entropy < 3.0);
            }
            _ => {} // Other classifications possible
        }
    }

    #[test]
    fn test_test_execution_stats_default() {
        let stats: TestExecutionStats = Default::default();
        assert_eq!(stats.states_captured, 0);
    }

    #[test]
    fn test_streaming_validation_result_success() {
        let mut validator = StreamingUxValidator::new();
        validator.start();
        validator.record_metric(StreamingMetric::FirstByteReceived);
        validator.record_metric(StreamingMetric::AudioChunk {
            samples: 1024,
            sample_rate: 16000,
        });

        // Add enough frames for good FPS
        for i in 0..60 {
            validator.record_metric(StreamingMetric::FrameRendered { timestamp: i * 33 });
        }

        validator.complete();

        let result = validator.validate();
        assert!(result.is_ok());
        if let Ok(result) = result {
            assert!(result.max_latency_recorded >= Duration::ZERO);
            assert!(result.average_fps >= 0.0);
        }
    }

    #[test]
    fn test_partial_result_clone() {
        let result = PartialResult {
            timestamp_ms: 100.0,
            text: "test".to_string(),
            is_final: false,
        };
        let cloned = result;
        assert_eq!(cloned.text, "test");
    }

    #[test]
    fn test_vu_meter_sample_clone() {
        let sample = VuMeterSample {
            timestamp_ms: 100.0,
            level: 0.5,
        };
        let cloned = sample;
        assert!((cloned.level - 0.5).abs() < f32::EPSILON);
    }

    #[test]
    fn test_streaming_metric_record_clone() {
        let record = StreamingMetricRecord {
            metric: StreamingMetric::BufferLevel(0.5),
            timestamp: Instant::now(),
        };
        let cloned = record;
        assert!(matches!(cloned.metric, StreamingMetric::BufferLevel(..)));
    }

    #[test]
    fn test_streaming_validation_error_clone() {
        let err = StreamingValidationError::LatencyExceeded {
            measured: Duration::from_millis(150),
            max: Duration::from_millis(100),
        };
        let cloned = err;
        assert!(matches!(
            cloned,
            StreamingValidationError::LatencyExceeded { .. }
        ));
    }

    #[test]
    fn test_vu_meter_error_clone() {
        let err = VuMeterError::Clipping(1.5);
        let cloned = err;
        assert!(matches!(cloned, VuMeterError::Clipping(..)));
    }

    // ========================================================================
    // Additional comprehensive tests for 95%+ coverage
    // ========================================================================

    #[test]
    fn test_average_fps_with_zero_duration() {
        let mut validator = StreamingUxValidator::new();
        // Add frames with same timestamp - zero duration
        validator.record_metric(StreamingMetric::FrameRendered { timestamp: 100 });
        validator.record_metric(StreamingMetric::FrameRendered { timestamp: 100 });

        // Should return 0.0 when duration is 0
        assert!((validator.average_fps() - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_average_fps_single_frame() {
        let mut validator = StreamingUxValidator::new();
        // Only one frame - not enough to calculate FPS
        validator.record_metric(StreamingMetric::FrameRendered { timestamp: 100 });

        assert!((validator.average_fps() - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_streaming_validation_result_fields() {
        let mut validator = StreamingUxValidator::new()
            .with_max_latency(Duration::from_secs(10))
            .with_buffer_underrun_threshold(100)
            .with_max_dropped_frames(100)
            .with_min_fps(1.0);

        validator.start();
        validator.record_metric(StreamingMetric::FirstByteReceived);
        validator.record_metric(StreamingMetric::Latency(Duration::from_millis(50)));

        // Add frames for FPS
        for i in 0..60 {
            validator.record_metric(StreamingMetric::FrameRendered { timestamp: i * 16 });
        }

        let result = validator.validate().unwrap();
        assert_eq!(result.buffer_underruns, 0);
        assert_eq!(result.dropped_frames, 0);
        assert!(result.average_fps > 0.0);
        assert!(result.total_frames > 0);
        assert!(result.max_latency_recorded >= Duration::ZERO);
    }

    #[test]
    fn test_max_recorded_latency_empty() {
        let validator = StreamingUxValidator::new();
        // No latency metrics recorded - should use max_recorded_latency internally
        let result = validator.validate();
        assert!(result.is_ok());
    }

    #[test]
    fn test_compression_ratio_with_zero_raw() {
        let mut stats = TestExecutionStats::new();
        // Record with 0 raw bytes
        stats.bytes_raw = 0;
        stats.bytes_compressed = 100;
        // compression_ratio should handle this edge case
        assert!((stats.compression_ratio() - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_throughput_with_zero_duration() {
        let mut stats = TestExecutionStats::new();
        stats.start();
        stats.record_state_capture(1000, 100);
        // Stop immediately - very short duration
        stats.stop();

        // Should not panic even with very small duration
        let throughput = stats.compress_throughput();
        assert!(throughput >= 0.0);
    }

    #[test]
    fn test_vu_meter_error_stale_clone() {
        let err = VuMeterError::Stale {
            last_update_ms: 100,
            current_ms: 200,
        };
        let cloned = err;
        assert!(matches!(
            cloned,
            VuMeterError::Stale {
                last_update_ms: 100,
                current_ms: 200,
            }
        ));
    }

    #[test]
    fn test_vu_meter_error_slow_update_rate_clone() {
        let err = VuMeterError::SlowUpdateRate {
            measured_hz: 15.0,
            expected_hz: 30.0,
        };
        let cloned = err;
        match cloned {
            VuMeterError::SlowUpdateRate {
                measured_hz,
                expected_hz,
            } => {
                assert!((measured_hz - 15.0).abs() < f32::EPSILON);
                assert!((expected_hz - 30.0).abs() < f32::EPSILON);
            }
            _ => panic!("Expected SlowUpdateRate"),
        }
    }

    #[test]
    fn test_vu_meter_error_not_animating_clone() {
        let err = VuMeterError::NotAnimating {
            sample_count: 10,
            value: 0.5,
        };
        let cloned = err;
        match cloned {
            VuMeterError::NotAnimating {
                sample_count,
                value,
            } => {
                assert_eq!(sample_count, 10);
                assert!((value - 0.5).abs() < f32::EPSILON);
            }
            _ => panic!("Expected NotAnimating"),
        }
    }

    #[test]
    fn test_streaming_validation_error_all_clone_variants() {
        // Test all error variants clone correctly
        let errors: Vec<StreamingValidationError> = vec![
            StreamingValidationError::LatencyExceeded {
                measured: Duration::from_millis(200),
                max: Duration::from_millis(100),
            },
            StreamingValidationError::BufferUnderrunThreshold {
                count: 10,
                threshold: 5,
            },
            StreamingValidationError::DroppedFrameThreshold { count: 20, max: 10 },
            StreamingValidationError::FpsBelowMinimum {
                measured: 15.0,
                min: 30.0,
            },
            StreamingValidationError::TtfbExceeded {
                measured: Duration::from_secs(5),
                max: Duration::from_secs(2),
            },
            StreamingValidationError::InvalidStateTransition {
                from: StreamingState::Idle,
                to: StreamingState::Completed,
            },
            StreamingValidationError::EndedInError,
        ];

        for err in errors {
            let cloned = err.clone();
            // Verify toString works on cloned
            let _ = cloned.to_string();
        }
    }

    #[test]
    fn test_streaming_metric_clone_all_variants() {
        let metrics = vec![
            StreamingMetric::Latency(Duration::from_millis(100)),
            StreamingMetric::FrameRendered { timestamp: 1000 },
            StreamingMetric::FrameDropped,
            StreamingMetric::BufferUnderrun,
            StreamingMetric::FirstByteReceived,
            StreamingMetric::BufferLevel(0.75),
            StreamingMetric::AudioChunk {
                samples: 2048,
                sample_rate: 44100,
            },
        ];

        for metric in metrics {
            let cloned = metric.clone();
            let _ = format!("{:?}", cloned);
        }
    }

    #[test]
    fn test_buffer_level_no_transition_when_not_streaming() {
        let mut validator = StreamingUxValidator::new();
        // Not started, not streaming
        validator.record_metric(StreamingMetric::BufferLevel(0.05));
        assert_eq!(validator.state(), StreamingState::Idle);

        // Buffer recovery when not stalled
        validator.record_metric(StreamingMetric::BufferLevel(0.5));
        assert_eq!(validator.state(), StreamingState::Idle);
    }

    #[test]
    fn test_latency_no_transition_when_exceeds_max() {
        let mut validator = StreamingUxValidator::new().with_max_latency(Duration::from_millis(50));
        validator.start();
        assert_eq!(validator.state(), StreamingState::Buffering);

        // High latency should not transition to streaming
        validator.record_metric(StreamingMetric::Latency(Duration::from_millis(100)));
        assert_eq!(validator.state(), StreamingState::Buffering);
    }

    #[test]
    fn test_frame_rendered_no_transition_when_not_stalled() {
        let mut validator = StreamingUxValidator::new();
        // In Idle state
        validator.record_metric(StreamingMetric::FrameRendered { timestamp: 100 });
        assert_eq!(validator.state(), StreamingState::Idle);

        // In Buffering state
        validator.start();
        validator.record_metric(StreamingMetric::FrameRendered { timestamp: 200 });
        assert_eq!(validator.state(), StreamingState::Buffering);
    }

    #[test]
    fn test_audio_chunk_no_transition_when_not_buffering() {
        let mut validator = StreamingUxValidator::new();
        // In Idle state - should not transition
        validator.record_metric(StreamingMetric::AudioChunk {
            samples: 1024,
            sample_rate: 16000,
        });
        assert_eq!(validator.state(), StreamingState::Idle);

        // In Streaming state - should stay streaming
        validator.start();
        validator.record_metric(StreamingMetric::AudioChunk {
            samples: 1024,
            sample_rate: 16000,
        });
        assert_eq!(validator.state(), StreamingState::Streaming);
        validator.record_metric(StreamingMetric::AudioChunk {
            samples: 1024,
            sample_rate: 16000,
        });
        assert_eq!(validator.state(), StreamingState::Streaming);
    }

    #[test]
    fn test_first_byte_no_transition_when_not_idle() {
        let mut validator = StreamingUxValidator::new();
        validator.start(); // Now in Buffering
        validator.record_metric(StreamingMetric::FirstByteReceived);
        assert_eq!(validator.state(), StreamingState::Buffering);
    }

    #[test]
    fn test_buffer_underrun_no_transition_when_not_streaming() {
        let mut validator = StreamingUxValidator::new();
        // In Idle state
        validator.record_metric(StreamingMetric::BufferUnderrun);
        assert_eq!(validator.state(), StreamingState::Idle);
        assert_eq!(validator.buffer_underruns(), 1);

        // In Buffering state
        validator.start();
        validator.record_metric(StreamingMetric::BufferUnderrun);
        assert_eq!(validator.state(), StreamingState::Buffering);
        assert_eq!(validator.buffer_underruns(), 2);
    }

    #[test]
    fn test_transition_to_same_state() {
        let mut validator = StreamingUxValidator::new();
        validator.start();
        let history_len = validator.state_history().len();

        // Try to transition to current state - should not add to history
        validator.record_metric(StreamingMetric::BufferLevel(0.5)); // Does nothing in Buffering
        assert_eq!(validator.state_history().len(), history_len);
    }

    #[test]
    fn test_screenshot_content_single_byte() {
        // Edge case: single byte input
        let content = ScreenshotContent::classify(&[128]);
        assert!(matches!(
            content,
            ScreenshotContent::Uniform { fill_value: 128 }
        ));
    }

    #[test]
    fn test_screenshot_content_two_bytes_same() {
        let content = ScreenshotContent::classify(&[42, 42]);
        assert!(matches!(
            content,
            ScreenshotContent::Uniform { fill_value: 42 }
        ));
    }

    #[test]
    fn test_screenshot_content_near_uniform_threshold() {
        // 94% same value - should NOT be uniform (threshold is 95%)
        let mut pixels = vec![255u8; 94];
        pixels.extend(vec![0u8; 6]);
        let content = ScreenshotContent::classify(&pixels);
        assert!(!matches!(content, ScreenshotContent::Uniform { .. }));
    }

    #[test]
    fn test_screenshot_content_exactly_at_uniform_threshold() {
        // 96% same value - should be uniform (> 95%)
        let mut pixels = vec![255u8; 96];
        pixels.extend(vec![0u8; 4]);
        let content = ScreenshotContent::classify(&pixels);
        assert!(matches!(
            content,
            ScreenshotContent::Uniform { fill_value: 255 }
        ));
    }

    #[test]
    fn test_screenshot_content_entropy_at_boundary_3() {
        // Create data with entropy around 3.0 (UI vs GameWorld boundary)
        let mut pixels = Vec::new();
        // 8 unique values, equally distributed = log2(8) = 3 bits entropy
        for _ in 0..125 {
            for v in 0u8..8u8 {
                pixels.push(v);
            }
        }
        let content = ScreenshotContent::classify(&pixels);
        // Could be either UI or GameWorld depending on exact calculation
        let entropy = content.entropy();
        assert!((2.5..=3.5).contains(&entropy));
    }

    #[test]
    fn test_screenshot_content_entropy_at_boundary_6() {
        // Create data with entropy around 6.0 (GameWorld vs HighEntropy boundary)
        let mut pixels = Vec::new();
        // 64 unique values = log2(64) = 6 bits entropy
        for _ in 0..16 {
            for v in 0u8..64u8 {
                pixels.push(v);
            }
        }
        let content = ScreenshotContent::classify(&pixels);
        let entropy = content.entropy();
        assert!((5.5..=6.5).contains(&entropy));
    }

    #[test]
    fn test_screenshot_content_maximum_entropy() {
        // Create data with maximum entropy - all 256 values equally distributed
        let mut pixels = Vec::new();
        for _ in 0..4 {
            for v in 0u8..=255u8 {
                pixels.push(v);
            }
        }
        let content = ScreenshotContent::classify(&pixels);
        assert!(matches!(content, ScreenshotContent::HighEntropy { .. }));
        assert!(content.entropy() > 7.0);
    }

    #[test]
    fn test_validate_multiple_latency_exceeded() {
        let mut validator = StreamingUxValidator::new().with_max_latency(Duration::from_millis(50));

        // Multiple latency violations
        validator.record_metric(StreamingMetric::Latency(Duration::from_millis(100)));
        validator.record_metric(StreamingMetric::Latency(Duration::from_millis(150)));
        validator.record_metric(StreamingMetric::Latency(Duration::from_millis(200)));

        let errors = validator.validate_all();
        assert_eq!(errors.len(), 3);
        for err in errors {
            assert!(matches!(
                err,
                StreamingValidationError::LatencyExceeded { .. }
            ));
        }
    }

    #[test]
    fn test_streaming_validation_result_debug() {
        let result = StreamingValidationResult {
            buffer_underruns: 2,
            dropped_frames: 5,
            average_fps: 30.0,
            max_latency_recorded: Duration::from_millis(100),
            total_frames: 1000,
        };
        let debug = format!("{:?}", result);
        assert!(debug.contains("StreamingValidationResult"));
        assert!(debug.contains("buffer_underruns"));
    }

    #[test]
    fn test_streaming_validation_result_clone() {
        let result = StreamingValidationResult {
            buffer_underruns: 3,
            dropped_frames: 7,
            average_fps: 60.0,
            max_latency_recorded: Duration::from_millis(50),
            total_frames: 2000,
        };
        let cloned = result;
        assert_eq!(cloned.buffer_underruns, 3);
        assert_eq!(cloned.dropped_frames, 7);
        assert!((cloned.average_fps - 60.0).abs() < f64::EPSILON);
        assert_eq!(cloned.max_latency_recorded, Duration::from_millis(50));
        assert_eq!(cloned.total_frames, 2000);
    }

    #[test]
    fn test_vu_meter_config_smoothing_tolerance() {
        let config = VuMeterConfig {
            min_level: 0.0,
            max_level: 1.0,
            update_rate_hz: 30.0,
            smoothing_tolerance: 0.2,
            max_stale_ms: 100,
        };

        // Level at max + tolerance should pass
        assert!(config.validate_sample(1.19).is_ok());

        // Level beyond max + tolerance should fail
        assert!(config.validate_sample(1.21).is_err());
    }

    #[test]
    fn test_compression_algorithm_debug() {
        let algos = [
            CompressionAlgorithm::Lz4,
            CompressionAlgorithm::Zstd,
            CompressionAlgorithm::Png,
            CompressionAlgorithm::Rle,
        ];
        for algo in algos {
            let debug = format!("{:?}", algo);
            assert!(!debug.is_empty());
        }
    }

    #[test]
    fn test_compression_algorithm_copy() {
        let algo = CompressionAlgorithm::Lz4;
        let copied = algo;
        assert_eq!(algo, copied);
    }

    #[test]
    fn test_test_execution_stats_large_values() {
        let mut stats = TestExecutionStats::new();
        stats.record_state_capture(u64::MAX / 2, u64::MAX / 4);

        // Should handle large values without overflow
        let ratio = stats.compression_ratio();
        assert!(ratio > 0.0);

        let efficiency = stats.efficiency();
        assert!(efficiency > 0.0 && efficiency < 1.0);
    }

    #[test]
    fn test_storage_savings_small_values() {
        let mut stats = TestExecutionStats::new();
        stats.record_state_capture(500_000, 400_000); // 0.1 MB saved

        let savings = stats.storage_savings_mb();
        assert!((savings - 0.1).abs() < 0.01);
    }

    #[test]
    fn test_storage_savings_compressed_larger_than_raw() {
        let mut stats = TestExecutionStats::new();
        // Edge case: compressed somehow larger than raw (saturating_sub handles this)
        stats.bytes_raw = 100;
        stats.bytes_compressed = 200;

        let savings = stats.storage_savings_mb();
        assert!((savings - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_same_fill_exactly_at_threshold() {
        let mut stats = TestExecutionStats::new();
        // Exactly 10% compression ratio - boundary case
        stats.record_state_capture(1000, 100);
        // 10% is not < 10%, so should not count as same-fill
        assert_eq!(stats.same_fill_pages, 0);

        // Just under 10%
        stats.record_state_capture(1000, 99);
        assert_eq!(stats.same_fill_pages, 1);
    }

    #[test]
    fn test_streaming_ux_validator_debug() {
        let validator = StreamingUxValidator::new();
        let debug = format!("{:?}", validator);
        assert!(debug.contains("StreamingUxValidator"));
    }

    #[test]
    fn test_streaming_metric_record_debug() {
        let record = StreamingMetricRecord {
            metric: StreamingMetric::FrameDropped,
            timestamp: Instant::now(),
        };
        let debug = format!("{:?}", record);
        assert!(debug.contains("StreamingMetricRecord"));
    }

    #[test]
    fn test_validate_all_empty_metrics() {
        let validator = StreamingUxValidator::new();
        let errors = validator.validate_all();
        assert!(errors.is_empty());
    }

    #[test]
    fn test_validate_with_error_state() {
        let mut validator = StreamingUxValidator::new();
        validator.error();

        let result = validator.validate();
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            StreamingValidationError::EndedInError
        ));
    }

    #[test]
    fn test_validate_all_multiple_error_types() {
        let mut validator = StreamingUxValidator::new()
            .with_max_latency(Duration::from_millis(10))
            .with_buffer_underrun_threshold(0)
            .with_max_dropped_frames(0)
            .with_min_fps(100.0);

        validator.record_metric(StreamingMetric::Latency(Duration::from_millis(50)));
        validator.record_metric(StreamingMetric::BufferUnderrun);
        validator.record_metric(StreamingMetric::FrameDropped);

        // Add slow frames for FPS error
        for i in 0..5 {
            validator.record_metric(StreamingMetric::FrameRendered {
                timestamp: i * 500, // 2 fps
            });
        }

        validator.error();

        let errors = validator.validate_all();
        // Should have: latency, underrun, dropped frames, fps, ended in error
        assert!(errors.len() >= 4);
    }

    #[test]
    fn test_vu_meter_error_negative_level_value() {
        let config = VuMeterConfig::default();
        let result = config.validate_sample(-10.5);
        match result {
            Err(VuMeterError::NegativeLevel(v)) => {
                assert!((v - (-10.5)).abs() < f32::EPSILON);
            }
            _ => panic!("Expected NegativeLevel error"),
        }
    }

    #[test]
    fn test_vu_meter_error_clipping_value() {
        let config = VuMeterConfig::default().with_max_level(0.5);
        let result = config.validate_sample(2.0);
        match result {
            Err(VuMeterError::Clipping(v)) => {
                assert!((v - 2.0).abs() < f32::EPSILON);
            }
            _ => panic!("Expected Clipping error"),
        }
    }

    #[test]
    fn test_streaming_state_hash() {
        use std::collections::HashSet;
        let mut set = HashSet::new();
        set.insert(StreamingState::Idle);
        set.insert(StreamingState::Buffering);
        set.insert(StreamingState::Streaming);
        set.insert(StreamingState::Stalled);
        set.insert(StreamingState::Error);
        set.insert(StreamingState::Completed);

        assert_eq!(set.len(), 6);
        assert!(set.contains(&StreamingState::Idle));
    }

    #[test]
    fn test_screenshot_content_clone() {
        let contents = vec![
            ScreenshotContent::Uniform { fill_value: 128 },
            ScreenshotContent::UiDominated { entropy: 2.5 },
            ScreenshotContent::GameWorld { entropy: 4.5 },
            ScreenshotContent::HighEntropy { entropy: 7.0 },
        ];

        for content in contents {
            let cloned = content.clone();
            assert!((cloned.entropy() - content.entropy()).abs() < f32::EPSILON);
        }
    }

    #[test]
    fn test_test_execution_stats_all_fields() {
        let mut stats = TestExecutionStats::new();
        stats.start();
        stats.record_state_capture(1000, 100);
        stats.record_state_capture(2000, 50); // same-fill
        stats.stop();

        assert_eq!(stats.states_captured, 2);
        assert_eq!(stats.bytes_raw, 3000);
        assert_eq!(stats.bytes_compressed, 150);
        assert_eq!(stats.same_fill_pages, 1);
    }

    #[test]
    fn test_frame_times_exactly_120() {
        let mut validator = StreamingUxValidator::new();
        // Add exactly 120 frames
        for i in 0..120 {
            validator.record_metric(StreamingMetric::FrameRendered { timestamp: i * 16 });
        }
        assert!(validator.average_fps() > 0.0);
    }

    #[test]
    fn test_frame_times_121() {
        let mut validator = StreamingUxValidator::new();
        // Add 121 frames - should cap at 120
        for i in 0..121 {
            validator.record_metric(StreamingMetric::FrameRendered { timestamp: i * 16 });
        }
        // The oldest frame should be removed
        assert!(validator.average_fps() > 0.0);
    }

    #[test]
    fn test_state_transition_fields_access() {
        let transition = StateTransition {
            from: "State1".to_string(),
            to: "State2".to_string(),
            timestamp_ms: 12345.67,
            duration_ms: 890.12,
        };

        assert_eq!(transition.from.as_str(), "State1");
        assert_eq!(transition.to.as_str(), "State2");
        assert!((transition.timestamp_ms - 12345.67).abs() < f64::EPSILON);
        assert!((transition.duration_ms - 890.12).abs() < f64::EPSILON);
    }

    #[test]
    fn test_partial_result_fields_access() {
        let partial = PartialResult {
            timestamp_ms: 999.99,
            text: "Hello World".to_string(),
            is_final: true,
        };

        assert!((partial.timestamp_ms - 999.99).abs() < f64::EPSILON);
        assert_eq!(partial.text.as_str(), "Hello World");
        assert!(partial.is_final);
    }

    #[test]
    fn test_vu_meter_sample_fields_access() {
        let sample = VuMeterSample {
            timestamp_ms: 1234.5,
            level: 0.789,
        };

        assert!((sample.timestamp_ms - 1234.5).abs() < f64::EPSILON);
        assert!((sample.level - 0.789).abs() < f32::EPSILON);
    }

    #[test]
    fn test_streaming_metric_record_fields_access() {
        let timestamp = Instant::now();
        let record = StreamingMetricRecord {
            metric: StreamingMetric::BufferLevel(0.42),
            timestamp,
        };

        assert!(matches!(record.metric, StreamingMetric::BufferLevel(..)));
        assert_eq!(record.timestamp, timestamp);
    }

    #[test]
    fn test_validate_returns_first_error() {
        let mut validator = StreamingUxValidator::new()
            .with_max_latency(Duration::from_millis(10))
            .with_buffer_underrun_threshold(0);

        // Record latency error first (in order)
        validator.record_metric(StreamingMetric::Latency(Duration::from_millis(50)));
        validator.record_metric(StreamingMetric::BufferUnderrun);

        let result = validator.validate();
        assert!(result.is_err());
        // Should return latency error (first in check order)
        assert!(matches!(
            result.unwrap_err(),
            StreamingValidationError::LatencyExceeded { .. }
        ));
    }

    #[test]
    fn test_validate_fps_error_only_when_positive() {
        let mut validator = StreamingUxValidator::new().with_min_fps(100.0);

        // No frames at all - fps is 0, should not trigger fps error
        let result = validator.validate();
        assert!(result.is_ok());

        // Add one frame - fps is still 0
        validator.record_metric(StreamingMetric::FrameRendered { timestamp: 0 });
        let result = validator.validate();
        assert!(result.is_ok());
    }

    #[test]
    fn test_buffer_level_recovery_threshold() {
        let mut validator = StreamingUxValidator::new();
        validator.start();
        validator.record_metric(StreamingMetric::AudioChunk {
            samples: 1024,
            sample_rate: 16000,
        });
        assert_eq!(validator.state(), StreamingState::Streaming);

        // Low buffer - should stall
        validator.record_metric(StreamingMetric::BufferLevel(0.05));
        assert_eq!(validator.state(), StreamingState::Stalled);

        // Buffer at exactly 0.3 - should NOT recover (threshold is > 0.3)
        validator.record_metric(StreamingMetric::BufferLevel(0.3));
        assert_eq!(validator.state(), StreamingState::Stalled);

        // Buffer above 0.3 - should recover
        validator.record_metric(StreamingMetric::BufferLevel(0.31));
        assert_eq!(validator.state(), StreamingState::Streaming);
    }

    #[test]
    fn test_buffer_level_stall_threshold() {
        let mut validator = StreamingUxValidator::new();
        validator.start();
        validator.record_metric(StreamingMetric::AudioChunk {
            samples: 1024,
            sample_rate: 16000,
        });
        assert_eq!(validator.state(), StreamingState::Streaming);

        // Buffer at exactly 0.1 - should NOT stall (threshold is < 0.1)
        validator.record_metric(StreamingMetric::BufferLevel(0.1));
        assert_eq!(validator.state(), StreamingState::Streaming);

        // Buffer below 0.1 - should stall
        validator.record_metric(StreamingMetric::BufferLevel(0.09));
        assert_eq!(validator.state(), StreamingState::Stalled);
    }

    // ========================================================================
    // Additional tests for 95%+ coverage - Edge cases and branches
    // ========================================================================

    #[test]
    fn test_vu_meter_config_default_values() {
        let config = VuMeterConfig::default();
        assert!((config.min_level - 0.0).abs() < f32::EPSILON);
        assert!((config.max_level - 1.0).abs() < f32::EPSILON);
        assert!((config.update_rate_hz - 30.0).abs() < f32::EPSILON);
        assert!((config.smoothing_tolerance - 0.1).abs() < f32::EPSILON);
        assert_eq!(config.max_stale_ms, 100);
    }

    #[test]
    fn test_vu_meter_error_display_all_variants() {
        // NegativeLevel
        let err = VuMeterError::NegativeLevel(-0.25);
        let display = format!("{}", err);
        assert!(display.contains("-0.25"));
        assert!(display.contains("negative"));

        // Clipping
        let err = VuMeterError::Clipping(1.75);
        let display = format!("{}", err);
        assert!(display.contains("1.75"));
        assert!(display.contains("clipping"));

        // Stale
        let err = VuMeterError::Stale {
            last_update_ms: 50,
            current_ms: 250,
        };
        let display = format!("{}", err);
        assert!(display.contains("200ms"));

        // SlowUpdateRate
        let err = VuMeterError::SlowUpdateRate {
            measured_hz: 20.0,
            expected_hz: 60.0,
        };
        let display = format!("{}", err);
        assert!(display.contains("20.0Hz"));
        assert!(display.contains("60.0Hz"));

        // NotAnimating
        let err = VuMeterError::NotAnimating {
            sample_count: 50,
            value: 0.75,
        };
        let display = format!("{}", err);
        assert!(display.contains("50 samples"));
        assert!(display.contains("0.75"));
    }

    #[test]
    fn test_streaming_validation_error_display_all_variants() {
        let err = StreamingValidationError::LatencyExceeded {
            measured: Duration::from_millis(300),
            max: Duration::from_millis(100),
        };
        assert!(err.to_string().contains("300"));

        let err = StreamingValidationError::BufferUnderrunThreshold {
            count: 15,
            threshold: 5,
        };
        assert!(err.to_string().contains("15"));
        assert!(err.to_string().contains('5'));

        let err = StreamingValidationError::DroppedFrameThreshold { count: 25, max: 10 };
        assert!(err.to_string().contains("25"));
        assert!(err.to_string().contains("10"));

        let err = StreamingValidationError::FpsBelowMinimum {
            measured: 20.5,
            min: 60.0,
        };
        assert!(err.to_string().contains("20.5"));
        assert!(err.to_string().contains("60.0"));

        let err = StreamingValidationError::TtfbExceeded {
            measured: Duration::from_secs(10),
            max: Duration::from_secs(3),
        };
        let display = err.to_string();
        assert!(display.contains("first byte"));

        let err = StreamingValidationError::InvalidStateTransition {
            from: StreamingState::Buffering,
            to: StreamingState::Completed,
        };
        let display = err.to_string();
        assert!(display.contains("Buffering"));
        assert!(display.contains("Completed"));

        let err = StreamingValidationError::EndedInError;
        assert!(err.to_string().contains("error state"));
    }

    #[test]
    fn test_streaming_state_display_coverage() {
        // Test all StreamingState Display implementations
        assert_eq!(format!("{}", StreamingState::Idle), "Idle");
        assert_eq!(format!("{}", StreamingState::Buffering), "Buffering");
        assert_eq!(format!("{}", StreamingState::Streaming), "Streaming");
        assert_eq!(format!("{}", StreamingState::Stalled), "Stalled");
        assert_eq!(format!("{}", StreamingState::Error), "Error");
        assert_eq!(format!("{}", StreamingState::Completed), "Completed");
    }

    #[test]
    fn test_test_execution_stats_zero_raw_bytes() {
        let stats = TestExecutionStats::new();
        // Zero raw bytes should not panic and return 0 efficiency
        assert!((stats.efficiency() - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_test_execution_stats_zero_compressed_bytes() {
        let mut stats = TestExecutionStats::new();
        stats.bytes_raw = 1000;
        stats.bytes_compressed = 0;
        // Zero compressed bytes should return 0 ratio (avoid div by zero)
        assert!((stats.compression_ratio() - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_test_execution_stats_zero_states_captured() {
        let stats = TestExecutionStats::new();
        // Zero states should return 0 same_fill_ratio
        assert!((stats.same_fill_ratio() - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_test_execution_stats_throughput_no_start() {
        let mut stats = TestExecutionStats::new();
        stats.stop();
        stats.record_state_capture(1000, 100);
        // No start time should return 0 throughput
        assert!((stats.compress_throughput() - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_test_execution_stats_throughput_only_end() {
        let mut stats = TestExecutionStats::new();
        stats.stop();
        // Only end time, no start - should return 0 throughput
        assert!((stats.compress_throughput() - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_test_execution_stats_same_fill_with_zero_raw() {
        let mut stats = TestExecutionStats::new();
        // Edge case: raw_bytes is 0, should not count as same-fill
        stats.record_state_capture(0, 0);
        assert_eq!(stats.same_fill_pages, 0);
    }

    #[test]
    fn test_screenshot_content_classify_single_pixel() {
        // Edge case: single pixel
        let content = ScreenshotContent::classify(&[42]);
        assert!(matches!(
            content,
            ScreenshotContent::Uniform { fill_value: 42 }
        ));
    }

    #[test]
    fn test_screenshot_content_all_different_values() {
        // All 256 different values - maximum entropy
        let pixels: Vec<u8> = (0..=255).collect();
        let content = ScreenshotContent::classify(&pixels);
        assert!(matches!(content, ScreenshotContent::HighEntropy { .. }));
        // Should have 8 bits of entropy
        assert!(content.entropy() > 7.5);
    }

    #[test]
    fn test_screenshot_content_entropy_method_uniform() {
        let content = ScreenshotContent::Uniform { fill_value: 200 };
        assert!((content.entropy() - 0.0).abs() < f32::EPSILON);
    }

    #[test]
    fn test_screenshot_content_recommended_algorithm_all() {
        assert_eq!(
            ScreenshotContent::Uniform { fill_value: 0 }.recommended_algorithm(),
            CompressionAlgorithm::Rle
        );
        assert_eq!(
            ScreenshotContent::UiDominated { entropy: 2.0 }.recommended_algorithm(),
            CompressionAlgorithm::Png
        );
        assert_eq!(
            ScreenshotContent::GameWorld { entropy: 4.5 }.recommended_algorithm(),
            CompressionAlgorithm::Zstd
        );
        assert_eq!(
            ScreenshotContent::HighEntropy { entropy: 7.0 }.recommended_algorithm(),
            CompressionAlgorithm::Lz4
        );
    }

    #[test]
    fn test_screenshot_content_expected_ratio_hint_all() {
        assert!(ScreenshotContent::Uniform { fill_value: 0 }
            .expected_ratio_hint()
            .contains("excellent"));
        assert!(ScreenshotContent::UiDominated { entropy: 2.0 }
            .expected_ratio_hint()
            .contains("good"));
        assert!(ScreenshotContent::GameWorld { entropy: 4.5 }
            .expected_ratio_hint()
            .contains("moderate"));
        assert!(ScreenshotContent::HighEntropy { entropy: 7.0 }
            .expected_ratio_hint()
            .contains("poor"));
    }

    #[test]
    fn test_streaming_ux_validator_builder_chain() {
        let validator = StreamingUxValidator::new()
            .with_max_latency(Duration::from_millis(150))
            .with_buffer_underrun_threshold(10)
            .with_max_dropped_frames(20)
            .with_min_fps(45.0)
            .with_ttfb_timeout(Duration::from_secs(5));

        assert_eq!(validator.max_latency, Duration::from_millis(150));
        assert_eq!(validator.buffer_underrun_threshold, 10);
        assert_eq!(validator.max_dropped_frames, 20);
        assert!((validator.min_fps - 45.0).abs() < f64::EPSILON);
        assert_eq!(validator.ttfb_timeout, Duration::from_secs(5));
    }

    #[test]
    fn test_streaming_validator_for_audio_preset() {
        let validator = StreamingUxValidator::for_audio();
        assert_eq!(validator.max_latency, Duration::from_millis(100));
        assert_eq!(validator.buffer_underrun_threshold, 3);
        assert_eq!(validator.ttfb_timeout, Duration::from_secs(2));
    }

    #[test]
    fn test_streaming_validator_for_video_preset() {
        let validator = StreamingUxValidator::for_video();
        assert_eq!(validator.max_latency, Duration::from_millis(500));
        assert!((validator.min_fps - 30.0).abs() < f64::EPSILON);
        assert_eq!(validator.max_dropped_frames, 5);
    }

    #[test]
    fn test_streaming_validator_average_fps_no_frames() {
        let validator = StreamingUxValidator::new();
        assert!((validator.average_fps() - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_streaming_validator_average_fps_one_frame() {
        let mut validator = StreamingUxValidator::new();
        validator.record_metric(StreamingMetric::FrameRendered { timestamp: 1000 });
        assert!((validator.average_fps() - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_streaming_validator_average_fps_same_timestamp() {
        let mut validator = StreamingUxValidator::new();
        validator.record_metric(StreamingMetric::FrameRendered { timestamp: 1000 });
        validator.record_metric(StreamingMetric::FrameRendered { timestamp: 1000 });
        validator.record_metric(StreamingMetric::FrameRendered { timestamp: 1000 });
        // Zero duration should return 0 fps
        assert!((validator.average_fps() - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_streaming_validator_max_recorded_latency_none() {
        let validator = StreamingUxValidator::new();
        let result = validator.validate();
        assert!(result.is_ok());
        let res = result.unwrap();
        assert_eq!(res.max_latency_recorded, Duration::ZERO);
    }

    #[test]
    fn test_streaming_validator_validate_no_ttfb() {
        let mut validator = StreamingUxValidator::new();
        validator.start();
        // No first byte received, but should still validate
        let result = validator.validate();
        assert!(result.is_ok());
    }

    #[test]
    fn test_streaming_validator_complete_and_validate() {
        let mut validator = StreamingUxValidator::new();
        validator.complete();
        assert_eq!(validator.state(), StreamingState::Completed);
        let result = validator.validate();
        assert!(result.is_ok());
    }

    #[test]
    fn test_streaming_validator_error_and_validate() {
        let mut validator = StreamingUxValidator::new();
        validator.error();
        assert_eq!(validator.state(), StreamingState::Error);
        let result = validator.validate();
        assert!(result.is_err());
    }

    #[test]
    fn test_streaming_validator_state_history_empty() {
        let validator = StreamingUxValidator::new();
        assert!(validator.state_history().is_empty());
    }

    #[test]
    fn test_streaming_validator_state_history_with_transitions() {
        let mut validator = StreamingUxValidator::new();
        validator.start();
        validator.record_metric(StreamingMetric::AudioChunk {
            samples: 1024,
            sample_rate: 16000,
        });
        validator.complete();

        let history = validator.state_history();
        assert!(history.len() >= 2);
    }

    #[test]
    fn test_streaming_validator_reset_full() {
        let mut validator = StreamingUxValidator::new();
        validator.start();
        validator.record_metric(StreamingMetric::Latency(Duration::from_millis(50)));
        validator.record_metric(StreamingMetric::BufferUnderrun);
        validator.record_metric(StreamingMetric::FrameDropped);
        validator.record_metric(StreamingMetric::FirstByteReceived);
        validator.record_metric(StreamingMetric::FrameRendered { timestamp: 100 });

        validator.reset();

        assert_eq!(validator.state(), StreamingState::Idle);
        assert_eq!(validator.buffer_underruns(), 0);
        assert_eq!(validator.dropped_frames(), 0);
        assert!(validator.state_history().is_empty());
    }

    #[test]
    fn test_streaming_validator_validate_all_with_error_state() {
        let mut validator = StreamingUxValidator::new();
        validator.error();
        let errors = validator.validate_all();
        assert!(errors
            .iter()
            .any(|e| matches!(e, StreamingValidationError::EndedInError)));
    }

    #[test]
    fn test_streaming_validation_result_fields_all() {
        let result = StreamingValidationResult {
            buffer_underruns: 1,
            dropped_frames: 2,
            average_fps: 30.0,
            max_latency_recorded: Duration::from_millis(50),
            total_frames: 100,
        };
        assert_eq!(result.buffer_underruns, 1);
        assert_eq!(result.dropped_frames, 2);
        assert!((result.average_fps - 30.0).abs() < f64::EPSILON);
        assert_eq!(result.max_latency_recorded, Duration::from_millis(50));
        assert_eq!(result.total_frames, 100);
    }

    #[test]
    fn test_state_transition_struct_fields_all() {
        let transition = StateTransition {
            from: "StateA".to_string(),
            to: "StateB".to_string(),
            timestamp_ms: 100.0,
            duration_ms: 50.0,
        };
        assert_eq!(&transition.from, "StateA");
        assert_eq!(&transition.to, "StateB");
        assert!((transition.timestamp_ms - 100.0).abs() < f64::EPSILON);
        assert!((transition.duration_ms - 50.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_partial_result_struct_fields() {
        let partial = PartialResult {
            timestamp_ms: 200.0,
            text: "partial text".to_string(),
            is_final: false,
        };
        assert!((partial.timestamp_ms - 200.0).abs() < f64::EPSILON);
        assert_eq!(&partial.text, "partial text");
        assert!(!partial.is_final);

        let final_result = PartialResult {
            timestamp_ms: 300.0,
            text: "final text".to_string(),
            is_final: true,
        };
        assert!(final_result.is_final);
    }

    #[test]
    fn test_vu_meter_sample_struct_fields() {
        let sample = VuMeterSample {
            timestamp_ms: 150.0,
            level: 0.65,
        };
        assert!((sample.timestamp_ms - 150.0).abs() < f64::EPSILON);
        assert!((sample.level - 0.65).abs() < f32::EPSILON);
    }

    #[test]
    fn test_streaming_metric_record_struct() {
        let now = Instant::now();
        let record = StreamingMetricRecord {
            metric: StreamingMetric::FrameDropped,
            timestamp: now,
        };
        assert!(matches!(record.metric, StreamingMetric::FrameDropped));
        assert_eq!(record.timestamp, now);
    }

    #[test]
    fn test_streaming_metric_latency_variant() {
        let metric = StreamingMetric::Latency(Duration::from_millis(123));
        if let StreamingMetric::Latency(d) = metric {
            assert_eq!(d, Duration::from_millis(123));
        } else {
            panic!("Expected Latency variant");
        }
    }

    #[test]
    fn test_streaming_metric_frame_rendered_variant() {
        let metric = StreamingMetric::FrameRendered { timestamp: 999 };
        if let StreamingMetric::FrameRendered { timestamp } = metric {
            assert_eq!(timestamp, 999);
        } else {
            panic!("Expected FrameRendered variant");
        }
    }

    #[test]
    fn test_streaming_metric_buffer_level_variant() {
        let metric = StreamingMetric::BufferLevel(0.42);
        if let StreamingMetric::BufferLevel(level) = metric {
            assert!((level - 0.42).abs() < f32::EPSILON);
        } else {
            panic!("Expected BufferLevel variant");
        }
    }

    #[test]
    fn test_streaming_metric_audio_chunk_variant() {
        let metric = StreamingMetric::AudioChunk {
            samples: 2048,
            sample_rate: 44100,
        };
        if let StreamingMetric::AudioChunk {
            samples,
            sample_rate,
        } = metric
        {
            assert_eq!(samples, 2048);
            assert_eq!(sample_rate, 44100);
        } else {
            panic!("Expected AudioChunk variant");
        }
    }

    #[test]
    fn test_compression_algorithm_eq() {
        assert_eq!(CompressionAlgorithm::Lz4, CompressionAlgorithm::Lz4);
        assert_eq!(CompressionAlgorithm::Zstd, CompressionAlgorithm::Zstd);
        assert_eq!(CompressionAlgorithm::Png, CompressionAlgorithm::Png);
        assert_eq!(CompressionAlgorithm::Rle, CompressionAlgorithm::Rle);
    }

    #[test]
    fn test_streaming_state_eq() {
        assert_eq!(StreamingState::Idle, StreamingState::Idle);
        assert_eq!(StreamingState::Buffering, StreamingState::Buffering);
        assert_eq!(StreamingState::Streaming, StreamingState::Streaming);
        assert_eq!(StreamingState::Stalled, StreamingState::Stalled);
        assert_eq!(StreamingState::Error, StreamingState::Error);
        assert_eq!(StreamingState::Completed, StreamingState::Completed);
    }

    #[test]
    fn test_streaming_state_ne() {
        assert_ne!(StreamingState::Idle, StreamingState::Buffering);
        assert_ne!(StreamingState::Streaming, StreamingState::Stalled);
        assert_ne!(StreamingState::Error, StreamingState::Completed);
    }

    #[test]
    fn test_vu_meter_error_debug() {
        let errors = vec![
            VuMeterError::NegativeLevel(-1.0),
            VuMeterError::Clipping(2.0),
            VuMeterError::Stale {
                last_update_ms: 100,
                current_ms: 200,
            },
            VuMeterError::SlowUpdateRate {
                measured_hz: 10.0,
                expected_hz: 30.0,
            },
            VuMeterError::NotAnimating {
                sample_count: 5,
                value: 0.5,
            },
        ];

        for err in errors {
            let debug = format!("{:?}", err);
            assert!(!debug.is_empty());
        }
    }

    #[test]
    fn test_streaming_validation_error_debug() {
        let errors: Vec<StreamingValidationError> = vec![
            StreamingValidationError::LatencyExceeded {
                measured: Duration::from_millis(100),
                max: Duration::from_millis(50),
            },
            StreamingValidationError::BufferUnderrunThreshold {
                count: 5,
                threshold: 3,
            },
            StreamingValidationError::DroppedFrameThreshold { count: 10, max: 5 },
            StreamingValidationError::FpsBelowMinimum {
                measured: 15.0,
                min: 30.0,
            },
            StreamingValidationError::TtfbExceeded {
                measured: Duration::from_secs(5),
                max: Duration::from_secs(2),
            },
            StreamingValidationError::InvalidStateTransition {
                from: StreamingState::Idle,
                to: StreamingState::Error,
            },
            StreamingValidationError::EndedInError,
        ];

        for err in errors {
            let debug = format!("{:?}", err);
            assert!(!debug.is_empty());
        }
    }

    #[test]
    fn test_screenshot_content_classify_boundary_uniform() {
        // Exactly 95% same value should still be Uniform (> 0.95)
        let mut pixels = vec![100u8; 96];
        pixels.extend(vec![200u8; 4]);
        let content = ScreenshotContent::classify(&pixels);
        assert!(matches!(
            content,
            ScreenshotContent::Uniform { fill_value: 100 }
        ));
    }

    #[test]
    fn test_screenshot_content_classify_just_under_uniform() {
        // 94% same value should NOT be uniform
        let mut pixels = vec![100u8; 94];
        pixels.extend(vec![200u8; 6]);
        let content = ScreenshotContent::classify(&pixels);
        // Should not be Uniform
        assert!(!matches!(content, ScreenshotContent::Uniform { .. }));
    }

    #[test]
    fn test_test_execution_stats_reset_clears_timing() {
        let mut stats = TestExecutionStats::new();
        stats.start();
        stats.record_state_capture(1000, 100);
        stats.stop();

        // Verify we have throughput
        assert!(stats.compress_throughput() > 0.0 || stats.bytes_raw > 0);

        stats.reset();

        // After reset, throughput should be 0 (no timing data)
        assert!((stats.compress_throughput() - 0.0).abs() < f64::EPSILON);
        assert_eq!(stats.states_captured, 0);
        assert_eq!(stats.bytes_raw, 0);
        assert_eq!(stats.bytes_compressed, 0);
        assert_eq!(stats.same_fill_pages, 0);
    }

    #[test]
    fn test_frame_times_cap_at_120() {
        let mut validator = StreamingUxValidator::new();

        // Add 200 frames
        for i in 0..200 {
            validator.record_metric(StreamingMetric::FrameRendered { timestamp: i * 16 });
        }

        // Frame times should be capped (checked via FPS calculation working)
        let fps = validator.average_fps();
        assert!(fps > 0.0);
    }

    #[test]
    fn test_latency_metric_triggers_buffering_to_streaming() {
        let mut validator =
            StreamingUxValidator::new().with_max_latency(Duration::from_millis(200));
        validator.start();
        assert_eq!(validator.state(), StreamingState::Buffering);

        // Good latency should transition to Streaming
        validator.record_metric(StreamingMetric::Latency(Duration::from_millis(50)));
        assert_eq!(validator.state(), StreamingState::Streaming);
    }

    #[test]
    fn test_latency_metric_high_latency_no_transition() {
        let mut validator = StreamingUxValidator::new().with_max_latency(Duration::from_millis(50));
        validator.start();
        assert_eq!(validator.state(), StreamingState::Buffering);

        // High latency should NOT transition to Streaming
        validator.record_metric(StreamingMetric::Latency(Duration::from_millis(100)));
        assert_eq!(validator.state(), StreamingState::Buffering);
    }

    #[test]
    fn test_buffer_level_stall_only_when_streaming() {
        let mut validator = StreamingUxValidator::new();
        // In Idle state
        validator.record_metric(StreamingMetric::BufferLevel(0.01));
        assert_eq!(validator.state(), StreamingState::Idle);

        // In Buffering state
        validator.start();
        validator.record_metric(StreamingMetric::BufferLevel(0.01));
        assert_eq!(validator.state(), StreamingState::Buffering);
    }

    #[test]
    fn test_buffer_level_recovery_only_when_stalled() {
        let mut validator = StreamingUxValidator::new();
        validator.start();
        validator.record_metric(StreamingMetric::AudioChunk {
            samples: 1024,
            sample_rate: 16000,
        });
        assert_eq!(validator.state(), StreamingState::Streaming);

        // High buffer level should NOT change state when already Streaming
        validator.record_metric(StreamingMetric::BufferLevel(0.9));
        assert_eq!(validator.state(), StreamingState::Streaming);
    }

    #[test]
    fn test_frame_rendered_recovery_from_stalled() {
        let mut validator = StreamingUxValidator::new();
        validator.start();
        validator.record_metric(StreamingMetric::AudioChunk {
            samples: 1024,
            sample_rate: 16000,
        });
        validator.record_metric(StreamingMetric::BufferLevel(0.01)); // Stall

        assert_eq!(validator.state(), StreamingState::Stalled);

        // Frame rendered should recover
        validator.record_metric(StreamingMetric::FrameRendered { timestamp: 100 });
        assert_eq!(validator.state(), StreamingState::Streaming);
    }

    #[test]
    fn test_audio_chunk_only_transitions_from_buffering() {
        let mut validator = StreamingUxValidator::new();

        // In Idle - should not transition
        validator.record_metric(StreamingMetric::AudioChunk {
            samples: 1024,
            sample_rate: 16000,
        });
        assert_eq!(validator.state(), StreamingState::Idle);
    }

    #[test]
    fn test_first_byte_received_only_transitions_from_idle() {
        let mut validator = StreamingUxValidator::new();
        validator.start(); // Now in Buffering

        // FirstByte when already buffering should not re-transition
        validator.record_metric(StreamingMetric::FirstByteReceived);
        assert_eq!(validator.state(), StreamingState::Buffering);
    }

    #[test]
    fn test_buffer_underrun_only_stalls_when_streaming() {
        let mut validator = StreamingUxValidator::new();

        // In Idle - underrun should not change state
        validator.record_metric(StreamingMetric::BufferUnderrun);
        assert_eq!(validator.state(), StreamingState::Idle);

        // In Buffering - underrun should not change state
        validator.start();
        validator.record_metric(StreamingMetric::BufferUnderrun);
        assert_eq!(validator.state(), StreamingState::Buffering);
    }

    #[test]
    fn test_validate_all_fps_error() {
        let mut validator = StreamingUxValidator::new().with_min_fps(60.0);

        // Add slow frames
        for i in 0..10 {
            validator.record_metric(StreamingMetric::FrameRendered {
                timestamp: i * 100, // 10 fps
            });
        }

        let errors = validator.validate_all();
        assert!(errors
            .iter()
            .any(|e| matches!(e, StreamingValidationError::FpsBelowMinimum { .. })));
    }

    #[test]
    fn test_validate_all_buffer_underrun_error() {
        let mut validator = StreamingUxValidator::new().with_buffer_underrun_threshold(1);

        validator.record_metric(StreamingMetric::BufferUnderrun);
        validator.record_metric(StreamingMetric::BufferUnderrun);

        let errors = validator.validate_all();
        assert!(errors
            .iter()
            .any(|e| matches!(e, StreamingValidationError::BufferUnderrunThreshold { .. })));
    }

    #[test]
    fn test_validate_all_dropped_frames_error() {
        let mut validator = StreamingUxValidator::new().with_max_dropped_frames(1);

        validator.record_metric(StreamingMetric::FrameDropped);
        validator.record_metric(StreamingMetric::FrameDropped);

        let errors = validator.validate_all();
        assert!(errors
            .iter()
            .any(|e| matches!(e, StreamingValidationError::DroppedFrameThreshold { .. })));
    }

    #[test]
    fn test_streaming_state_copy_clone() {
        let state = StreamingState::Streaming;
        let copied = state;
        let cloned = state;
        assert_eq!(copied, cloned);
        assert_eq!(state, StreamingState::Streaming);
    }

    #[test]
    fn test_compression_algorithm_copy_clone() {
        let algo = CompressionAlgorithm::Zstd;
        let copied = algo;
        let cloned = algo;
        assert_eq!(copied, cloned);
        assert_eq!(algo, CompressionAlgorithm::Zstd);
    }
}