selfware 0.2.2

Your personal AI workshop — software you own, software that lasts
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
//! Usage Analytics Dashboard
//!
//! Track ROI and productivity metrics:
//! - Time saved through automation
//! - Bugs prevented
//! - Code quality metrics
//! - Productivity trends
//!
//! Privacy: Analytics can be disabled via `SELFWARE_ANALYTICS=false` env var
//! or by calling `AnalyticsDashboard::set_enabled(false)`. When disabled,
//! all `record_*` methods become no-ops.

#![allow(dead_code, unused_imports, unused_variables)]

use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::RwLock;
use std::time::{SystemTime, UNIX_EPOCH};

/// Global flag controlling whether analytics are collected.
/// Defaults to `true` unless the `SELFWARE_ANALYTICS` env var is set to `"false"` or `"0"`.
static ANALYTICS_ENABLED: AtomicBool = AtomicBool::new(true);

/// Initialize the analytics enabled flag from the environment.
/// Called automatically on first `AnalyticsDashboard::new()`, but can be called
/// explicitly for early configuration.
pub fn init_analytics_from_env() {
    if let Ok(val) = std::env::var("SELFWARE_ANALYTICS") {
        let lower = val.to_lowercase();
        if lower == "false" || lower == "0" || lower == "no" || lower == "off" {
            ANALYTICS_ENABLED.store(false, Ordering::Relaxed);
        }
    }
}

/// Check if analytics collection is currently enabled.
pub fn analytics_enabled() -> bool {
    ANALYTICS_ENABLED.load(Ordering::Relaxed)
}

/// Enable or disable analytics collection globally.
pub fn set_analytics_enabled(enabled: bool) {
    ANALYTICS_ENABLED.store(enabled, Ordering::Relaxed);
}

/// Anonymize a task description by hashing it.
///
/// Prevents sensitive task content (which may include file paths, secrets, or
/// proprietary code snippets) from being stored in plaintext analytics records.
/// The first 16 hex characters of the SHA-256 hash are used as the anonymized
/// identifier, providing enough uniqueness for aggregation while being irreversible.
fn anonymize_task(task: &str) -> String {
    let hash = hex::encode(Sha256::digest(task.as_bytes()));
    format!("task:{}", &hash[..16])
}

/// Time period for aggregation
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TimePeriod {
    Hour,
    Day,
    Week,
    Month,
    All,
}

impl TimePeriod {
    /// Duration in seconds
    pub fn seconds(&self) -> u64 {
        match self {
            Self::Hour => 3600,
            Self::Day => 86400,
            Self::Week => 604800,
            Self::Month => 2592000,
            Self::All => u64::MAX,
        }
    }

    /// Label for display
    pub fn label(&self) -> &'static str {
        match self {
            Self::Hour => "Last Hour",
            Self::Day => "Last 24 Hours",
            Self::Week => "Last Week",
            Self::Month => "Last Month",
            Self::All => "All Time",
        }
    }
}

/// Record of time saved
#[derive(Debug, Clone)]
pub struct TimeSavingsRecord {
    /// Task description
    pub task: String,
    /// Estimated manual time (seconds)
    pub manual_time_secs: u64,
    /// Actual automated time (seconds)
    pub automated_time_secs: u64,
    /// Task category
    pub category: String,
    /// Timestamp
    pub timestamp: u64,
}

impl TimeSavingsRecord {
    pub fn new(task: &str, manual_secs: u64, automated_secs: u64, category: &str) -> Self {
        Self {
            task: task.to_string(),
            manual_time_secs: manual_secs,
            automated_time_secs: automated_secs,
            category: category.to_string(),
            timestamp: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
        }
    }

    /// Time saved in seconds
    pub fn time_saved(&self) -> i64 {
        self.manual_time_secs as i64 - self.automated_time_secs as i64
    }

    /// Efficiency ratio
    pub fn efficiency(&self) -> f64 {
        if self.automated_time_secs == 0 {
            1.0
        } else {
            self.manual_time_secs as f64 / self.automated_time_secs as f64
        }
    }
}

/// Tracker for time savings
pub struct TimeSavingsTracker {
    /// Recorded savings
    records: Vec<TimeSavingsRecord>,
    /// Category estimates (task category -> estimated manual time)
    category_estimates: HashMap<String, u64>,
    /// Maximum records
    max_records: usize,
}

impl TimeSavingsTracker {
    pub fn new() -> Self {
        let mut estimates = HashMap::new();
        // Default estimates for common tasks (in seconds)
        estimates.insert("code_write".to_string(), 1800); // 30 min
        estimates.insert("code_review".to_string(), 900); // 15 min
        estimates.insert("bug_fix".to_string(), 3600); // 1 hour
        estimates.insert("test_write".to_string(), 1200); // 20 min
        estimates.insert("refactor".to_string(), 2400); // 40 min
        estimates.insert("documentation".to_string(), 600); // 10 min
        estimates.insert("search".to_string(), 300); // 5 min

        Self {
            records: Vec::new(),
            category_estimates: estimates,
            max_records: 10000,
        }
    }

    /// Set estimate for a category
    pub fn set_category_estimate(&mut self, category: &str, estimate_secs: u64) {
        self.category_estimates
            .insert(category.to_string(), estimate_secs);
    }

    /// Record time savings.
    ///
    /// Task description is anonymized (hashed) before storage.
    pub fn record(&mut self, task: &str, automated_secs: u64, category: &str) {
        let manual_secs = self
            .category_estimates
            .get(category)
            .copied()
            .unwrap_or(300);
        let anon = anonymize_task(task);
        self.records.push(TimeSavingsRecord::new(
            &anon,
            manual_secs,
            automated_secs,
            category,
        ));

        if self.records.len() > self.max_records {
            self.records.drain(0..self.max_records / 2);
        }
    }

    /// Record with explicit manual time.
    ///
    /// Task description is anonymized (hashed) before storage.
    pub fn record_explicit(
        &mut self,
        task: &str,
        manual_secs: u64,
        automated_secs: u64,
        category: &str,
    ) {
        let anon = anonymize_task(task);
        self.records.push(TimeSavingsRecord::new(
            &anon,
            manual_secs,
            automated_secs,
            category,
        ));

        if self.records.len() > self.max_records {
            self.records.drain(0..self.max_records / 2);
        }
    }

    /// Get total time saved
    pub fn total_time_saved(&self, period: TimePeriod) -> i64 {
        let cutoff = Self::cutoff_time(period);
        self.records
            .iter()
            .filter(|r| r.timestamp >= cutoff)
            .map(|r| r.time_saved())
            .sum()
    }

