aprender-present-test 0.60.0

Testing harness for Presentar applications
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
#![allow(
    clippy::derive_partial_eq_without_eq,
    clippy::doc_markdown,
    clippy::missing_const_for_fn
)]
//! Grade scoring system for quality evaluation.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Quality grade levels (A+ through F) per spec.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub enum Grade {
    /// Failing (0-49)
    #[default]
    F,
    /// Incomplete (50-54)
    D,
    /// Sketch (55-59)
    CMinus,
    /// Draft (60-64)
    C,
    /// Prototype (65-69)
    CPlus,
    /// Development (70-74)
    BMinus,
    /// Alpha Quality (75-79)
    B,
    /// Beta Quality (80-84)
    BPlus,
    /// Release Candidate (85-89)
    AMinus,
    /// Production Ready (90-94)
    A,
    /// Production Excellence (95-100)
    APlus,
}

impl PartialOrd for Grade {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Grade {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // Compare by minimum percentage (A > B > C > D > F)
        self.min_percentage()
            .partial_cmp(&other.min_percentage())
            .unwrap_or(std::cmp::Ordering::Equal)
    }
}

impl Grade {
    /// Create a grade from a percentage score (0-100 scale).
    #[must_use]
    pub fn from_percentage(percent: f32) -> Self {
        match percent {
            p if p >= 95.0 => Self::APlus,
            p if p >= 90.0 => Self::A,
            p if p >= 85.0 => Self::AMinus,
            p if p >= 80.0 => Self::BPlus,
            p if p >= 75.0 => Self::B,
            p if p >= 70.0 => Self::BMinus,
            p if p >= 65.0 => Self::CPlus,
            p if p >= 60.0 => Self::C,
            p if p >= 55.0 => Self::CMinus,
            p if p >= 50.0 => Self::D,
            _ => Self::F,
        }
    }

    /// Get the minimum percentage for this grade.
    #[must_use]
    pub const fn min_percentage(&self) -> f32 {
        match self {
            Self::APlus => 95.0,
            Self::A => 90.0,
            Self::AMinus => 85.0,
            Self::BPlus => 80.0,
            Self::B => 75.0,
            Self::BMinus => 70.0,
            Self::CPlus => 65.0,
            Self::C => 60.0,
            Self::CMinus => 55.0,
            Self::D => 50.0,
            Self::F => 0.0,
        }
    }

    /// Get grade as a letter string.
    #[must_use]
    pub const fn letter(&self) -> &'static str {
        match self {
            Self::APlus => "A+",
            Self::A => "A",
            Self::AMinus => "A-",
            Self::BPlus => "B+",
            Self::B => "B",
            Self::BMinus => "B-",
            Self::CPlus => "C+",
            Self::C => "C",
            Self::CMinus => "C-",
            Self::D => "D",
            Self::F => "F",
        }
    }

    /// Check if this is a passing grade (C or better = 60+).
    #[must_use]
    pub const fn is_passing(&self) -> bool {
        matches!(
            self,
            Self::APlus
                | Self::A
                | Self::AMinus
                | Self::BPlus
                | Self::B
                | Self::BMinus
                | Self::CPlus
                | Self::C
        )
    }

    /// Check if this grade is production ready (B+ or better = 80+).
    #[must_use]
    pub const fn is_production_ready(&self) -> bool {
        matches!(self, Self::APlus | Self::A | Self::AMinus | Self::BPlus)
    }
}

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

/// A scored criterion with name, weight, and result.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Criterion {
    /// Name of the criterion
    pub name: String,
    /// Description of what is being measured
    pub description: String,
    /// Weight (importance) of this criterion (0.0 - 1.0)
    pub weight: f32,
    /// Score achieved (0.0 - 100.0)
    pub score: f32,
    /// Whether this criterion passed
    pub passed: bool,
    /// Detailed feedback
    pub feedback: Option<String>,
}

impl Criterion {
    /// Create a new criterion.
    #[must_use]
    pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            weight: 1.0,
            score: 0.0,
            passed: false,
            feedback: None,
        }
    }

    /// Set the weight.
    #[must_use]
    pub fn weight(mut self, weight: f32) -> Self {
        self.weight = weight.clamp(0.0, 1.0);
        self
    }

    /// Set the score.
    #[must_use]
    pub fn score(mut self, score: f32) -> Self {
        self.score = score.clamp(0.0, 100.0);
        self.passed = self.score >= 60.0;
        self
    }

    /// Mark as passed with a perfect score.
    #[must_use]
    pub const fn pass(mut self) -> Self {
        self.score = 100.0;
        self.passed = true;
        self
    }

    /// Mark as failed with zero score.
    #[must_use]
    pub const fn fail(mut self) -> Self {
        self.score = 0.0;
        self.passed = false;
        self
    }

    /// Add feedback.
    #[must_use]
    pub fn feedback(mut self, feedback: impl Into<String>) -> Self {
        self.feedback = Some(feedback.into());
        self
    }

    /// Get the grade for this criterion.
    #[must_use]
    pub fn grade(&self) -> Grade {
        Grade::from_percentage(self.score)
    }

    /// Get weighted score (score * weight).
    #[must_use]
    pub fn weighted_score(&self) -> f32 {
        self.score * self.weight
    }
}

/// A report card containing multiple criteria scores.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ReportCard {
    /// Title of the evaluation
    pub title: String,
    /// Individual criteria scores
    pub criteria: Vec<Criterion>,
    /// Category scores (aggregated)
    pub categories: HashMap<String, f32>,
}

impl ReportCard {
    /// Create a new report card.
    #[must_use]
    pub fn new(title: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            criteria: Vec::new(),
            categories: HashMap::new(),
        }
    }

    /// Add a criterion.
    pub fn add_criterion(&mut self, criterion: Criterion) {
        self.criteria.push(criterion);
    }

    /// Add criterion with builder pattern.
    #[must_use]
    pub fn criterion(mut self, criterion: Criterion) -> Self {
        self.criteria.push(criterion);
        self
    }

    /// Add a category score.
    pub fn add_category(&mut self, name: impl Into<String>, score: f32) {
        self.categories.insert(name.into(), score.clamp(0.0, 100.0));
    }

    /// Calculate the overall weighted score.
    #[must_use]
    pub fn overall_score(&self) -> f32 {
        if self.criteria.is_empty() {
            return 0.0;
        }

        let total_weight: f32 = self.criteria.iter().map(|c| c.weight).sum();
        if total_weight == 0.0 {
            return 0.0;
        }

        let weighted_sum: f32 = self.criteria.iter().map(Criterion::weighted_score).sum();
        weighted_sum / total_weight
    }

    /// Get the overall grade.
    #[must_use]
    pub fn overall_grade(&self) -> Grade {
        Grade::from_percentage(self.overall_score())
    }

    /// Check if all criteria passed.
    #[must_use]
    pub fn all_passed(&self) -> bool {
        self.criteria.iter().all(|c| c.passed)
    }

    /// Count passed criteria.
    #[must_use]
    pub fn passed_count(&self) -> usize {
        self.criteria.iter().filter(|c| c.passed).count()
    }

    /// Count failed criteria.
    #[must_use]
    pub fn failed_count(&self) -> usize {
        self.criteria.iter().filter(|c| !c.passed).count()
    }

    /// Get all failing criteria.
    #[must_use]
    pub fn failures(&self) -> Vec<&Criterion> {
        self.criteria.iter().filter(|c| !c.passed).collect()
    }

    /// Check if the overall grade is passing.
    #[must_use]
    pub fn is_passing(&self) -> bool {
        self.overall_grade().is_passing()
    }
}

