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
//! Carbon Footprint Tracker
//!
//! Track environmental impact of compute operations, API calls,
//! and provide optimization suggestions for sustainability.
//!
//! **Disclaimer:** All carbon and energy estimates produced by this module are
//! approximate. They are based on average cloud GPU power consumption data,
//! publicly available PUE figures, and grid carbon intensity averages from IEA
//! and Ember. Actual emissions vary significantly by hardware, region, time of
//! day, provider, and workload characteristics. These figures are intended for
//! directional awareness, not precise carbon accounting.

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

use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

/// Atomic counter for unique IDs
static EMISSION_COUNTER: AtomicU64 = AtomicU64::new(0);
static REPORT_COUNTER: AtomicU64 = AtomicU64::new(0);

/// Generate unique emission ID
fn generate_emission_id() -> String {
    format!(
        "emission-{}",
        EMISSION_COUNTER.fetch_add(1, Ordering::SeqCst)
    )
}

/// Generate unique report ID
fn generate_report_id() -> String {
    format!("report-{}", REPORT_COUNTER.fetch_add(1, Ordering::SeqCst))
}

/// Carbon emission source type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EmissionSource {
    /// LLM API call
    LlmApiCall,
    /// GPU compute
    GpuCompute,
    /// CPU compute
    CpuCompute,
    /// Data transfer
    DataTransfer,
    /// Storage operations
    Storage,
    /// Network operations
    Network,
    /// Build/compile operations
    Build,
    /// Container operations
    Container,
    /// Database queries
    Database,
    /// Other
    Other,
}

impl std::fmt::Display for EmissionSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EmissionSource::LlmApiCall => write!(f, "LLM API"),
            EmissionSource::GpuCompute => write!(f, "GPU Compute"),
            EmissionSource::CpuCompute => write!(f, "CPU Compute"),
            EmissionSource::DataTransfer => write!(f, "Data Transfer"),
            EmissionSource::Storage => write!(f, "Storage"),
            EmissionSource::Network => write!(f, "Network"),
            EmissionSource::Build => write!(f, "Build"),
            EmissionSource::Container => write!(f, "Container"),
            EmissionSource::Database => write!(f, "Database"),
            EmissionSource::Other => write!(f, "Other"),
        }
    }
}

/// Energy grid carbon intensity (gCO2e/kWh)
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum GridIntensity {
    /// Very low carbon grid (e.g., Iceland, Norway)
    VeryLow,
    /// Low carbon grid (e.g., France, Sweden)
    Low,
    /// Medium carbon grid (e.g., UK, California)
    Medium,
    /// High carbon grid (e.g., US average)
    High,
    /// Very high carbon grid (e.g., China, India)
    VeryHigh,
    /// Custom intensity value
    Custom(f64),
}

impl GridIntensity {
    /// Get gCO2e per kWh.
    ///
    /// Values are approximate averages based on IEA and Ember global
    /// electricity data (2022-2023). Actual grid carbon intensity varies by
    /// time of day, season, and specific grid region.
    pub fn grams_co2_per_kwh(&self) -> f64 {
        match self {
            GridIntensity::VeryLow => 20.0, // e.g. Iceland, Norway (hydro/geothermal)
            GridIntensity::Low => 50.0,     // e.g. France, Sweden (nuclear/hydro)
            GridIntensity::Medium => 250.0, // e.g. UK, California
            GridIntensity::High => 400.0,   // e.g. US average
            GridIntensity::VeryHigh => 600.0, // e.g. China, India (coal-heavy grids)
            GridIntensity::Custom(v) => *v,
        }
    }
}

impl std::fmt::Display for GridIntensity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            GridIntensity::VeryLow => write!(f, "Very Low (~20g CO2e/kWh)"),
            GridIntensity::Low => write!(f, "Low (~50g CO2e/kWh)"),
            GridIntensity::Medium => write!(f, "Medium (~250g CO2e/kWh)"),
            GridIntensity::High => write!(f, "High (~400g CO2e/kWh)"),
            GridIntensity::VeryHigh => write!(f, "Very High (~600g CO2e/kWh)"),
            GridIntensity::Custom(v) => write!(f, "Custom ({}g CO2e/kWh)", v),
        }
    }
}

/// Cloud provider with carbon data
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CloudProvider {
    /// Amazon Web Services
    Aws,
    /// Google Cloud Platform
    Gcp,
    /// Microsoft Azure
    Azure,
    /// Self-hosted
    SelfHosted,
    /// Local development
    Local,
    /// Other
    Other,
}

impl std::fmt::Display for CloudProvider {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CloudProvider::Aws => write!(f, "AWS"),
            CloudProvider::Gcp => write!(f, "GCP"),
            CloudProvider::Azure => write!(f, "Azure"),
            CloudProvider::SelfHosted => write!(f, "Self-Hosted"),
            CloudProvider::Local => write!(f, "Local"),
            CloudProvider::Other => write!(f, "Other"),
        }
    }
}

impl CloudProvider {
    /// Get Power Usage Effectiveness (PUE) factor.
    ///
    /// PUE = Total Facility Energy / IT Equipment Energy. A PUE of 1.0 would
    /// mean zero overhead; real datacenters range from ~1.1 (hyperscale) to
    /// ~2.0+ (small/older facilities).
    ///
    /// Sources:
    /// - GCP: 1.10 -- Google Environmental Report 2023
    /// - AWS: 1.20 -- estimated from AWS sustainability disclosures
    /// - Azure: 1.18 -- Microsoft Sustainability Report 2023
    /// - Self-hosted: 1.60 -- Uptime Institute 2022 global average for
    ///   enterprise datacenters
    /// - Local: 2.0 -- conservative estimate for home/office environments
    pub fn pue(&self) -> f64 {
        match self {
            CloudProvider::Gcp => 1.1,        // Google Environmental Report 2023
            CloudProvider::Aws => 1.2,        // AWS sustainability disclosures (estimated)
            CloudProvider::Azure => 1.18,     // Microsoft Sustainability Report 2023
            CloudProvider::SelfHosted => 1.6, // Uptime Institute 2022 global average
            CloudProvider::Local => 2.0,      // Conservative estimate for home/office
            CloudProvider::Other => 1.5,      // Conservative estimate
        }
    }