    /// Get savings by category
    pub fn savings_by_category(&self, period: TimePeriod) -> HashMap<String, i64> {
        let cutoff = Self::cutoff_time(period);
        let mut by_cat = HashMap::new();

        for record in self.records.iter().filter(|r| r.timestamp >= cutoff) {
            *by_cat.entry(record.category.clone()).or_insert(0) += record.time_saved();
        }

        by_cat
    }

    /// Get average efficiency
    pub fn average_efficiency(&self, period: TimePeriod) -> f64 {
        let cutoff = Self::cutoff_time(period);
        let records: Vec<_> = self
            .records
            .iter()
            .filter(|r| r.timestamp >= cutoff)
            .collect();

        if records.is_empty() {
            return 1.0;
        }

        let total_manual: u64 = records.iter().map(|r| r.manual_time_secs).sum();
        let total_auto: u64 = records.iter().map(|r| r.automated_time_secs).sum();

        if total_auto == 0 {
            1.0
        } else {
            total_manual as f64 / total_auto as f64
        }
    }

    /// Get record count
    pub fn record_count(&self) -> usize {
        self.records.len()
    }

    fn cutoff_time(period: TimePeriod) -> u64 {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        now.saturating_sub(period.seconds())
    }
}

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

/// Bug prevention severity
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BugSeverity {
    /// Minor issue
    Low,
    /// Moderate issue
    Medium,
    /// Significant issue
    High,
    /// Critical/security issue
    Critical,
}

impl BugSeverity {
    /// Value score for severity
    pub fn value_score(&self) -> u32 {
        match self {
            Self::Low => 1,
            Self::Medium => 3,
            Self::High => 10,
            Self::Critical => 50,
        }
    }

    /// Estimated fix time (hours)
    pub fn estimated_fix_hours(&self) -> f32 {
        match self {
            Self::Low => 0.5,
            Self::Medium => 2.0,
            Self::High => 8.0,
            Self::Critical => 24.0,
        }
    }
}

/// Record of a bug prevented
#[derive(Debug, Clone)]
pub struct BugPreventionRecord {
    /// Bug description
    pub description: String,
    /// Bug type
    pub bug_type: String,
    /// Severity
    pub severity: BugSeverity,
    /// How it was prevented (lint, test, review, etc.)
    pub prevention_method: String,
    /// File where bug would have occurred
    pub file: Option<String>,
    /// Timestamp
    pub timestamp: u64,
}

impl BugPreventionRecord {
    pub fn new(description: &str, bug_type: &str, severity: BugSeverity, method: &str) -> Self {
        Self {
            description: description.to_string(),
            bug_type: bug_type.to_string(),
            severity,
            prevention_method: method.to_string(),
            file: None,
            timestamp: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
        }
    }

    pub fn with_file(mut self, file: &str) -> Self {
        self.file = Some(file.to_string());
        self
    }
}

/// Tracker for bugs prevented
pub struct BugPreventionTracker {
    /// Records
    records: Vec<BugPreventionRecord>,
    /// Maximum records
    max_records: usize,
}

impl BugPreventionTracker {
    pub fn new() -> Self {
        Self {
            records: Vec::new(),
            max_records: 10000,
        }
    }

    /// Record a bug prevented.
    ///
    /// The description is anonymized (hashed) before storage.
    pub fn record(
        &mut self,
        description: &str,
        bug_type: &str,
        severity: BugSeverity,
        method: &str,
    ) {
        let anon_desc = anonymize_task(description);
        self.records.push(BugPreventionRecord::new(
            &anon_desc, bug_type, severity, method,
        ));

        if self.records.len() > self.max_records {
            self.records.drain(0..self.max_records / 2);
        }
    }

    /// Get count by severity
    pub fn count_by_severity(&self, period: TimePeriod) -> HashMap<BugSeverity, usize> {
        let cutoff = Self::cutoff_time(period);
        let mut counts = HashMap::new();

        for record in self.records.iter().filter(|r| r.timestamp >= cutoff) {
            *counts.entry(record.severity).or_insert(0) += 1;
        }

        counts
    }

    /// Get count by type
    pub fn count_by_type(&self, period: TimePeriod) -> HashMap<String, usize> {
        let cutoff = Self::cutoff_time(period);
        let mut counts = HashMap::new();

        for record in self.records.iter().filter(|r| r.timestamp >= cutoff) {
            *counts.entry(record.bug_type.clone()).or_insert(0) += 1;
        }

        counts
    }

    /// Get count by prevention method
    pub fn count_by_method(&self, period: TimePeriod) -> HashMap<String, usize> {
        let cutoff = Self::cutoff_time(period);
        let mut counts = HashMap::new();

        for record in self.records.iter().filter(|r| r.timestamp >= cutoff) {
            *counts.entry(record.prevention_method.clone()).or_insert(0) += 1;
        }

        counts
    }

    /// Total value score of bugs prevented
    pub fn total_value(&self, period: TimePeriod) -> u32 {
        let cutoff = Self::cutoff_time(period);
        self.records
            .iter()
            .filter(|r| r.timestamp >= cutoff)
            .map(|r| r.severity.value_score())
            .sum()
    }

    /// Estimated time saved by preventing bugs (hours)
    pub fn estimated_time_saved_hours(&self, period: TimePeriod) -> f32 {
        let cutoff = Self::cutoff_time(period);
        self.records
            .iter()
            .filter(|r| r.timestamp >= cutoff)
            .map(|r| r.severity.estimated_fix_hours())
            .sum()
    }

    /// Total count
    pub fn total_count(&self, period: TimePeriod) -> usize {
        let cutoff = Self::cutoff_time(period);
        self.records
            .iter()
            .filter(|r| r.timestamp >= cutoff)
            .count()
    }

    fn cutoff_time(period: TimePeriod) -> u64 {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        now.saturating_sub(period.seconds())
    }
}

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

/// Code quality metric snapshot
#[derive(Debug, Clone)]
pub struct QualitySnapshot {
    /// Timestamp
    pub timestamp: u64,
    /// Lines of code
    pub lines_of_code: usize,
    /// Test coverage percentage
    pub test_coverage: f32,
    /// Number of tests
    pub test_count: usize,
    /// Passing tests
    pub tests_passing: usize,
    /// Number of lints/warnings
    pub warnings: usize,
    /// Documentation coverage
    pub doc_coverage: f32,
    /// Complexity score (lower is better)
    pub complexity_score: f32,
    /// Technical debt score (lower is better)
    pub tech_debt_score: f32,
}