/// Standard evaluation categories.
pub mod categories {
    /// Accessibility evaluation.
    pub const ACCESSIBILITY: &str = "accessibility";
    /// Performance evaluation.
    pub const PERFORMANCE: &str = "performance";
    /// Visual consistency.
    pub const VISUAL: &str = "visual";
    /// Code quality.
    pub const CODE_QUALITY: &str = "code_quality";
    /// Test coverage.
    pub const TESTING: &str = "testing";
    /// Documentation.
    pub const DOCUMENTATION: &str = "documentation";
    /// Security.
    pub const SECURITY: &str = "security";
}

// =============================================================================
// AppQualityScore - Per Spec Section 5.1
// =============================================================================

/// App Quality Score breakdown per spec (6 orthogonal metrics).
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ScoreBreakdown {
    // Structural (25 points)
    /// Cyclomatic complexity (McCabe, 1976)
    pub widget_complexity: f64,
    /// Nesting depth penalty
    pub layout_depth: f64,
    /// Widget count vs viewport
    pub component_count: f64,

    // Performance (20 points)
    /// 95th percentile frame time
    pub render_time_p95: f64,
    /// Peak memory vs baseline
    pub memory_usage: f64,
    /// WASM binary size
    pub bundle_size: f64,

    // Accessibility (20 points)
    /// WCAG 2.1 AA checklist
    pub wcag_aa_compliance: f64,
    /// Full keyboard support
    pub keyboard_navigation: f64,
    /// ARIA labels coverage
    pub screen_reader: f64,

    // Data Quality (15 points)
    /// Missing value ratio
    pub data_completeness: f64,
    /// Staleness penalty
    pub data_freshness: f64,
    /// Type errors
    pub schema_validation: f64,

    // Documentation (10 points)
    /// Required fields coverage
    pub manifest_completeness: f64,
    /// Model/data cards present
    pub card_coverage: f64,

    // Consistency (10 points)
    /// Design system compliance
    pub theme_adherence: f64,
    /// ID/class naming
    pub naming_conventions: f64,
}

impl ScoreBreakdown {
    /// Calculate structural score (contributes 25% to total).
    #[must_use]
    pub fn structural_score(&self) -> f64 {
        (self.widget_complexity + self.layout_depth + self.component_count) / 3.0 * 0.25
    }

    /// Calculate performance score (contributes 20% to total).
    #[must_use]
    pub fn performance_score(&self) -> f64 {
        (self.render_time_p95 + self.memory_usage + self.bundle_size) / 3.0 * 0.20
    }

    /// Calculate accessibility score (contributes 20% to total).
    #[must_use]
    pub fn accessibility_score(&self) -> f64 {
        (self.wcag_aa_compliance + self.keyboard_navigation + self.screen_reader) / 3.0 * 0.20
    }

    /// Calculate data quality score (contributes 15% to total).
    #[must_use]
    pub fn data_quality_score(&self) -> f64 {
        (self.data_completeness + self.data_freshness + self.schema_validation) / 3.0 * 0.15
    }

    /// Calculate documentation score (contributes 10% to total).
    #[must_use]
    pub fn documentation_score(&self) -> f64 {
        (self.manifest_completeness + self.card_coverage) / 2.0 * 0.10
    }

    /// Calculate consistency score (contributes 10% to total).
    #[must_use]
    pub fn consistency_score(&self) -> f64 {
        (self.theme_adherence + self.naming_conventions) / 2.0 * 0.10
    }

    /// Calculate total score (0-100).
    #[must_use]
    pub fn total(&self) -> f64 {
        self.structural_score()
            + self.performance_score()
            + self.accessibility_score()
            + self.data_quality_score()
            + self.documentation_score()
            + self.consistency_score()
    }
}

/// App Quality Score (0-100, F-A+).
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct AppQualityScore {
    /// Overall score (0-100)
    pub overall: f64,
    /// Grade (F through A+)
    pub grade: Grade,
    /// Detailed breakdown
    pub breakdown: ScoreBreakdown,
}

impl AppQualityScore {
    /// Create from a score breakdown.
    #[must_use]
    pub fn from_breakdown(breakdown: ScoreBreakdown) -> Self {
        let overall = breakdown.total();
        let grade = Grade::from_percentage(overall as f32);
        Self {
            overall,
            grade,
            breakdown,
        }
    }

    /// Check if score meets minimum grade requirement.
    #[must_use]
    pub fn meets_minimum(&self, min_grade: Grade) -> bool {
        self.grade >= min_grade
    }

    /// Check if production ready (B+ or better).
    #[must_use]
    pub fn is_production_ready(&self) -> bool {
        self.grade.is_production_ready()
    }
}

/// Builder for constructing AppQualityScore.
#[derive(Debug, Clone, Default)]
pub struct QualityScoreBuilder {
    breakdown: ScoreBreakdown,
}

impl QualityScoreBuilder {
    /// Create a new quality score builder.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set structural metrics.
    #[must_use]
    pub fn structural(mut self, complexity: f64, depth: f64, count: f64) -> Self {
        self.breakdown.widget_complexity = complexity.clamp(0.0, 100.0);
        self.breakdown.layout_depth = depth.clamp(0.0, 100.0);
        self.breakdown.component_count = count.clamp(0.0, 100.0);
        self
    }

    /// Set performance metrics.
    #[must_use]
    pub fn performance(mut self, render_time: f64, memory: f64, bundle: f64) -> Self {
        self.breakdown.render_time_p95 = render_time.clamp(0.0, 100.0);
        self.breakdown.memory_usage = memory.clamp(0.0, 100.0);
        self.breakdown.bundle_size = bundle.clamp(0.0, 100.0);
        self
    }

    /// Set accessibility metrics.
    #[must_use]
    pub fn accessibility(mut self, wcag: f64, keyboard: f64, screen_reader: f64) -> Self {
        self.breakdown.wcag_aa_compliance = wcag.clamp(0.0, 100.0);
        self.breakdown.keyboard_navigation = keyboard.clamp(0.0, 100.0);
        self.breakdown.screen_reader = screen_reader.clamp(0.0, 100.0);
        self
    }

    /// Set data quality metrics.
    #[must_use]
    pub fn data_quality(mut self, completeness: f64, freshness: f64, schema: f64) -> Self {
        self.breakdown.data_completeness = completeness.clamp(0.0, 100.0);
        self.breakdown.data_freshness = freshness.clamp(0.0, 100.0);
        self.breakdown.schema_validation = schema.clamp(0.0, 100.0);
        self
    }

    /// Set documentation metrics.
    #[must_use]
    pub fn documentation(mut self, manifest: f64, cards: f64) -> Self {
        self.breakdown.manifest_completeness = manifest.clamp(0.0, 100.0);
        self.breakdown.card_coverage = cards.clamp(0.0, 100.0);
        self
    }

    /// Set consistency metrics.
    #[must_use]
    pub fn consistency(mut self, theme: f64, naming: f64) -> Self {
        self.breakdown.theme_adherence = theme.clamp(0.0, 100.0);
        self.breakdown.naming_conventions = naming.clamp(0.0, 100.0);
        self
    }

    /// Build the final quality score.
    #[must_use]
    pub fn build(self) -> AppQualityScore {
        AppQualityScore::from_breakdown(self.breakdown)
    }
}