    /// Whether provider offers carbon-neutral options
    pub fn has_green_option(&self) -> bool {
        match self {
            CloudProvider::Gcp => true,   // Carbon neutral since 2007
            CloudProvider::Aws => true,   // Climate pledge
            CloudProvider::Azure => true, // Carbon negative goal
            CloudProvider::SelfHosted | CloudProvider::Local | CloudProvider::Other => false,
        }
    }
}

/// LLM model type for emission estimation
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LlmModel {
    /// GPT-4 or similar large model
    GptLarge,
    /// GPT-3.5 or similar medium model
    GptMedium,
    /// Small model (e.g., Llama 7B)
    Small,
    /// Tiny model (e.g., Phi-2)
    Tiny,
    /// Local model
    Local,
    /// Claude models
    Claude,
    /// Custom with specified parameters
    Custom,
}

impl std::fmt::Display for LlmModel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LlmModel::GptLarge => write!(f, "GPT-4/Large"),
            LlmModel::GptMedium => write!(f, "GPT-3.5/Medium"),
            LlmModel::Small => write!(f, "Small (7B)"),
            LlmModel::Tiny => write!(f, "Tiny (<3B)"),
            LlmModel::Local => write!(f, "Local"),
            LlmModel::Claude => write!(f, "Claude"),
            LlmModel::Custom => write!(f, "Custom"),
        }
    }
}

impl LlmModel {
    /// Estimated energy per 1000 tokens (Wh).
    ///
    /// **Disclaimer:** These are rough approximations based on publicly available
    /// research and blog posts, not direct measurements. Actual energy
    /// consumption varies significantly depending on hardware, batch size,
    /// quantization, datacenter efficiency, and inference framework.
    ///
    /// Sources / assumptions:
    /// - Large models (~175B params): ~0.5 Wh/1k tokens, extrapolated from
    ///   Luccioni et al. (2023) "Power Hungry Processing" (arXiv:2311.16863)
    /// - Medium models (~20-70B params): ~0.1 Wh/1k tokens, same source scaled
    /// - Small models (~7B params): ~0.05 Wh/1k tokens, based on typical
    ///   single-GPU inference power draw (~100W) and throughput (~40 tok/s)
    /// - Tiny models (<3B params): ~0.01 Wh/1k tokens, similar methodology
    /// - Claude: ~0.3 Wh/1k tokens, rough estimate assuming large-model class
    /// - Local/Custom: conservative middle-ground estimates
    pub fn wh_per_1k_tokens(&self) -> f64 {
        match self {
            LlmModel::GptLarge => 0.5,  // ~500 Wh/1M tokens (175B+ param models)
            LlmModel::GptMedium => 0.1, // ~100 Wh/1M tokens (20-70B param models)
            LlmModel::Small => 0.05,    // ~50 Wh/1M tokens (7B param models)
            LlmModel::Tiny => 0.01,     // ~10 Wh/1M tokens (<3B param models)
            LlmModel::Local => 0.1,     // Varies widely by hardware; conservative default
            LlmModel::Claude => 0.3,    // Estimated, large-model class
            LlmModel::Custom => 0.2,    // Default estimate for unknown models
        }
    }
}

/// A single emission record
#[derive(Debug, Clone)]
pub struct EmissionRecord {
    /// Unique identifier
    pub id: String,
    /// Source of emission
    pub source: EmissionSource,
    /// Carbon dioxide equivalent in grams
    pub co2e_grams: f64,
    /// Energy consumed in Wh
    pub energy_wh: f64,
    /// Timestamp
    pub timestamp: u64,
    /// Duration of operation
    pub duration: Option<Duration>,
    /// Description
    pub description: String,
    /// Associated operation
    pub operation: Option<String>,
    /// Provider used
    pub provider: Option<CloudProvider>,
    /// Region
    pub region: Option<String>,
}

impl EmissionRecord {
    /// Create a new emission record
    pub fn new(source: EmissionSource, co2e_grams: f64) -> Self {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();

        Self {
            id: generate_emission_id(),
            source,
            co2e_grams,
            energy_wh: 0.0,
            timestamp,
            duration: None,
            description: String::new(),
            operation: None,
            provider: None,
            region: None,
        }
    }

    /// Set energy consumption
    pub fn with_energy(mut self, energy_wh: f64) -> Self {
        self.energy_wh = energy_wh;
        self
    }

    /// Set duration
    pub fn with_duration(mut self, duration: Duration) -> Self {
        self.duration = Some(duration);
        self
    }

    /// Set description
    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
        self.description = desc.into();
        self
    }

    /// Set operation
    pub fn with_operation(mut self, op: impl Into<String>) -> Self {
        self.operation = Some(op.into());
        self
    }

    /// Set provider
    pub fn with_provider(mut self, provider: CloudProvider) -> Self {
        self.provider = Some(provider);
        self
    }

    /// Set region
    pub fn with_region(mut self, region: impl Into<String>) -> Self {
        self.region = Some(region.into());
        self
    }
}

/// Optimization suggestion
#[derive(Debug, Clone)]
pub struct Optimization {
    /// Suggestion title
    pub title: String,
    /// Description
    pub description: String,
    /// Estimated CO2e savings in grams
    pub estimated_savings_grams: f64,
    /// Effort level to implement
    pub effort: EffortLevel,
    /// Priority
    pub priority: Priority,
    /// Category
    pub category: OptimizationCategory,
}