impl QualitySnapshot {
    pub fn new() -> Self {
        Self {
            timestamp: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
            lines_of_code: 0,
            test_coverage: 0.0,
            test_count: 0,
            tests_passing: 0,
            warnings: 0,
            doc_coverage: 0.0,
            complexity_score: 0.0,
            tech_debt_score: 0.0,
        }
    }

    /// Test pass rate
    pub fn test_pass_rate(&self) -> f32 {
        if self.test_count == 0 {
            1.0
        } else {
            self.tests_passing as f32 / self.test_count as f32
        }
    }

    /// Overall health score (0-100)
    pub fn health_score(&self) -> f32 {
        let coverage_score = self.test_coverage * 30.0;
        let pass_rate_score = self.test_pass_rate() * 25.0;
        let warning_score = (1.0 - (self.warnings as f32 / 100.0).min(1.0)) * 15.0;
        let doc_score = self.doc_coverage * 10.0;
        let complexity_penalty = (self.complexity_score / 100.0).min(1.0) * 10.0;
        let debt_penalty = (self.tech_debt_score / 100.0).min(1.0) * 10.0;

        (coverage_score + pass_rate_score + warning_score + doc_score
            - complexity_penalty
            - debt_penalty)
            .max(0.0)
    }
}

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

/// Tracker for code quality over time
pub struct CodeQualityTracker {
    /// Snapshots over time
    snapshots: Vec<QualitySnapshot>,
    /// Maximum snapshots
    max_snapshots: usize,
}

impl CodeQualityTracker {
    pub fn new() -> Self {
        Self {
            snapshots: Vec::new(),
            max_snapshots: 1000,
        }
    }

    /// Record a snapshot
    pub fn record(&mut self, snapshot: QualitySnapshot) {
        self.snapshots.push(snapshot);

        if self.snapshots.len() > self.max_snapshots {
            self.snapshots.drain(0..self.max_snapshots / 2);
        }
    }

    /// Get latest snapshot
    pub fn latest(&self) -> Option<&QualitySnapshot> {
        self.snapshots.last()
    }

    /// Get trend for a metric over period
    pub fn trend(&self, period: TimePeriod) -> Option<QualityTrend> {
        let cutoff = Self::cutoff_time(period);
        let relevant: Vec<_> = self
            .snapshots
            .iter()
            .filter(|s| s.timestamp >= cutoff)
            .collect();

        if relevant.len() < 2 {
            return None;
        }

        let first = relevant.first().unwrap();
        let last = relevant.last().unwrap();

        Some(QualityTrend {
            coverage_change: last.test_coverage - first.test_coverage,
            test_count_change: last.test_count as i32 - first.test_count as i32,
            warning_change: last.warnings as i32 - first.warnings as i32,
            health_change: last.health_score() - first.health_score(),
            snapshots: relevant.len(),
        })
    }

    /// Get average health score
    pub fn average_health(&self, period: TimePeriod) -> f32 {
        let cutoff = Self::cutoff_time(period);
        let relevant: Vec<_> = self
            .snapshots
            .iter()
            .filter(|s| s.timestamp >= cutoff)
            .collect();

        if relevant.is_empty() {
            return 0.0;
        }

        relevant.iter().map(|s| s.health_score()).sum::<f32>() / relevant.len() as f32
    }

    fn cutoff_time(period: TimePeriod) -> u64 {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        now.saturating_sub(period.seconds())
    }
}

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

/// Quality trend over time
#[derive(Debug, Clone)]
pub struct QualityTrend {
    pub coverage_change: f32,
    pub test_count_change: i32,
    pub warning_change: i32,
    pub health_change: f32,
    pub snapshots: usize,
}

impl QualityTrend {
    /// Is trend positive overall?
    pub fn is_positive(&self) -> bool {
        self.health_change > 0.0
    }
}

/// Productivity data point
#[derive(Debug, Clone)]
pub struct ProductivityPoint {
    /// Timestamp
    pub timestamp: u64,
    /// Tasks completed
    pub tasks_completed: usize,
    /// Lines of code written
    pub lines_written: usize,
    /// Commits made
    pub commits: usize,
    /// Reviews completed
    pub reviews: usize,
    /// Bugs fixed
    pub bugs_fixed: usize,
    /// Tests written
    pub tests_written: usize,
}

impl ProductivityPoint {
    pub fn new() -> Self {
        Self {
            timestamp: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
            tasks_completed: 0,
            lines_written: 0,
            commits: 0,
            reviews: 0,
            bugs_fixed: 0,
            tests_written: 0,
        }
    }

    /// Total activity score
    pub fn activity_score(&self) -> usize {
        self.tasks_completed * 10
            + self.lines_written / 10
            + self.commits * 5
            + self.reviews * 8
            + self.bugs_fixed * 15
            + self.tests_written * 3
    }
}

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

/// Tracker for productivity trends
pub struct ProductivityTracker {
    /// Data points
    points: Vec<ProductivityPoint>,
    /// Current accumulator (for the current period)
    current: ProductivityPoint,
    /// Accumulation period (seconds)
    period_secs: u64,
    /// Maximum points
    max_points: usize,
}

impl ProductivityTracker {
    pub fn new() -> Self {
        Self {
            points: Vec::new(),
            current: ProductivityPoint::new(),
            period_secs: 3600, // 1 hour periods by default
            max_points: 720,   // 30 days of hourly data
        }
    }

    /// Set accumulation period
    pub fn with_period_secs(mut self, secs: u64) -> Self {
        self.period_secs = secs;
        self
    }

    /// Record task completion
    pub fn record_task(&mut self) {
        self.maybe_flush();
        self.current.tasks_completed += 1;
    }

    /// Record lines written
    pub fn record_lines(&mut self, count: usize) {
        self.maybe_flush();
        self.current.lines_written += count;
    }

    /// Record a commit
    pub fn record_commit(&mut self) {
        self.maybe_flush();
        self.current.commits += 1;
    }

    /// Record a review
    pub fn record_review(&mut self) {
        self.maybe_flush();
        self.current.reviews += 1;
    }

    /// Record bug fix
    pub fn record_bug_fix(&mut self) {
        self.maybe_flush();
        self.current.bugs_fixed += 1;
    }

    /// Record test written
    pub fn record_test(&mut self) {
        self.maybe_flush();
        self.current.tests_written += 1;
    }

    /// Flush current point if period elapsed
    fn maybe_flush(&mut self) {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();

        if now - self.current.timestamp >= self.period_secs {
            // Save current point
            let point = std::mem::take(&mut self.current);
            if point.activity_score() > 0 {
                self.points.push(point);
            }

            // Trim old points
            if self.points.len() > self.max_points {
                self.points.drain(0..self.max_points / 2);
            }
        }
    }