// =============================================================================
// QualityGates - Per Spec Section 5.3
// =============================================================================

/// Quality gate configuration (from .presentar-gates.toml).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct QualityGates {
    /// Minimum required grade
    pub min_grade: Grade,
    /// Minimum required score (0-100)
    pub min_score: f64,
    /// Performance requirements
    pub performance: PerformanceGates,
    /// Accessibility requirements
    pub accessibility: AccessibilityGates,
    /// Data requirements
    pub data: DataGates,
    /// Documentation requirements
    pub documentation: DocumentationGates,
}

/// Performance quality gates.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PerformanceGates {
    /// Maximum render time in milliseconds (60fps = 16ms)
    pub max_render_time_ms: u32,
    /// Maximum bundle size in KB
    pub max_bundle_size_kb: u32,
    /// Maximum memory usage in MB
    pub max_memory_mb: u32,
}

/// Accessibility quality gates.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AccessibilityGates {
    /// WCAG level ("A", "AA", "AAA")
    pub wcag_level: String,
    /// Minimum contrast ratio
    pub min_contrast_ratio: f32,
    /// Require full keyboard navigation
    pub require_keyboard_nav: bool,
    /// Require ARIA labels
    pub require_aria_labels: bool,
}

/// Data quality gates.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DataGates {
    /// Maximum staleness in minutes
    pub max_staleness_minutes: u32,
    /// Require schema validation
    pub require_schema_validation: bool,
}

/// Documentation quality gates.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DocumentationGates {
    /// Require model cards
    pub require_model_cards: bool,
    /// Require data cards
    pub require_data_cards: bool,
    /// Minimum manifest fields
    pub min_manifest_fields: Vec<String>,
}

impl Default for QualityGates {
    fn default() -> Self {
        Self {
            min_grade: Grade::BPlus,
            min_score: 80.0,
            performance: PerformanceGates::default(),
            accessibility: AccessibilityGates::default(),
            data: DataGates::default(),
            documentation: DocumentationGates::default(),
        }
    }
}

impl Default for PerformanceGates {
    fn default() -> Self {
        Self {
            max_render_time_ms: 16,
            max_bundle_size_kb: 500,
            max_memory_mb: 100,
        }
    }
}

impl Default for AccessibilityGates {
    fn default() -> Self {
        Self {
            wcag_level: "AA".to_string(),
            min_contrast_ratio: 4.5,
            require_keyboard_nav: true,
            require_aria_labels: true,
        }
    }
}

impl Default for DataGates {
    fn default() -> Self {
        Self {
            max_staleness_minutes: 60,
            require_schema_validation: true,
        }
    }
}

impl Default for DocumentationGates {
    fn default() -> Self {
        Self {
            require_model_cards: true,
            require_data_cards: true,
            min_manifest_fields: vec![
                "name".to_string(),
                "version".to_string(),
                "description".to_string(),
            ],
        }
    }
}

/// Result of checking quality gates.
#[derive(Debug, Clone)]
pub struct GateCheckResult {
    /// Whether all gates passed
    pub passed: bool,
    /// List of gate violations
    pub violations: Vec<GateViolation>,
}

/// A single gate violation.
#[derive(Debug, Clone)]
pub struct GateViolation {
    /// Gate name
    pub gate: String,
    /// Expected value
    pub expected: String,
    /// Actual value
    pub actual: String,
    /// Severity
    pub severity: ViolationSeverity,
}

/// Severity of a gate violation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ViolationSeverity {
    /// Warning - gate not met but not blocking
    Warning,
    /// Error - gate not met and blocking
    Error,
}

impl QualityGates {
    /// Check if a quality score passes all gates.
    #[must_use]
    pub fn check(&self, score: &AppQualityScore) -> GateCheckResult {
        let mut violations = Vec::new();

        // Check minimum grade
        if score.grade < self.min_grade {
            violations.push(GateViolation {
                gate: "min_grade".to_string(),
                expected: self.min_grade.letter().to_string(),
                actual: score.grade.letter().to_string(),
                severity: ViolationSeverity::Error,
            });
        }

        // Check minimum score
        if score.overall < self.min_score {
            violations.push(GateViolation {
                gate: "min_score".to_string(),
                expected: format!("{:.1}", self.min_score),
                actual: format!("{:.1}", score.overall),
                severity: ViolationSeverity::Error,
            });
        }

        GateCheckResult {
            passed: violations.is_empty(),
            violations,
        }
    }
}

/// Builder for creating standard evaluation criteria.
#[derive(Debug, Clone, Default)]
pub struct EvaluationBuilder {
    report: ReportCard,
}

impl EvaluationBuilder {
    /// Create a new evaluation builder.
    #[must_use]
    pub fn new(title: impl Into<String>) -> Self {
        Self {
            report: ReportCard::new(title),
        }
    }

    /// Add accessibility criterion.
    #[must_use]
    pub fn accessibility(mut self, score: f32, feedback: Option<&str>) -> Self {
        let mut criterion = Criterion::new(
            "Accessibility",
            "WCAG 2.1 AA compliance and screen reader support",
        )
        .weight(1.0)
        .score(score);

        if let Some(fb) = feedback {
            criterion = criterion.feedback(fb);
        }

        self.report.add_criterion(criterion);
        self.report
            .add_category(categories::ACCESSIBILITY.to_string(), score);
        self
    }

    /// Add performance criterion.
    #[must_use]
    pub fn performance(mut self, score: f32, feedback: Option<&str>) -> Self {
        let mut criterion = Criterion::new(
            "Performance",
            "Frame rate, memory usage, and responsiveness",
        )
        .weight(1.0)
        .score(score);

        if let Some(fb) = feedback {
            criterion = criterion.feedback(fb);
        }

        self.report.add_criterion(criterion);
        self.report
            .add_category(categories::PERFORMANCE.to_string(), score);
        self
    }

    /// Add visual criterion.
    #[must_use]
    pub fn visual(mut self, score: f32, feedback: Option<&str>) -> Self {
        let mut criterion =
            Criterion::new("Visual Consistency", "Theme adherence and visual polish")
                .weight(0.8)
                .score(score);

        if let Some(fb) = feedback {
            criterion = criterion.feedback(fb);
        }

        self.report.add_criterion(criterion);
        self.report
            .add_category(categories::VISUAL.to_string(), score);
        self
    }

    /// Add code quality criterion.
    #[must_use]
    pub fn code_quality(mut self, score: f32, feedback: Option<&str>) -> Self {
        let mut criterion = Criterion::new(
            "Code Quality",
            "Lint compliance, documentation, and maintainability",
        )
        .weight(0.8)
        .score(score);

        if let Some(fb) = feedback {
            criterion = criterion.feedback(fb);
        }

        self.report.add_criterion(criterion);
        self.report
            .add_category(categories::CODE_QUALITY.to_string(), score);
        self
    }

    /// Add testing criterion.
    #[must_use]
    pub fn testing(mut self, score: f32, feedback: Option<&str>) -> Self {
        let mut criterion = Criterion::new("Testing", "Test coverage and mutation testing score")
            .weight(1.0)
            .score(score);

        if let Some(fb) = feedback {
            criterion = criterion.feedback(fb);
        }

        self.report.add_criterion(criterion);
        self.report
            .add_category(categories::TESTING.to_string(), score);
        self
    }