impl Optimization {
    /// Create a new optimization
    pub fn new(title: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            description: description.into(),
            estimated_savings_grams: 0.0,
            effort: EffortLevel::Low,
            priority: Priority::Medium,
            category: OptimizationCategory::Compute,
        }
    }

    /// Set estimated savings
    pub fn with_savings(mut self, grams: f64) -> Self {
        self.estimated_savings_grams = grams;
        self
    }

    /// Set effort level
    pub fn with_effort(mut self, effort: EffortLevel) -> Self {
        self.effort = effort;
        self
    }

    /// Set priority
    pub fn with_priority(mut self, priority: Priority) -> Self {
        self.priority = priority;
        self
    }

    /// Set category
    pub fn with_category(mut self, category: OptimizationCategory) -> Self {
        self.category = category;
        self
    }
}

/// Effort level
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum EffortLevel {
    /// Minimal effort
    Low,
    /// Moderate effort
    Medium,
    /// Significant effort
    High,
}

impl std::fmt::Display for EffortLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EffortLevel::Low => write!(f, "Low"),
            EffortLevel::Medium => write!(f, "Medium"),
            EffortLevel::High => write!(f, "High"),
        }
    }
}

/// Priority level
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Priority {
    /// Low priority
    Low,
    /// Medium priority
    Medium,
    /// High priority
    High,
    /// Critical priority
    Critical,
}

impl std::fmt::Display for Priority {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Priority::Low => write!(f, "Low"),
            Priority::Medium => write!(f, "Medium"),
            Priority::High => write!(f, "High"),
            Priority::Critical => write!(f, "Critical"),
        }
    }
}

/// Optimization category
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum OptimizationCategory {
    /// Compute optimization
    Compute,
    /// API optimization
    Api,
    /// Storage optimization
    Storage,
    /// Network optimization
    Network,
    /// Hosting optimization
    Hosting,
    /// Caching optimization
    Caching,
    /// Model selection
    ModelSelection,
}

impl std::fmt::Display for OptimizationCategory {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            OptimizationCategory::Compute => write!(f, "Compute"),
            OptimizationCategory::Api => write!(f, "API"),
            OptimizationCategory::Storage => write!(f, "Storage"),
            OptimizationCategory::Network => write!(f, "Network"),
            OptimizationCategory::Hosting => write!(f, "Hosting"),
            OptimizationCategory::Caching => write!(f, "Caching"),
            OptimizationCategory::ModelSelection => write!(f, "Model Selection"),
        }
    }
}

/// Green hosting recommendation
#[derive(Debug, Clone)]
pub struct GreenHosting {
    /// Provider name
    pub provider: String,
    /// Region
    pub region: String,
    /// Grid intensity
    pub grid_intensity: GridIntensity,
    /// Renewable energy percentage
    pub renewable_percentage: u8,
    /// Carbon neutral
    pub carbon_neutral: bool,
    /// Description
    pub description: String,
}

impl GreenHosting {
    /// Create a new green hosting recommendation
    pub fn new(provider: impl Into<String>, region: impl Into<String>) -> Self {
        Self {
            provider: provider.into(),
            region: region.into(),
            grid_intensity: GridIntensity::Medium,
            renewable_percentage: 0,
            carbon_neutral: false,
            description: String::new(),
        }
    }

    /// Set grid intensity
    pub fn with_intensity(mut self, intensity: GridIntensity) -> Self {
        self.grid_intensity = intensity;
        self
    }

    /// Set renewable percentage
    pub fn with_renewable(mut self, percentage: u8) -> Self {
        self.renewable_percentage = percentage.min(100);
        self
    }

    /// Mark as carbon neutral
    pub fn carbon_neutral(mut self) -> Self {
        self.carbon_neutral = true;
        self
    }

    /// Set description
    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
        self.description = desc.into();
        self
    }
}

/// Emission calculator
#[derive(Debug)]
pub struct EmissionCalculator {
    /// Grid intensity
    grid_intensity: GridIntensity,
    /// Cloud provider
    provider: CloudProvider,
}

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

impl EmissionCalculator {
    /// Create a new calculator
    pub fn new() -> Self {
        Self {
            grid_intensity: GridIntensity::Medium,
            provider: CloudProvider::Local,
        }
    }

    /// Set grid intensity
    pub fn with_intensity(mut self, intensity: GridIntensity) -> Self {
        self.grid_intensity = intensity;
        self
    }

    /// Set cloud provider
    pub fn with_provider(mut self, provider: CloudProvider) -> Self {
        self.provider = provider;
        self
    }

    /// Calculate CO2e from energy consumption
    pub fn energy_to_co2e(&self, energy_wh: f64) -> f64 {
        // Apply PUE factor
        let adjusted_energy = energy_wh * self.provider.pue();
        // Convert to kWh and multiply by grid intensity
        (adjusted_energy / 1000.0) * self.grid_intensity.grams_co2_per_kwh()
    }

    /// Calculate emissions from LLM API call
    pub fn llm_call_emission(&self, model: LlmModel, tokens: u64) -> EmissionRecord {
        let energy_wh = model.wh_per_1k_tokens() * (tokens as f64 / 1000.0);
        let co2e = self.energy_to_co2e(energy_wh);

        EmissionRecord::new(EmissionSource::LlmApiCall, co2e)
            .with_energy(energy_wh)
            .with_description(format!("{} API call with {} tokens", model, tokens))
    }

    /// Calculate emissions from CPU compute
    pub fn cpu_emission(&self, duration: Duration, cpu_power_w: f64) -> EmissionRecord {
        let hours = duration.as_secs_f64() / 3600.0;
        let energy_wh = cpu_power_w * hours;
        let co2e = self.energy_to_co2e(energy_wh);

        EmissionRecord::new(EmissionSource::CpuCompute, co2e)
            .with_energy(energy_wh)
            .with_duration(duration)
            .with_description(format!(
                "CPU compute at {}W for {:?}",
                cpu_power_w, duration
            ))
    }

