s3-pricing 0.2.0

S3 pricing module
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
use anyhow::{Result, anyhow};
use aws_sdk_pricing::Client;
use aws_sdk_pricing::types::Filter;
use quick_cache::sync::Cache;
use std::sync::OnceLock;

// Module-level static filter caches for commonly used filters
static PRODUCT_FAMILY_STORAGE: OnceLock<Filter> = OnceLock::new();
static PRODUCT_FAMILY_API_REQUEST: OnceLock<Filter> = OnceLock::new();
static TRANSFER_TYPE_AWS_OUTBOUND: OnceLock<Filter> = OnceLock::new();
static TRANSFER_TYPE_INTERREGION: OnceLock<Filter> = OnceLock::new();

/// Client for AWS Pricing API to fetch S3 costs dynamically.
///
/// This client connects to the AWS Pricing API to retrieve up-to-date pricing
/// information for Amazon S3 operations including storage, requests, and data transfer.
///
/// # Example
///
/// ```ignore
/// let client = S3PricingClient::new(Some("my-profile")).await?;
/// let price = client.get_storage_price("us-east-1", "STANDARD").await?;
/// ```
///
/// # Notes
///
/// - The Pricing API is only available in `us-east-1` (global) or `cn-northwest-1` (China)
/// - Global pricing endpoint: api.pricing.us-east-1.amazonaws.com
/// - China pricing endpoint: api.pricing.cn-northwest-1.amazonaws.com.cn
/// - For China regions (cn-north-1, cn-northwest-1), the pricing is in CNY
/// - Credentials are resolved from the environment, shared config, or SSO profile
/// - Results are cached to reduce API calls (uses fast in-memory caching)
pub struct S3PricingClient {
    /// The AWS Pricing API client
    client: Client,
    /// Whether this client is using China pricing endpoint (CNY currency)
    is_china: bool,
    /// Cache for storing price results (1 hour TTL)
    cache: Cache<String, f64>,
    /// Cache for storing negative results (failed lookups) to prevent repeated API calls
    negative_cache: Cache<String, ()>,
}

impl S3PricingClient {
    /// Creates a new S3PricingClient for global AWS regions (USD pricing).
    ///
    /// # Arguments
    ///
    /// * `profile` - Optional AWS profile name for credential resolution. If `None`,
    ///   uses default credentials from environment or IAM role.
    ///
    /// # Errors
    ///
    /// Returns an error if AWS configuration fails or credentials cannot be resolved.
    ///
    /// # Note
    ///
    /// The Pricing API is only available in `us-east-1` endpoint for global regions.
    /// Use `new_china()` for AWS China regions.
    pub async fn new(profile: Option<&str>) -> Result<Self> {
        Self::new_with_endpoint(profile, None).await
    }

    /// Creates a new S3PricingClient for AWS China regions (CNY pricing).
    ///
    /// # Arguments
    ///
    /// * `profile` - Optional AWS profile name for credential resolution. If `None`,
    ///   uses default credentials from environment or IAM role.
    ///
    /// # Errors
    ///
    /// Returns an error if AWS configuration fails or credentials cannot be resolved.
    ///
    /// # Note
    ///
    /// The Pricing API for China is available in `cn-northwest-1` endpoint (api.pricing.cn-northwest-1.amazonaws.com.cn).
    /// All prices returned are in CNY.
    pub async fn new_china(profile: Option<&str>) -> Result<Self> {
        Self::new_with_endpoint(profile, Some("cn-northwest-1")).await
    }

    /// Creates a new S3PricingClient with optional endpoint override.
    ///
    /// # Arguments
    ///
    /// * `profile` - Optional AWS profile name for credential resolution
    /// * `endpoint_region` - Optional region for pricing endpoint. If `None`, uses global pricing (USD).
    ///   Use "cn-northwest-1" for China pricing (CNY).
    async fn new_with_endpoint(
        profile: Option<&str>,
        endpoint_region: Option<&str>,
    ) -> Result<Self> {
        let is_china = endpoint_region.is_some();

        // Determine the pricing endpoint region (convert to owned string for lifetime safety)
        let pricing_region = endpoint_region
            .map(|s| s.to_string())
            .unwrap_or_else(|| "us-east-1".to_string());

        // Configure AWS SDK with the pricing endpoint region
        let mut loader = aws_config::defaults(aws_config::BehaviorVersion::latest())
            .region(aws_config::Region::new(pricing_region.clone()));

        if let Some(p) = profile {
            loader = loader.profile_name(p);
        }

        let config = loader.load().await;
        let client = Client::new(&config);

        // Initialize caches for pricing data
        // Main cache with 1 hour TTL for successful results
        let cache = Cache::new(1000);
        // Negative cache with 5 minute TTL to prevent repeated failed API calls
        let negative_cache = Cache::new(500);

        Ok(Self {
            client,
            is_china,
            cache,
            negative_cache,
        })
    }

    /// Builds a filter for the Pricing API query.
    ///
    /// # Arguments
    ///
    /// * `field` - The field name to filter on
    /// * `value` - The value to match
    ///
    /// # Returns
    ///
    /// A configured `Filter` ready for use in `get_products` calls.
    fn build_filter(field: &str, value: &str) -> Result<Filter> {
        Filter::builder()
            .field(field)
            .value(value)
            .set_type(Some(aws_sdk_pricing::types::FilterType::TermMatch))
            .build()
            .map_err(|e| anyhow!("Failed to build filter: {}", e))
    }