    /// Force flush current point
    pub fn flush(&mut self) {
        if self.current.activity_score() > 0 {
            let point = std::mem::take(&mut self.current);
            self.points.push(point);
        }
    }

    /// Get average productivity score
    pub fn average_score(&self, period: TimePeriod) -> f64 {
        let cutoff = Self::cutoff_time(period);
        let relevant: Vec<_> = self
            .points
            .iter()
            .filter(|p| p.timestamp >= cutoff)
            .collect();

        if relevant.is_empty() {
            return 0.0;
        }

        relevant
            .iter()
            .map(|p| p.activity_score() as f64)
            .sum::<f64>()
            / relevant.len() as f64
    }

    /// Get trend
    pub fn trend(&self, period: TimePeriod) -> Option<ProductivityTrend> {
        let cutoff = Self::cutoff_time(period);
        let relevant: Vec<_> = self
            .points
            .iter()
            .filter(|p| p.timestamp >= cutoff)
            .collect();

        if relevant.len() < 2 {
            return None;
        }

        // Compare first half to second half
        let mid = relevant.len() / 2;
        let first_half: f64 = relevant[..mid]
            .iter()
            .map(|p| p.activity_score() as f64)
            .sum::<f64>()
            / mid as f64;
        let second_half: f64 = relevant[mid..]
            .iter()
            .map(|p| p.activity_score() as f64)
            .sum::<f64>()
            / (relevant.len() - mid) as f64;

        Some(ProductivityTrend {
            change_percent: if first_half > 0.0 {
                ((second_half - first_half) / first_half) * 100.0
            } else {
                0.0
            },
            first_half_avg: first_half,
            second_half_avg: second_half,
            data_points: relevant.len(),
        })
    }

    fn cutoff_time(period: TimePeriod) -> u64 {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        now.saturating_sub(period.seconds())
    }
}

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

/// Productivity trend
#[derive(Debug, Clone)]
pub struct ProductivityTrend {
    pub change_percent: f64,
    pub first_half_avg: f64,
    pub second_half_avg: f64,
    pub data_points: usize,
}

impl ProductivityTrend {
    /// Is productivity improving?
    pub fn is_improving(&self) -> bool {
        self.change_percent > 5.0
    }

    /// Is productivity declining?
    pub fn is_declining(&self) -> bool {
        self.change_percent < -5.0
    }
}

/// Main analytics dashboard
pub struct AnalyticsDashboard {
    /// Time savings tracker
    time_savings: RwLock<TimeSavingsTracker>,
    /// Bug prevention tracker
    bug_prevention: RwLock<BugPreventionTracker>,
    /// Code quality tracker
    code_quality: RwLock<CodeQualityTracker>,
    /// Productivity tracker
    productivity: RwLock<ProductivityTracker>,
}

impl AnalyticsDashboard {
    pub fn new() -> Self {
        // Initialize analytics enabled flag from environment on first creation
        init_analytics_from_env();

        Self {
            time_savings: RwLock::new(TimeSavingsTracker::new()),
            bug_prevention: RwLock::new(BugPreventionTracker::new()),
            code_quality: RwLock::new(CodeQualityTracker::new()),
            productivity: RwLock::new(ProductivityTracker::new()),
        }
    }

    /// Check if analytics collection is enabled.
    pub fn is_enabled(&self) -> bool {
        analytics_enabled()
    }

    /// Clear all stored analytics data across all trackers.
    pub fn clear_analytics_data(&self) {
        if let Ok(mut tracker) = self.time_savings.write() {
            *tracker = TimeSavingsTracker::new();
        }
        if let Ok(mut tracker) = self.bug_prevention.write() {
            *tracker = BugPreventionTracker::new();
        }
        if let Ok(mut tracker) = self.code_quality.write() {
            *tracker = CodeQualityTracker::new();
        }
        if let Ok(mut tracker) = self.productivity.write() {
            *tracker = ProductivityTracker::new();
        }
    }

    /// Record time savings
    pub fn record_time_savings(&self, task: &str, automated_secs: u64, category: &str) {
        if !analytics_enabled() {
            return;
        }
        if let Ok(mut tracker) = self.time_savings.write() {
            tracker.record(task, automated_secs, category);
        }
    }

    /// Record bug prevented
    pub fn record_bug_prevented(
        &self,
        description: &str,
        bug_type: &str,
        severity: BugSeverity,
        method: &str,
    ) {
        if !analytics_enabled() {
            return;
        }
        if let Ok(mut tracker) = self.bug_prevention.write() {
            tracker.record(description, bug_type, severity, method);
        }
    }

    /// Record quality snapshot
    pub fn record_quality_snapshot(&self, snapshot: QualitySnapshot) {
        if !analytics_enabled() {
            return;
        }
        if let Ok(mut tracker) = self.code_quality.write() {
            tracker.record(snapshot);
        }
    }

    /// Record productivity events
    pub fn record_task_completed(&self) {
        if !analytics_enabled() {
            return;
        }
        if let Ok(mut tracker) = self.productivity.write() {
            tracker.record_task();
        }
    }

    pub fn record_lines_written(&self, count: usize) {
        if !analytics_enabled() {
            return;
        }
        if let Ok(mut tracker) = self.productivity.write() {
            tracker.record_lines(count);
        }
    }

    pub fn record_commit(&self) {
        if !analytics_enabled() {
            return;
        }
        if let Ok(mut tracker) = self.productivity.write() {
            tracker.record_commit();
        }
    }

    /// Get summary for a period
    pub fn get_summary(&self, period: TimePeriod) -> DashboardSummary {
        let time_saved = self
            .time_savings
            .read()
            .map(|t| t.total_time_saved(period))
            .unwrap_or(0);

        let efficiency = self
            .time_savings
            .read()
            .map(|t| t.average_efficiency(period))
            .unwrap_or(1.0);

        let bugs_prevented = self
            .bug_prevention
            .read()
            .map(|t| t.total_count(period))
            .unwrap_or(0);

        let bug_value = self
            .bug_prevention
            .read()
            .map(|t| t.total_value(period))
            .unwrap_or(0);

        let health_score = self
            .code_quality
            .read()
            .map(|t| t.average_health(period))
            .unwrap_or(0.0);

        let productivity_score = self
            .productivity
            .read()
            .map(|t| t.average_score(period))
            .unwrap_or(0.0);

        DashboardSummary {
            period,
            time_saved_secs: time_saved,
            efficiency_ratio: efficiency,
            bugs_prevented,
            bug_prevention_value: bug_value,
            health_score,
            productivity_score,
        }
    }