    /// Calculate emissions from GPU compute
    pub fn gpu_emission(&self, duration: Duration, gpu_power_w: f64) -> EmissionRecord {
        let hours = duration.as_secs_f64() / 3600.0;
        let energy_wh = gpu_power_w * hours;
        let co2e = self.energy_to_co2e(energy_wh);

        EmissionRecord::new(EmissionSource::GpuCompute, co2e)
            .with_energy(energy_wh)
            .with_duration(duration)
            .with_description(format!(
                "GPU compute at {}W for {:?}",
                gpu_power_w, duration
            ))
    }

    /// Calculate emissions from data transfer
    pub fn data_transfer_emission(&self, bytes: u64) -> EmissionRecord {
        // Approximate: ~0.06 kWh per GB of data transfer.
        // Source: IEA (2022) and Aslan et al. "Electricity Intensity of
        // Internet Data Transmission" (2018). Real-world values depend
        // heavily on network topology and equipment age.
        let gb = bytes as f64 / (1024.0 * 1024.0 * 1024.0);
        let energy_wh = gb * 60.0; // 60 Wh per GB (approximate)
        let co2e = self.energy_to_co2e(energy_wh);

        EmissionRecord::new(EmissionSource::DataTransfer, co2e)
            .with_energy(energy_wh)
            .with_description(format!("Data transfer: ~{:.2} GB", gb))
    }

    /// Calculate emissions from storage
    pub fn storage_emission(&self, gb_months: f64) -> EmissionRecord {
        // Approximate: ~0.7 kWh per GB per month for SSD storage.
        // Source: Tannu & Nair (2023), rough average across SSD/HDD.
        // Actual values vary by drive type, RAID configuration, and
        // storage controller overhead.
        let energy_wh = gb_months * 700.0; // 700 Wh per GB-month (approximate)
        let co2e = self.energy_to_co2e(energy_wh);

        EmissionRecord::new(EmissionSource::Storage, co2e)
            .with_energy(energy_wh)
            .with_description(format!("Storage: ~{:.2} GB-months", gb_months))
    }

    /// Calculate emissions from build operation
    pub fn build_emission(
        &self,
        duration: Duration,
        cpu_cores: u32,
        core_power_w: f64,
    ) -> EmissionRecord {
        let hours = duration.as_secs_f64() / 3600.0;
        let total_power = cpu_cores as f64 * core_power_w;
        let energy_wh = total_power * hours;
        let co2e = self.energy_to_co2e(energy_wh);

        EmissionRecord::new(EmissionSource::Build, co2e)
            .with_energy(energy_wh)
            .with_duration(duration)
            .with_description(format!("Build with {} cores for {:?}", cpu_cores, duration))
    }
}

/// Carbon footprint tracker
#[derive(Debug)]
pub struct CarbonTracker {
    /// Emission records
    records: Vec<EmissionRecord>,
    /// Calculator
    calculator: EmissionCalculator,
    /// Session start time
    _session_start: u64,
    /// Provider
    provider: CloudProvider,
    /// Region
    region: Option<String>,
}

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

impl CarbonTracker {
    /// Create a new carbon tracker
    pub fn new() -> Self {
        let _session_start = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();

        Self {
            records: Vec::new(),
            calculator: EmissionCalculator::new(),
            _session_start,
            provider: CloudProvider::Local,
            region: None,
        }
    }

    /// Set calculator configuration
    pub fn with_calculator(mut self, calculator: EmissionCalculator) -> Self {
        self.calculator = calculator;
        self
    }

    /// Set provider
    pub fn with_provider(mut self, provider: CloudProvider) -> Self {
        self.provider = provider;
        self.calculator = self.calculator.with_provider(provider);
        self
    }

    /// Set region
    pub fn with_region(mut self, region: impl Into<String>) -> Self {
        self.region = Some(region.into());
        self
    }

    /// Record an emission
    pub fn record(&mut self, record: EmissionRecord) {
        self.records.push(record);
    }

    /// Track LLM API call
    pub fn track_llm_call(&mut self, model: LlmModel, tokens: u64) {
        let record = self
            .calculator
            .llm_call_emission(model, tokens)
            .with_provider(self.provider);
        self.record(record);
    }

    /// Track CPU compute
    pub fn track_cpu(&mut self, duration: Duration, power_w: f64) {
        let record = self
            .calculator
            .cpu_emission(duration, power_w)
            .with_provider(self.provider);
        self.record(record);
    }

    /// Track GPU compute
    pub fn track_gpu(&mut self, duration: Duration, power_w: f64) {
        let record = self
            .calculator
            .gpu_emission(duration, power_w)
            .with_provider(self.provider);
        self.record(record);
    }

    /// Track data transfer
    pub fn track_data_transfer(&mut self, bytes: u64) {
        let record = self
            .calculator
            .data_transfer_emission(bytes)
            .with_provider(self.provider);
        self.record(record);
    }

    /// Get total CO2e in grams
    pub fn total_co2e(&self) -> f64 {
        self.records.iter().map(|r| r.co2e_grams).sum()
    }

    /// Get total energy in Wh
    pub fn total_energy(&self) -> f64 {
        self.records.iter().map(|r| r.energy_wh).sum()
    }

    /// Get emissions by source
    pub fn by_source(&self) -> HashMap<EmissionSource, f64> {
        let mut result = HashMap::new();
        for record in &self.records {
            *result.entry(record.source).or_insert(0.0) += record.co2e_grams;
        }
        result
    }

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

    /// Get all records
    pub fn records(&self) -> &[EmissionRecord] {
        &self.records
    }