    /// Add custom criterion.
    #[must_use]
    pub fn custom(mut self, criterion: Criterion) -> Self {
        self.report.add_criterion(criterion);
        self
    }

    /// Build the final report card.
    #[must_use]
    pub fn build(self) -> ReportCard {
        self.report
    }
}

// =============================================================================
// TOML Configuration Loading
// =============================================================================

/// Error type for quality gate configuration.
#[derive(Debug, Clone, PartialEq)]
pub enum GateConfigError {
    /// Failed to parse TOML
    ParseError(String),
    /// Failed to read file
    IoError(String),
    /// Invalid configuration value
    InvalidValue(String),
}

impl std::fmt::Display for GateConfigError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::ParseError(msg) => write!(f, "parse error: {msg}"),
            Self::IoError(msg) => write!(f, "IO error: {msg}"),
            Self::InvalidValue(msg) => write!(f, "invalid value: {msg}"),
        }
    }
}

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

impl QualityGates {
    /// Default config file name.
    pub const CONFIG_FILE: &'static str = ".presentar-gates.toml";

    /// Parse quality gates from a TOML string.
    ///
    /// # Errors
    ///
    /// Returns error if TOML is invalid or values are out of range.
    pub fn from_toml(toml_str: &str) -> Result<Self, GateConfigError> {
        toml::from_str(toml_str).map_err(|e| GateConfigError::ParseError(e.to_string()))
    }

    /// Serialize quality gates to a TOML string.
    #[must_use]
    pub fn to_toml(&self) -> String {
        toml::to_string_pretty(self).unwrap_or_default()
    }

    /// Load quality gates from a file.
    ///
    /// # Errors
    ///
    /// Returns error if file cannot be read or parsed.
    pub fn load_from_file(path: &std::path::Path) -> Result<Self, GateConfigError> {
        let contents =
            std::fs::read_to_string(path).map_err(|e| GateConfigError::IoError(e.to_string()))?;
        Self::from_toml(&contents)
    }

    /// Save quality gates to a file.
    ///
    /// # Errors
    ///
    /// Returns error if file cannot be written.
    pub fn save_to_file(&self, path: &std::path::Path) -> Result<(), GateConfigError> {
        let contents = self.to_toml();
        std::fs::write(path, contents).map_err(|e| GateConfigError::IoError(e.to_string()))
    }

    /// Load from default config file in current directory.
    ///
    /// Returns default config if file doesn't exist.
    #[must_use]
    pub fn load_default() -> Self {
        let path = std::path::Path::new(Self::CONFIG_FILE);
        Self::load_from_file(path).unwrap_or_default()
    }

    /// Check a score with extended validation (performance, bundle size, etc.).
    #[must_use]
    pub fn check_extended(
        &self,
        score: &AppQualityScore,
        render_time_ms: Option<u32>,
        bundle_size_kb: Option<u32>,
        memory_mb: Option<u32>,
    ) -> GateCheckResult {
        let mut result = self.check(score);

        // Check performance gates
        if let Some(render_time) = render_time_ms {
            if render_time > self.performance.max_render_time_ms {
                result.violations.push(GateViolation {
                    gate: "max_render_time_ms".to_string(),
                    expected: format!("<= {}ms", self.performance.max_render_time_ms),
                    actual: format!("{}ms", render_time),
                    severity: ViolationSeverity::Error,
                });
            }
        }

        if let Some(bundle) = bundle_size_kb {
            if bundle > self.performance.max_bundle_size_kb {
                result.violations.push(GateViolation {
                    gate: "max_bundle_size_kb".to_string(),
                    expected: format!("<= {}KB", self.performance.max_bundle_size_kb),
                    actual: format!("{}KB", bundle),
                    severity: ViolationSeverity::Error,
                });
            }
        }

        if let Some(memory) = memory_mb {
            if memory > self.performance.max_memory_mb {
                result.violations.push(GateViolation {
                    gate: "max_memory_mb".to_string(),
                    expected: format!("<= {}MB", self.performance.max_memory_mb),
                    actual: format!("{}MB", memory),
                    severity: ViolationSeverity::Warning,
                });
            }
        }

        result.passed = result
            .violations
            .iter()
            .all(|v| v.severity != ViolationSeverity::Error);
        result
    }

    /// Generate a sample TOML config file content.
    #[must_use]
    pub fn sample_config() -> String {
        r#"# Presentar Quality Gates Configuration
# Place this file at .presentar-gates.toml in your project root

# Minimum required grade (F, D, C, C+, B-, B, B+, A-, A, A+)
min_grade = "B+"

# Minimum required score (0-100)
min_score = 80.0

[performance]
# Maximum render time in milliseconds (60fps = 16ms)
max_render_time_ms = 16

# Maximum bundle size in KB
max_bundle_size_kb = 500

# Maximum memory usage in MB
max_memory_mb = 100

[accessibility]
# WCAG level: "A", "AA", or "AAA"
wcag_level = "AA"

# Minimum contrast ratio
min_contrast_ratio = 4.5

# Require full keyboard navigation
require_keyboard_nav = true

# Require ARIA labels
require_aria_labels = true

[data]
# Maximum data staleness in minutes
max_staleness_minutes = 60

# Require schema validation
require_schema_validation = true

[documentation]
# Require model cards for ML models
require_model_cards = true

# Require data cards for datasets
require_data_cards = true

# Minimum required manifest fields
min_manifest_fields = ["name", "version", "description"]
"#
        .to_string()
    }
}