    /// Gets or creates the product family filter for Storage queries.
    fn get_product_family_storage_filter() -> &'static Filter {
        PRODUCT_FAMILY_STORAGE.get_or_init(|| {
            Self::build_filter("productFamily", "Storage").expect("Failed to create storage filter")
        })
    }

    /// Gets or creates the product family filter for API Request queries.
    fn get_product_family_api_request_filter() -> &'static Filter {
        PRODUCT_FAMILY_API_REQUEST.get_or_init(|| {
            Self::build_filter("productFamily", "API Request")
                .expect("Failed to create API request filter")
        })
    }

    /// Gets or creates the transfer type filter for AWS Outbound queries.
    fn get_transfer_type_aws_outbound_filter() -> &'static Filter {
        TRANSFER_TYPE_AWS_OUTBOUND.get_or_init(|| {
            Self::build_filter("transferType", "AWS Outbound")
                .expect("Failed to create AWS outbound filter")
        })
    }

    /// Gets or creates the transfer type filter for InterRegion Outbound queries.
    fn get_transfer_type_interregion_filter() -> &'static Filter {
        TRANSFER_TYPE_INTERREGION.get_or_init(|| {
            Self::build_filter("transferType", "InterRegion Outbound")
                .expect("Failed to create interregion filter")
        })
    }

    /// Checks if the given region is an AWS China region.
    ///
    /// AWS China regions require a different pricing API endpoint and use CNY currency.
    ///
    /// # Arguments
    ///
    /// * `region` - AWS region code (e.g., "cn-north-1", "cn-northwest-1")
    ///
    /// # Returns
    ///
    /// `true` if the region is a China region, `false` otherwise.
    pub fn is_china_region(region: &str) -> bool {
        region.starts_with("cn-")
    }

    /// Maps an AWS region code to the corresponding Pricing API location name.
    ///
    /// These values must exactly match the location names returned by the AWS Pricing API.
    ///
    /// # Arguments
    ///
    /// * `region` - AWS region code (e.g., "us-east-1", "eu-west-1", "cn-north-1")
    ///
    /// # Returns
    ///
    /// The exact location name as expected by the AWS Pricing API.
    ///
    /// # Errors
    ///
    /// Returns an error if the region is not recognized.
    fn region_to_location(region: &str) -> Result<&'static str> {
        match region {
            // Global regions
            "us-east-1" => Ok("US East (N. Virginia)"),
            "us-east-2" => Ok("US East (Ohio)"),
            "us-west-1" => Ok("US West (N. California)"),
            "us-west-2" => Ok("US West (Oregon)"),
            "af-south-1" => Ok("Africa (Cape Town)"),
            "ap-east-1" => Ok("Asia Pacific (Hong Kong)"),
            "ap-east-2" => Ok("Asia Pacific (Taipei)"),
            "ap-south-1" => Ok("Asia Pacific (Mumbai)"),
            "ap-south-2" => Ok("Asia Pacific (Hyderabad)"),
            "ap-northeast-3" => Ok("Asia Pacific (Osaka)"),
            "ap-northeast-2" => Ok("Asia Pacific (Seoul)"),
            "ap-southeast-1" => Ok("Asia Pacific (Singapore)"),
            "ap-southeast-2" => Ok("Asia Pacific (Sydney)"),
            "ap-southeast-3" => Ok("Asia Pacific (Jakarta)"),
            "ap-southeast-4" => Ok("Asia Pacific (Melbourne)"),
            "ap-southeast-5" => Ok("Asia Pacific (Malaysia)"),
            "ap-southeast-6" => Ok("Asia Pacific (New Zealand)"),
            "ap-southeast-7" => Ok("Asia Pacific (Thailand)"),
            "ap-northeast-1" => Ok("Asia Pacific (Tokyo)"),
            "ca-central-1" => Ok("Canada (Central)"),
            "ca-west-1" => Ok("Canada West (Calgary)"),
            "eu-central-1" => Ok("EU (Frankfurt)"),
            "eu-central-2" => Ok("Europe (Zurich)"),
            "eu-west-1" => Ok("EU (Ireland)"),
            "eu-west-2" => Ok("EU (London)"),
            "eu-west-3" => Ok("EU (Paris)"),
            "eu-north-1" => Ok("EU (Stockholm)"),
            "eu-south-1" => Ok("EU (Milan)"),
            "eu-south-2" => Ok("Europe (Spain)"),
            "il-central-1" => Ok("Israel (Tel Aviv)"),
            "me-central-1" => Ok("Middle East (UAE)"),
            "me-south-1" => Ok("Middle East (Bahrain)"),
            "mx-central-1" => Ok("Mexico (Central)"),
            "sa-east-1" => Ok("South America (Sao Paulo)"),
            // China regions
            "cn-north-1" => Ok("China (Beijing)"),
            "cn-northwest-1" => Ok("China (Ningxia)"),
            _ => Err(anyhow!("Unknown AWS region: {}", region)),
        }
    }

    /// Maps an S3 storage class to the corresponding `volumeType` value used in the Pricing API.
    ///
    /// # Arguments
    ///
    /// * `storage_class` - S3 storage class (e.g., "STANDARD", "GLACIER", "STANDARD_IA")
    ///
    /// # Returns
    ///
    /// The `volumeType` filter value as expected by the AWS Pricing API.
    fn storage_class_to_volume_type(storage_class: &str) -> &'static str {
        match storage_class {
            "STANDARD" => "Standard",
            "STANDARD_IA" => "Standard - Infrequent Access",
            "ONEZONE_IA" => "One Zone - Infrequent Access",
            "INTELLIGENT_TIERING" => "Intelligent-Tiering",
            "GLACIER" | "GLACIER_FLEXIBLE_RETRIEVAL" => "Amazon Glacier",
            "DEEP_ARCHIVE" => "Glacier Deep Archive",
            "GLACIER_IR" | "GLACIER_INSTANT_RETRIEVAL" => "Glacier Instant Retrieval",
            "EXPRESS_ONEZONE" => "Express One Zone",
            "REDUCED_REDUNDANCY" => "Reduced Redundancy",
            _ => "Standard",
        }
    }

    /// Maps an S3 storage class to the corresponding `storageClass` filter value used in the Pricing API.
    ///
    /// # Arguments
    ///
    /// * `storage_class` - S3 storage class (e.g., "STANDARD", "GLACIER", "STANDARD_IA")
    ///
    /// # Returns
    ///
    /// The `storageClass` filter value as expected by the AWS Pricing API.
    fn storage_class_to_filter(storage_class: &str) -> &'static str {
        match storage_class {
            "STANDARD" => "General Purpose",
            "STANDARD_IA" | "ONEZONE_IA" => "Infrequent Access",
            "INTELLIGENT_TIERING" => "Intelligent-Tiering",
            "GLACIER" | "GLACIER_FLEXIBLE_RETRIEVAL" => "Archive",
            "DEEP_ARCHIVE" => "Archive",
            "GLACIER_IR" | "GLACIER_INSTANT_RETRIEVAL" => "Archive Instant Retrieval",
            "EXPRESS_ONEZONE" => "High Performance",
            _ => "General Purpose",
        }
    }

    /// Maps an S3 storage class to the corresponding API request group prefix used in the Pricing API.
    ///
    /// The prefix is used to construct the full request group name:
    /// - Standard uses `"S3-API-Tier1"` / `"S3-API-Tier2"`
    /// - Standard-IA uses `"S3-API-SIA-Tier1"` / `"S3-API-SIA-Tier2"`
    /// - And so on for other storage classes
    ///
    /// # Arguments
    ///
    /// * `storage_class` - S3 storage class (e.g., "STANDARD", "GLACIER", "STANDARD_IA")
    ///
    /// # Returns
    ///
    /// The API group prefix (e.g., "S3-API", "S3-API-SIA", "S3-API-GLACIER").
    fn storage_class_to_api_group_prefix(storage_class: &str) -> &'static str {
        match storage_class {
            "STANDARD" => "S3-API",
            "STANDARD_IA" => "S3-API-SIA",
            "ONEZONE_IA" => "S3-API-ZIA",
            "INTELLIGENT_TIERING" => "S3-API-INT",
            "GLACIER" | "GLACIER_FLEXIBLE_RETRIEVAL" => "S3-API-GLACIER",
            "DEEP_ARCHIVE" => "S3-API-DAA",
            "GLACIER_IR" | "GLACIER_INSTANT_RETRIEVAL" => "S3-API-GIR",
            "EXPRESS_ONEZONE" => "S3-API-XZ",
            _ => "S3-API",
        }
    }

    /// Fetches the storage price per GB per month for a given region and storage class.
    ///
    /// This method queries the AWS Pricing API to retrieve the current on-demand
    /// storage pricing for Amazon S3.
    ///
    /// # Arguments
    ///
    /// * `region` - AWS region code (e.g., "us-east-1", "eu-west-1")
    /// * `storage_class` - S3 storage class (e.g., "STANDARD", "GLACIER", "STANDARD_IA")
    ///
    /// # Returns
    ///
    /// Price in USD per GB per month.
    ///
    /// # Errors
    ///
    /// Returns an error if the Pricing API call fails or no pricing is found.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let price = client.get_storage_price("us-east-1", "STANDARD_IA").await?;
    /// println!("${:.4} per GB-Mo", price);
    /// ```
    pub async fn get_storage_price(&self, region: &str, storage_class: &str) -> Result<f64> {
        let cache_key = format!("storage:{}:{}:GB-Mo", region, storage_class);

        // Check negative cache first
        if self.negative_cache.get(&cache_key).is_some() {
            return Err(anyhow!(
                "Price not found (cached negative result): {}",
                cache_key
            ));
        }

        if let Some(cached) = self.cache.get(&cache_key) {
            return Ok(cached);
        }

        let location = Self::region_to_location(region)?;
        let volume_type = Self::storage_class_to_volume_type(storage_class);
        let sc_filter = Self::storage_class_to_filter(storage_class);

        let filters = vec![
            Self::build_filter("location", location)?,
            Self::get_product_family_storage_filter().clone(),
            Self::build_filter("volumeType", volume_type)?,
            Self::build_filter("storageClass", sc_filter)?,
        ];

        let result = self
            .client
            .get_products()
            .service_code("AmazonS3")
            .set_filters(Some(filters))
            .send()
            .await?;

        let price = self.extract_first_tier_price(result.price_list(), "GB-Mo")?;
        self.cache.insert(cache_key.clone(), price);
        Ok(price)
    }

    /// Fetches the price for Class A requests (PUT, COPY, POST, LIST) per request.
    ///
    /// Class A requests include:
    /// - PUT, COPY, POST, LIST
    /// - Lifecycle transitions
    /// - Initiating multipart uploads
    ///
    /// # Arguments
    ///
    /// * `region` - AWS region code (e.g., "us-east-1", "eu-west-1")
    /// * `storage_class` - S3 storage class (e.g., "STANDARD", "GLACIER")
    ///
    /// # Returns
    ///
    /// Price in USD per single request. Multiply by 1,000 for per-1,000 request pricing.
    ///
    /// # Errors
    ///
    /// Returns an error if the Pricing API call fails or no pricing is found for the storage class.
    ///
    /// # Note
    ///
    /// If no specific pricing exists for the given storage class, this method falls back
    /// to the standard S3 pricing.
    pub async fn get_class_a_request_price(
        &self,
        region: &str,
        storage_class: &str,
    ) -> Result<f64> {
        let prefix = Self::storage_class_to_api_group_prefix(storage_class);
        let group = format!("{}-Tier1", prefix);

        // Try specific group first
        if let Some(price) = self
            .get_request_price_by_group(region, &group, storage_class)
            .await?
        {
            return Ok(price);
        }

        // Fallback to standard if specific group not found
        if prefix != "S3-API"
            && let Some(price) = self
                .get_request_price_by_group(region, "S3-API-Tier1", storage_class)
                .await?
        {
            return Ok(price);
        }

        Err(anyhow!(
            "Could not find Class A request price for {} in {}",
            storage_class,
            region
        ))
    }

    /// Fetches the price for Class B requests (GET, SELECT, and all other non-Class-A operations) per request.
    ///
    /// Class B requests include:
    /// - GET, LIST, SELECT
    /// - Multipart upload completions
    /// - Object expiry
    ///
    /// # Arguments
    ///
    /// * `region` - AWS region code (e.g., "us-east-1", "eu-west-1")
    /// * `storage_class` - S3 storage class (e.g., "STANDARD", "GLACIER")
    ///
    /// # Returns
    ///
    /// Price in USD per single request. Multiply by 10,000 for per-10,000 request pricing.
    ///
    /// # Errors
    ///
    /// Returns an error if the Pricing API call fails or no pricing is found for the storage class.
    ///
    /// # Note
    ///
    /// If no specific pricing exists for the given storage class, this method falls back
    /// to the standard S3 pricing.
    pub async fn get_class_b_request_price(
        &self,
        region: &str,
        storage_class: &str,
    ) -> Result<f64> {
        let prefix = Self::storage_class_to_api_group_prefix(storage_class);
        let group = format!("{}-Tier2", prefix);

        // Try specific group first
        if let Some(price) = self
            .get_request_price_by_group(region, &group, storage_class)
            .await?
        {
            return Ok(price);
        }

        // Fallback to standard if specific group not found
        if prefix != "S3-API"
            && let Some(price) = self
                .get_request_price_by_group(region, "S3-API-Tier2", storage_class)
                .await?
        {
            return Ok(price);
        }

        Err(anyhow!(
            "Could not find Class B request price for {} in {}",
            storage_class,
            region
        ))
    }

    /// Fetches the request price using the API group filter.
    ///
    /// This is an internal helper method that queries the Pricing API for a specific
    /// request group (e.g., "S3-API-Tier1", "S3-API-SIA-Tier2").
    ///
    /// # Arguments
    ///
    /// * `region` - AWS region code (e.g., "us-east-1")
    /// * `group` - The API group name to query (e.g., "S3-API-Tier1")
    ///
    /// # Returns
    ///
    /// Returns `Ok(Some(price))` if pricing is found, `Ok(None)` if no pricing exists
    /// for the specified group, or an error if the API call fails.
    async fn get_request_price_by_group(
        &self,
        region: &str,
        group: &str,
        storage_class: &str,
    ) -> Result<Option<f64>> {
        // Cache key now includes storage class to avoid collisions
        let cache_key = format!("request:{}:{}:{}:Requests", region, storage_class, group);

        // Check negative cache first
        if self.negative_cache.get(&cache_key).is_some() {
            return Ok(None);
        }

        if let Some(cached) = self.cache.get(&cache_key) {
            return Ok(Some(cached));
        }

        let location = Self::region_to_location(region)?;

        let filters = vec![
            Self::build_filter("location", location)?,
            Self::get_product_family_api_request_filter().clone(),
            Self::build_filter("group", group)?,
        ];

        let result = self
            .client
            .get_products()
            .service_code("AmazonS3")
            .set_filters(Some(filters))
            .send()
            .await?;

        let price_list = result.price_list();
        if price_list.is_empty() {
            // Cache negative result to prevent repeated failed API calls
            self.negative_cache.insert(cache_key, ());
            return Ok(None);
        }

        let price = self.extract_first_tier_price(price_list, "Requests")?;
        self.cache.insert(cache_key.clone(), price);
        Ok(Some(price))
    }

    /// Fetches the data transfer OUT price per GB (S3 to Internet).
    ///
    /// This method retrieves the cost of transferring data from S3 to the internet.
    /// This is also known as "data transfer out" or "egress" pricing.
    ///
    /// # Arguments
    ///
    /// * `region` - Source AWS region (e.g., "us-east-1")
    ///
    /// # Returns
    ///
    /// Price in USD per GB for data transferred out to the internet.
    ///
    /// # Errors
    ///
    /// Returns an error if the Pricing API call fails or no pricing is found.
    pub async fn get_data_transfer_price(&self, region: &str) -> Result<f64> {
        let cache_key = format!("transfer:{}:GB", region);

        // Check negative cache first
        if self.negative_cache.get(&cache_key).is_some() {
            return Err(anyhow!(
                "Transfer price not found (cached negative result): {}",
                cache_key
            ));
        }

        if let Some(cached) = self.cache.get(&cache_key) {
            return Ok(cached);
        }

        let location = Self::region_to_location(region)?;

        let filters = vec![
            Self::build_filter("fromLocation", location)?,
            Self::get_transfer_type_aws_outbound_filter().clone(),
        ];

        let result = self
            .client
            .get_products()
            .service_code("AWSDataTransfer")
            .set_filters(Some(filters))
            .send()
            .await?;

        let price = self.extract_first_tier_price(result.price_list(), "GB")?;
        self.cache.insert(cache_key.clone(), price);
        Ok(price)
    }

    /// Fetches the cross-region data transfer price between two regions.
    ///
    /// This method retrieves the cost of transferring data from one AWS region to another.
    ///
    /// # Arguments
    ///
    /// * `from_region` - Source region code (e.g., "us-east-1")
    /// * `to_region` - Destination region code (e.g., "eu-west-1")
    ///
    /// # Returns
    ///
    /// Price in USD per GB transferred between regions.
    ///
    /// # Errors
    ///
    /// Returns an error if the Pricing API call fails or no pricing is found for the specified route.
    pub async fn get_cross_region_transfer_price(
        &self,
        from_region: &str,
        to_region: &str,
    ) -> Result<f64> {
        let cache_key = format!("transfer:{}:{}:GB", from_region, to_region);

        // Check negative cache first
        if self.negative_cache.get(&cache_key).is_some() {
            return Err(anyhow!(
                "Cross-region transfer price not found (cached negative result): {}",
                cache_key
            ));
        }

        if let Some(cached) = self.cache.get(&cache_key) {
            return Ok(cached);
        }

        let filters = vec![
            Self::build_filter("fromRegionCode", from_region)?,
            Self::build_filter("toRegionCode", to_region)?,
            Self::get_transfer_type_interregion_filter().clone(),
        ];

        let result = self
            .client
            .get_products()
            .service_code("AWSDataTransfer")
            .set_filters(Some(filters))
            .send()
            .await?;

        let price_list = result.price_list();
        if price_list.is_empty() {
            // Cache negative result
            self.negative_cache.insert(cache_key, ());
            return Err(anyhow!(
                "No cross-region transfer price found between {} and {}",
                from_region,
                to_region
            ));
        }

        // Parse JSON once and filter using serde_json::Value (more efficient than string matching)
        let mut first_tier_price: Option<f64> = None;

        for product_json in price_list {
            if let Ok(v) = serde_json::from_str::<serde_json::Value>(product_json) {
                // Check for empty operation field
                let has_empty_operation = v
                    .get("operation")
                    .and_then(|op| op.as_str())
                    .map(|op| op.is_empty())
                    .unwrap_or(false);

                if has_empty_operation
                    && let Ok(price) =
                        self.extract_first_tier_price(std::slice::from_ref(product_json), "GB")
                {
                    first_tier_price = Some(price);
                    break;
                }
            }
        }

        let price = if let Some(price) = first_tier_price {
            price
        } else {
            self.extract_first_tier_price(price_list, "GB")?
        };

        self.cache.insert(cache_key.clone(), price);
        Ok(price)
    }

    /// Displays formatted regional pricing information to stdout.
    ///
    /// Prints storage costs, request costs (both Class A and Class B),
    /// and optionally data transfer costs to a destination region or the internet.
    ///
    /// # Arguments
    ///
    /// * `region` - AWS region to display pricing for (e.g., "us-east-1")
    /// * `storage_class` - S3 storage class (e.g., "STANDARD", "GLACIER")
    /// * `dest_region_opt` - Optional destination region for cross-region transfer pricing
    ///
    /// # Errors
    ///
    /// Returns an error if any of the underlying pricing API calls fail.
    ///
    /// # Output Format
    ///
    /// The output includes:
    /// - Storage price per GB per month
    /// - Class A request price (PUT, COPY, POST, LIST) per 1,000 requests
    /// - Class B request price (GET, etc.) per 10,000 requests
    /// - Data transfer cost (to internet or cross-region)
    pub async fn display_pricing(
        &self,
        region: &str,
        storage_class: &str,
        dest_region_opt: Option<&String>,
    ) -> Result<()> {
        // Determine currency symbol based on region type
        let currency_symbol = if self.is_china { "Â¥" } else { "$" };

        // Fetch storage and request prices in parallel
        let (storage_cost, put_cost, get_cost) = tokio::join!(
            self.get_storage_price(region, storage_class),
            self.get_class_a_request_price(region, storage_class),
            self.get_class_b_request_price(region, storage_class)
        );

        let storage_cost = storage_cost?;
        let put_cost = put_cost?;
        let get_cost = get_cost?;

        let region_type = if self.is_china { " (China)" } else { "" };
        println!(
            "\n📦 S3 Regional Pricing for {} in {}{}",
            storage_class, region, region_type
        );
        println!("─────────────────────────────────────────");
        println!(
            "  Storage:                    {} {:.4} per GB-Mo",
            currency_symbol, storage_cost
        );
        println!(
            "  PUT/COPY/POST/LIST requests: {} {:.10} per request ({} {:.4} per 1,000)",
            currency_symbol,
            put_cost,
            currency_symbol,
            put_cost * 1000.0
        );
        println!(
            "  GET and all other requests:  {} {:.10} per request ({} {:.4} per 10,000)",
            currency_symbol,
            get_cost,
            currency_symbol,
            get_cost * 10000.0
        );

        if let Some(dest_region) = dest_region_opt {
            if region == dest_region {
                println!("  Data Transfer to {}:    FREE (same region)", dest_region);
            } else {
                match self
                    .get_cross_region_transfer_price(region, dest_region)
                    .await
                {
                    Ok(transfer_cost) => {
                        println!(
                            "  Data Transfer to {}:    {} {:.4} per GB",
                            dest_region, currency_symbol, transfer_cost
                        );
                    }
                    Err(_) => {
                        if let Ok(transfer_cost) = self.get_data_transfer_price(region).await {
                            println!(
                                "  Data Transfer (Standard):   {} {:.4} per GB",
                                currency_symbol, transfer_cost
                            );
                        }
                    }
                }
            }
        } else {
            if let Ok(transfer_cost) = self.get_data_transfer_price(region).await {
                println!(
                    "  Data Transfer to Internet:  {} {:.4} per GB",
                    currency_symbol, transfer_cost
                );
            }
        }
        println!();

        Ok(())
    }

    /// Parses the Pricing API JSON response and extracts the first-tier OnDemand price.
    ///
    /// This is an internal helper method that iterates through the price list returned
    /// by the AWS Pricing API and extracts the price for the first tier (where `beginRange == "0"`),
    /// which represents the base on-demand pricing.
    ///
    /// # Arguments
    ///
    /// * `price_list` - Vector of JSON strings returned by the Pricing API
    /// * `unit_contains` - String to match against the price unit (e.g., "GB-Mo", "Requests", "GB")
    ///
    /// # Returns
    ///
    /// The price in USD (or CNY for China regions) for the matching unit.
    /// Prefers the first-tier price (cheapest), falls back to any matching tier if first tier is not available.
    ///
    /// # Errors
    ///
    /// Returns an error if parsing fails or no matching price is found.
    fn extract_first_tier_price(&self, price_list: &[String], unit_contains: &str) -> Result<f64> {
        let unit_lower = unit_contains.to_lowercase();

        // Determine which currency field to look for based on region
        let currency = if self.is_china { "CNY" } else { "USD" };

        for product_json in price_list {
            let v: serde_json::Value = serde_json::from_str(product_json)?;

            if let Some(on_demand) = v.get("terms").and_then(|t| t.get("OnDemand")) {
                for (_term_id, term_val) in on_demand
                    .as_object()
                    .ok_or_else(|| anyhow!("Invalid OnDemand format"))?
                {
                    if let Some(price_dimensions) = term_val.get("priceDimensions") {
                        // Iterate through price dimensions and return early when first tier is found
                        for (_dim_id, dim_val) in price_dimensions
                            .as_object()
                            .ok_or_else(|| anyhow!("Invalid priceDimensions format"))?
                        {
                            let unit = dim_val.get("unit").and_then(|u| u.as_str()).unwrap_or("");
                            if !unit.to_lowercase().contains(&unit_lower) {
                                continue;
                            }

                            if let Some(price_per_unit) =
                                dim_val.get("pricePerUnit").and_then(|p| p.get(currency))
                                && let Some(price_str) = price_per_unit.as_str()
                            {
                                let price = price_str.parse::<f64>()?;

                                // Check if this is the first tier
                                let begin_range = dim_val
                                    .get("beginRange")
                                    .and_then(|b| b.as_str())
                                    .unwrap_or("");
                                if begin_range == "0" {
                                    // Early return when first tier is found (optimization)
                                    return Ok(price);
                                }
                            }
                        }

                        // If we get here, we didn't find a first tier price, so try to find any tier
                        for (_dim_id, dim_val) in price_dimensions
                            .as_object()
                            .ok_or_else(|| anyhow!("Invalid priceDimensions format"))?
                        {
                            let unit = dim_val.get("unit").and_then(|u| u.as_str()).unwrap_or("");
                            if !unit.to_lowercase().contains(&unit_lower) {
                                continue;
                            }

                            if let Some(price_per_unit) =
                                dim_val.get("pricePerUnit").and_then(|p| p.get(currency))
                                && let Some(price_str) = price_per_unit.as_str()
                            {
                                let price = price_str.parse::<f64>()?;
                                return Ok(price);
                            }
                        }
                    }
                }
            }
        }
        Err(anyhow!(
            "Could not find price for unit containing '{}' in results",
            unit_contains
        ))
    }
}

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

    // =====================================================================
    // region_to_location tests
    // =====================================================================

    #[test]
    fn test_region_to_location_us_east_1() {
        assert_eq!(
            S3PricingClient::region_to_location("us-east-1").unwrap(),
            "US East (N. Virginia)"
        );
    }

    #[test]
    fn test_region_to_location_us_west_2() {
        assert_eq!(
            S3PricingClient::region_to_location("us-west-2").unwrap(),
            "US West (Oregon)"
        );
    }

    #[test]
    fn test_region_to_location_eu_west_1() {
        assert_eq!(
            S3PricingClient::region_to_location("eu-west-1").unwrap(),
            "EU (Ireland)"
        );
    }

    #[test]
    fn test_region_to_location_ap_southeast_1() {
        assert_eq!(
            S3PricingClient::region_to_location("ap-southeast-1").unwrap(),
            "Asia Pacific (Singapore)"
        );
    }

    #[test]
    fn test_region_to_location_unknown_returns_error() {
        assert!(
            S3PricingClient::region_to_location("unknown-region").is_err(),
            "Unknown region should return an error"
        );
    }

    // =====================================================================
    // China region tests
    // =====================================================================

    #[test]
    fn test_region_to_location_cn_north_1() {
        assert_eq!(
            S3PricingClient::region_to_location("cn-north-1").unwrap(),
            "China (Beijing)"
        );
    }

    #[test]
    fn test_region_to_location_cn_northwest_1() {
        assert_eq!(
            S3PricingClient::region_to_location("cn-northwest-1").unwrap(),
            "China (Ningxia)"
        );
    }

    #[test]
    fn test_is_china_region_cn_north_1() {
        assert!(S3PricingClient::is_china_region("cn-north-1"));
    }

    #[test]
    fn test_is_china_region_cn_northwest_1() {
        assert!(S3PricingClient::is_china_region("cn-northwest-1"));
    }

    #[test]
    fn test_is_china_region_global_region() {
        assert!(!S3PricingClient::is_china_region("us-east-1"));
        assert!(!S3PricingClient::is_china_region("eu-west-1"));
        assert!(!S3PricingClient::is_china_region("ap-southeast-1"));
    }

    // =====================================================================
    // storage_class_to_volume_type tests
    // =====================================================================

    #[test]
    fn test_storage_class_to_volume_type_standard() {
        assert_eq!(
            S3PricingClient::storage_class_to_volume_type("STANDARD"),
            "Standard"
        );
    }

    #[test]
    fn test_storage_class_to_volume_type_standard_ia() {
        assert_eq!(
            S3PricingClient::storage_class_to_volume_type("STANDARD_IA"),
            "Standard - Infrequent Access"
        );
    }

    #[test]
    fn test_storage_class_to_volume_type_onezone_ia() {
        assert_eq!(
            S3PricingClient::storage_class_to_volume_type("ONEZONE_IA"),
            "One Zone - Infrequent Access"
        );
    }

    #[test]
    fn test_storage_class_to_volume_type_glacier() {
        assert_eq!(
            S3PricingClient::storage_class_to_volume_type("GLACIER"),
            "Amazon Glacier"
        );
    }

    #[test]
    fn test_storage_class_to_volume_type_glacier_flexible_retrieval() {
        assert_eq!(
            S3PricingClient::storage_class_to_volume_type("GLACIER_FLEXIBLE_RETRIEVAL"),
            "Amazon Glacier"
        );
    }

    #[test]
    fn test_storage_class_to_volume_type_deep_archive() {
        assert_eq!(
            S3PricingClient::storage_class_to_volume_type("DEEP_ARCHIVE"),
            "Glacier Deep Archive"
        );
    }

    #[test]
    fn test_storage_class_to_volume_type_intelligent_tiering() {
        assert_eq!(
            S3PricingClient::storage_class_to_volume_type("INTELLIGENT_TIERING"),
            "Intelligent-Tiering"
        );
    }

    #[test]
    fn test_storage_class_to_volume_type_express_onezone() {
        assert_eq!(
            S3PricingClient::storage_class_to_volume_type("EXPRESS_ONEZONE"),
            "Express One Zone"
        );
    }

    #[test]
    fn test_storage_class_to_volume_type_unknown_defaults_to_standard() {
        assert_eq!(
            S3PricingClient::storage_class_to_volume_type("UNKNOWN"),
            "Standard"
        );
    }

    // =====================================================================
    // storage_class_to_filter tests
    // =====================================================================

    #[test]
    fn test_storage_class_to_filter_standard() {
        assert_eq!(
            S3PricingClient::storage_class_to_filter("STANDARD"),
            "General Purpose"
        );
    }

    #[test]
    fn test_storage_class_to_filter_standard_ia() {
        assert_eq!(
            S3PricingClient::storage_class_to_filter("STANDARD_IA"),
            "Infrequent Access"
        );
    }

    #[test]
    fn test_storage_class_to_filter_onezone_ia() {
        assert_eq!(
            S3PricingClient::storage_class_to_filter("ONEZONE_IA"),
            "Infrequent Access"
        );
    }

    #[test]
    fn test_storage_class_to_filter_intelligent_tiering() {
        assert_eq!(
            S3PricingClient::storage_class_to_filter("INTELLIGENT_TIERING"),
            "Intelligent-Tiering"
        );
    }

    #[test]
    fn test_storage_class_to_filter_glacier() {
        assert_eq!(
            S3PricingClient::storage_class_to_filter("GLACIER"),
            "Archive"
        );
    }

    #[test]
    fn test_storage_class_to_filter_deep_archive() {
        assert_eq!(
            S3PricingClient::storage_class_to_filter("DEEP_ARCHIVE"),
            "Archive"
        );
    }

    #[test]
    fn test_storage_class_to_filter_glacier_ir() {
        assert_eq!(
            S3PricingClient::storage_class_to_filter("GLACIER_IR"),
            "Archive Instant Retrieval"
        );
    }

    #[test]
    fn test_storage_class_to_filter_express_onezone() {
        assert_eq!(
            S3PricingClient::storage_class_to_filter("EXPRESS_ONEZONE"),
            "High Performance"
        );
    }

    // =====================================================================
    // storage_class_to_api_group_prefix tests
    // =====================================================================

    #[test]
    fn test_storage_class_to_api_group_prefix_standard() {
        assert_eq!(
            S3PricingClient::storage_class_to_api_group_prefix("STANDARD"),
            "S3-API"
        );
    }

    #[test]
    fn test_storage_class_to_api_group_prefix_standard_ia() {
        assert_eq!(
            S3PricingClient::storage_class_to_api_group_prefix("STANDARD_IA"),
            "S3-API-SIA"
        );
    }

    #[test]
    fn test_storage_class_to_api_group_prefix_onezone_ia() {
        assert_eq!(
            S3PricingClient::storage_class_to_api_group_prefix("ONEZONE_IA"),
            "S3-API-ZIA"
        );
    }

    #[test]
    fn test_storage_class_to_api_group_prefix_intelligent_tiering() {
        assert_eq!(
            S3PricingClient::storage_class_to_api_group_prefix("INTELLIGENT_TIERING"),
            "S3-API-INT"
        );
    }

    #[test]
    fn test_storage_class_to_api_group_prefix_glacier() {
        assert_eq!(
            S3PricingClient::storage_class_to_api_group_prefix("GLACIER"),
            "S3-API-GLACIER"
        );
    }

    #[test]
    fn test_storage_class_to_api_group_prefix_glacier_flexible() {
        assert_eq!(
            S3PricingClient::storage_class_to_api_group_prefix("GLACIER_FLEXIBLE_RETRIEVAL"),
            "S3-API-GLACIER"
        );
    }

    #[test]
    fn test_storage_class_to_api_group_prefix_deep_archive() {
        assert_eq!(
            S3PricingClient::storage_class_to_api_group_prefix("DEEP_ARCHIVE"),
            "S3-API-DAA"
        );
    }

    #[test]
    fn test_storage_class_to_api_group_prefix_glacier_ir() {
        assert_eq!(
            S3PricingClient::storage_class_to_api_group_prefix("GLACIER_IR"),
            "S3-API-GIR"
        );
    }

    #[test]
    fn test_storage_class_to_api_group_prefix_glacier_instant_retrieval() {
        assert_eq!(
            S3PricingClient::storage_class_to_api_group_prefix("GLACIER_INSTANT_RETRIEVAL"),
            "S3-API-GIR"
        );
    }

    #[test]
    fn test_storage_class_to_api_group_prefix_express_onezone() {
        assert_eq!(
            S3PricingClient::storage_class_to_api_group_prefix("EXPRESS_ONEZONE"),
            "S3-API-XZ"
        );
    }

    #[test]
    fn test_storage_class_to_api_group_prefix_unknown_defaults_to_s3_api() {
        assert_eq!(
            S3PricingClient::storage_class_to_api_group_prefix("UNKNOWN"),
            "S3-API"
        );
    }

    // =====================================================================
    // Combined mapping tests - ensuring consistency
    // =====================================================================

    #[test]
    fn test_all_standard_storage_classes_map_correctly() {
        // All storage classes should map to non-empty strings
        let classes = [
            "STANDARD",
            "STANDARD_IA",
            "ONEZONE_IA",
            "INTELLIGENT_TIERING",
            "GLACIER",
            "GLACIER_FLEXIBLE_RETRIEVAL",
            "DEEP_ARCHIVE",
            "GLACIER_IR",
            "GLACIER_INSTANT_RETRIEVAL",
            "EXPRESS_ONEZONE",
            "REDUCED_REDUNDANCY",
        ];

        for class in classes {
            assert!(
                !S3PricingClient::storage_class_to_volume_type(class).is_empty(),
                "volumeType should not be empty for {}",
                class
            );
            assert!(
                !S3PricingClient::storage_class_to_filter(class).is_empty(),
                "filter should not be empty for {}",
                class
            );
            assert!(
                !S3PricingClient::storage_class_to_api_group_prefix(class).is_empty(),
                "api group prefix should not be empty for {}",
                class
            );
        }
    }

    #[test]
    fn test_all_regions_map_to_valid_locations() {
        let regions = [
            "us-east-1",
            "us-east-2",
            "us-west-1",
            "us-west-2",
            "eu-west-1",
            "eu-west-2",
            "eu-central-1",
            "ap-northeast-1",
            "ap-southeast-1",
            "ap-southeast-2",
            "sa-east-1",
            "ca-central-1",
        ];

        for region in regions {
            let location =
                S3PricingClient::region_to_location(region).expect("Valid region should return Ok");
            assert!(
                !location.is_empty(),
                "location should not be empty for region {}",
                region
            );
        }
    }
}