    /// Generate optimization suggestions
    pub fn suggest_optimizations(&self) -> Vec<Optimization> {
        let mut suggestions = Vec::new();
        let by_source = self.by_source();

        // LLM API optimizations
        if let Some(&llm_co2) = by_source.get(&EmissionSource::LlmApiCall) {
            if llm_co2 > 100.0 {
                suggestions.push(
                    Optimization::new(
                        "Use smaller models for simple tasks",
                        "Consider using GPT-3.5 or smaller models for tasks that don't require GPT-4 level capabilities",
                    )
                    .with_savings(llm_co2 * 0.5)
                    .with_category(OptimizationCategory::ModelSelection)
                    .with_priority(Priority::High)
                );

                suggestions.push(
                    Optimization::new(
                        "Implement response caching",
                        "Cache responses for repeated queries to avoid redundant API calls",
                    )
                    .with_savings(llm_co2 * 0.3)
                    .with_category(OptimizationCategory::Caching)
                    .with_effort(EffortLevel::Medium),
                );
            }
        }

        // Compute optimizations
        let compute_co2 = by_source.get(&EmissionSource::CpuCompute).unwrap_or(&0.0)
            + by_source.get(&EmissionSource::GpuCompute).unwrap_or(&0.0);

        if compute_co2 > 50.0 {
            suggestions.push(
                Optimization::new(
                    "Schedule compute during low-carbon hours",
                    "Run batch jobs during off-peak hours when renewable energy is more available",
                )
                .with_savings(compute_co2 * 0.2)
                .with_category(OptimizationCategory::Compute)
                .with_effort(EffortLevel::Medium),
            );
        }

        // Data transfer optimizations
        if let Some(&transfer_co2) = by_source.get(&EmissionSource::DataTransfer) {
            if transfer_co2 > 10.0 {
                suggestions.push(
                    Optimization::new(
                        "Compress data transfers",
                        "Use gzip or brotli compression to reduce data transfer volume",
                    )
                    .with_savings(transfer_co2 * 0.6)
                    .with_category(OptimizationCategory::Network)
                    .with_effort(EffortLevel::Low),
                );
            }
        }

        // Green hosting suggestions
        if !self.provider.has_green_option() {
            suggestions.push(
                Optimization::new(
                    "Switch to green cloud provider",
                    "Consider using GCP (carbon neutral) or AWS/Azure with renewable energy options",
                )
                .with_savings(self.total_co2e() * 0.8)
                .with_category(OptimizationCategory::Hosting)
                .with_effort(EffortLevel::High)
                .with_priority(Priority::Critical)
            );
        }

        suggestions
    }

    /// Get green hosting recommendations
    pub fn green_hosting_recommendations(&self) -> Vec<GreenHosting> {
        vec![
            GreenHosting::new("GCP", "us-central1")
                .with_intensity(GridIntensity::Low)
                .with_renewable(100)
                .carbon_neutral()
                .with_description("Carbon neutral since 2007, 100% renewable energy matching"),
            GreenHosting::new("AWS", "eu-north-1")
                .with_intensity(GridIntensity::VeryLow)
                .with_renewable(100)
                .with_description("Stockholm region runs on 100% renewable energy"),
            GreenHosting::new("Azure", "Sweden Central")
                .with_intensity(GridIntensity::VeryLow)
                .with_renewable(100)
                .with_description("Swedish data centers powered by renewable energy"),
            GreenHosting::new("AWS", "us-west-2")
                .with_intensity(GridIntensity::Low)
                .with_renewable(95)
                .with_description("Oregon region with high renewable energy mix"),
        ]
    }

    /// Generate carbon report
    pub fn generate_report(&self) -> CarbonReport {
        CarbonReport::new(self)
    }
}

/// Carbon emissions report
#[derive(Debug)]
pub struct CarbonReport {
    /// Report ID
    pub id: String,
    /// Total CO2e in grams
    pub total_co2e_grams: f64,
    /// Total energy in Wh
    pub total_energy_wh: f64,
    /// Emissions by source
    pub by_source: HashMap<EmissionSource, f64>,
    /// Number of records
    pub record_count: usize,
    /// Optimizations suggested
    pub optimizations: Vec<Optimization>,
    /// Green hosting options
    pub green_options: Vec<GreenHosting>,
    /// Equivalents for context
    pub equivalents: CarbonEquivalents,
}

impl CarbonReport {
    /// Create a new report from tracker
    pub fn new(tracker: &CarbonTracker) -> Self {
        let total_co2e_grams = tracker.total_co2e();
        Self {
            id: generate_report_id(),
            total_co2e_grams,
            total_energy_wh: tracker.total_energy(),
            by_source: tracker.by_source(),
            record_count: tracker.record_count(),
            optimizations: tracker.suggest_optimizations(),
            green_options: tracker.green_hosting_recommendations(),
            equivalents: CarbonEquivalents::from_co2e_grams(total_co2e_grams),
        }
    }