impl Grade {
    /// Parse grade from string (e.g., "A+", "B-", "C").
    ///
    /// # Errors
    ///
    /// Returns error if string is not a valid grade.
    pub fn from_str(s: &str) -> Result<Self, GateConfigError> {
        match s.trim().to_uppercase().as_str() {
            "A+" => Ok(Self::APlus),
            "A" => Ok(Self::A),
            "A-" => Ok(Self::AMinus),
            "B+" => Ok(Self::BPlus),
            "B" => Ok(Self::B),
            "B-" => Ok(Self::BMinus),
            "C+" => Ok(Self::CPlus),
            "C" => Ok(Self::C),
            "C-" => Ok(Self::CMinus),
            "D" => Ok(Self::D),
            "F" => Ok(Self::F),
            _ => Err(GateConfigError::InvalidValue(format!(
                "Invalid grade: {s}. Valid values: A+, A, A-, B+, B, B-, C+, C, C-, D, F"
            ))),
        }
    }
}

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

    // =========================================================================
    // Grade Tests - TESTS FIRST
    // =========================================================================

    #[test]
    fn test_grade_from_percentage() {
        assert_eq!(Grade::from_percentage(100.0), Grade::APlus);
        assert_eq!(Grade::from_percentage(95.0), Grade::APlus);
        assert_eq!(Grade::from_percentage(92.0), Grade::A);
        assert_eq!(Grade::from_percentage(90.0), Grade::A);
        assert_eq!(Grade::from_percentage(87.0), Grade::AMinus);
        assert_eq!(Grade::from_percentage(85.0), Grade::AMinus);
        assert_eq!(Grade::from_percentage(82.0), Grade::BPlus);
        assert_eq!(Grade::from_percentage(80.0), Grade::BPlus);
        assert_eq!(Grade::from_percentage(77.0), Grade::B);
        assert_eq!(Grade::from_percentage(75.0), Grade::B);
        assert_eq!(Grade::from_percentage(72.0), Grade::BMinus);
        assert_eq!(Grade::from_percentage(70.0), Grade::BMinus);
        assert_eq!(Grade::from_percentage(67.0), Grade::CPlus);
        assert_eq!(Grade::from_percentage(65.0), Grade::CPlus);
        assert_eq!(Grade::from_percentage(62.0), Grade::C);
        assert_eq!(Grade::from_percentage(60.0), Grade::C);
        assert_eq!(Grade::from_percentage(57.0), Grade::CMinus);
        assert_eq!(Grade::from_percentage(55.0), Grade::CMinus);
        assert_eq!(Grade::from_percentage(52.0), Grade::D);
        assert_eq!(Grade::from_percentage(50.0), Grade::D);
        assert_eq!(Grade::from_percentage(49.0), Grade::F);
        assert_eq!(Grade::from_percentage(0.0), Grade::F);
    }

    #[test]
    fn test_grade_min_percentage() {
        assert_eq!(Grade::APlus.min_percentage(), 95.0);
        assert_eq!(Grade::A.min_percentage(), 90.0);
        assert_eq!(Grade::AMinus.min_percentage(), 85.0);
        assert_eq!(Grade::BPlus.min_percentage(), 80.0);
        assert_eq!(Grade::B.min_percentage(), 75.0);
        assert_eq!(Grade::BMinus.min_percentage(), 70.0);
        assert_eq!(Grade::CPlus.min_percentage(), 65.0);
        assert_eq!(Grade::C.min_percentage(), 60.0);
        assert_eq!(Grade::CMinus.min_percentage(), 55.0);
        assert_eq!(Grade::D.min_percentage(), 50.0);
        assert_eq!(Grade::F.min_percentage(), 0.0);
    }

    #[test]
    fn test_grade_letter() {
        assert_eq!(Grade::APlus.letter(), "A+");
        assert_eq!(Grade::A.letter(), "A");
        assert_eq!(Grade::AMinus.letter(), "A-");
        assert_eq!(Grade::BPlus.letter(), "B+");
        assert_eq!(Grade::B.letter(), "B");
        assert_eq!(Grade::BMinus.letter(), "B-");
        assert_eq!(Grade::CPlus.letter(), "C+");
        assert_eq!(Grade::C.letter(), "C");
        assert_eq!(Grade::CMinus.letter(), "C-");
        assert_eq!(Grade::D.letter(), "D");
        assert_eq!(Grade::F.letter(), "F");
    }

    #[test]
    fn test_grade_is_passing() {
        assert!(Grade::APlus.is_passing());
        assert!(Grade::A.is_passing());
        assert!(Grade::AMinus.is_passing());
        assert!(Grade::BPlus.is_passing());
        assert!(Grade::B.is_passing());
        assert!(Grade::BMinus.is_passing());
        assert!(Grade::CPlus.is_passing());
        assert!(Grade::C.is_passing());
        assert!(!Grade::CMinus.is_passing());
        assert!(!Grade::D.is_passing());
        assert!(!Grade::F.is_passing());
    }

    #[test]
    fn test_grade_is_production_ready() {
        assert!(Grade::APlus.is_production_ready());
        assert!(Grade::A.is_production_ready());
        assert!(Grade::AMinus.is_production_ready());
        assert!(Grade::BPlus.is_production_ready());
        assert!(!Grade::B.is_production_ready());
        assert!(!Grade::BMinus.is_production_ready());
        assert!(!Grade::F.is_production_ready());
    }

    #[test]
    fn test_grade_default() {
        assert_eq!(Grade::default(), Grade::F);
    }

    #[test]
    fn test_grade_display() {
        assert_eq!(format!("{}", Grade::APlus), "A+");
        assert_eq!(format!("{}", Grade::A), "A");
        assert_eq!(format!("{}", Grade::F), "F");
    }

    #[test]
    fn test_grade_ordering() {
        assert!(Grade::APlus > Grade::A);
        assert!(Grade::A > Grade::AMinus);
        assert!(Grade::AMinus > Grade::BPlus);
        assert!(Grade::BPlus > Grade::B);
        assert!(Grade::B > Grade::BMinus);
        assert!(Grade::BMinus > Grade::CPlus);
        assert!(Grade::CPlus > Grade::C);
        assert!(Grade::C > Grade::CMinus);
        assert!(Grade::CMinus > Grade::D);
        assert!(Grade::D > Grade::F);
    }

    // =========================================================================
    // Criterion Tests - TESTS FIRST
    // =========================================================================

    #[test]
    fn test_criterion_new() {
        let c = Criterion::new("Test", "Description");
        assert_eq!(c.name, "Test");
        assert_eq!(c.description, "Description");
        assert_eq!(c.weight, 1.0);
        assert_eq!(c.score, 0.0);
        assert!(!c.passed);
    }

    #[test]
    fn test_criterion_weight() {
        let c = Criterion::new("Test", "Desc").weight(0.5);
        assert_eq!(c.weight, 0.5);
    }

    #[test]
    fn test_criterion_weight_clamped() {
        let c1 = Criterion::new("Test", "Desc").weight(2.0);
        assert_eq!(c1.weight, 1.0);

        let c2 = Criterion::new("Test", "Desc").weight(-1.0);
        assert_eq!(c2.weight, 0.0);
    }

    #[test]
    fn test_criterion_score() {
        let c = Criterion::new("Test", "Desc").score(85.0);
        assert_eq!(c.score, 85.0);
        assert!(c.passed);
    }

    #[test]
    fn test_criterion_score_failing() {
        let c = Criterion::new("Test", "Desc").score(50.0);
        assert_eq!(c.score, 50.0);
        assert!(!c.passed);
    }

    #[test]
    fn test_criterion_score_clamped() {
        let c1 = Criterion::new("Test", "Desc").score(150.0);
        assert_eq!(c1.score, 100.0);

        let c2 = Criterion::new("Test", "Desc").score(-10.0);
        assert_eq!(c2.score, 0.0);
    }

    #[test]
    fn test_criterion_pass() {
        let c = Criterion::new("Test", "Desc").pass();
        assert_eq!(c.score, 100.0);
        assert!(c.passed);
    }

    #[test]
    fn test_criterion_fail() {
        let c = Criterion::new("Test", "Desc").fail();
        assert_eq!(c.score, 0.0);
        assert!(!c.passed);
    }

    #[test]
    fn test_criterion_feedback() {
        let c = Criterion::new("Test", "Desc").feedback("Good work!");
        assert_eq!(c.feedback, Some("Good work!".to_string()));
    }

    #[test]
    fn test_criterion_grade() {
        assert_eq!(Criterion::new("T", "D").score(95.0).grade(), Grade::APlus);
        assert_eq!(Criterion::new("T", "D").score(90.0).grade(), Grade::A);
        assert_eq!(Criterion::new("T", "D").score(85.0).grade(), Grade::AMinus);
        assert_eq!(Criterion::new("T", "D").score(80.0).grade(), Grade::BPlus);
        assert_eq!(Criterion::new("T", "D").score(75.0).grade(), Grade::B);
        assert_eq!(Criterion::new("T", "D").score(70.0).grade(), Grade::BMinus);
        assert_eq!(Criterion::new("T", "D").score(65.0).grade(), Grade::CPlus);
        assert_eq!(Criterion::new("T", "D").score(60.0).grade(), Grade::C);
        assert_eq!(Criterion::new("T", "D").score(55.0).grade(), Grade::CMinus);
        assert_eq!(Criterion::new("T", "D").score(50.0).grade(), Grade::D);
        assert_eq!(Criterion::new("T", "D").score(40.0).grade(), Grade::F);
    }

    #[test]
    fn test_criterion_weighted_score() {
        let c = Criterion::new("Test", "Desc").weight(0.5).score(80.0);
        assert_eq!(c.weighted_score(), 40.0);
    }

    // =========================================================================
    // ReportCard Tests - TESTS FIRST
    // =========================================================================

    #[test]
    fn test_report_card_new() {
        let report = ReportCard::new("My Report");
        assert_eq!(report.title, "My Report");
        assert!(report.criteria.is_empty());
    }

    #[test]
    fn test_report_card_add_criterion() {
        let mut report = ReportCard::new("Test");
        report.add_criterion(Criterion::new("C1", "D1").score(90.0));
        assert_eq!(report.criteria.len(), 1);
    }

    #[test]
    fn test_report_card_builder() {
        let report = ReportCard::new("Test")
            .criterion(Criterion::new("C1", "D1").score(90.0))
            .criterion(Criterion::new("C2", "D2").score(80.0));
        assert_eq!(report.criteria.len(), 2);
    }

    #[test]
    fn test_report_card_overall_score_empty() {
        let report = ReportCard::new("Test");
        assert_eq!(report.overall_score(), 0.0);
    }

    #[test]
    fn test_report_card_overall_score_equal_weights() {
        let report = ReportCard::new("Test")
            .criterion(Criterion::new("C1", "D1").weight(1.0).score(100.0))
            .criterion(Criterion::new("C2", "D2").weight(1.0).score(80.0));
        assert_eq!(report.overall_score(), 90.0);
    }

    #[test]
    fn test_report_card_overall_score_different_weights() {
        let report = ReportCard::new("Test")
            .criterion(Criterion::new("C1", "D1").weight(0.75).score(100.0))
            .criterion(Criterion::new("C2", "D2").weight(0.25).score(80.0));
        // (100*0.75 + 80*0.25) / (0.75 + 0.25) = (75 + 20) / 1.0 = 95
        assert_eq!(report.overall_score(), 95.0);
    }

    #[test]
    fn test_report_card_overall_grade() {
        let report = ReportCard::new("Test").criterion(Criterion::new("C1", "D1").score(90.0));
        assert_eq!(report.overall_grade(), Grade::A);
    }

    #[test]
    fn test_report_card_all_passed() {
        let report = ReportCard::new("Test")
            .criterion(Criterion::new("C1", "D1").pass())
            .criterion(Criterion::new("C2", "D2").pass());
        assert!(report.all_passed());
    }

    #[test]
    fn test_report_card_not_all_passed() {
        let report = ReportCard::new("Test")
            .criterion(Criterion::new("C1", "D1").pass())
            .criterion(Criterion::new("C2", "D2").fail());
        assert!(!report.all_passed());
    }

    #[test]
    fn test_report_card_passed_count() {
        let report = ReportCard::new("Test")
            .criterion(Criterion::new("C1", "D1").pass())
            .criterion(Criterion::new("C2", "D2").pass())
            .criterion(Criterion::new("C3", "D3").fail());
        assert_eq!(report.passed_count(), 2);
        assert_eq!(report.failed_count(), 1);
    }

    #[test]
    fn test_report_card_failures() {
        let report = ReportCard::new("Test")
            .criterion(Criterion::new("C1", "D1").pass())
            .criterion(Criterion::new("C2", "D2").fail());
        let failures = report.failures();
        assert_eq!(failures.len(), 1);
        assert_eq!(failures[0].name, "C2");
    }

    #[test]
    fn test_report_card_is_passing() {
        let passing = ReportCard::new("Test").criterion(Criterion::new("C1", "D1").score(90.0));
        assert!(passing.is_passing());

        let failing = ReportCard::new("Test").criterion(Criterion::new("C1", "D1").score(50.0));
        assert!(!failing.is_passing());
    }

    #[test]
    fn test_report_card_add_category() {
        let mut report = ReportCard::new("Test");
        report.add_category("performance", 95.0);
        assert_eq!(report.categories.get("performance"), Some(&95.0));
    }

    // =========================================================================
    // EvaluationBuilder Tests - TESTS FIRST
    // =========================================================================

    #[test]
    fn test_evaluation_builder_new() {
        let builder = EvaluationBuilder::new("My Eval");
        let report = builder.build();
        assert_eq!(report.title, "My Eval");
    }

    #[test]
    fn test_evaluation_builder_accessibility() {
        let report = EvaluationBuilder::new("Test")
            .accessibility(95.0, Some("Good a11y"))
            .build();

        assert_eq!(report.criteria.len(), 1);
        assert_eq!(report.criteria[0].name, "Accessibility");
        assert_eq!(report.criteria[0].score, 95.0);
        assert_eq!(
            report.categories.get(categories::ACCESSIBILITY),
            Some(&95.0)
        );
    }

    #[test]
    fn test_evaluation_builder_performance() {
        let report = EvaluationBuilder::new("Test")
            .performance(88.0, None)
            .build();

        assert_eq!(report.criteria[0].name, "Performance");
        assert_eq!(report.criteria[0].score, 88.0);
    }

    #[test]
    fn test_evaluation_builder_full() {
        let report = EvaluationBuilder::new("Full Evaluation")
            .accessibility(95.0, None)
            .performance(90.0, None)
            .visual(85.0, None)
            .code_quality(92.0, None)
            .testing(98.0, None)
            .build();

        assert_eq!(report.criteria.len(), 5);
        assert!(report.overall_score() > 90.0);
        assert_eq!(report.overall_grade(), Grade::A);
    }

    #[test]
    fn test_evaluation_builder_custom() {
        let report = EvaluationBuilder::new("Test")
            .custom(Criterion::new("Custom", "My custom criterion").score(75.0))
            .build();

        assert_eq!(report.criteria[0].name, "Custom");
    }

    // =========================================================================
    // AppQualityScore Tests - TESTS FIRST
    // =========================================================================

    #[test]
    fn test_score_breakdown_default() {
        let breakdown = ScoreBreakdown::default();
        assert_eq!(breakdown.total(), 0.0);
    }

    #[test]
    fn test_score_breakdown_perfect() {
        let breakdown = ScoreBreakdown {
            widget_complexity: 100.0,
            layout_depth: 100.0,
            component_count: 100.0,
            render_time_p95: 100.0,
            memory_usage: 100.0,
            bundle_size: 100.0,
            wcag_aa_compliance: 100.0,
            keyboard_navigation: 100.0,
            screen_reader: 100.0,
            data_completeness: 100.0,
            data_freshness: 100.0,
            schema_validation: 100.0,
            manifest_completeness: 100.0,
            card_coverage: 100.0,
            theme_adherence: 100.0,
            naming_conventions: 100.0,
        };

        assert!((breakdown.total() - 100.0).abs() < 0.01);
    }

    #[test]
    fn test_score_breakdown_category_scores() {
        let breakdown = ScoreBreakdown {
            widget_complexity: 90.0,
            layout_depth: 90.0,
            component_count: 90.0,
            render_time_p95: 80.0,
            memory_usage: 80.0,
            bundle_size: 80.0,
            wcag_aa_compliance: 100.0,
            keyboard_navigation: 100.0,
            screen_reader: 100.0,
            data_completeness: 70.0,
            data_freshness: 70.0,
            schema_validation: 70.0,
            manifest_completeness: 60.0,
            card_coverage: 60.0,
            theme_adherence: 50.0,
            naming_conventions: 50.0,
        };

        // structural: 90 * 0.25 = 22.5
        assert!((breakdown.structural_score() - 22.5).abs() < 0.01);
        // performance: 80 * 0.20 = 16.0
        assert!((breakdown.performance_score() - 16.0).abs() < 0.01);
        // accessibility: 100 * 0.20 = 20.0
        assert!((breakdown.accessibility_score() - 20.0).abs() < 0.01);
    }

    #[test]
    fn test_app_quality_score_from_breakdown() {
        let breakdown = ScoreBreakdown {
            widget_complexity: 90.0,
            layout_depth: 90.0,
            component_count: 90.0,
            render_time_p95: 90.0,
            memory_usage: 90.0,
            bundle_size: 90.0,
            wcag_aa_compliance: 90.0,
            keyboard_navigation: 90.0,
            screen_reader: 90.0,
            data_completeness: 90.0,
            data_freshness: 90.0,
            schema_validation: 90.0,
            manifest_completeness: 90.0,
            card_coverage: 90.0,
            theme_adherence: 90.0,
            naming_conventions: 90.0,
        };

        let score = AppQualityScore::from_breakdown(breakdown);
        assert!((score.overall - 90.0).abs() < 0.01);
        assert_eq!(score.grade, Grade::A);
    }

    #[test]
    fn test_app_quality_score_meets_minimum() {
        let score = QualityScoreBuilder::new()
            .structural(85.0, 85.0, 85.0)
            .performance(85.0, 85.0, 85.0)
            .accessibility(85.0, 85.0, 85.0)
            .data_quality(85.0, 85.0, 85.0)
            .documentation(85.0, 85.0)
            .consistency(85.0, 85.0)
            .build();

        assert!(score.meets_minimum(Grade::BPlus));
        assert!(!score.meets_minimum(Grade::A));
    }

    #[test]
    fn test_app_quality_score_production_ready() {
        let ready = QualityScoreBuilder::new()
            .structural(90.0, 90.0, 90.0)
            .performance(90.0, 90.0, 90.0)
            .accessibility(90.0, 90.0, 90.0)
            .data_quality(90.0, 90.0, 90.0)
            .documentation(90.0, 90.0)
            .consistency(90.0, 90.0)
            .build();

        assert!(ready.is_production_ready());

        let not_ready = QualityScoreBuilder::new()
            .structural(70.0, 70.0, 70.0)
            .performance(70.0, 70.0, 70.0)
            .accessibility(70.0, 70.0, 70.0)
            .data_quality(70.0, 70.0, 70.0)
            .documentation(70.0, 70.0)
            .consistency(70.0, 70.0)
            .build();

        assert!(!not_ready.is_production_ready());
    }

    #[test]
    fn test_quality_score_builder() {
        let score = QualityScoreBuilder::new()
            .structural(100.0, 100.0, 100.0)
            .performance(100.0, 100.0, 100.0)
            .accessibility(100.0, 100.0, 100.0)
            .data_quality(100.0, 100.0, 100.0)
            .documentation(100.0, 100.0)
            .consistency(100.0, 100.0)
            .build();

        assert!((score.overall - 100.0).abs() < 0.01);
        assert_eq!(score.grade, Grade::APlus);
    }

    #[test]
    fn test_quality_score_builder_clamping() {
        let score = QualityScoreBuilder::new()
            .structural(150.0, -10.0, 200.0)
            .build();

        // Values should be clamped to 0-100
        assert_eq!(score.breakdown.widget_complexity, 100.0);
        assert_eq!(score.breakdown.layout_depth, 0.0);
        assert_eq!(score.breakdown.component_count, 100.0);
    }

    // =========================================================================
    // QualityGates Tests
    // =========================================================================

    #[test]
    fn test_quality_gates_default() {
        let gates = QualityGates::default();
        assert_eq!(gates.min_grade, Grade::BPlus);
        assert_eq!(gates.min_score, 80.0);
        assert_eq!(gates.performance.max_render_time_ms, 16);
        assert_eq!(gates.accessibility.wcag_level, "AA");
    }

    #[test]
    fn test_quality_gates_check_passes() {
        let gates = QualityGates::default();
        let score = QualityScoreBuilder::new()
            .structural(90.0, 90.0, 90.0)
            .performance(90.0, 90.0, 90.0)
            .accessibility(90.0, 90.0, 90.0)
            .data_quality(90.0, 90.0, 90.0)
            .documentation(90.0, 90.0)
            .consistency(90.0, 90.0)
            .build();

        let result = gates.check(&score);
        assert!(result.passed);
        assert!(result.violations.is_empty());
    }

    #[test]
    fn test_quality_gates_check_fails_grade() {
        let gates = QualityGates::default();
        let score = QualityScoreBuilder::new()
            .structural(60.0, 60.0, 60.0)
            .performance(60.0, 60.0, 60.0)
            .accessibility(60.0, 60.0, 60.0)
            .data_quality(60.0, 60.0, 60.0)
            .documentation(60.0, 60.0)
            .consistency(60.0, 60.0)
            .build();

        let result = gates.check(&score);
        assert!(!result.passed);
        assert!(!result.violations.is_empty());
        assert_eq!(result.violations[0].gate, "min_grade");
    }

    #[test]
    fn test_quality_gates_check_fails_score() {
        let gates = QualityGates {
            min_grade: Grade::C, // Lower grade threshold
            min_score: 95.0,     // But require high score
            ..QualityGates::default()
        };

        let score = QualityScoreBuilder::new()
            .structural(85.0, 85.0, 85.0)
            .performance(85.0, 85.0, 85.0)
            .accessibility(85.0, 85.0, 85.0)
            .data_quality(85.0, 85.0, 85.0)
            .documentation(85.0, 85.0)
            .consistency(85.0, 85.0)
            .build();

        let result = gates.check(&score);
        assert!(!result.passed);
        assert!(result.violations.iter().any(|v| v.gate == "min_score"));
    }

    #[test]
    fn test_performance_gates_default() {
        let gates = PerformanceGates::default();
        assert_eq!(gates.max_render_time_ms, 16);
        assert_eq!(gates.max_bundle_size_kb, 500);
        assert_eq!(gates.max_memory_mb, 100);
    }

    #[test]
    fn test_accessibility_gates_default() {
        let gates = AccessibilityGates::default();
        assert_eq!(gates.wcag_level, "AA");
        assert_eq!(gates.min_contrast_ratio, 4.5);
        assert!(gates.require_keyboard_nav);
        assert!(gates.require_aria_labels);
    }

    #[test]
    fn test_documentation_gates_default() {
        let gates = DocumentationGates::default();
        assert!(gates.require_model_cards);
        assert!(gates.require_data_cards);
        assert!(gates.min_manifest_fields.contains(&"name".to_string()));
        assert!(gates.min_manifest_fields.contains(&"version".to_string()));
    }

    #[test]
    fn test_violation_severity() {
        let violation = GateViolation {
            gate: "test".to_string(),
            expected: "A".to_string(),
            actual: "B".to_string(),
            severity: ViolationSeverity::Error,
        };
        assert_eq!(violation.severity, ViolationSeverity::Error);
    }

    // =========================================================================
    // TOML Configuration Tests
    // =========================================================================

    #[test]
    fn test_gate_config_error_display() {
        let err = GateConfigError::ParseError("invalid toml".to_string());
        assert!(err.to_string().contains("parse error"));

        let err = GateConfigError::IoError("file not found".to_string());
        assert!(err.to_string().contains("IO error"));

        let err = GateConfigError::InvalidValue("out of range".to_string());
        assert!(err.to_string().contains("invalid value"));
    }

    #[test]
    fn test_quality_gates_to_toml() {
        let gates = QualityGates::default();
        let toml_str = gates.to_toml();

        assert!(toml_str.contains("min_score"));
        assert!(toml_str.contains("[performance]"));
        assert!(toml_str.contains("[accessibility]"));
        assert!(toml_str.contains("max_render_time_ms"));
    }

    #[test]
    fn test_quality_gates_from_toml() {
        let toml_str = r#"
            min_grade = "A"
            min_score = 90.0

            [performance]
            max_render_time_ms = 8
            max_bundle_size_kb = 300
            max_memory_mb = 50

            [accessibility]
            wcag_level = "AAA"
            min_contrast_ratio = 7.0
            require_keyboard_nav = true
            require_aria_labels = true

            [data]
            max_staleness_minutes = 30
            require_schema_validation = true

            [documentation]
            require_model_cards = true
            require_data_cards = true
            min_manifest_fields = ["name", "version"]
        "#;

        let gates = QualityGates::from_toml(toml_str).unwrap();
        assert_eq!(gates.min_score, 90.0);
        assert_eq!(gates.performance.max_render_time_ms, 8);
        assert_eq!(gates.performance.max_bundle_size_kb, 300);
        assert_eq!(gates.accessibility.wcag_level, "AAA");
        assert_eq!(gates.accessibility.min_contrast_ratio, 7.0);
        assert_eq!(gates.data.max_staleness_minutes, 30);
    }

    #[test]
    fn test_quality_gates_roundtrip() {
        let original = QualityGates::default();
        let toml_str = original.to_toml();
        let parsed = QualityGates::from_toml(&toml_str).unwrap();

        assert_eq!(parsed.min_score, original.min_score);
        assert_eq!(
            parsed.performance.max_render_time_ms,
            original.performance.max_render_time_ms
        );
        assert_eq!(
            parsed.accessibility.wcag_level,
            original.accessibility.wcag_level
        );
    }

    #[test]
    fn test_quality_gates_from_toml_invalid() {
        let result = QualityGates::from_toml("this is not valid toml {{{");
        assert!(matches!(result, Err(GateConfigError::ParseError(_))));
    }

    #[test]
    fn test_quality_gates_sample_config() {
        let sample = QualityGates::sample_config();
        assert!(sample.contains("min_grade"));
        assert!(sample.contains("max_bundle_size_kb"));
        assert!(sample.contains("wcag_level"));
        assert!(sample.contains("[performance]"));
        assert!(sample.contains("[accessibility]"));
        assert!(sample.contains("[data]"));
        assert!(sample.contains("[documentation]"));
    }

    #[test]
    fn test_quality_gates_check_extended_passes() {
        let gates = QualityGates::default();
        let score = QualityScoreBuilder::new()
            .structural(90.0, 90.0, 90.0)
            .performance(90.0, 90.0, 90.0)
            .accessibility(90.0, 90.0, 90.0)
            .data_quality(90.0, 90.0, 90.0)
            .documentation(90.0, 90.0)
            .consistency(90.0, 90.0)
            .build();

        let result = gates.check_extended(&score, Some(10), Some(400), Some(50));
        assert!(result.passed);
        assert!(result.violations.is_empty());
    }

    #[test]
    fn test_quality_gates_check_extended_render_time_fails() {
        let gates = QualityGates::default();
        let score = QualityScoreBuilder::new()
            .structural(90.0, 90.0, 90.0)
            .performance(90.0, 90.0, 90.0)
            .accessibility(90.0, 90.0, 90.0)
            .data_quality(90.0, 90.0, 90.0)
            .documentation(90.0, 90.0)
            .consistency(90.0, 90.0)
            .build();

        // Render time exceeds 16ms limit
        let result = gates.check_extended(&score, Some(25), Some(400), Some(50));
        assert!(!result.passed);
        assert!(result
            .violations
            .iter()
            .any(|v| v.gate == "max_render_time_ms"));
    }

    #[test]
    fn test_quality_gates_check_extended_bundle_size_fails() {
        let gates = QualityGates::default();
        let score = QualityScoreBuilder::new()
            .structural(90.0, 90.0, 90.0)
            .performance(90.0, 90.0, 90.0)
            .accessibility(90.0, 90.0, 90.0)
            .data_quality(90.0, 90.0, 90.0)
            .documentation(90.0, 90.0)
            .consistency(90.0, 90.0)
            .build();

        // Bundle size exceeds 500KB limit
        let result = gates.check_extended(&score, Some(10), Some(600), Some(50));
        assert!(!result.passed);
        assert!(result
            .violations
            .iter()
            .any(|v| v.gate == "max_bundle_size_kb"));
    }

    #[test]
    fn test_quality_gates_check_extended_memory_warning() {
        let gates = QualityGates::default();
        let score = QualityScoreBuilder::new()
            .structural(90.0, 90.0, 90.0)
            .performance(90.0, 90.0, 90.0)
            .accessibility(90.0, 90.0, 90.0)
            .data_quality(90.0, 90.0, 90.0)
            .documentation(90.0, 90.0)
            .consistency(90.0, 90.0)
            .build();

        // Memory exceeds limit but is only a warning
        let result = gates.check_extended(&score, Some(10), Some(400), Some(150));
        assert!(result.passed); // Memory is a warning, not error
        assert!(result.violations.iter().any(|v| v.gate == "max_memory_mb"));
        assert!(result
            .violations
            .iter()
            .any(|v| v.severity == ViolationSeverity::Warning));
    }

    #[test]
    fn test_grade_from_str() {
        assert_eq!(Grade::from_str("A+").unwrap(), Grade::APlus);
        assert_eq!(Grade::from_str("a+").unwrap(), Grade::APlus);
        assert_eq!(Grade::from_str("A").unwrap(), Grade::A);
        assert_eq!(Grade::from_str("A-").unwrap(), Grade::AMinus);
        assert_eq!(Grade::from_str("B+").unwrap(), Grade::BPlus);
        assert_eq!(Grade::from_str("B").unwrap(), Grade::B);
        assert_eq!(Grade::from_str("B-").unwrap(), Grade::BMinus);
        assert_eq!(Grade::from_str("C+").unwrap(), Grade::CPlus);
        assert_eq!(Grade::from_str("C").unwrap(), Grade::C);
        assert_eq!(Grade::from_str("C-").unwrap(), Grade::CMinus);
        assert_eq!(Grade::from_str("D").unwrap(), Grade::D);
        assert_eq!(Grade::from_str("F").unwrap(), Grade::F);
    }

    #[test]
    fn test_grade_from_str_invalid() {
        assert!(matches!(
            Grade::from_str("X"),
            Err(GateConfigError::InvalidValue(_))
        ));
        assert!(matches!(
            Grade::from_str("E"),
            Err(GateConfigError::InvalidValue(_))
        ));
        assert!(matches!(
            Grade::from_str(""),
            Err(GateConfigError::InvalidValue(_))
        ));
    }

    #[test]
    fn test_quality_gates_config_file_constant() {
        assert_eq!(QualityGates::CONFIG_FILE, ".presentar-gates.toml");
    }
}