Skip to main content

briefcase_core/
cost.rs

1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3use thiserror::Error;
4
5#[derive(Debug, Clone, Serialize, Deserialize)]
6pub struct ModelPricing {
7    pub model_name: String,
8    pub provider: String,
9    pub input_cost_per_1k_tokens: f64,  // USD
10    pub output_cost_per_1k_tokens: f64, // USD
11    pub context_window: usize,
12    pub max_output_tokens: Option<usize>,
13}
14
15impl ModelPricing {
16    /// Build flat pricing from provider per-MTok (per-1,000,000-token) prices,
17    /// converting to the per-1K unit stored internally (`$5/MTok` → `0.005/1K`).
18    fn from_mtok(
19        model_name: &str,
20        provider: &str,
21        input_per_mtok: f64,
22        output_per_mtok: f64,
23        context_window: usize,
24        max_output_tokens: Option<usize>,
25    ) -> Self {
26        ModelPricing {
27            model_name: model_name.to_string(),
28            provider: provider.to_string(),
29            input_cost_per_1k_tokens: input_per_mtok / 1000.0,
30            output_cost_per_1k_tokens: output_per_mtok / 1000.0,
31            context_window,
32            max_output_tokens,
33        }
34    }
35}
36
37#[derive(Debug, Clone, Serialize, Deserialize)]
38pub struct CostEstimate {
39    pub model_name: String,
40    pub input_tokens: usize,
41    pub output_tokens: usize,
42    pub input_cost: f64,
43    pub output_cost: f64,
44    /// Cost of prompt-cache reads/writes (0.0 unless cache tokens were supplied).
45    #[serde(default)]
46    pub cache_cost: f64,
47    pub total_cost: f64,
48    pub currency: String,
49}
50
51#[derive(Debug, Clone, Serialize, Deserialize)]
52pub struct BudgetStatus {
53    pub budget_usd: f64,
54    pub spent_usd: f64,
55    pub remaining_usd: f64,
56    pub percent_used: f64,
57    pub status: BudgetAlert,
58}
59
60#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
61pub enum BudgetAlert {
62    Ok,       // < 80% used
63    Warning,  // 80-95% used
64    Critical, // 95-100% used
65    Exceeded, // > 100% used
66}
67
68/// Cloud platform a model is billed through. Token rates match the first-party
69/// API across platforms; the difference is captured by modifiers such as the
70/// regional-endpoint premium (see [`RateCard::regional_endpoint`]).
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
72pub enum Platform {
73    /// Provider's own API (Anthropic / OpenAI / Google).
74    #[default]
75    FirstParty,
76    /// AWS Bedrock.
77    Bedrock,
78    /// Google Vertex AI.
79    Vertex,
80    /// Azure OpenAI.
81    Azure,
82}
83
84/// Pricing tier within a platform.
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
86pub enum PricingTier {
87    /// On-demand pricing.
88    #[default]
89    Standard,
90    /// Asynchronous batch processing — 0.5x of standard input and output.
91    Batch,
92    /// Bill `input_tokens` at the model's cache-read rate (fully-cached input).
93    Cached,
94    /// Priority/premium tier — per-model multiplier (errors if the model has none).
95    Priority,
96    /// Flex tier (Gemini) — 0.5x of standard.
97    Flex,
98}
99
100/// Data-residency selection. `Us` applies a 1.1x multiplier on eligible models.
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
102pub enum DataResidency {
103    /// Global routing (default), standard pricing.
104    #[default]
105    Global,
106    /// US-only inference (`inference_geo=us`) — 1.1x on eligible models.
107    Us,
108}
109
110/// A selectable rate card: `platform × tier × modifiers`. The [`Default`]
111/// (first-party, standard, global, no premium) reproduces legacy pricing.
112#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
113pub struct RateCard {
114    pub platform: Platform,
115    pub tier: PricingTier,
116    pub data_residency: DataResidency,
117    /// Regional/multi-region endpoint — +10% on eligible models.
118    pub regional_endpoint: bool,
119    /// Use the model's fast-mode premium rates (if defined).
120    pub fast_mode: bool,
121}
122
123impl RateCard {
124    /// Parse a forgiving string such as `"batch"`, `"bedrock:batch"`,
125    /// `"vertex/standard,us"`, `"azure regional"`, or `"first_party/fast"`.
126    /// Tokens may be separated by any of `/ : , +` or whitespace; order is
127    /// irrelevant. An empty string (or `"standard"`) yields the default card.
128    pub fn parse(s: &str) -> Result<RateCard, CostError> {
129        let mut card = RateCard::default();
130        for raw in
131            s.split(|c: char| c == '/' || c == ':' || c == ',' || c == '+' || c.is_whitespace())
132        {
133            let token = raw.trim().to_ascii_lowercase();
134            if token.is_empty() {
135                continue;
136            }
137            match token.as_str() {
138                "first_party" | "firstparty" | "first-party" | "direct" | "anthropic"
139                | "openai" | "google" => card.platform = Platform::FirstParty,
140                "bedrock" | "aws" => card.platform = Platform::Bedrock,
141                "vertex" | "vertexai" | "gcp" => card.platform = Platform::Vertex,
142                "azure" => card.platform = Platform::Azure,
143                "standard" | "ondemand" | "on-demand" => card.tier = PricingTier::Standard,
144                "batch" => card.tier = PricingTier::Batch,
145                "cached" | "cache" => card.tier = PricingTier::Cached,
146                "priority" => card.tier = PricingTier::Priority,
147                "flex" => card.tier = PricingTier::Flex,
148                "regional" | "region" | "multiregion" | "multi-region" => {
149                    card.regional_endpoint = true
150                }
151                "us" | "residency" | "data-residency" | "us-only" => {
152                    card.data_residency = DataResidency::Us
153                }
154                "global" => card.data_residency = DataResidency::Global,
155                "fast" | "fast-mode" | "fastmode" => card.fast_mode = true,
156                other => return Err(CostError::UnknownRateCard(other.to_string())),
157            }
158        }
159        Ok(card)
160    }
161}
162
163/// Per-call token usage. The cache fields default to 0, so the common
164/// `{ input_tokens, output_tokens }` form behaves like the legacy path.
165#[derive(Debug, Clone, Copy, Default)]
166pub struct TokenUsage {
167    pub input_tokens: usize,
168    pub output_tokens: usize,
169    pub cache_read_tokens: usize,
170    pub cache_write_5m_tokens: usize,
171    pub cache_write_1h_tokens: usize,
172}
173
174/// Prompt-cache rates (per-1K USD, absolute). `read` is the cache-hit rate;
175/// writes are the 5-minute / 1-hour cache-creation rates (Anthropic only).
176#[derive(Debug, Clone, Copy)]
177struct CacheRates {
178    read_per_1k: f64,
179    write_5m_per_1k: Option<f64>,
180    write_1h_per_1k: Option<f64>,
181}
182
183impl CacheRates {
184    /// Anthropic-style cache rates from per-MTok prices.
185    fn from_mtok(read: f64, write_5m: f64, write_1h: f64) -> Self {
186        Self {
187            read_per_1k: read / 1000.0,
188            write_5m_per_1k: Some(write_5m / 1000.0),
189            write_1h_per_1k: Some(write_1h / 1000.0),
190        }
191    }
192    /// Read-only cache rate (OpenAI cached-input / Gemini cache) from per-MTok.
193    fn read_only_mtok(read: f64) -> Self {
194        Self {
195            read_per_1k: read / 1000.0,
196            write_5m_per_1k: None,
197            write_1h_per_1k: None,
198        }
199    }
200}
201
202/// An input/output rate pair (per-1K USD).
203#[derive(Debug, Clone, Copy)]
204struct TokenRates {
205    input_per_1k: f64,
206    output_per_1k: f64,
207}
208
209impl TokenRates {
210    fn from_mtok(input: f64, output: f64) -> Self {
211        Self {
212            input_per_1k: input / 1000.0,
213            output_per_1k: output / 1000.0,
214        }
215    }
216}
217
218/// A long-context pricing tier: when `input_tokens` exceeds `threshold_tokens`
219/// the whole request is billed at these (per-1K) rates instead of the base.
220#[derive(Debug, Clone, Copy)]
221struct ContextTier {
222    threshold_tokens: usize,
223    input_per_1k: f64,
224    output_per_1k: f64,
225}
226
227impl ContextTier {
228    fn from_mtok(threshold_tokens: usize, input: f64, output: f64) -> Self {
229        Self {
230            threshold_tokens,
231            input_per_1k: input / 1000.0,
232            output_per_1k: output / 1000.0,
233        }
234    }
235}
236
237/// Eligibility flags for percentage modifiers.
238#[derive(Debug, Clone, Copy, Default)]
239struct ModifierFlags {
240    /// Eligible for the US data-residency 1.1x multiplier.
241    supports_data_residency: bool,
242    /// Eligible for the regional/multi-region endpoint +10% premium.
243    supports_regional_premium: bool,
244}
245
246/// Rich rate-card data attached to a model, alongside the flat [`ModelPricing`].
247/// Models without an entry resolve to first-party standard pricing only.
248#[derive(Debug, Clone, Default)]
249struct PricingExtras {
250    cache_rates: Option<CacheRates>,
251    fast_mode_rates: Option<TokenRates>,
252    long_context_tiers: Vec<ContextTier>,
253    priority_multiplier: Option<f64>,
254    /// Per-MTok-per-hour context-cache storage rate (time-based; see
255    /// [`CostCalculator::estimate_cache_storage_cost`]).
256    cache_storage_per_mtok_hour: Option<f64>,
257    flags: ModifierFlags,
258}
259
260/// Whether a [`TokenUsage`] describes one request or a total over many.
261#[derive(Debug, Clone, Copy, PartialEq, Eq)]
262enum UsageScope {
263    SingleRequest,
264    Aggregate,
265}
266
267pub struct CostCalculator {
268    pricing_table: HashMap<String, ModelPricing>,
269    /// Rich rate-card data keyed by model name (parallel to `pricing_table`).
270    extras: HashMap<String, PricingExtras>,
271}
272
273impl CostCalculator {
274    /// Create with default pricing table (OpenAI, Anthropic, etc.)
275    pub fn new() -> Self {
276        let mut pricing_table = HashMap::new();
277
278        // OpenAI models
279        pricing_table.insert(
280            "gpt-4".to_string(),
281            ModelPricing {
282                model_name: "gpt-4".to_string(),
283                provider: "openai".to_string(),
284                input_cost_per_1k_tokens: 0.03,
285                output_cost_per_1k_tokens: 0.06,
286                context_window: 8192,
287                max_output_tokens: Some(4096),
288            },
289        );
290
291        pricing_table.insert(
292            "gpt-4-turbo".to_string(),
293            ModelPricing {
294                model_name: "gpt-4-turbo".to_string(),
295                provider: "openai".to_string(),
296                input_cost_per_1k_tokens: 0.01,
297                output_cost_per_1k_tokens: 0.03,
298                context_window: 128000,
299                max_output_tokens: Some(4096),
300            },
301        );
302
303        pricing_table.insert(
304            "gpt-3.5-turbo".to_string(),
305            ModelPricing {
306                model_name: "gpt-3.5-turbo".to_string(),
307                provider: "openai".to_string(),
308                input_cost_per_1k_tokens: 0.0005,
309                output_cost_per_1k_tokens: 0.0015,
310                context_window: 16385,
311                max_output_tokens: Some(4096),
312            },
313        );
314
315        pricing_table.insert(
316            "gpt-4o".to_string(),
317            ModelPricing {
318                model_name: "gpt-4o".to_string(),
319                provider: "openai".to_string(),
320                input_cost_per_1k_tokens: 0.005,
321                output_cost_per_1k_tokens: 0.015,
322                context_window: 128000,
323                max_output_tokens: Some(16384),
324            },
325        );
326
327        pricing_table.insert(
328            "gpt-4o-mini".to_string(),
329            ModelPricing {
330                model_name: "gpt-4o-mini".to_string(),
331                provider: "openai".to_string(),
332                input_cost_per_1k_tokens: 0.00015,
333                output_cost_per_1k_tokens: 0.0006,
334                context_window: 128000,
335                max_output_tokens: Some(16384),
336            },
337        );
338
339        // Anthropic models
340        pricing_table.insert(
341            "claude-3-opus".to_string(),
342            ModelPricing {
343                model_name: "claude-3-opus".to_string(),
344                provider: "anthropic".to_string(),
345                input_cost_per_1k_tokens: 0.015,
346                output_cost_per_1k_tokens: 0.075,
347                context_window: 200000,
348                max_output_tokens: Some(4096),
349            },
350        );
351
352        pricing_table.insert(
353            "claude-3-sonnet".to_string(),
354            ModelPricing {
355                model_name: "claude-3-sonnet".to_string(),
356                provider: "anthropic".to_string(),
357                input_cost_per_1k_tokens: 0.003,
358                output_cost_per_1k_tokens: 0.015,
359                context_window: 200000,
360                max_output_tokens: Some(4096),
361            },
362        );
363
364        pricing_table.insert(
365            "claude-3-haiku".to_string(),
366            ModelPricing {
367                model_name: "claude-3-haiku".to_string(),
368                provider: "anthropic".to_string(),
369                input_cost_per_1k_tokens: 0.00025,
370                output_cost_per_1k_tokens: 0.00125,
371                context_window: 200000,
372                max_output_tokens: Some(4096),
373            },
374        );
375
376        pricing_table.insert(
377            "claude-3-5-sonnet".to_string(),
378            ModelPricing {
379                model_name: "claude-3-5-sonnet".to_string(),
380                provider: "anthropic".to_string(),
381                input_cost_per_1k_tokens: 0.003,
382                output_cost_per_1k_tokens: 0.015,
383                context_window: 200000,
384                max_output_tokens: Some(8192),
385            },
386        );
387
388        // Google models
389        pricing_table.insert(
390            "gemini-pro".to_string(),
391            ModelPricing {
392                model_name: "gemini-pro".to_string(),
393                provider: "google".to_string(),
394                input_cost_per_1k_tokens: 0.0005,
395                output_cost_per_1k_tokens: 0.0015,
396                context_window: 30720,
397                max_output_tokens: Some(2048),
398            },
399        );
400
401        pricing_table.insert(
402            "gemini-ultra".to_string(),
403            ModelPricing {
404                model_name: "gemini-ultra".to_string(),
405                provider: "google".to_string(),
406                input_cost_per_1k_tokens: 0.0125,
407                output_cost_per_1k_tokens: 0.0375,
408                context_window: 30720,
409                max_output_tokens: Some(2048),
410            },
411        );
412
413        let mut calculator = Self {
414            pricing_table,
415            extras: HashMap::new(),
416        };
417        calculator.install_modern_models();
418        calculator
419    }
420
421    /// Canonicalizes a platform-qualified model id to a pricing-table key.
422    /// In order, it strips:
423    ///
424    /// - a path prefix, keeping the last segment (`models/gemini-2.5-pro`,
425    ///   `anthropic/claude-sonnet-4-6`, `publishers/google/models/...`)
426    /// - region prefixes (us./eu./apac./global.) and vendor prefixes
427    ///   (anthropic./amazon./cohere./mistral./meta.)
428    /// - a Vertex `@version` suffix (`claude-sonnet-4-5@20250929`)
429    /// - `-vN:M` / `:N` version suffixes and a `-latest` alias suffix
430    /// - a trailing `-YYYYMMDD` or `-YYYY-MM-DD` date stamp
431    ///
432    /// and then maps the provider's `claude-3-5-haiku` spelling onto the
433    /// table's `claude-haiku-3-5` key. Lookups try the exact id first, so a
434    /// registered platform-qualified name always wins.
435    pub fn normalize_model_id(model_id: &str) -> String {
436        let mut id = model_id.rsplit('/').next().unwrap_or(model_id);
437        for region in ["us.", "eu.", "apac.", "global."] {
438            if let Some(rest) = id.strip_prefix(region) {
439                id = rest;
440                break;
441            }
442        }
443        for vendor in ["anthropic.", "amazon.", "cohere.", "mistral.", "meta."] {
444            if let Some(rest) = id.strip_prefix(vendor) {
445                id = rest;
446                break;
447            }
448        }
449        // Vertex @version suffix, e.g. @20250929 or @001
450        if let Some(pos) = id.find('@') {
451            if pos > 0 {
452                id = &id[..pos];
453            }
454        }
455        let mut out = id.to_string();
456        // -vN:M version suffix, e.g. -v1:0
457        if let Some(pos) = out.rfind("-v") {
458            let tail = &out[pos + 2..];
459            if !tail.is_empty() && tail.chars().all(|c| c.is_ascii_digit() || c == ':') {
460                out.truncate(pos);
461            }
462        }
463        // bare :N suffix
464        if let Some(pos) = out.rfind(':') {
465            if out[pos + 1..].chars().all(|c| c.is_ascii_digit()) && !out[pos + 1..].is_empty() {
466                out.truncate(pos);
467            }
468        }
469        if let Some(head) = out.strip_suffix("-latest") {
470            out = head.to_string();
471        }
472        if let Some(len) = Self::date_stamp_len(&out) {
473            out.truncate(out.len() - len);
474        }
475        match out.as_str() {
476            "claude-3-5-haiku" => "claude-haiku-3-5".to_string(),
477            _ => out,
478        }
479    }
480
481    /// Length of a trailing `-YYYYMMDD` or `-YYYY-MM-DD` date stamp, if `id`
482    /// ends in one and has a name in front of it.
483    fn date_stamp_len(id: &str) -> Option<usize> {
484        let bytes = id.as_bytes();
485        let matches = |pattern: &[u8]| {
486            bytes.len() > pattern.len()
487                && bytes[bytes.len() - pattern.len()..]
488                    .iter()
489                    .zip(pattern)
490                    .all(|(b, p)| match p {
491                        b'd' => b.is_ascii_digit(),
492                        _ => b == p,
493                    })
494        };
495        if matches(b"-dddd-dd-dd") {
496            Some(11)
497        } else if matches(b"-dddddddd") {
498            Some(9)
499        } else {
500            None
501        }
502    }
503
504    /// Resolves a model id to the pricing-table key: the exact id when
505    /// registered, otherwise its normalized form when that is registered.
506    fn resolve_model_key(&self, model_name: &str) -> Option<String> {
507        if self.pricing_table.contains_key(model_name) {
508            return Some(model_name.to_string());
509        }
510        let normalized = Self::normalize_model_id(model_name);
511        if self.pricing_table.contains_key(&normalized) {
512            return Some(normalized);
513        }
514        None
515    }
516
517    /// Register a model's flat pricing together with its rate-card extras.
518    fn insert_model(&mut self, pricing: ModelPricing, extras: PricingExtras) {
519        let name = pricing.model_name.clone();
520        self.extras.insert(name.clone(), extras);
521        self.pricing_table.insert(name, pricing);
522    }
523
524    /// Add the current (2026) Claude 4.x, GPT-5.x, and Gemini 2.5/3.x models
525    /// with their rate-card data. Earlier models remain registered in `new()`.
526    fn install_modern_models(&mut self) {
527        // ---- Anthropic (Claude API, first-party) ----
528        // Opus 4.x / Sonnet 4.x share: cache read 0.1x, 5m-write 1.25x, 1h-write 2x.
529        self.insert_model(
530            ModelPricing::from_mtok(
531                "claude-opus-4-8",
532                "anthropic",
533                5.0,
534                25.0,
535                1_000_000,
536                Some(64_000),
537            ),
538            PricingExtras {
539                cache_rates: Some(CacheRates::from_mtok(0.5, 6.25, 10.0)),
540                fast_mode_rates: Some(TokenRates::from_mtok(10.0, 50.0)),
541                flags: ModifierFlags {
542                    supports_data_residency: true,
543                    supports_regional_premium: true,
544                },
545                ..Default::default()
546            },
547        );
548        self.insert_model(
549            ModelPricing::from_mtok(
550                "claude-opus-4-7",
551                "anthropic",
552                5.0,
553                25.0,
554                1_000_000,
555                Some(64_000),
556            ),
557            PricingExtras {
558                cache_rates: Some(CacheRates::from_mtok(0.5, 6.25, 10.0)),
559                fast_mode_rates: Some(TokenRates::from_mtok(30.0, 150.0)),
560                flags: ModifierFlags {
561                    supports_data_residency: true,
562                    supports_regional_premium: true,
563                },
564                ..Default::default()
565            },
566        );
567        self.insert_model(
568            ModelPricing::from_mtok(
569                "claude-opus-4-6",
570                "anthropic",
571                5.0,
572                25.0,
573                1_000_000,
574                Some(64_000),
575            ),
576            PricingExtras {
577                cache_rates: Some(CacheRates::from_mtok(0.5, 6.25, 10.0)),
578                fast_mode_rates: Some(TokenRates::from_mtok(30.0, 150.0)),
579                flags: ModifierFlags {
580                    supports_data_residency: true,
581                    supports_regional_premium: true,
582                },
583                ..Default::default()
584            },
585        );
586        self.insert_model(
587            ModelPricing::from_mtok(
588                "claude-opus-4-5",
589                "anthropic",
590                5.0,
591                25.0,
592                200_000,
593                Some(64_000),
594            ),
595            PricingExtras {
596                cache_rates: Some(CacheRates::from_mtok(0.5, 6.25, 10.0)),
597                flags: ModifierFlags {
598                    supports_data_residency: false,
599                    supports_regional_premium: true,
600                },
601                ..Default::default()
602            },
603        );
604        self.insert_model(
605            ModelPricing::from_mtok(
606                "claude-opus-4-1",
607                "anthropic",
608                15.0,
609                75.0,
610                200_000,
611                Some(32_000),
612            ),
613            PricingExtras {
614                cache_rates: Some(CacheRates::from_mtok(1.5, 18.75, 30.0)),
615                ..Default::default()
616            },
617        );
618        self.insert_model(
619            ModelPricing::from_mtok(
620                "claude-sonnet-4-6",
621                "anthropic",
622                3.0,
623                15.0,
624                1_000_000,
625                Some(64_000),
626            ),
627            PricingExtras {
628                cache_rates: Some(CacheRates::from_mtok(0.3, 3.75, 6.0)),
629                flags: ModifierFlags {
630                    supports_data_residency: true,
631                    supports_regional_premium: true,
632                },
633                ..Default::default()
634            },
635        );
636        self.insert_model(
637            ModelPricing::from_mtok(
638                "claude-sonnet-4-5",
639                "anthropic",
640                3.0,
641                15.0,
642                200_000,
643                Some(64_000),
644            ),
645            PricingExtras {
646                cache_rates: Some(CacheRates::from_mtok(0.3, 3.75, 6.0)),
647                flags: ModifierFlags {
648                    supports_data_residency: false,
649                    supports_regional_premium: true,
650                },
651                ..Default::default()
652            },
653        );
654        self.insert_model(
655            ModelPricing::from_mtok(
656                "claude-haiku-4-5",
657                "anthropic",
658                1.0,
659                5.0,
660                200_000,
661                Some(64_000),
662            ),
663            PricingExtras {
664                cache_rates: Some(CacheRates::from_mtok(0.1, 1.25, 2.0)),
665                flags: ModifierFlags {
666                    supports_data_residency: false,
667                    supports_regional_premium: true,
668                },
669                ..Default::default()
670            },
671        );
672        self.insert_model(
673            ModelPricing::from_mtok(
674                "claude-haiku-3-5",
675                "anthropic",
676                0.8,
677                4.0,
678                200_000,
679                Some(8_192),
680            ),
681            PricingExtras {
682                cache_rates: Some(CacheRates::from_mtok(0.08, 1.0, 1.6)),
683                ..Default::default()
684            },
685        );
686
687        // ---- OpenAI (first-party) ----
688        // Cached-input ~= 0.1x; batch = 0.5x; regional +10% (models >= 2026-03-05).
689        self.insert_model(
690            ModelPricing::from_mtok("gpt-5.5", "openai", 5.0, 30.0, 1_050_000, Some(128_000)),
691            PricingExtras {
692                cache_rates: Some(CacheRates::read_only_mtok(0.5)),
693                priority_multiplier: Some(2.5),
694                flags: ModifierFlags {
695                    supports_data_residency: false,
696                    supports_regional_premium: true,
697                },
698                ..Default::default()
699            },
700        );
701        self.insert_model(
702            ModelPricing::from_mtok("gpt-5.5-pro", "openai", 30.0, 180.0, 400_000, Some(128_000)),
703            PricingExtras {
704                flags: ModifierFlags {
705                    supports_data_residency: false,
706                    supports_regional_premium: true,
707                },
708                ..Default::default()
709            },
710        );
711        self.insert_model(
712            ModelPricing::from_mtok("gpt-5.4", "openai", 2.5, 15.0, 400_000, Some(128_000)),
713            PricingExtras {
714                cache_rates: Some(CacheRates::read_only_mtok(0.25)),
715                flags: ModifierFlags {
716                    supports_data_residency: false,
717                    supports_regional_premium: true,
718                },
719                ..Default::default()
720            },
721        );
722        self.insert_model(
723            ModelPricing::from_mtok("gpt-5.4-mini", "openai", 0.75, 4.5, 400_000, Some(128_000)),
724            PricingExtras {
725                cache_rates: Some(CacheRates::read_only_mtok(0.075)),
726                flags: ModifierFlags {
727                    supports_data_residency: false,
728                    supports_regional_premium: true,
729                },
730                ..Default::default()
731            },
732        );
733        self.insert_model(
734            ModelPricing::from_mtok("gpt-5.4-nano", "openai", 0.2, 1.25, 400_000, Some(128_000)),
735            PricingExtras {
736                cache_rates: Some(CacheRates::read_only_mtok(0.02)),
737                flags: ModifierFlags {
738                    supports_data_residency: false,
739                    supports_regional_premium: true,
740                },
741                ..Default::default()
742            },
743        );
744        self.insert_model(
745            ModelPricing::from_mtok("gpt-5.4-pro", "openai", 30.0, 180.0, 400_000, Some(128_000)),
746            PricingExtras {
747                flags: ModifierFlags {
748                    supports_data_residency: false,
749                    supports_regional_premium: true,
750                },
751                ..Default::default()
752            },
753        );
754
755        // ---- Google Gemini ----
756        // Batch/Flex = 0.5x; Pro models price >200K prompts at a higher tier.
757        self.insert_model(
758            ModelPricing::from_mtok(
759                "gemini-3.5-flash",
760                "google",
761                1.5,
762                9.0,
763                1_048_576,
764                Some(65_536),
765            ),
766            PricingExtras {
767                cache_rates: Some(CacheRates::read_only_mtok(0.15)),
768                priority_multiplier: Some(1.8),
769                cache_storage_per_mtok_hour: Some(1.0),
770                ..Default::default()
771            },
772        );
773        self.insert_model(
774            ModelPricing::from_mtok(
775                "gemini-3.1-pro",
776                "google",
777                2.0,
778                12.0,
779                1_048_576,
780                Some(65_536),
781            ),
782            PricingExtras {
783                long_context_tiers: vec![ContextTier::from_mtok(200_000, 4.0, 18.0)],
784                ..Default::default()
785            },
786        );
787        self.insert_model(
788            ModelPricing::from_mtok(
789                "gemini-3.1-flash-lite",
790                "google",
791                0.25,
792                1.5,
793                1_048_576,
794                Some(65_536),
795            ),
796            PricingExtras::default(),
797        );
798        self.insert_model(
799            ModelPricing::from_mtok(
800                "gemini-3-flash",
801                "google",
802                0.5,
803                3.0,
804                1_048_576,
805                Some(65_536),
806            ),
807            PricingExtras::default(),
808        );
809        self.insert_model(
810            ModelPricing::from_mtok(
811                "gemini-2.5-pro",
812                "google",
813                1.25,
814                10.0,
815                1_048_576,
816                Some(65_536),
817            ),
818            PricingExtras {
819                cache_rates: Some(CacheRates::read_only_mtok(0.125)),
820                cache_storage_per_mtok_hour: Some(4.5),
821                long_context_tiers: vec![ContextTier::from_mtok(200_000, 2.5, 15.0)],
822                ..Default::default()
823            },
824        );
825        self.insert_model(
826            ModelPricing::from_mtok(
827                "gemini-2.5-flash",
828                "google",
829                0.3,
830                2.5,
831                1_048_576,
832                Some(65_536),
833            ),
834            PricingExtras::default(),
835        );
836        self.insert_model(
837            ModelPricing::from_mtok(
838                "gemini-2.5-flash-lite",
839                "google",
840                0.1,
841                0.4,
842                1_048_576,
843                Some(65_536),
844            ),
845            PricingExtras::default(),
846        );
847
848        // ---- Amazon Nova and Bedrock embedding models ----
849        // Flat rates are the Bedrock us-east-1 list prices; these models are
850        // served through Bedrock, so the first-party rate is the Bedrock rate.
851        self.insert_model(
852            ModelPricing::from_mtok("nova-premier", "amazon", 2.5, 12.5, 1_000_000, Some(10_000)),
853            PricingExtras::default(),
854        );
855        self.insert_model(
856            ModelPricing::from_mtok("nova-pro", "amazon", 0.8, 3.2, 300_000, Some(5_120)),
857            PricingExtras::default(),
858        );
859        self.insert_model(
860            ModelPricing::from_mtok("nova-lite", "amazon", 0.06, 0.24, 300_000, Some(5_120)),
861            PricingExtras::default(),
862        );
863        self.insert_model(
864            ModelPricing::from_mtok("nova-micro", "amazon", 0.035, 0.14, 128_000, Some(5_120)),
865            PricingExtras::default(),
866        );
867        self.insert_model(
868            ModelPricing::from_mtok("titan-embed-text", "amazon", 0.1, 0.0, 8_192, None),
869            PricingExtras::default(),
870        );
871        self.insert_model(
872            ModelPricing::from_mtok("cohere-embed", "cohere", 0.1, 0.0, 8_192, None),
873            PricingExtras::default(),
874        );
875    }
876
877    /// Estimate cost for a given model and token counts (first-party standard
878    /// pricing). Equivalent to [`Self::estimate_cost_with_card`] with the
879    /// default [`RateCard`] and no cache tokens.
880    pub fn estimate_cost(
881        &self,
882        model_name: &str,
883        input_tokens: usize,
884        output_tokens: usize,
885    ) -> Result<CostEstimate, CostError> {
886        self.estimate_cost_with_card(
887            model_name,
888            TokenUsage {
889                input_tokens,
890                output_tokens,
891                ..Default::default()
892            },
893            RateCard::default(),
894        )
895    }
896
897    /// Estimate cost under a specific [`RateCard`] with full token accounting
898    /// (including prompt-cache reads/writes). This is the rate-card engine that
899    /// [`Self::estimate_cost`] delegates to.
900    pub fn estimate_cost_with_card(
901        &self,
902        model_name: &str,
903        usage: TokenUsage,
904        card: RateCard,
905    ) -> Result<CostEstimate, CostError> {
906        self.price_usage(model_name, usage, card, UsageScope::SingleRequest)
907    }
908
909    /// The rate-card engine. `scope` says whether `usage` is one request,
910    /// which must fit the model's limits and may hit a long-context tier, or
911    /// a total over many requests, to which neither applies.
912    fn price_usage(
913        &self,
914        model_name: &str,
915        usage: TokenUsage,
916        card: RateCard,
917        scope: UsageScope,
918    ) -> Result<CostEstimate, CostError> {
919        let single_request = scope == UsageScope::SingleRequest;
920        let key = self
921            .resolve_model_key(model_name)
922            .ok_or_else(|| CostError::UnknownModel(model_name.to_string()))?;
923        let pricing = self
924            .pricing_table
925            .get(&key)
926            .ok_or_else(|| CostError::UnknownModel(model_name.to_string()))?;
927        let extras = self.extras.get(&key);
928
929        let billable = usage.input_tokens
930            + usage.output_tokens
931            + usage.cache_read_tokens
932            + usage.cache_write_5m_tokens
933            + usage.cache_write_1h_tokens;
934        if billable == 0 {
935            return Err(CostError::InvalidTokenCount);
936        }
937
938        // Context-window and max-output checks count only input + output;
939        // cache tokens are a billing dimension, not additional context.
940        if single_request {
941            if usage.input_tokens + usage.output_tokens > pricing.context_window {
942                return Err(CostError::InvalidTokenCount);
943            }
944            if let Some(max_output) = pricing.max_output_tokens {
945                if usage.output_tokens > max_output {
946                    return Err(CostError::InvalidTokenCount);
947                }
948            }
949        }
950
951        // 1. Base rates.
952        let mut base_in = pricing.input_cost_per_1k_tokens;
953        let mut base_out = pricing.output_cost_per_1k_tokens;
954
955        // 2. Long-context tier (base replacement): highest threshold below the
956        //    input size wins. It is a per-request rule, so an aggregate total
957        //    (whose request sizes are unknown) stays on the base rates.
958        if let Some(ex) = extras.filter(|_| single_request) {
959            if let Some(tier) = ex
960                .long_context_tiers
961                .iter()
962                .filter(|t| usage.input_tokens > t.threshold_tokens)
963                .max_by_key(|t| t.threshold_tokens)
964            {
965                base_in = tier.input_per_1k;
966                base_out = tier.output_per_1k;
967            }
968        }
969
970        // 3. Fast-mode (absolute base override, not a multiplier).
971        if card.fast_mode {
972            if let Some(fm) = extras.and_then(|e| e.fast_mode_rates) {
973                base_in = fm.input_per_1k;
974                base_out = fm.output_per_1k;
975            }
976        }
977
978        // 4. Tier multiplier (Cached is handled separately on the input leg).
979        let tier_mult = match card.tier {
980            PricingTier::Standard | PricingTier::Cached => 1.0,
981            PricingTier::Batch | PricingTier::Flex => 0.5,
982            PricingTier::Priority => match extras.and_then(|e| e.priority_multiplier) {
983                Some(m) => m,
984                None => {
985                    return Err(CostError::TierUnavailable {
986                        model: model_name.to_string(),
987                        tier: "priority".to_string(),
988                    })
989                }
990            },
991        };
992
993        // 5. Platform regional-endpoint premium (+10% on eligible models).
994        let mut platform_mult = 1.0;
995        if card.regional_endpoint
996            && extras
997                .map(|e| e.flags.supports_regional_premium)
998                .unwrap_or(false)
999        {
1000            platform_mult *= 1.10;
1001        }
1002
1003        // 6. Data-residency premium (+10% on eligible models).
1004        let mut residency_mult = 1.0;
1005        if card.data_residency == DataResidency::Us
1006            && extras
1007                .map(|e| e.flags.supports_data_residency)
1008                .unwrap_or(false)
1009        {
1010            residency_mult *= 1.10;
1011        }
1012
1013        let mult = tier_mult * platform_mult * residency_mult;
1014
1015        // 7. Effective per-1K rates. For the Cached tier, fresh input is billed
1016        //    at the cache-read rate (tier_mult is 1.0, so `mult` carries only
1017        //    the platform/residency premiums).
1018        let eff_in = if card.tier == PricingTier::Cached {
1019            extras
1020                .and_then(|e| e.cache_rates)
1021                .map(|c| c.read_per_1k)
1022                .unwrap_or(base_in)
1023                * mult
1024        } else {
1025            base_in * mult
1026        };
1027        let eff_out = base_out * mult;
1028
1029        // 8. Explicit cache legs. Batch halves them; priority never scales them.
1030        let cache_leg_mult = if card.tier == PricingTier::Batch {
1031            0.5
1032        } else {
1033            1.0
1034        };
1035        let mut cache_cost = 0.0;
1036        if let Some(cr) = extras.and_then(|e| e.cache_rates) {
1037            cache_cost +=
1038                (usage.cache_read_tokens as f64 / 1000.0) * cr.read_per_1k * cache_leg_mult;
1039            if let Some(w5) = cr.write_5m_per_1k {
1040                cache_cost += (usage.cache_write_5m_tokens as f64 / 1000.0) * w5 * cache_leg_mult;
1041            }
1042            if let Some(w1) = cr.write_1h_per_1k {
1043                cache_cost += (usage.cache_write_1h_tokens as f64 / 1000.0) * w1 * cache_leg_mult;
1044            }
1045        }
1046
1047        let input_cost = (usage.input_tokens as f64 / 1000.0) * eff_in;
1048        let output_cost = (usage.output_tokens as f64 / 1000.0) * eff_out;
1049        let total_cost = input_cost + output_cost + cache_cost;
1050
1051        Ok(CostEstimate {
1052            model_name: model_name.to_string(),
1053            input_tokens: usage.input_tokens,
1054            output_tokens: usage.output_tokens,
1055            input_cost,
1056            output_cost,
1057            cache_cost,
1058            total_cost,
1059            currency: "USD".to_string(),
1060        })
1061    }
1062
1063    /// Ergonomic shim: estimate cost under a [`RateCard`] without building a
1064    /// [`TokenUsage`] (no explicit cache tokens).
1065    pub fn estimate_cost_on(
1066        &self,
1067        model_name: &str,
1068        input_tokens: usize,
1069        output_tokens: usize,
1070        card: RateCard,
1071    ) -> Result<CostEstimate, CostError> {
1072        self.estimate_cost_with_card(
1073            model_name,
1074            TokenUsage {
1075                input_tokens,
1076                output_tokens,
1077                ..Default::default()
1078            },
1079            card,
1080        )
1081    }
1082
1083    /// Representative rate-card identifiers understood by [`RateCard::parse`].
1084    /// Any `platform × tier × modifier` combination is also accepted.
1085    pub fn available_rate_cards(&self) -> Vec<String> {
1086        [
1087            "standard",
1088            "batch",
1089            "cached",
1090            "priority",
1091            "flex",
1092            "first_party:fast",
1093            "first_party:standard,us",
1094            "bedrock:standard",
1095            "bedrock:batch",
1096            "bedrock:standard,regional",
1097            "vertex:standard",
1098            "vertex:batch",
1099            "vertex:standard,regional",
1100            "azure:standard",
1101            "azure:standard,regional",
1102        ]
1103        .into_iter()
1104        .map(String::from)
1105        .collect()
1106    }
1107
1108    /// Estimate the time-based context-cache *storage* cost (separate from the
1109    /// per-call read/write token costs). Returns 0.0 for models without a
1110    /// storage rate. Errors only on an unknown model.
1111    pub fn estimate_cache_storage_cost(
1112        &self,
1113        model_name: &str,
1114        cached_tokens: usize,
1115        hours: f64,
1116    ) -> Result<f64, CostError> {
1117        let key = self
1118            .resolve_model_key(model_name)
1119            .ok_or_else(|| CostError::UnknownModel(model_name.to_string()))?;
1120        let rate = self
1121            .extras
1122            .get(&key)
1123            .and_then(|e| e.cache_storage_per_mtok_hour)
1124            .unwrap_or(0.0);
1125        Ok((cached_tokens as f64 / 1_000_000.0) * rate * hours)
1126    }
1127
1128    /// Estimate cost from text (estimates tokens) under standard pricing.
1129    pub fn estimate_cost_from_text(
1130        &self,
1131        model_name: &str,
1132        input_text: &str,
1133        estimated_output_tokens: usize,
1134    ) -> Result<CostEstimate, CostError> {
1135        self.estimate_cost_from_text_with_card(
1136            model_name,
1137            input_text,
1138            estimated_output_tokens,
1139            RateCard::default(),
1140        )
1141    }
1142
1143    /// Estimate cost from text under a specific [`RateCard`].
1144    pub fn estimate_cost_from_text_with_card(
1145        &self,
1146        model_name: &str,
1147        input_text: &str,
1148        estimated_output_tokens: usize,
1149        card: RateCard,
1150    ) -> Result<CostEstimate, CostError> {
1151        let input_tokens = self.estimate_tokens(input_text);
1152        self.estimate_cost_on(model_name, input_tokens, estimated_output_tokens, card)
1153    }
1154
1155    /// Check budget status
1156    pub fn check_budget(&self, spent: f64, budget: f64) -> BudgetStatus {
1157        if budget <= 0.0 {
1158            return BudgetStatus {
1159                budget_usd: budget,
1160                spent_usd: spent,
1161                remaining_usd: budget - spent,
1162                percent_used: 100.0,
1163                status: BudgetAlert::Exceeded,
1164            };
1165        }
1166
1167        let percent_used = (spent / budget) * 100.0;
1168        let remaining = budget - spent;
1169
1170        let status = match percent_used {
1171            p if p >= 100.0 => BudgetAlert::Exceeded,
1172            p if p >= 95.0 => BudgetAlert::Critical,
1173            p if p >= 80.0 => BudgetAlert::Warning,
1174            _ => BudgetAlert::Ok,
1175        };
1176
1177        BudgetStatus {
1178            budget_usd: budget,
1179            spent_usd: spent,
1180            remaining_usd: remaining,
1181            percent_used: percent_used.min(100.0),
1182            status,
1183        }
1184    }
1185
1186    /// Get cheapest model for a given context size
1187    pub fn get_cheapest_model(&self, min_context_window: usize) -> Option<&ModelPricing> {
1188        self.pricing_table
1189            .values()
1190            .filter(|pricing| pricing.context_window >= min_context_window)
1191            .min_by(|a, b| {
1192                let avg_cost_a = (a.input_cost_per_1k_tokens + a.output_cost_per_1k_tokens) / 2.0;
1193                let avg_cost_b = (b.input_cost_per_1k_tokens + b.output_cost_per_1k_tokens) / 2.0;
1194                avg_cost_a
1195                    .partial_cmp(&avg_cost_b)
1196                    .unwrap_or(std::cmp::Ordering::Equal)
1197            })
1198    }
1199
1200    /// Get all models under a cost threshold (per 1k tokens average)
1201    pub fn get_models_under_cost(&self, max_cost_per_1k: f64) -> Vec<&ModelPricing> {
1202        self.pricing_table
1203            .values()
1204            .filter(|pricing| {
1205                let avg_cost =
1206                    (pricing.input_cost_per_1k_tokens + pricing.output_cost_per_1k_tokens) / 2.0;
1207                avg_cost <= max_cost_per_1k
1208            })
1209            .collect()
1210    }
1211
1212    /// Get models by provider
1213    pub fn get_models_by_provider(&self, provider: &str) -> Vec<&ModelPricing> {
1214        self.pricing_table
1215            .values()
1216            .filter(|pricing| pricing.provider.eq_ignore_ascii_case(provider))
1217            .collect()
1218    }
1219
1220    /// Compare cost between two models for given usage
1221    pub fn compare_models(
1222        &self,
1223        model_a: &str,
1224        model_b: &str,
1225        input_tokens: usize,
1226        output_tokens: usize,
1227    ) -> Result<ModelComparison, CostError> {
1228        let cost_a = self.estimate_cost(model_a, input_tokens, output_tokens)?;
1229        let cost_b = self.estimate_cost(model_b, input_tokens, output_tokens)?;
1230
1231        let savings = cost_a.total_cost - cost_b.total_cost;
1232        let percent_difference = if cost_a.total_cost > 0.0 {
1233            (savings / cost_a.total_cost) * 100.0
1234        } else {
1235            0.0
1236        };
1237
1238        Ok(ModelComparison {
1239            model_a: cost_a,
1240            model_b: cost_b,
1241            cheaper_model: if savings > 0.0 { model_b } else { model_a }.to_string(),
1242            savings: savings.abs(),
1243            percent_difference: percent_difference.abs(),
1244        })
1245    }
1246
1247    /// Add custom model pricing, replacing any model of the same name.
1248    ///
1249    /// The model is priced at exactly these flat rates: rate-card data a
1250    /// built-in model of that name carried (long-context tiers, cache and
1251    /// fast-mode rates, priority multiplier, premium eligibility) is dropped
1252    /// rather than left to bill the override at the old model's rates.
1253    pub fn add_model(&mut self, pricing: ModelPricing) {
1254        self.extras.remove(&pricing.model_name);
1255        self.pricing_table
1256            .insert(pricing.model_name.clone(), pricing);
1257    }
1258
1259    /// Remove a model from pricing table
1260    pub fn remove_model(&mut self, model_name: &str) -> Option<ModelPricing> {
1261        self.extras.remove(model_name);
1262        self.pricing_table.remove(model_name)
1263    }
1264
1265    /// Add or override models from a JSON pricing document, so a model can be
1266    /// priced without waiting for a release. Returns how many were loaded.
1267    ///
1268    /// The document is an object with a `models` array; each entry has the
1269    /// fields of [`ModelPricing`], with prices in USD per 1,000 tokens:
1270    ///
1271    /// ```json
1272    /// {
1273    ///   "models": [
1274    ///     {
1275    ///       "model_name": "my-model",
1276    ///       "provider": "acme",
1277    ///       "input_cost_per_1k_tokens": 0.0025,
1278    ///       "output_cost_per_1k_tokens": 0.01,
1279    ///       "context_window": 128000,
1280    ///       "max_output_tokens": 16384
1281    ///     }
1282    ///   ]
1283    /// }
1284    /// ```
1285    ///
1286    /// `max_output_tokens` may be omitted or `null` for no output cap. Each
1287    /// entry is registered as by [`Self::add_model`], so it replaces a
1288    /// built-in model of the same name outright. The document is validated
1289    /// as a whole: on any error nothing is loaded.
1290    pub fn load_pricing_json(&mut self, json: &str) -> Result<usize, CostError> {
1291        #[derive(Deserialize)]
1292        struct PricingDocument {
1293            models: Vec<ModelPricing>,
1294        }
1295
1296        let document: PricingDocument =
1297            serde_json::from_str(json).map_err(|e| CostError::InvalidPricing(e.to_string()))?;
1298
1299        for model in &document.models {
1300            let valid_rate = |rate: f64| rate.is_finite() && rate >= 0.0;
1301            let problem = if model.model_name.trim().is_empty() {
1302                Some("model_name is empty")
1303            } else if !valid_rate(model.input_cost_per_1k_tokens)
1304                || !valid_rate(model.output_cost_per_1k_tokens)
1305            {
1306                Some("costs must be finite and non-negative")
1307            } else if model.context_window == 0 {
1308                Some("context_window must be greater than 0")
1309            } else {
1310                None
1311            };
1312            if let Some(problem) = problem {
1313                return Err(CostError::InvalidPricing(format!(
1314                    "model '{}': {}",
1315                    model.model_name, problem
1316                )));
1317            }
1318        }
1319
1320        let count = document.models.len();
1321        for model in document.models {
1322            self.add_model(model);
1323        }
1324        Ok(count)
1325    }
1326
1327    /// [`Self::load_pricing_json`] from a file.
1328    pub fn load_pricing_file(
1329        &mut self,
1330        path: impl AsRef<std::path::Path>,
1331    ) -> Result<usize, CostError> {
1332        let path = path.as_ref();
1333        let json = std::fs::read_to_string(path)
1334            .map_err(|e| CostError::InvalidPricing(format!("{}: {}", path.display(), e)))?;
1335        self.load_pricing_json(&json)
1336    }
1337
1338    /// Get all available models
1339    pub fn get_all_models(&self) -> Vec<&ModelPricing> {
1340        self.pricing_table.values().collect()
1341    }
1342
1343    /// Estimate tokens from text (rough approximation: chars / 4)
1344    fn estimate_tokens(&self, text: &str) -> usize {
1345        // Basic tokenization approximation
1346        // Real-world implementations should use proper tokenizers like tiktoken
1347        let char_count = text.len();
1348
1349        // Account for different languages and complexity
1350        let token_estimate = if text.is_ascii() {
1351            // English text: roughly 4 chars per token
1352            (char_count as f64 / 4.0).ceil() as usize
1353        } else {
1354            // Non-ASCII text: typically more tokens
1355            (char_count as f64 / 3.0).ceil() as usize
1356        };
1357
1358        // Add some tokens for special tokens, formatting, etc.
1359        token_estimate + (token_estimate / 20) // Add 5% overhead
1360    }
1361
1362    /// Calculate monthly cost projection under standard pricing.
1363    pub fn project_monthly_cost(
1364        &self,
1365        model_name: &str,
1366        daily_input_tokens: usize,
1367        daily_output_tokens: usize,
1368        days_per_month: f64,
1369    ) -> Result<CostProjection, CostError> {
1370        self.project_monthly_cost_with_card(
1371            model_name,
1372            daily_input_tokens,
1373            daily_output_tokens,
1374            days_per_month,
1375            RateCard::default(),
1376        )
1377    }
1378
1379    /// Calculate monthly cost projection under a specific [`RateCard`].
1380    ///
1381    /// The daily token counts are totals across many requests, so they are
1382    /// not held to the model's per-request context window or output cap, and
1383    /// are priced at the base rates (long-context tiers depend on individual
1384    /// request sizes, which a daily total does not carry).
1385    pub fn project_monthly_cost_with_card(
1386        &self,
1387        model_name: &str,
1388        daily_input_tokens: usize,
1389        daily_output_tokens: usize,
1390        days_per_month: f64,
1391        card: RateCard,
1392    ) -> Result<CostProjection, CostError> {
1393        let daily_cost = self.price_usage(
1394            model_name,
1395            TokenUsage {
1396                input_tokens: daily_input_tokens,
1397                output_tokens: daily_output_tokens,
1398                ..Default::default()
1399            },
1400            card,
1401            UsageScope::Aggregate,
1402        )?;
1403        let monthly_cost = daily_cost.total_cost * days_per_month;
1404
1405        Ok(CostProjection {
1406            model_name: model_name.to_string(),
1407            daily_cost: daily_cost.total_cost,
1408            monthly_cost,
1409            annual_cost: monthly_cost * 12.0,
1410            currency: "USD".to_string(),
1411        })
1412    }
1413}
1414
1415impl Default for CostCalculator {
1416    fn default() -> Self {
1417        Self::new()
1418    }
1419}
1420
1421#[derive(Debug, Clone)]
1422pub struct ModelComparison {
1423    pub model_a: CostEstimate,
1424    pub model_b: CostEstimate,
1425    pub cheaper_model: String,
1426    pub savings: f64,
1427    pub percent_difference: f64,
1428}
1429
1430#[derive(Debug, Clone, Serialize, Deserialize)]
1431pub struct CostProjection {
1432    pub model_name: String,
1433    pub daily_cost: f64,
1434    pub monthly_cost: f64,
1435    pub annual_cost: f64,
1436    pub currency: String,
1437}
1438
1439#[derive(Error, Debug, Clone, PartialEq)]
1440pub enum CostError {
1441    #[error("Unknown model: {0}")]
1442    UnknownModel(String),
1443    #[error("Invalid token count")]
1444    InvalidTokenCount,
1445    #[error("Unknown rate card: {0}")]
1446    UnknownRateCard(String),
1447    #[error("Pricing tier '{tier}' is not available for model '{model}'")]
1448    TierUnavailable { model: String, tier: String },
1449    #[error("Invalid pricing data: {0}")]
1450    InvalidPricing(String),
1451}
1452
1453#[cfg(test)]
1454mod tests {
1455    use super::*;
1456
1457    #[test]
1458    fn normalize_model_id_strips_platform_qualifiers() {
1459        for (raw, expected) in [
1460            ("us.amazon.nova-pro-v1:0", "nova-pro"),
1461            ("us.amazon.nova-micro-v1:0", "nova-micro"),
1462            ("eu.anthropic.claude-sonnet-4-6", "claude-sonnet-4-6"),
1463            (
1464                "us.anthropic.claude-haiku-4-5-20251001-v1:0",
1465                "claude-haiku-4-5",
1466            ),
1467            ("amazon.titan-embed-text-v2:0", "titan-embed-text"),
1468            ("cohere.cohere-embed-v3:0", "cohere-embed"),
1469            ("gpt-4o", "gpt-4o"),
1470        ] {
1471            assert_eq!(CostCalculator::normalize_model_id(raw), expected, "{raw}");
1472        }
1473    }
1474
1475    #[test]
1476    fn platform_qualified_bedrock_ids_price_via_normalization() {
1477        let calc = CostCalculator::new();
1478        let direct = calc.estimate_cost("nova-pro", 100_000, 1_000).unwrap();
1479        let qualified = calc
1480            .estimate_cost("us.amazon.nova-pro-v1:0", 100_000, 1_000)
1481            .unwrap();
1482        assert_eq!(direct.total_cost, qualified.total_cost);
1483        // 100k input at 0.8/MTok + 1k output at 3.2/MTok
1484        assert!((direct.total_cost - (0.08 + 0.0032)).abs() < 1e-9);
1485    }
1486
1487    #[test]
1488    fn nova_and_embedding_models_price_at_bedrock_list_rates() {
1489        let calc = CostCalculator::new();
1490        for (model, input_rate, output_rate, input_tokens, output_tokens) in [
1491            ("nova-premier", 2.5, 12.5, 100_000, 1_000),
1492            ("nova-pro", 0.8, 3.2, 100_000, 1_000),
1493            ("nova-lite", 0.06, 0.24, 100_000, 1_000),
1494            ("nova-micro", 0.035, 0.14, 100_000, 1_000),
1495            ("titan-embed-text", 0.1, 0.0, 8_000, 0),
1496            ("cohere-embed", 0.1, 0.0, 8_000, 0),
1497        ] {
1498            let est = calc
1499                .estimate_cost(model, input_tokens, output_tokens)
1500                .unwrap();
1501            let expected = (input_tokens as f64) * input_rate / 1_000_000.0
1502                + (output_tokens as f64) * output_rate / 1_000_000.0;
1503            assert!(
1504                (est.total_cost - expected).abs() < 1e-9,
1505                "{model}: {} vs {expected}",
1506                est.total_cost
1507            );
1508        }
1509    }
1510
1511    #[test]
1512    fn normalize_model_id_handles_provider_and_gateway_spellings() {
1513        for (raw, expected) in [
1514            ("gpt-4o-2024-08-06", "gpt-4o"),
1515            ("gpt-4o-mini-2024-07-18", "gpt-4o-mini"),
1516            ("claude-3-5-haiku-20241022", "claude-haiku-3-5"),
1517            ("claude-3-5-haiku-latest", "claude-haiku-3-5"),
1518            ("claude-3-5-sonnet-20241022", "claude-3-5-sonnet"),
1519            ("models/gemini-2.5-pro", "gemini-2.5-pro"),
1520            (
1521                "publishers/google/models/gemini-2.5-flash",
1522                "gemini-2.5-flash",
1523            ),
1524            ("anthropic/claude-sonnet-4-6", "claude-sonnet-4-6"),
1525            ("openai/gpt-4o-2024-08-06", "gpt-4o"),
1526            ("claude-sonnet-4-5@20250929", "claude-sonnet-4-5"),
1527            ("claude-3-5-haiku@20241022", "claude-haiku-3-5"),
1528            (
1529                "bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
1530                "claude-haiku-4-5",
1531            ),
1532            // Not date stamps: left alone.
1533            ("gpt-5.4", "gpt-5.4"),
1534            ("claude-opus-4-1", "claude-opus-4-1"),
1535            ("gemini-2.5-flash-lite", "gemini-2.5-flash-lite"),
1536            ("20241022", "20241022"),
1537        ] {
1538            assert_eq!(CostCalculator::normalize_model_id(raw), expected, "{raw}");
1539        }
1540    }
1541
1542    #[test]
1543    fn normalized_ids_price_like_their_table_key() {
1544        let calc = CostCalculator::new();
1545        for (raw, key) in [
1546            ("gpt-4o-2024-08-06", "gpt-4o"),
1547            ("claude-3-5-haiku-20241022", "claude-haiku-3-5"),
1548            ("models/gemini-2.5-pro", "gemini-2.5-pro"),
1549            ("anthropic/claude-sonnet-4-6", "claude-sonnet-4-6"),
1550            ("claude-sonnet-4-5@20250929", "claude-sonnet-4-5"),
1551        ] {
1552            let a = calc.estimate_cost(raw, 10_000, 1_000).unwrap();
1553            let b = calc.estimate_cost(key, 10_000, 1_000).unwrap();
1554            assert_eq!(a.total_cost, b.total_cost, "{raw}");
1555        }
1556    }
1557
1558    #[test]
1559    fn monthly_projection_accepts_volumes_beyond_one_context_window() {
1560        let calc = CostCalculator::new();
1561        // gpt-4 has an 8,192-token window and a 4,096-token output cap; a
1562        // day's traffic is many requests and far exceeds both.
1563        let projection = calc
1564            .project_monthly_cost("gpt-4", 50_000_000, 10_000_000, 30.0)
1565            .unwrap();
1566        let daily = 50_000.0 * 0.03 + 10_000.0 * 0.06;
1567        assert!((projection.daily_cost - daily).abs() < 1e-6);
1568        assert!((projection.monthly_cost - daily * 30.0).abs() < 1e-6);
1569
1570        // A single request of that size is still rejected.
1571        assert!(matches!(
1572            calc.estimate_cost("gpt-4", 50_000_000, 0),
1573            Err(CostError::InvalidTokenCount)
1574        ));
1575    }
1576
1577    #[test]
1578    fn monthly_projection_does_not_apply_long_context_tier_to_totals() {
1579        let calc = CostCalculator::new();
1580        // gemini-2.5-pro bills requests over 200K input tokens at a higher
1581        // tier; a 10M-token day made of small requests must not hit it.
1582        let projection = calc
1583            .project_monthly_cost("gemini-2.5-pro", 10_000_000, 0, 1.0)
1584            .unwrap();
1585        assert!((projection.daily_cost - 12.5).abs() < 1e-9);
1586    }
1587
1588    #[test]
1589    fn add_model_override_drops_the_old_models_rate_card_data() {
1590        let mut calc = CostCalculator::new();
1591        calc.add_model(ModelPricing {
1592            model_name: "gemini-2.5-pro".to_string(),
1593            provider: "google".to_string(),
1594            input_cost_per_1k_tokens: 0.001,
1595            output_cost_per_1k_tokens: 0.002,
1596            context_window: 1_048_576,
1597            max_output_tokens: None,
1598        });
1599
1600        // 300K input is over the built-in model's 200K long-context
1601        // threshold; the override has no such tier.
1602        let est = calc.estimate_cost("gemini-2.5-pro", 300_000, 0).unwrap();
1603        assert!((est.total_cost - 0.3).abs() < 1e-9, "{}", est.total_cost);
1604        assert_eq!(
1605            calc.estimate_cache_storage_cost("gemini-2.5-pro", 1_000_000, 1.0),
1606            Ok(0.0)
1607        );
1608
1609        calc.remove_model("gemini-2.5-pro");
1610        assert!(!calc.extras.contains_key("gemini-2.5-pro"));
1611    }
1612
1613    #[test]
1614    fn cache_storage_cost_normalizes_the_model_id() {
1615        let calc = CostCalculator::new();
1616        let direct = calc
1617            .estimate_cache_storage_cost("gemini-2.5-pro", 1_000_000, 2.0)
1618            .unwrap();
1619        let qualified = calc
1620            .estimate_cache_storage_cost("models/gemini-2.5-pro", 1_000_000, 2.0)
1621            .unwrap();
1622        assert!(direct > 0.0);
1623        assert_eq!(direct, qualified);
1624    }
1625
1626    #[test]
1627    fn gpt_4o_allows_its_full_output_cap() {
1628        let calc = CostCalculator::new();
1629        assert!(calc.estimate_cost("gpt-4o", 1_000, 16_384).is_ok());
1630        assert!(calc.estimate_cost("gpt-4o", 1_000, 16_385).is_err());
1631    }
1632
1633    #[test]
1634    fn load_pricing_json_adds_and_overrides_models() {
1635        let mut calc = CostCalculator::new();
1636        let loaded = calc
1637            .load_pricing_json(
1638                r#"{"models": [
1639                    {"model_name": "acme-large", "provider": "acme",
1640                     "input_cost_per_1k_tokens": 0.002,
1641                     "output_cost_per_1k_tokens": 0.004,
1642                     "context_window": 100000},
1643                    {"model_name": "gpt-4", "provider": "openai",
1644                     "input_cost_per_1k_tokens": 0.01,
1645                     "output_cost_per_1k_tokens": 0.02,
1646                     "context_window": 8192, "max_output_tokens": 4096}
1647                ]}"#,
1648            )
1649            .unwrap();
1650        assert_eq!(loaded, 2);
1651
1652        let est = calc.estimate_cost("acme-large", 1_000, 1_000).unwrap();
1653        assert!((est.total_cost - 0.006).abs() < 1e-12);
1654        // No max_output_tokens given: no output cap.
1655        assert!(calc.estimate_cost("acme-large", 1_000, 90_000).is_ok());
1656        let est = calc.estimate_cost("gpt-4", 1_000, 1_000).unwrap();
1657        assert!((est.total_cost - 0.03).abs() < 1e-12);
1658    }
1659
1660    #[test]
1661    fn load_pricing_json_rejects_bad_documents_without_loading_any() {
1662        let mut calc = CostCalculator::new();
1663        let before = calc.get_all_models().len();
1664
1665        for bad in [
1666            "not json",
1667            r#"{"models": [{"model_name": "x"}]}"#,
1668            r#"{"models": [
1669                {"model_name": "ok", "provider": "p", "input_cost_per_1k_tokens": 1.0,
1670                 "output_cost_per_1k_tokens": 1.0, "context_window": 10},
1671                {"model_name": "neg", "provider": "p", "input_cost_per_1k_tokens": -1.0,
1672                 "output_cost_per_1k_tokens": 1.0, "context_window": 10}
1673            ]}"#,
1674            r#"{"models": [{"model_name": " ", "provider": "p",
1675                "input_cost_per_1k_tokens": 1.0, "output_cost_per_1k_tokens": 1.0,
1676                "context_window": 10}]}"#,
1677            r#"{"models": [{"model_name": "zero", "provider": "p",
1678                "input_cost_per_1k_tokens": 1.0, "output_cost_per_1k_tokens": 1.0,
1679                "context_window": 0}]}"#,
1680        ] {
1681            assert!(
1682                matches!(
1683                    calc.load_pricing_json(bad),
1684                    Err(CostError::InvalidPricing(_))
1685                ),
1686                "{bad}"
1687            );
1688        }
1689        assert_eq!(calc.get_all_models().len(), before);
1690    }
1691
1692    #[test]
1693    fn load_pricing_file_reads_the_same_schema() {
1694        let dir = tempfile::tempdir().unwrap();
1695        let path = dir.path().join("pricing.json");
1696        std::fs::write(
1697            &path,
1698            r#"{"models": [{"model_name": "from-file", "provider": "p",
1699                "input_cost_per_1k_tokens": 0.001, "output_cost_per_1k_tokens": 0.001,
1700                "context_window": 1000}]}"#,
1701        )
1702        .unwrap();
1703
1704        let mut calc = CostCalculator::new();
1705        assert_eq!(calc.load_pricing_file(&path), Ok(1));
1706        assert!(calc.estimate_cost("from-file", 10, 10).is_ok());
1707        assert!(matches!(
1708            calc.load_pricing_file(dir.path().join("missing.json")),
1709            Err(CostError::InvalidPricing(_))
1710        ));
1711    }
1712
1713    #[test]
1714    fn test_cost_estimation() {
1715        let calculator = CostCalculator::new();
1716
1717        let estimate = calculator.estimate_cost("gpt-4", 1000, 500).unwrap();
1718
1719        assert_eq!(estimate.model_name, "gpt-4");
1720        assert_eq!(estimate.input_tokens, 1000);
1721        assert_eq!(estimate.output_tokens, 500);
1722        assert_eq!(estimate.input_cost, 0.03); // 1000 tokens = 1k tokens * $0.03
1723        assert_eq!(estimate.output_cost, 0.03); // 500 tokens = 0.5k tokens * $0.06
1724        assert_eq!(estimate.total_cost, 0.06);
1725        assert_eq!(estimate.currency, "USD");
1726    }
1727
1728    #[test]
1729    fn test_unknown_model() {
1730        let calculator = CostCalculator::new();
1731        let result = calculator.estimate_cost("unknown-model", 1000, 500);
1732
1733        assert!(matches!(result, Err(CostError::UnknownModel(_))));
1734    }
1735
1736    #[test]
1737    fn test_invalid_token_count() {
1738        let calculator = CostCalculator::new();
1739
1740        // Zero tokens
1741        let result = calculator.estimate_cost("gpt-4", 0, 0);
1742        assert!(matches!(result, Err(CostError::InvalidTokenCount)));
1743
1744        // Exceeding context window (gpt-4 has 8192)
1745        let result = calculator.estimate_cost("gpt-4", 10000, 0);
1746        assert!(matches!(result, Err(CostError::InvalidTokenCount)));
1747
1748        // Exceeding max output tokens (gpt-4 has 4096)
1749        let result = calculator.estimate_cost("gpt-4", 1000, 5000);
1750        assert!(matches!(result, Err(CostError::InvalidTokenCount)));
1751    }
1752
1753    #[test]
1754    fn test_budget_status() {
1755        let calculator = CostCalculator::new();
1756
1757        // OK status
1758        let status = calculator.check_budget(50.0, 100.0);
1759        assert_eq!(status.status, BudgetAlert::Ok);
1760        assert_eq!(status.percent_used, 50.0);
1761        assert_eq!(status.remaining_usd, 50.0);
1762
1763        // Warning status
1764        let status = calculator.check_budget(85.0, 100.0);
1765        assert_eq!(status.status, BudgetAlert::Warning);
1766
1767        // Critical status
1768        let status = calculator.check_budget(96.0, 100.0);
1769        assert_eq!(status.status, BudgetAlert::Critical);
1770
1771        // Exceeded status
1772        let status = calculator.check_budget(110.0, 100.0);
1773        assert_eq!(status.status, BudgetAlert::Exceeded);
1774        assert_eq!(status.remaining_usd, -10.0);
1775    }
1776
1777    #[test]
1778    fn test_cheapest_model() {
1779        let calculator = CostCalculator::new();
1780
1781        let cheapest = calculator.get_cheapest_model(8000);
1782        assert!(cheapest.is_some());
1783        let model = cheapest.unwrap();
1784
1785        // Should be one of the cheaper models with sufficient context
1786        assert!(model.context_window >= 8000);
1787    }
1788
1789    #[test]
1790    fn test_models_under_cost() {
1791        let calculator = CostCalculator::new();
1792
1793        let cheap_models = calculator.get_models_under_cost(0.01);
1794        assert!(!cheap_models.is_empty());
1795
1796        // All returned models should have average cost <= 0.01
1797        for model in &cheap_models {
1798            let avg_cost = (model.input_cost_per_1k_tokens + model.output_cost_per_1k_tokens) / 2.0;
1799            assert!(avg_cost <= 0.01);
1800        }
1801    }
1802
1803    #[test]
1804    fn test_models_by_provider() {
1805        let calculator = CostCalculator::new();
1806
1807        let openai_models = calculator.get_models_by_provider("openai");
1808        assert!(!openai_models.is_empty());
1809        for model in &openai_models {
1810            assert_eq!(model.provider, "openai");
1811        }
1812
1813        let anthropic_models = calculator.get_models_by_provider("anthropic");
1814        assert!(!anthropic_models.is_empty());
1815        for model in &anthropic_models {
1816            assert_eq!(model.provider, "anthropic");
1817        }
1818    }
1819
1820    #[test]
1821    fn test_model_comparison() {
1822        let calculator = CostCalculator::new();
1823
1824        let comparison = calculator
1825            .compare_models("gpt-4", "gpt-3.5-turbo", 1000, 500)
1826            .unwrap();
1827
1828        // GPT-3.5-turbo should be cheaper than GPT-4
1829        assert_eq!(comparison.cheaper_model, "gpt-3.5-turbo");
1830        assert!(comparison.savings > 0.0);
1831        assert!(comparison.percent_difference > 0.0);
1832    }
1833
1834    #[test]
1835    fn test_cost_from_text() {
1836        let calculator = CostCalculator::new();
1837
1838        let text = "Hello, world!";
1839        let estimate = calculator
1840            .estimate_cost_from_text("gpt-3.5-turbo", text, 100)
1841            .unwrap();
1842
1843        assert!(estimate.input_tokens > 0);
1844        assert_eq!(estimate.output_tokens, 100);
1845        assert!(estimate.total_cost > 0.0);
1846    }
1847
1848    #[test]
1849    fn test_token_estimation() {
1850        let calculator = CostCalculator::new();
1851
1852        // English text
1853        let english_text = "Hello, world! This is a test.";
1854        let tokens = calculator.estimate_tokens(english_text);
1855
1856        // Should be roughly chars/4 with some overhead
1857        let expected = ((english_text.len() as f64 / 4.0).ceil() as usize * 105) / 100; // 5% overhead
1858        assert!(tokens >= expected - 2 && tokens <= expected + 2);
1859
1860        // Empty text
1861        assert_eq!(calculator.estimate_tokens(""), 0);
1862    }
1863
1864    #[test]
1865    fn test_custom_model() {
1866        let mut calculator = CostCalculator::new();
1867
1868        let custom_model = ModelPricing {
1869            model_name: "custom-model".to_string(),
1870            provider: "custom".to_string(),
1871            input_cost_per_1k_tokens: 0.001,
1872            output_cost_per_1k_tokens: 0.002,
1873            context_window: 4096,
1874            max_output_tokens: Some(2048),
1875        };
1876
1877        calculator.add_model(custom_model.clone());
1878
1879        let estimate = calculator.estimate_cost("custom-model", 1000, 500).unwrap();
1880        assert_eq!(estimate.input_cost, 0.001);
1881        assert_eq!(estimate.output_cost, 0.001);
1882        assert_eq!(estimate.total_cost, 0.002);
1883
1884        // Test removal
1885        let removed = calculator.remove_model("custom-model");
1886        assert!(removed.is_some());
1887        assert_eq!(removed.unwrap().model_name, "custom-model");
1888
1889        // Should no longer be available
1890        let result = calculator.estimate_cost("custom-model", 1000, 500);
1891        assert!(matches!(result, Err(CostError::UnknownModel(_))));
1892    }
1893
1894    #[test]
1895    fn test_cost_projection() {
1896        let calculator = CostCalculator::new();
1897
1898        let projection = calculator
1899            .project_monthly_cost("gpt-4", 4000, 2000, 30.0)
1900            .unwrap();
1901
1902        assert_eq!(projection.model_name, "gpt-4");
1903        assert!(projection.daily_cost > 0.0);
1904        assert_eq!(projection.monthly_cost, projection.daily_cost * 30.0);
1905        assert_eq!(projection.annual_cost, projection.monthly_cost * 12.0);
1906    }
1907
1908    #[test]
1909    fn test_all_default_models_available() {
1910        let calculator = CostCalculator::new();
1911
1912        // Test all default models (legacy + modern) can be used for cost estimation
1913        let test_models = [
1914            // Legacy
1915            "gpt-4",
1916            "gpt-4-turbo",
1917            "gpt-3.5-turbo",
1918            "gpt-4o",
1919            "gpt-4o-mini",
1920            "claude-3-opus",
1921            "claude-3-sonnet",
1922            "claude-3-haiku",
1923            "claude-3-5-sonnet",
1924            "gemini-pro",
1925            "gemini-ultra",
1926            // Modern (2026)
1927            "claude-opus-4-8",
1928            "claude-opus-4-7",
1929            "claude-opus-4-6",
1930            "claude-opus-4-5",
1931            "claude-opus-4-1",
1932            "claude-sonnet-4-6",
1933            "claude-sonnet-4-5",
1934            "claude-haiku-4-5",
1935            "claude-haiku-3-5",
1936            "gpt-5.5",
1937            "gpt-5.5-pro",
1938            "gpt-5.4",
1939            "gpt-5.4-mini",
1940            "gpt-5.4-nano",
1941            "gpt-5.4-pro",
1942            "gemini-3.5-flash",
1943            "gemini-3.1-pro",
1944            "gemini-3.1-flash-lite",
1945            "gemini-3-flash",
1946            "gemini-2.5-pro",
1947            "gemini-2.5-flash",
1948            "gemini-2.5-flash-lite",
1949        ];
1950
1951        for model in &test_models {
1952            let result = calculator.estimate_cost(model, 1000, 500);
1953            assert!(result.is_ok(), "Model {} should be available", model);
1954        }
1955    }
1956
1957    #[test]
1958    fn test_rate_card_default_equals_standard() {
1959        let calc = CostCalculator::new();
1960        let plain = calc.estimate_cost("claude-opus-4-8", 1000, 500).unwrap();
1961        let standard = calc
1962            .estimate_cost_on(
1963                "claude-opus-4-8",
1964                1000,
1965                500,
1966                RateCard::parse("standard").unwrap(),
1967            )
1968            .unwrap();
1969        let default = calc
1970            .estimate_cost_on("claude-opus-4-8", 1000, 500, RateCard::default())
1971            .unwrap();
1972        assert_eq!(plain.total_cost, standard.total_cost);
1973        assert_eq!(plain.total_cost, default.total_cost);
1974        assert_eq!(plain.cache_cost, 0.0);
1975    }
1976
1977    #[test]
1978    fn test_rate_card_batch_is_half() {
1979        let calc = CostCalculator::new();
1980        // 500K in / 50K out stays within the 1M window and 64K max-output.
1981        let standard = calc
1982            .estimate_cost("claude-opus-4-8", 500_000, 50_000)
1983            .unwrap();
1984        let batch = calc
1985            .estimate_cost_on(
1986                "claude-opus-4-8",
1987                500_000,
1988                50_000,
1989                RateCard::parse("batch").unwrap(),
1990            )
1991            .unwrap();
1992        assert!((batch.total_cost - 0.5 * standard.total_cost).abs() < 1e-9);
1993    }
1994
1995    #[test]
1996    fn test_rate_card_cache_read_is_tenth_of_input() {
1997        let calc = CostCalculator::new();
1998        let usage = TokenUsage {
1999            input_tokens: 0,
2000            output_tokens: 1000,
2001            cache_read_tokens: 100_000,
2002            ..Default::default()
2003        };
2004        let est = calc
2005            .estimate_cost_with_card("claude-opus-4-8", usage, RateCard::default())
2006            .unwrap();
2007        // Cache-read rate (0.0005/1K) is 0.1x the base input rate (0.005/1K).
2008        let base_input_for_100k = (100_000.0 / 1000.0) * 0.005;
2009        assert!((est.cache_cost - 0.1 * base_input_for_100k).abs() < 1e-9);
2010    }
2011
2012    #[test]
2013    fn test_rate_card_bedrock_regional_premium() {
2014        let calc = CostCalculator::new();
2015        let standard = calc.estimate_cost("claude-opus-4-8", 1000, 500).unwrap();
2016        let regional = calc
2017            .estimate_cost_on(
2018                "claude-opus-4-8",
2019                1000,
2020                500,
2021                RateCard::parse("bedrock:regional").unwrap(),
2022            )
2023            .unwrap();
2024        assert!((regional.total_cost - 1.10 * standard.total_cost).abs() < 1e-9);
2025    }
2026
2027    #[test]
2028    fn test_rate_card_data_residency_premium() {
2029        let calc = CostCalculator::new();
2030        let standard = calc.estimate_cost("claude-sonnet-4-6", 1000, 500).unwrap();
2031        let us = calc
2032            .estimate_cost_on(
2033                "claude-sonnet-4-6",
2034                1000,
2035                500,
2036                RateCard::parse("first_party:standard,us").unwrap(),
2037            )
2038            .unwrap();
2039        assert!((us.total_cost - 1.10 * standard.total_cost).abs() < 1e-9);
2040    }
2041
2042    #[test]
2043    fn test_rate_card_fast_mode_override() {
2044        let calc = CostCalculator::new();
2045        // opus-4-8 fast-mode rates are 10/50 per MTok (0.010/0.050 per 1K).
2046        let fast = calc
2047            .estimate_cost_on(
2048                "claude-opus-4-8",
2049                1000,
2050                1000,
2051                RateCard::parse("fast").unwrap(),
2052            )
2053            .unwrap();
2054        let expected = (1000.0 / 1000.0) * 0.010 + (1000.0 / 1000.0) * 0.050;
2055        assert!((fast.total_cost - expected).abs() < 1e-9);
2056        let standard = calc.estimate_cost("claude-opus-4-8", 1000, 1000).unwrap();
2057        assert!(fast.total_cost > standard.total_cost);
2058    }
2059
2060    #[test]
2061    fn test_rate_card_long_context_tier() {
2062        let calc = CostCalculator::new();
2063        // gemini-2.5-pro: base 1.25/10 per MTok, >200K tier 2.5/15 per MTok.
2064        let below = calc.estimate_cost("gemini-2.5-pro", 150_000, 1000).unwrap();
2065        let above = calc.estimate_cost("gemini-2.5-pro", 250_000, 1000).unwrap();
2066        assert!((below.input_cost - (150_000.0 / 1000.0) * 0.00125).abs() < 1e-9);
2067        assert!((above.input_cost - (250_000.0 / 1000.0) * 0.0025).abs() < 1e-9);
2068    }
2069
2070    #[test]
2071    fn test_rate_card_priority_and_errors() {
2072        // Unknown token in a rate card.
2073        assert!(matches!(
2074            RateCard::parse("totally-bogus"),
2075            Err(CostError::UnknownRateCard(_))
2076        ));
2077
2078        let calc = CostCalculator::new();
2079        // gpt-5.5 has a priority multiplier (2.5x); gpt-5.4-pro does not.
2080        let standard = calc.estimate_cost("gpt-5.5", 1000, 500).unwrap();
2081        let priority = calc
2082            .estimate_cost_on("gpt-5.5", 1000, 500, RateCard::parse("priority").unwrap())
2083            .unwrap();
2084        assert!((priority.total_cost - 2.5 * standard.total_cost).abs() < 1e-9);
2085
2086        let unavailable = calc.estimate_cost_on(
2087            "gpt-5.4-pro",
2088            1000,
2089            500,
2090            RateCard::parse("priority").unwrap(),
2091        );
2092        assert!(matches!(
2093            unavailable,
2094            Err(CostError::TierUnavailable { .. })
2095        ));
2096    }
2097
2098    #[test]
2099    fn test_cache_storage_cost() {
2100        let calc = CostCalculator::new();
2101        // gemini-2.5-pro storage is $4.50 per MTok per hour.
2102        let cost = calc
2103            .estimate_cache_storage_cost("gemini-2.5-pro", 1_000_000, 2.0)
2104            .unwrap();
2105        assert!((cost - 9.0).abs() < 1e-9);
2106        // Models without a storage rate return 0.0 (not an error).
2107        let none = calc
2108            .estimate_cache_storage_cost("gpt-4", 1_000_000, 2.0)
2109            .unwrap();
2110        assert_eq!(none, 0.0);
2111    }
2112}