    /// Render as markdown
    pub fn to_markdown(&self) -> String {
        let mut output = String::new();

        output.push_str("# Carbon Footprint Report\n\n");
        output.push_str(
            "> **Note:** Carbon estimates are approximate, based on average \
             cloud GPU power consumption data and publicly available research. \
             Actual emissions depend on hardware, grid region, time of day, and \
             provider-specific efficiency. Use these figures for directional \
             awareness, not precise accounting.\n\n",
        );

        // Summary
        output.push_str("## Summary\n\n");
        output.push_str(&format!(
            "- **Estimated Total CO2e**: ~{:.2}g (~{:.4} kg)\n",
            self.total_co2e_grams,
            self.total_co2e_grams / 1000.0
        ));
        output.push_str(&format!(
            "- **Estimated Total Energy**: ~{:.2} Wh (~{:.4} kWh)\n",
            self.total_energy_wh,
            self.total_energy_wh / 1000.0
        ));
        output.push_str(&format!(
            "- **Operations Tracked**: {}\n\n",
            self.record_count
        ));

        // Equivalents
        output.push_str("## Environmental Impact Context (approximate)\n\n");
        output.push_str(&format!(
            "- ~{} km driven in a car\n",
            self.equivalents.car_km
        ));
        output.push_str(&format!(
            "- ~{} smartphone charges\n",
            self.equivalents.smartphone_charges
        ));
        output.push_str(&format!(
            "- ~{} hours of laptop use\n",
            self.equivalents.laptop_hours
        ));
        output.push_str(&format!(
            "- ~{} liters of water heated\n",
            self.equivalents.liters_water_heated
        ));
        output.push('\n');

        // By source
        output.push_str("## Emissions by Source (estimated)\n\n");
        let mut sources: Vec<_> = self.by_source.iter().collect();
        sources.sort_by(|a, b| b.1.partial_cmp(a.1).unwrap_or(std::cmp::Ordering::Equal));
        for (source, co2e) in sources {
            let percentage = if self.total_co2e_grams > 0.0 {
                (co2e / self.total_co2e_grams) * 100.0
            } else {
                0.0
            };
            output.push_str(&format!(
                "- **{}**: ~{:.2}g (~{:.1}%)\n",
                source, co2e, percentage
            ));
        }
        output.push('\n');

        // Optimizations
        if !self.optimizations.is_empty() {
            output.push_str("## Optimization Suggestions\n\n");
            for opt in &self.optimizations {
                output.push_str(&format!("### {} [{}]\n\n", opt.title, opt.priority));
                output.push_str(&format!("{}\n\n", opt.description));
                output.push_str(&format!("- **Category**: {}\n", opt.category));
                output.push_str(&format!("- **Effort**: {}\n", opt.effort));
                output.push_str(&format!(
                    "- **Est. Savings**: ~{:.2}g CO2e\n\n",
                    opt.estimated_savings_grams
                ));
            }
        }

        // Green hosting
        output.push_str("## Green Hosting Options\n\n");
        for hosting in &self.green_options {
            output.push_str(&format!(
                "### {} - {}\n\n",
                hosting.provider, hosting.region
            ));
            if hosting.carbon_neutral {
                output.push_str("*Carbon Neutral*\n\n");
            }
            output.push_str(&format!(
                "- Renewable Energy: {}%\n",
                hosting.renewable_percentage
            ));
            output.push_str(&format!("- Grid Intensity: {}\n", hosting.grid_intensity));
            if !hosting.description.is_empty() {
                output.push_str(&format!("\n{}\n\n", hosting.description));
            }
        }

        output
    }
}

/// Carbon equivalents for context
#[derive(Debug, Clone)]
pub struct CarbonEquivalents {
    /// Kilometers driven in an average car
    pub car_km: f64,
    /// Number of smartphone charges
    pub smartphone_charges: u32,
    /// Hours of laptop use
    pub laptop_hours: f64,
    /// Liters of water heated to boiling
    pub liters_water_heated: f64,
}

impl CarbonEquivalents {
    /// Calculate equivalents from CO2e grams.
    ///
    /// These equivalents are approximate and intended to give intuitive
    /// context, not precise comparisons. Sources:
    /// - Car: ~120 g CO2/km -- EU average for new passenger cars (EEA, 2022)
    /// - Smartphone charge: ~8 g CO2 -- US EPA equivalencies calculator
    /// - Laptop use: ~30-50 g CO2/hour -- based on ~50W avg power draw at
    ///   medium grid intensity; we use 40 g/hr as a midpoint
    /// - Water heating: ~50 g CO2/liter -- natural gas water heater estimate
    pub fn from_co2e_grams(grams: f64) -> Self {
        Self {
            // Average car emits ~120 g CO2/km (EU average, EEA 2022)
            car_km: (grams / 120.0 * 100.0).round() / 100.0,
            // Smartphone charge: ~8 g CO2 (US EPA equivalencies)
            smartphone_charges: (grams / 8.0).ceil() as u32,
            // Laptop use: ~30-50 g CO2/hour; using 40 g/hr midpoint
            laptop_hours: (grams / 40.0 * 100.0).round() / 100.0,
            // Heating water: ~50 g CO2/liter (natural gas heater)
            liters_water_heated: (grams / 50.0 * 100.0).round() / 100.0,
        }
    }
}

/// Carbon budget
#[derive(Debug)]
pub struct CarbonBudget {
    /// Daily budget in grams
    pub daily_grams: f64,
    /// Weekly budget in grams
    pub weekly_grams: f64,
    /// Monthly budget in grams
    pub monthly_grams: f64,
    /// Used today
    pub used_today: f64,
    /// Used this week
    pub used_week: f64,
    /// Used this month
    pub used_month: f64,
}

impl CarbonBudget {
    /// Create a new budget
    pub fn new(daily_grams: f64) -> Self {
        Self {
            daily_grams,
            weekly_grams: daily_grams * 7.0,
            monthly_grams: daily_grams * 30.0,
            used_today: 0.0,
            used_week: 0.0,
            used_month: 0.0,
        }
    }

    /// Add usage
    pub fn add_usage(&mut self, grams: f64) {
        self.used_today += grams;
        self.used_week += grams;
        self.used_month += grams;
    }

    /// Check if over daily budget
    pub fn over_daily(&self) -> bool {
        self.used_today > self.daily_grams
    }

    /// Get daily usage percentage
    pub fn daily_percentage(&self) -> f64 {
        if self.daily_grams > 0.0 {
            (self.used_today / self.daily_grams) * 100.0
        } else {
            0.0
        }
    }

    /// Get remaining daily budget
    pub fn remaining_today(&self) -> f64 {
        (self.daily_grams - self.used_today).max(0.0)
    }

    /// Reset daily usage
    pub fn reset_daily(&mut self) {
        self.used_today = 0.0;
    }

    /// Reset weekly usage
    pub fn reset_weekly(&mut self) {
        self.used_week = 0.0;
    }