    /// Get ROI estimate (simplified)
    pub fn estimate_roi(&self, period: TimePeriod, hourly_rate: f64) -> RoiEstimate {
        let summary = self.get_summary(period);

        // Time saved value
        let time_value = (summary.time_saved_secs as f64 / 3600.0) * hourly_rate;

        // Bug prevention value (estimated based on fix time avoided)
        let bug_fix_hours = self
            .bug_prevention
            .read()
            .map(|t| t.estimated_time_saved_hours(period))
            .unwrap_or(0.0);
        let bug_value = bug_fix_hours as f64 * hourly_rate;

        // Total value
        let total_value = time_value + bug_value;

        RoiEstimate {
            period,
            time_value,
            bug_prevention_value: bug_value,
            total_value,
            hourly_rate,
        }
    }

    /// Generate text report
    pub fn generate_report(&self, period: TimePeriod) -> String {
        let summary = self.get_summary(period);
        let roi = self.estimate_roi(period, 50.0); // Default $50/hour

        let mut report = String::new();
        report.push_str(&format!("# Analytics Report - {}\n\n", period.label()));

        report.push_str("## Time Savings\n");
        report.push_str(&format!(
            "- Time saved: {} hours\n",
            summary.time_saved_secs / 3600
        ));
        report.push_str(&format!(
            "- Efficiency ratio: {:.1}x\n\n",
            summary.efficiency_ratio
        ));

        report.push_str("## Bug Prevention\n");
        report.push_str(&format!("- Bugs prevented: {}\n", summary.bugs_prevented));
        report.push_str(&format!(
            "- Value score: {}\n\n",
            summary.bug_prevention_value
        ));

        report.push_str("## Code Quality\n");
        report.push_str(&format!(
            "- Health score: {:.1}/100\n\n",
            summary.health_score
        ));

        report.push_str("## Productivity\n");
        report.push_str(&format!(
            "- Average score: {:.1}\n\n",
            summary.productivity_score
        ));

        report.push_str("## ROI Estimate\n");
        report.push_str(&format!("- Time value: ${:.2}\n", roi.time_value));
        report.push_str(&format!(
            "- Bug prevention value: ${:.2}\n",
            roi.bug_prevention_value
        ));
        report.push_str(&format!("- Total value: ${:.2}\n", roi.total_value));

        report
    }
}

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

/// Dashboard summary
#[derive(Debug, Clone)]
pub struct DashboardSummary {
    pub period: TimePeriod,
    pub time_saved_secs: i64,
    pub efficiency_ratio: f64,
    pub bugs_prevented: usize,
    pub bug_prevention_value: u32,
    pub health_score: f32,
    pub productivity_score: f64,
}

/// ROI estimate
#[derive(Debug, Clone)]
pub struct RoiEstimate {
    pub period: TimePeriod,
    pub time_value: f64,
    pub bug_prevention_value: f64,
    pub total_value: f64,
    pub hourly_rate: f64,
}

#[cfg(test)]
mod tests {
    use super::*;
    use once_cell::sync::Lazy;
    use std::sync::Mutex;