    /// Reset monthly usage
    pub fn reset_monthly(&mut self) {
        self.used_month = 0.0;
    }
}

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

    #[test]
    fn test_emission_source_display() {
        assert_eq!(format!("{}", EmissionSource::LlmApiCall), "LLM API");
        assert_eq!(format!("{}", EmissionSource::GpuCompute), "GPU Compute");
    }

    #[test]
    fn test_grid_intensity_values() {
        assert_eq!(GridIntensity::VeryLow.grams_co2_per_kwh(), 20.0);
        assert_eq!(GridIntensity::Low.grams_co2_per_kwh(), 50.0);
        assert_eq!(GridIntensity::Custom(100.0).grams_co2_per_kwh(), 100.0);
    }

    #[test]
    fn test_cloud_provider_pue() {
        assert!(CloudProvider::Gcp.pue() < CloudProvider::Local.pue());
        assert!(CloudProvider::Aws.pue() < CloudProvider::SelfHosted.pue());
    }

    #[test]
    fn test_cloud_provider_green_option() {
        assert!(CloudProvider::Gcp.has_green_option());
        assert!(CloudProvider::Aws.has_green_option());
        assert!(!CloudProvider::Local.has_green_option());
    }

    #[test]
    fn test_llm_model_energy() {
        assert!(LlmModel::GptLarge.wh_per_1k_tokens() > LlmModel::Tiny.wh_per_1k_tokens());
        assert!(LlmModel::GptMedium.wh_per_1k_tokens() < LlmModel::GptLarge.wh_per_1k_tokens());
    }

    #[test]
    fn test_emission_record_creation() {
        let record = EmissionRecord::new(EmissionSource::LlmApiCall, 10.0)
            .with_energy(5.0)
            .with_description("Test call");

        assert_eq!(record.source, EmissionSource::LlmApiCall);
        assert_eq!(record.co2e_grams, 10.0);
        assert_eq!(record.energy_wh, 5.0);
    }

    #[test]
    fn test_optimization_creation() {
        let opt = Optimization::new("Test", "Description")
            .with_savings(100.0)
            .with_effort(EffortLevel::High)
            .with_priority(Priority::Critical);

        assert_eq!(opt.title, "Test");
        assert_eq!(opt.estimated_savings_grams, 100.0);
        assert_eq!(opt.effort, EffortLevel::High);
        assert_eq!(opt.priority, Priority::Critical);
    }

    #[test]
    fn test_green_hosting_creation() {
        let hosting = GreenHosting::new("GCP", "us-central1")
            .with_renewable(100)
            .carbon_neutral();

        assert_eq!(hosting.provider, "GCP");
        assert_eq!(hosting.renewable_percentage, 100);
        assert!(hosting.carbon_neutral);
    }

    #[test]
    fn test_emission_calculator_energy_to_co2e() {
        let calc = EmissionCalculator::new()
            .with_intensity(GridIntensity::Medium)
            .with_provider(CloudProvider::Local);

        let co2e = calc.energy_to_co2e(1000.0); // 1 kWh

        // 1 kWh * 2.0 PUE * 250 gCO2/kWh = 500g
        assert!((co2e - 500.0).abs() < 0.01);
    }

    #[test]
    fn test_emission_calculator_llm_call() {
        let calc = EmissionCalculator::new().with_intensity(GridIntensity::Medium);

        let record = calc.llm_call_emission(LlmModel::GptLarge, 1000);

        assert!(record.energy_wh > 0.0);
        assert!(record.co2e_grams > 0.0);
        assert_eq!(record.source, EmissionSource::LlmApiCall);
    }

    #[test]
    fn test_emission_calculator_cpu() {
        let calc = EmissionCalculator::new();
        let record = calc.cpu_emission(Duration::from_secs(3600), 100.0);

        assert!(record.energy_wh > 0.0);
        assert!(record.co2e_grams > 0.0);
        assert_eq!(record.source, EmissionSource::CpuCompute);
    }

    #[test]
    fn test_emission_calculator_gpu() {
        let calc = EmissionCalculator::new();
        let record = calc.gpu_emission(Duration::from_secs(1800), 300.0);

        assert!(record.energy_wh > 0.0);
        assert!(record.co2e_grams > 0.0);
        assert_eq!(record.source, EmissionSource::GpuCompute);
    }

    #[test]
    fn test_emission_calculator_data_transfer() {
        let calc = EmissionCalculator::new();
        let record = calc.data_transfer_emission(1024 * 1024 * 1024); // 1 GB

        assert!(record.energy_wh > 0.0);
        assert!(record.co2e_grams > 0.0);
    }

    #[test]
    fn test_carbon_tracker_creation() {
        let tracker = CarbonTracker::new();
        assert_eq!(tracker.record_count(), 0);
        assert_eq!(tracker.total_co2e(), 0.0);
    }

    #[test]
    fn test_carbon_tracker_track_llm() {
        let mut tracker = CarbonTracker::new();
        tracker.track_llm_call(LlmModel::GptLarge, 1000);

        assert_eq!(tracker.record_count(), 1);
        assert!(tracker.total_co2e() > 0.0);
    }

    #[test]
    fn test_carbon_tracker_track_multiple() {
        let mut tracker = CarbonTracker::new();
        tracker.track_llm_call(LlmModel::GptLarge, 1000);
        tracker.track_cpu(Duration::from_secs(60), 50.0);
        tracker.track_data_transfer(1024 * 1024);

        assert_eq!(tracker.record_count(), 3);
    }

    #[test]
    fn test_carbon_tracker_by_source() {
        let mut tracker = CarbonTracker::new();
        tracker.track_llm_call(LlmModel::GptLarge, 1000);
        tracker.track_cpu(Duration::from_secs(60), 50.0);

        let by_source = tracker.by_source();

        assert!(by_source.contains_key(&EmissionSource::LlmApiCall));
        assert!(by_source.contains_key(&EmissionSource::CpuCompute));
    }

    #[test]
    fn test_carbon_tracker_suggest_optimizations() {
        let mut tracker = CarbonTracker::new();

        // Generate enough LLM emissions to trigger suggestions
        for _ in 0..100 {
            tracker.track_llm_call(LlmModel::GptLarge, 10000);
        }

        let suggestions = tracker.suggest_optimizations();

        assert!(!suggestions.is_empty());
    }

    #[test]
    fn test_carbon_tracker_green_hosting_recommendations() {
        let tracker = CarbonTracker::new();
        let recommendations = tracker.green_hosting_recommendations();

        assert!(!recommendations.is_empty());
        assert!(recommendations.iter().any(|r| r.carbon_neutral));
    }

    #[test]
    fn test_carbon_report_generation() {
        let mut tracker = CarbonTracker::new();
        tracker.track_llm_call(LlmModel::GptMedium, 500);

        let report = tracker.generate_report();

        assert!(report.total_co2e_grams > 0.0);
        assert_eq!(report.record_count, 1);
    }

    #[test]
    fn test_carbon_report_markdown() {
        let mut tracker = CarbonTracker::new();
        tracker.track_llm_call(LlmModel::GptMedium, 500);

        let report = tracker.generate_report();
        let md = report.to_markdown();

        assert!(md.contains("# Carbon Footprint Report"));
        assert!(md.contains("Summary"));
    }

    #[test]
    fn test_carbon_equivalents() {
        let equiv = CarbonEquivalents::from_co2e_grams(120.0);

        assert!((equiv.car_km - 1.0).abs() < 0.01);
        assert!(equiv.smartphone_charges > 0);
    }

    #[test]
    fn test_carbon_budget_creation() {
        let budget = CarbonBudget::new(100.0);

        assert_eq!(budget.daily_grams, 100.0);
        assert_eq!(budget.weekly_grams, 700.0);
        assert_eq!(budget.used_today, 0.0);
    }

    #[test]
    fn test_carbon_budget_add_usage() {
        let mut budget = CarbonBudget::new(100.0);
        budget.add_usage(50.0);

        assert_eq!(budget.used_today, 50.0);
        assert_eq!(budget.daily_percentage(), 50.0);
        assert!(!budget.over_daily());
    }

    #[test]
    fn test_carbon_budget_over_daily() {
        let mut budget = CarbonBudget::new(100.0);
        budget.add_usage(150.0);

        assert!(budget.over_daily());
        assert_eq!(budget.remaining_today(), 0.0);
    }

    #[test]
    fn test_carbon_budget_reset() {
        let mut budget = CarbonBudget::new(100.0);
        budget.add_usage(50.0);
        budget.reset_daily();

        assert_eq!(budget.used_today, 0.0);
        assert_eq!(budget.used_week, 50.0); // Week not reset
    }

    #[test]
    fn test_unique_emission_ids() {
        let r1 = EmissionRecord::new(EmissionSource::Other, 0.0);
        let r2 = EmissionRecord::new(EmissionSource::Other, 0.0);

        assert_ne!(r1.id, r2.id);
    }

    #[test]
    fn test_unique_report_ids() {
        let tracker = CarbonTracker::new();
        let r1 = tracker.generate_report();
        let r2 = tracker.generate_report();

        assert_ne!(r1.id, r2.id);
    }

    #[test]
    fn test_effort_level_ordering() {
        assert!(EffortLevel::Low < EffortLevel::Medium);
        assert!(EffortLevel::Medium < EffortLevel::High);
    }

    #[test]
    fn test_priority_ordering() {
        assert!(Priority::Low < Priority::Medium);
        assert!(Priority::High < Priority::Critical);
    }

    #[test]
    fn test_green_hosting_renewable_clamping() {
        let hosting = GreenHosting::new("Test", "region").with_renewable(150); // Over 100

        assert_eq!(hosting.renewable_percentage, 100);
    }

    #[test]
    fn test_optimization_category_display() {
        assert_eq!(format!("{}", OptimizationCategory::Compute), "Compute");
        assert_eq!(
            format!("{}", OptimizationCategory::ModelSelection),
            "Model Selection"
        );
    }

    #[test]
    fn test_cloud_provider_display() {
        assert_eq!(format!("{}", CloudProvider::Aws), "AWS");
        assert_eq!(format!("{}", CloudProvider::Gcp), "GCP");
    }

    #[test]
    fn test_llm_model_display() {
        assert_eq!(format!("{}", LlmModel::GptLarge), "GPT-4/Large");
        assert_eq!(format!("{}", LlmModel::Claude), "Claude");
    }

    #[test]
    fn test_emission_record_with_all_fields() {
        let record = EmissionRecord::new(EmissionSource::Build, 50.0)
            .with_energy(100.0)
            .with_duration(Duration::from_secs(300))
            .with_description("Build project")
            .with_operation("cargo build")
            .with_provider(CloudProvider::Local)
            .with_region("local");

        assert!(record.duration.is_some());
        assert!(record.operation.is_some());
        assert!(record.provider.is_some());
        assert!(record.region.is_some());
    }

    #[test]
    fn test_carbon_tracker_with_config() {
        let tracker = CarbonTracker::new()
            .with_provider(CloudProvider::Gcp)
            .with_region("us-central1");

        assert_eq!(tracker.provider, CloudProvider::Gcp);
        assert_eq!(tracker.region, Some("us-central1".to_string()));
    }

    #[test]
    fn test_build_emission() {
        let calc = EmissionCalculator::new();
        let record = calc.build_emission(Duration::from_secs(60), 4, 15.0);

        assert!(record.energy_wh > 0.0);
        assert!(record.co2e_grams > 0.0);
        assert_eq!(record.source, EmissionSource::Build);
    }

    #[test]
    fn test_storage_emission() {
        let calc = EmissionCalculator::new();
        let record = calc.storage_emission(10.0); // 10 GB-months

        assert!(record.energy_wh > 0.0);
        assert!(record.co2e_grams > 0.0);
        assert_eq!(record.source, EmissionSource::Storage);
    }
}