    static ANALYTICS_TEST_MUTEX: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));

    #[test]
    fn test_time_period_seconds() {
        assert_eq!(TimePeriod::Hour.seconds(), 3600);
        assert_eq!(TimePeriod::Day.seconds(), 86400);
    }

    #[test]
    fn test_time_period_label() {
        assert_eq!(TimePeriod::Week.label(), "Last Week");
    }

    #[test]
    fn test_time_savings_record() {
        let record = TimeSavingsRecord::new("test", 100, 50, "code");
        assert_eq!(record.time_saved(), 50);
        assert_eq!(record.efficiency(), 2.0);
    }

    #[test]
    fn test_time_savings_tracker_new() {
        let tracker = TimeSavingsTracker::new();
        assert_eq!(tracker.record_count(), 0);
    }

    #[test]
    fn test_time_savings_tracker_record() {
        let mut tracker = TimeSavingsTracker::new();
        tracker.record("test task", 30, "code_write");
        assert_eq!(tracker.record_count(), 1);
    }

    #[test]
    fn test_time_savings_tracker_total() {
        let mut tracker = TimeSavingsTracker::new();
        tracker.record_explicit("task1", 100, 50, "code");
        tracker.record_explicit("task2", 200, 100, "code");
        assert!(tracker.total_time_saved(TimePeriod::All) > 0);
    }

    #[test]
    fn test_bug_severity_value() {
        assert!(BugSeverity::Critical.value_score() > BugSeverity::Low.value_score());
    }

    #[test]
    fn test_bug_severity_fix_hours() {
        assert!(
            BugSeverity::Critical.estimated_fix_hours() > BugSeverity::Low.estimated_fix_hours()
        );
    }

    #[test]
    fn test_bug_prevention_record() {
        let record = BugPreventionRecord::new("null check", "null_ptr", BugSeverity::High, "lint");
        assert_eq!(record.bug_type, "null_ptr");
    }

    #[test]
    fn test_bug_prevention_tracker_new() {
        let tracker = BugPreventionTracker::new();
        assert_eq!(tracker.total_count(TimePeriod::All), 0);
    }

    #[test]
    fn test_bug_prevention_tracker_record() {
        let mut tracker = BugPreventionTracker::new();
        tracker.record("bug", "type", BugSeverity::Medium, "review");
        assert_eq!(tracker.total_count(TimePeriod::All), 1);
    }

    #[test]
    fn test_bug_prevention_by_severity() {
        let mut tracker = BugPreventionTracker::new();
        tracker.record("bug1", "type", BugSeverity::Low, "lint");
        tracker.record("bug2", "type", BugSeverity::High, "lint");

        let counts = tracker.count_by_severity(TimePeriod::All);
        assert_eq!(counts.get(&BugSeverity::Low), Some(&1));
        assert_eq!(counts.get(&BugSeverity::High), Some(&1));
    }

    #[test]
    fn test_quality_snapshot_new() {
        let snapshot = QualitySnapshot::new();
        assert!(snapshot.timestamp > 0);
    }

    #[test]
    fn test_quality_snapshot_pass_rate() {
        let mut snapshot = QualitySnapshot::new();
        snapshot.test_count = 10;
        snapshot.tests_passing = 8;
        assert_eq!(snapshot.test_pass_rate(), 0.8);
    }

    #[test]
    fn test_quality_snapshot_health_score() {
        let mut snapshot = QualitySnapshot::new();
        snapshot.test_coverage = 0.8;
        snapshot.test_count = 100;
        snapshot.tests_passing = 100;
        let score = snapshot.health_score();
        assert!(score > 0.0);
    }

    #[test]
    fn test_code_quality_tracker_new() {
        let tracker = CodeQualityTracker::new();
        assert!(tracker.latest().is_none());
    }

    #[test]
    fn test_code_quality_tracker_record() {
        let mut tracker = CodeQualityTracker::new();
        tracker.record(QualitySnapshot::new());
        assert!(tracker.latest().is_some());
    }

    #[test]
    fn test_productivity_point_new() {
        let point = ProductivityPoint::new();
        assert_eq!(point.activity_score(), 0);
    }

    #[test]
    fn test_productivity_point_score() {
        let mut point = ProductivityPoint::new();
        point.tasks_completed = 5;
        point.commits = 3;
        assert!(point.activity_score() > 0);
    }

    #[test]
    fn test_productivity_tracker_new() {
        let tracker = ProductivityTracker::new();
        assert_eq!(tracker.average_score(TimePeriod::All), 0.0);
    }

    #[test]
    fn test_productivity_tracker_record() {
        let mut tracker = ProductivityTracker::new();
        tracker.record_task();
        tracker.record_commit();
        tracker.flush();
        // After flush, should have some data
    }

    #[test]
    fn test_analytics_dashboard_new() {
        let dashboard = AnalyticsDashboard::new();
        let summary = dashboard.get_summary(TimePeriod::All);
        assert_eq!(summary.bugs_prevented, 0);
    }

    #[test]
    fn test_analytics_dashboard_record_time() {
        let dashboard = AnalyticsDashboard::new();
        dashboard.record_time_savings("test", 60, "code_write");
        // Verify recorded (would need accessor to check)
    }

    #[test]
    fn test_analytics_dashboard_record_bug() {
        let dashboard = AnalyticsDashboard::new();
        dashboard.record_bug_prevented("null check", "null_ptr", BugSeverity::High, "lint");
        let summary = dashboard.get_summary(TimePeriod::All);
        assert_eq!(summary.bugs_prevented, 1);
    }

    #[test]
    fn test_analytics_dashboard_roi() {
        let dashboard = AnalyticsDashboard::new();
        let roi = dashboard.estimate_roi(TimePeriod::All, 50.0);
        assert_eq!(roi.hourly_rate, 50.0);
    }

    #[test]
    fn test_analytics_dashboard_report() {
        let dashboard = AnalyticsDashboard::new();
        let report = dashboard.generate_report(TimePeriod::Week);
        assert!(report.contains("Analytics Report"));
        assert!(report.contains("Time Savings"));
        assert!(report.contains("ROI"));
    }

    #[test]
    fn test_quality_trend_positive() {
        let trend = QualityTrend {
            coverage_change: 0.1,
            test_count_change: 10,
            warning_change: -5,
            health_change: 5.0,
            snapshots: 10,
        };
        assert!(trend.is_positive());
    }

    #[test]
    fn test_productivity_trend_improving() {
        let trend = ProductivityTrend {
            change_percent: 20.0,
            first_half_avg: 50.0,
            second_half_avg: 60.0,
            data_points: 20,
        };
        assert!(trend.is_improving());
        assert!(!trend.is_declining());
    }

    #[test]
    fn test_time_savings_by_category() {
        let mut tracker = TimeSavingsTracker::new();
        tracker.record_explicit("t1", 100, 50, "code_write");
        tracker.record_explicit("t2", 200, 100, "bug_fix");

        let by_cat = tracker.savings_by_category(TimePeriod::All);
        assert!(by_cat.contains_key("code_write"));
        assert!(by_cat.contains_key("bug_fix"));
    }

    #[test]
    fn test_dashboard_summary() {
        let summary = DashboardSummary {
            period: TimePeriod::Week,
            time_saved_secs: 3600,
            efficiency_ratio: 2.0,
            bugs_prevented: 5,
            bug_prevention_value: 50,
            health_score: 75.0,
            productivity_score: 100.0,
        };
        assert_eq!(summary.time_saved_secs, 3600);
    }

    #[test]
    fn test_roi_estimate() {
        let roi = RoiEstimate {
            period: TimePeriod::Month,
            time_value: 1000.0,
            bug_prevention_value: 500.0,
            total_value: 1500.0,
            hourly_rate: 50.0,
        };
        assert_eq!(roi.total_value, 1500.0);
    }

    #[test]
    fn test_time_period_all_variants() {
        let periods = [
            TimePeriod::Hour,
            TimePeriod::Day,
            TimePeriod::Week,
            TimePeriod::Month,
            TimePeriod::All,
        ];

        for period in periods {
            let _ = period.seconds();
            let _ = period.label();
        }
    }

    #[test]
    fn test_time_period_seconds_all() {
        assert_eq!(TimePeriod::Week.seconds(), 604800);
        assert_eq!(TimePeriod::Month.seconds(), 2592000);
        assert_eq!(TimePeriod::All.seconds(), u64::MAX);
    }

    #[test]
    fn test_time_period_label_all() {
        assert_eq!(TimePeriod::Hour.label(), "Last Hour");
        assert_eq!(TimePeriod::Day.label(), "Last 24 Hours");
        assert_eq!(TimePeriod::All.label(), "All Time");
    }

    #[test]
    fn test_time_savings_record_clone() {
        let record = TimeSavingsRecord::new("task", 100, 50, "code");
        let cloned = record.clone();
        assert_eq!(record.task, cloned.task);
        assert_eq!(record.time_saved(), cloned.time_saved());
    }

    #[test]
    fn test_time_savings_record_efficiency_zero_automated() {
        let record = TimeSavingsRecord::new("instant", 100, 0, "fast");
        assert_eq!(record.efficiency(), 1.0);
    }

    #[test]
    fn test_time_savings_record_negative_savings() {
        let record = TimeSavingsRecord::new("slow", 50, 100, "code");
        assert_eq!(record.time_saved(), -50);
    }

    #[test]
    fn test_time_savings_tracker_default() {
        let tracker = TimeSavingsTracker::default();
        assert_eq!(tracker.record_count(), 0);
    }

    #[test]
    fn test_time_savings_tracker_set_category_estimate() {
        let mut tracker = TimeSavingsTracker::new();
        tracker.set_category_estimate("custom", 5000);
        tracker.record("custom task", 100, "custom");
        // The estimate should be used
        assert!(tracker.total_time_saved(TimePeriod::All) > 0);
    }

    #[test]
    fn test_time_savings_tracker_average_efficiency() {
        let mut tracker = TimeSavingsTracker::new();
        tracker.record_explicit("task1", 100, 50, "code");
        tracker.record_explicit("task2", 200, 50, "code");
        let efficiency = tracker.average_efficiency(TimePeriod::All);
        assert!(efficiency > 1.0);
    }

    #[test]
    fn test_time_savings_tracker_average_efficiency_empty() {
        let tracker = TimeSavingsTracker::new();
        assert_eq!(tracker.average_efficiency(TimePeriod::All), 1.0);
    }

    #[test]
    fn test_bug_severity_all_variants() {
        let severities = [
            BugSeverity::Critical,
            BugSeverity::High,
            BugSeverity::Medium,
            BugSeverity::Low,
        ];

        for severity in severities {
            let _ = severity.value_score();
            let _ = severity.estimated_fix_hours();
        }
    }

    #[test]
    fn test_bug_prevention_record_clone() {
        let record = BugPreventionRecord::new("desc", "type", BugSeverity::High, "source");
        let cloned = record.clone();
        assert_eq!(record.description, cloned.description);
        assert_eq!(record.severity, cloned.severity);
    }

    #[test]
    fn test_bug_prevention_tracker_default() {
        let tracker = BugPreventionTracker::default();
        assert_eq!(tracker.total_count(TimePeriod::All), 0);
    }

    #[test]
    fn test_bug_prevention_tracker_by_type() {
        let mut tracker = BugPreventionTracker::new();
        tracker.record("bug1", "null_ptr", BugSeverity::High, "lint");
        tracker.record("bug2", "null_ptr", BugSeverity::Low, "lint");
        tracker.record("bug3", "race", BugSeverity::Critical, "review");

        let by_type = tracker.count_by_type(TimePeriod::All);
        assert_eq!(by_type.get("null_ptr"), Some(&2));
        assert_eq!(by_type.get("race"), Some(&1));
    }

    #[test]
    fn test_bug_prevention_tracker_by_method() {
        let mut tracker = BugPreventionTracker::new();
        tracker.record("bug1", "type", BugSeverity::High, "lint");
        tracker.record("bug2", "type", BugSeverity::Low, "review");

        let by_method = tracker.count_by_method(TimePeriod::All);
        assert!(by_method.contains_key("lint"));
        assert!(by_method.contains_key("review"));
    }

    #[test]
    fn test_bug_prevention_tracker_total_value() {
        let mut tracker = BugPreventionTracker::new();
        tracker.record("bug", "type", BugSeverity::Critical, "lint");
        let value = tracker.total_value(TimePeriod::All);
        assert!(value > 0);
    }

    #[test]
    fn test_quality_snapshot_clone() {
        let snapshot = QualitySnapshot::new();
        let cloned = snapshot.clone();
        assert_eq!(snapshot.test_coverage, cloned.test_coverage);
    }

    #[test]
    fn test_quality_snapshot_pass_rate_no_tests() {
        let snapshot = QualitySnapshot::new();
        assert_eq!(snapshot.test_pass_rate(), 1.0);
    }

    #[test]
    fn test_quality_snapshot_health_score_with_warnings() {
        let mut snapshot = QualitySnapshot::new();
        snapshot.test_coverage = 0.8;
        snapshot.test_count = 100;
        snapshot.tests_passing = 100;
        snapshot.warnings = 10;
        let score = snapshot.health_score();
        assert!(score > 0.0 && score <= 100.0);
    }

    #[test]
    fn test_code_quality_tracker_default() {
        let tracker = CodeQualityTracker::default();
        assert!(tracker.latest().is_none());
    }

    #[test]
    fn test_code_quality_tracker_trend() {
        let mut tracker = CodeQualityTracker::new();

        let mut s1 = QualitySnapshot::new();
        s1.test_coverage = 0.5;
        s1.test_count = 50;

        let mut s2 = QualitySnapshot::new();
        s2.test_coverage = 0.6;
        s2.test_count = 60;

        tracker.record(s1);
        tracker.record(s2);

        let trend = tracker.trend(TimePeriod::All);
        assert!(trend.is_some());
        assert!(trend.unwrap().coverage_change > 0.0);
    }

    #[test]
    fn test_code_quality_tracker_trend_empty() {
        let tracker = CodeQualityTracker::new();
        let trend = tracker.trend(TimePeriod::All);
        assert!(trend.is_none());
    }

    #[test]
    fn test_productivity_point_clone() {
        let mut point = ProductivityPoint::new();
        point.tasks_completed = 5;
        let cloned = point.clone();
        assert_eq!(point.tasks_completed, cloned.tasks_completed);
    }

    #[test]
    fn test_productivity_tracker_default() {
        let tracker = ProductivityTracker::default();
        assert_eq!(tracker.average_score(TimePeriod::All), 0.0);
    }

    #[test]
    fn test_productivity_tracker_record_line() {
        let mut tracker = ProductivityTracker::new();
        tracker.record_lines(100);
        tracker.flush();
        // Just verify it doesn't panic
    }

    #[test]
    fn test_productivity_tracker_record_review() {
        let mut tracker = ProductivityTracker::new();
        tracker.record_review();
        tracker.flush();
    }

    #[test]
    fn test_productivity_tracker_trend() {
        let mut tracker = ProductivityTracker::new();

        for _ in 0..5 {
            tracker.record_task();
            tracker.flush();
        }

        let trend = tracker.trend(TimePeriod::All);
        // Verify trend calculation works after recording tasks
        if let Some(t) = trend {
            // We recorded 5 tasks, so should have meaningful data points
            assert!(
                t.data_points > 0,
                "Expected data points after recording tasks"
            );
            // Verify trend values are finite (not NaN or Inf)
            assert!(
                t.change_percent.is_finite(),
                "Change percent should be finite"
            );
            assert!(
                t.first_half_avg.is_finite(),
                "First half avg should be finite"
            );
            assert!(
                t.second_half_avg.is_finite(),
                "Second half avg should be finite"
            );
        }
    }

    #[test]
    fn test_productivity_trend_declining() {
        let trend = ProductivityTrend {
            change_percent: -20.0,
            first_half_avg: 60.0,
            second_half_avg: 50.0,
            data_points: 20,
        };
        assert!(!trend.is_improving());
        assert!(trend.is_declining());
    }

    #[test]
    fn test_productivity_trend_neutral() {
        let trend = ProductivityTrend {
            change_percent: 0.0,
            first_half_avg: 50.0,
            second_half_avg: 50.0,
            data_points: 20,
        };
        assert!(!trend.is_improving());
        assert!(!trend.is_declining());
    }

    #[test]
    fn test_quality_trend_negative() {
        let trend = QualityTrend {
            coverage_change: -0.1,
            test_count_change: -5,
            warning_change: 10,
            health_change: -10.0,
            snapshots: 10,
        };
        assert!(!trend.is_positive());
    }

    #[test]
    fn test_analytics_dashboard_record_quality() {
        let dashboard = AnalyticsDashboard::new();
        dashboard.record_quality_snapshot(QualitySnapshot::new());
        // Verify it doesn't panic
    }

    #[test]
    fn test_analytics_dashboard_record_productivity_task() {
        let dashboard = AnalyticsDashboard::new();
        dashboard.record_task_completed();
    }

    #[test]
    fn test_analytics_dashboard_record_productivity_commit() {
        let dashboard = AnalyticsDashboard::new();
        dashboard.record_commit();
    }

    #[test]
    fn test_analytics_dashboard_get_summary_default() {
        let dashboard = AnalyticsDashboard::new();
        let summary = dashboard.get_summary(TimePeriod::All);
        assert_eq!(summary.bugs_prevented, 0);
        assert_eq!(summary.time_saved_secs, 0);
    }

    #[test]
    fn test_analytics_dashboard_estimate_roi_default() {
        let dashboard = AnalyticsDashboard::new();
        let roi = dashboard.estimate_roi(TimePeriod::All, 50.0);
        assert_eq!(roi.hourly_rate, 50.0);
        assert_eq!(roi.total_value, 0.0);
    }

    #[test]
    fn test_dashboard_summary_clone() {
        let summary = DashboardSummary {
            period: TimePeriod::Week,
            time_saved_secs: 3600,
            efficiency_ratio: 2.0,
            bugs_prevented: 5,
            bug_prevention_value: 50,
            health_score: 75.0,
            productivity_score: 100.0,
        };
        let cloned = summary.clone();
        assert_eq!(summary.time_saved_secs, cloned.time_saved_secs);
    }

    #[test]
    fn test_roi_estimate_clone() {
        let roi = RoiEstimate {
            period: TimePeriod::Month,
            time_value: 1000.0,
            bug_prevention_value: 500.0,
            total_value: 1500.0,
            hourly_rate: 50.0,
        };
        let cloned = roi.clone();
        assert_eq!(roi.total_value, cloned.total_value);
    }

    #[test]
    fn test_analytics_dashboard_report_all_periods() {
        let dashboard = AnalyticsDashboard::new();

        for period in [
            TimePeriod::Hour,
            TimePeriod::Day,
            TimePeriod::Week,
            TimePeriod::Month,
            TimePeriod::All,
        ] {
            let report = dashboard.generate_report(period);
            assert!(!report.is_empty());
        }
    }

    #[test]
    fn test_time_period_hash() {
        use std::collections::HashSet;
        let mut set = HashSet::new();
        set.insert(TimePeriod::Hour);
        set.insert(TimePeriod::Day);
        set.insert(TimePeriod::Hour); // Duplicate
        assert_eq!(set.len(), 2);
    }

    #[test]
    fn test_analytics_dashboard_comprehensive() {
        // Ensure analytics is enabled for this test
        set_analytics_enabled(true);
        let dashboard = AnalyticsDashboard::new();

        // Record various data
        dashboard.record_time_savings("write code", 60, "code_write");
        dashboard.record_bug_prevented("null check", "null", BugSeverity::High, "lint");
        dashboard.record_quality_snapshot(QualitySnapshot::new());
        dashboard.record_task_completed();
        dashboard.record_commit();

        // Get summary
        let summary = dashboard.get_summary(TimePeriod::All);
        assert_eq!(summary.bugs_prevented, 1);

        // Get ROI
        let roi = dashboard.estimate_roi(TimePeriod::All, 75.0);
        assert_eq!(roi.hourly_rate, 75.0);

        // Generate report
        let report = dashboard.generate_report(TimePeriod::All);
        assert!(report.contains("Analytics Report"));
    }

    #[test]
    fn test_analytics_enabled_default() {
        let _guard = ANALYTICS_TEST_MUTEX.lock().unwrap();
        // Default should be true (unless env var overrides)
        // Reset to known state
        set_analytics_enabled(true);
        assert!(analytics_enabled());
    }

    #[test]
    fn test_analytics_disable_enable() {
        let _guard = ANALYTICS_TEST_MUTEX.lock().unwrap();
        let original = analytics_enabled();

        set_analytics_enabled(false);
        assert!(!analytics_enabled());

        set_analytics_enabled(true);
        assert!(analytics_enabled());

        // Restore original state
        set_analytics_enabled(original);
    }

    #[test]
    fn test_analytics_disabled_noop() {
        let _guard = ANALYTICS_TEST_MUTEX.lock().unwrap();
        let original = analytics_enabled();
        set_analytics_enabled(false);

        let dashboard = AnalyticsDashboard::new();
        // These should be no-ops when disabled
        dashboard.record_time_savings("task", 100, "code_write");
        dashboard.record_bug_prevented("bug", "type", BugSeverity::High, "lint");
        dashboard.record_quality_snapshot(QualitySnapshot::new());
        dashboard.record_task_completed();
        dashboard.record_lines_written(100);
        dashboard.record_commit();

        // Summary should show nothing recorded
        let summary = dashboard.get_summary(TimePeriod::All);
        assert_eq!(summary.bugs_prevented, 0);
        assert_eq!(summary.time_saved_secs, 0);

        // Restore
        set_analytics_enabled(original);
    }

    #[test]
    fn test_clear_analytics_data() {
        let _guard = ANALYTICS_TEST_MUTEX.lock().unwrap();
        let original = analytics_enabled();
        set_analytics_enabled(true);

        let dashboard = AnalyticsDashboard::new();
        dashboard.record_time_savings("task", 100, "code_write");
        dashboard.record_bug_prevented("bug", "type", BugSeverity::High, "lint");

        // Verify data is recorded
        let summary = dashboard.get_summary(TimePeriod::All);
        assert_eq!(summary.bugs_prevented, 1);

        // Clear all data
        dashboard.clear_analytics_data();

        // Verify data is cleared
        let summary = dashboard.get_summary(TimePeriod::All);
        assert_eq!(summary.bugs_prevented, 0);
        assert_eq!(summary.time_saved_secs, 0);

        // Restore
        set_analytics_enabled(original);
    }

    #[test]
    fn test_dashboard_is_enabled() {
        let _guard = ANALYTICS_TEST_MUTEX.lock().unwrap();
        let original = analytics_enabled();
        set_analytics_enabled(true);
        let dashboard = AnalyticsDashboard::new();
        assert!(dashboard.is_enabled());

        set_analytics_enabled(false);
        assert!(!dashboard.is_enabled());

        set_analytics_enabled(original);
    }
}