nika-engine 0.47.0

Nika workflow engine — embeddable runtime, provider, DAG, and binding logic
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
//! Cost calculation for LLM providers
//!
//! Provides pricing tables and cost calculation for all supported providers.
//! Prices are in USD per million tokens.
//!
//! ## Usage
//!
//! ```rust,ignore
//! use nika::provider::cost::{calculate_cost, ProviderKind};
//!
//! // Calculate cost for 1000 input tokens and 500 output tokens
//! let cost = calculate_cost(ProviderKind::Claude, "claude-sonnet-4-6", 1000, 500);
//! println!("Cost: ${:.6}", cost);
//! ```

use rustc_hash::FxHashMap;
use std::sync::LazyLock;

// ═══════════════════════════════════════════════════════════════════════════
// PROVIDER KIND
// ═══════════════════════════════════════════════════════════════════════════

/// Provider kind for cost calculation
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ProviderKind {
    Claude,
    OpenAI,
    Mistral,
    Groq,
    DeepSeek,
    Gemini,
    /// xAI (Grok) provider
    XAi,
    /// Native local provider - GGUF models via mistral.rs
    Native,
}

impl ProviderKind {
    /// Parse provider kind from string (case-insensitive)
    /// PERF(L3): eq_ignore_ascii_case avoids to_lowercase() allocation
    pub fn parse(s: &str) -> Option<Self> {
        if s.eq_ignore_ascii_case("claude") || s.eq_ignore_ascii_case("anthropic") {
            Some(Self::Claude)
        } else if s.eq_ignore_ascii_case("openai") || s.eq_ignore_ascii_case("gpt") {
            Some(Self::OpenAI)
        } else if s.eq_ignore_ascii_case("mistral") {
            Some(Self::Mistral)
        } else if s.eq_ignore_ascii_case("groq") {
            Some(Self::Groq)
        } else if s.eq_ignore_ascii_case("deepseek") {
            Some(Self::DeepSeek)
        } else if s.eq_ignore_ascii_case("gemini") || s.eq_ignore_ascii_case("google") {
            Some(Self::Gemini)
        } else if s.eq_ignore_ascii_case("xai")
            || s.eq_ignore_ascii_case("grok")
            || s.eq_ignore_ascii_case("x-ai")
        {
            Some(Self::XAi)
        } else if s.eq_ignore_ascii_case("native") {
            Some(Self::Native)
        } else {
            None
        }
    }

    /// Get provider name
    pub fn name(&self) -> &'static str {
        match self {
            Self::Claude => "Claude",
            Self::OpenAI => "OpenAI",
            Self::Mistral => "Mistral",
            Self::Groq => "Groq",
            Self::DeepSeek => "DeepSeek",
            Self::Gemini => "Gemini",
            Self::XAi => "xAI",
            Self::Native => "Native",
        }
    }

    /// Check if provider is free (local or free tier)
    pub fn is_free(&self) -> bool {
        matches!(self, Self::Native)
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// MODEL PRICING
// ═══════════════════════════════════════════════════════════════════════════

/// Pricing for a model (per million tokens)
#[derive(Debug, Clone, Copy)]
pub struct ModelPricing {
    /// Cost per million input tokens
    pub input_per_million: f64,
    /// Cost per million output tokens
    pub output_per_million: f64,
}

impl ModelPricing {
    /// Create new pricing
    pub const fn new(input_per_million: f64, output_per_million: f64) -> Self {
        Self {
            input_per_million,
            output_per_million,
        }
    }

    /// Calculate cost for given token counts
    ///
    /// Returns 0.0 if the result is NaN or Infinity (prevents NDJSON serialization failures).
    pub fn calculate(&self, input_tokens: u64, output_tokens: u64) -> f64 {
        let cost = (input_tokens as f64 / 1_000_000.0) * self.input_per_million
            + (output_tokens as f64 / 1_000_000.0) * self.output_per_million;
        if cost.is_finite() {
            cost
        } else {
            0.0
        }
    }

    /// Calculate cost with cached token discount (cached tokens at 10% of input rate).
    pub fn calculate_with_cache(
        &self,
        input_tokens: u64,
        output_tokens: u64,
        cached_tokens: u64,
    ) -> f64 {
        let effective_input = input_tokens.saturating_sub(cached_tokens);
        let cached_cost = (cached_tokens as f64 / 1_000_000.0) * self.input_per_million * 0.1;
        let input_cost = (effective_input as f64 / 1_000_000.0) * self.input_per_million;
        let output_cost = (output_tokens as f64 / 1_000_000.0) * self.output_per_million;
        let cost = cached_cost + input_cost + output_cost;
        if cost.is_finite() {
            cost
        } else {
            0.0
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// PRICING TABLES (per million tokens, as of March 2026)
// ═══════════════════════════════════════════════════════════════════════════

/// Claude models pricing
static CLAUDE_PRICING: LazyLock<FxHashMap<&'static str, ModelPricing>> = LazyLock::new(|| {
    let mut m = FxHashMap::default();
    // Claude 4.6 Opus
    m.insert("claude-opus-4-6", ModelPricing::new(15.0, 75.0));
    // Claude 4 Opus
    m.insert("claude-opus-4-20250514", ModelPricing::new(15.0, 75.0));
    m.insert("claude-opus-4", ModelPricing::new(15.0, 75.0));
    // Claude 4.6 Sonnet
    m.insert("claude-sonnet-4-6-20250514", ModelPricing::new(3.0, 15.0));
    m.insert("claude-sonnet-4-6", ModelPricing::new(3.0, 15.0));
    // Claude 4 Sonnet
    m.insert("claude-sonnet-4-20250514", ModelPricing::new(3.0, 15.0));
    m.insert("claude-sonnet-4", ModelPricing::new(3.0, 15.0));
    // Claude 4.5 Haiku
    m.insert("claude-haiku-4-5-20251001", ModelPricing::new(0.8, 4.0));
    m.insert("claude-haiku-4-5", ModelPricing::new(0.8, 4.0));
    // Claude 3.5 Sonnet
    m.insert("claude-3-5-sonnet-20241022", ModelPricing::new(3.0, 15.0));
    m.insert("claude-3-5-sonnet-latest", ModelPricing::new(3.0, 15.0));
    // Claude 3.5 Haiku
    m.insert("claude-3-5-haiku-20241022", ModelPricing::new(0.8, 4.0));
    m.insert("claude-3-5-haiku-latest", ModelPricing::new(0.8, 4.0));
    // Claude 3 Opus
    m.insert("claude-3-opus-20240229", ModelPricing::new(15.0, 75.0));
    m.insert("claude-3-opus-latest", ModelPricing::new(15.0, 75.0));
    // Claude 3 Sonnet
    m.insert("claude-3-sonnet-20240229", ModelPricing::new(3.0, 15.0));
    // Claude 3 Haiku
    m.insert("claude-3-haiku-20240307", ModelPricing::new(0.25, 1.25));
    m
});

/// OpenAI models pricing
static OPENAI_PRICING: LazyLock<FxHashMap<&'static str, ModelPricing>> = LazyLock::new(|| {
    let mut m = FxHashMap::default();
    // GPT-4o
    m.insert("gpt-4o", ModelPricing::new(2.5, 10.0));
    m.insert("gpt-4o-2024-11-20", ModelPricing::new(2.5, 10.0));
    m.insert("gpt-4o-mini", ModelPricing::new(0.15, 0.6));
    m.insert("gpt-4o-mini-2024-07-18", ModelPricing::new(0.15, 0.6));
    // GPT-4 Turbo
    m.insert("gpt-4-turbo", ModelPricing::new(10.0, 30.0));
    m.insert("gpt-4-turbo-2024-04-09", ModelPricing::new(10.0, 30.0));
    m.insert("gpt-4-turbo-preview", ModelPricing::new(10.0, 30.0));
    // GPT-4
    m.insert("gpt-4", ModelPricing::new(30.0, 60.0));
    m.insert("gpt-4-0613", ModelPricing::new(30.0, 60.0));
    // GPT-3.5 Turbo
    m.insert("gpt-3.5-turbo", ModelPricing::new(0.5, 1.5));
    m.insert("gpt-3.5-turbo-0125", ModelPricing::new(0.5, 1.5));
    // o1
    m.insert("o1", ModelPricing::new(15.0, 60.0));
    m.insert("o1-2024-12-17", ModelPricing::new(15.0, 60.0));
    m.insert("o1-preview", ModelPricing::new(15.0, 60.0));
    m.insert("o1-mini", ModelPricing::new(3.0, 12.0));
    m.insert("o1-mini-2024-09-12", ModelPricing::new(3.0, 12.0));
    // GPT-4.1
    m.insert("gpt-4.1", ModelPricing::new(2.0, 8.0));
    m.insert("gpt-4.1-2025-04-14", ModelPricing::new(2.0, 8.0));
    m.insert("gpt-4.1-mini", ModelPricing::new(0.4, 1.6));
    m.insert("gpt-4.1-mini-2025-04-14", ModelPricing::new(0.4, 1.6));
    m.insert("gpt-4.1-nano", ModelPricing::new(0.1, 0.4));
    m.insert("gpt-4.1-nano-2025-04-14", ModelPricing::new(0.1, 0.4));
    // o3-mini
    m.insert("o3-mini", ModelPricing::new(1.1, 4.4));
    m.insert("o3-mini-2025-01-31", ModelPricing::new(1.1, 4.4));
    // o3
    m.insert("o3", ModelPricing::new(2.0, 8.0));
    m.insert("o3-2025-04-16", ModelPricing::new(2.0, 8.0));
    // o4-mini
    m.insert("o4-mini", ModelPricing::new(1.1, 4.4));
    m.insert("o4-mini-2025-04-16", ModelPricing::new(1.1, 4.4));
    m
});

/// Mistral models pricing
static MISTRAL_PRICING: LazyLock<FxHashMap<&'static str, ModelPricing>> = LazyLock::new(|| {
    let mut m = FxHashMap::default();
    // Large
    m.insert("mistral-large-latest", ModelPricing::new(2.0, 6.0));
    m.insert("mistral-large-2411", ModelPricing::new(2.0, 6.0));
    // Medium (deprecated but still available)
    m.insert("mistral-medium-latest", ModelPricing::new(2.7, 8.1));
    // Small
    m.insert("mistral-small-latest", ModelPricing::new(0.2, 0.6));
    m.insert("mistral-small-2409", ModelPricing::new(0.2, 0.6));
    // Codestral
    m.insert("codestral-latest", ModelPricing::new(0.3, 0.9));
    m.insert("codestral-2501", ModelPricing::new(0.3, 0.9));
    // Ministral
    m.insert("ministral-8b-latest", ModelPricing::new(0.1, 0.1));
    m.insert("ministral-3b-latest", ModelPricing::new(0.04, 0.04));
    // Pixtral
    m.insert("pixtral-large-latest", ModelPricing::new(2.0, 6.0));
    m.insert("pixtral-12b-2409", ModelPricing::new(0.15, 0.15));
    m
});

/// Groq models pricing (very low cost)
static GROQ_PRICING: LazyLock<FxHashMap<&'static str, ModelPricing>> = LazyLock::new(|| {
    let mut m = FxHashMap::default();
    // Llama 3.3
    m.insert("llama-3.3-70b-versatile", ModelPricing::new(0.59, 0.79));
    m.insert("llama-3.3-70b-specdec", ModelPricing::new(0.59, 0.99));
    // Llama 3.1
    m.insert("llama-3.1-70b-versatile", ModelPricing::new(0.59, 0.79));
    m.insert("llama-3.1-8b-instant", ModelPricing::new(0.05, 0.08));
    // Llama 3
    m.insert("llama3-70b-8192", ModelPricing::new(0.59, 0.79));
    m.insert("llama3-8b-8192", ModelPricing::new(0.05, 0.08));
    // Mixtral
    m.insert("mixtral-8x7b-32768", ModelPricing::new(0.24, 0.24));
    // Gemma
    m.insert("gemma2-9b-it", ModelPricing::new(0.20, 0.20));
    m
});

/// DeepSeek models pricing
static DEEPSEEK_PRICING: LazyLock<FxHashMap<&'static str, ModelPricing>> = LazyLock::new(|| {
    let mut m = FxHashMap::default();
    m.insert("deepseek-chat", ModelPricing::new(0.14, 0.28));
    m.insert("deepseek-reasoner", ModelPricing::new(0.55, 2.19));
    m.insert("deepseek-coder", ModelPricing::new(0.14, 0.28));
    m
});

/// Gemini models pricing
static GEMINI_PRICING: LazyLock<FxHashMap<&'static str, ModelPricing>> = LazyLock::new(|| {
    let mut m = FxHashMap::default();
    // Gemini 2.5
    m.insert("gemini-2.5-pro", ModelPricing::new(1.25, 10.0));
    m.insert(
        "gemini-2.5-pro-preview-05-06",
        ModelPricing::new(1.25, 10.0),
    );
    m.insert("gemini-2.5-flash", ModelPricing::new(0.15, 0.60));
    m.insert(
        "gemini-2.5-flash-preview-05-20",
        ModelPricing::new(0.15, 0.60),
    );
    // Gemini 2.0
    m.insert("gemini-2.0-flash", ModelPricing::new(0.1, 0.4));
    m.insert("gemini-2.0-flash-exp", ModelPricing::new(0.0, 0.0)); // Free preview
    m.insert("gemini-2.0-flash-thinking", ModelPricing::new(0.0, 0.0)); // Free preview
                                                                        // Gemini 1.5
    m.insert("gemini-1.5-pro", ModelPricing::new(1.25, 5.0));
    m.insert("gemini-1.5-pro-latest", ModelPricing::new(1.25, 5.0));
    m.insert("gemini-1.5-flash", ModelPricing::new(0.075, 0.3));
    m.insert("gemini-1.5-flash-latest", ModelPricing::new(0.075, 0.3));
    m.insert("gemini-1.5-flash-8b", ModelPricing::new(0.0375, 0.15));
    // Gemini 1.0 Pro
    m.insert("gemini-pro", ModelPricing::new(0.5, 1.5));
    m
});

/// xAI (Grok) models pricing
static XAI_PRICING: LazyLock<FxHashMap<&'static str, ModelPricing>> = LazyLock::new(|| {
    let mut m = FxHashMap::default();
    // Grok-3
    m.insert("grok-3", ModelPricing::new(3.0, 15.0));
    // Grok-3 Fast
    m.insert("grok-3-fast", ModelPricing::new(0.6, 4.0));
    // Grok-3 Mini
    m.insert("grok-3-mini", ModelPricing::new(0.3, 0.5));
    // Grok-3 Mini Fast
    m.insert("grok-3-mini-fast", ModelPricing::new(0.1, 0.4));
    // Grok-2
    m.insert("grok-2", ModelPricing::new(2.0, 10.0));
    m
});

// ═══════════════════════════════════════════════════════════════════════════
// DEFAULT PRICING (fallback)
// ═══════════════════════════════════════════════════════════════════════════

/// Default pricing when model is unknown (conservative estimate)
const DEFAULT_PRICING: ModelPricing = ModelPricing::new(5.0, 15.0);

/// Free pricing for local models
const FREE_PRICING: ModelPricing = ModelPricing::new(0.0, 0.0);

// ═══════════════════════════════════════════════════════════════════════════
// COST CALCULATION
// ═══════════════════════════════════════════════════════════════════════════

/// List all known models with pricing for a provider.
///
/// Returns `(model_name, pricing)` pairs sorted by model name.
/// Used by `nika model list` to display cloud models with costs.
pub fn list_provider_models(provider: ProviderKind) -> Vec<(&'static str, ModelPricing)> {
    if provider.is_free() {
        return Vec::new();
    }
    let table: &FxHashMap<&'static str, ModelPricing> = match provider {
        ProviderKind::Claude => &CLAUDE_PRICING,
        ProviderKind::OpenAI => &OPENAI_PRICING,
        ProviderKind::Mistral => &MISTRAL_PRICING,
        ProviderKind::Groq => &GROQ_PRICING,
        ProviderKind::DeepSeek => &DEEPSEEK_PRICING,
        ProviderKind::Gemini => &GEMINI_PRICING,
        ProviderKind::XAi => &XAI_PRICING,
        ProviderKind::Native => return Vec::new(),
    };
    // Deduplicate: skip date-suffixed variants (e.g., "gpt-4o-2024-11-20" when "gpt-4o" exists)
    let mut entries: Vec<(&str, ModelPricing)> = table.iter().map(|(&k, &v)| (k, v)).collect();
    entries.sort_by_key(|(name, _)| name.len());
    let all_names: Vec<&str> = entries.iter().map(|(n, _)| *n).collect();
    let mut result: Vec<(&str, ModelPricing)> = Vec::new();
    for &(name, pricing) in &entries {
        // A name is a date variant if a shorter name is its prefix followed by -YYYY
        // (at least 4 digits after the dash, e.g., -2024-11-20, -20250514)
        // This avoids false positives like claude-sonnet-4-6 being treated as
        // a date variant of claude-sonnet-4 (the -6 is a version, not a date).
        let is_date_variant = all_names.iter().any(|shorter| {
            if shorter.len() >= name.len() || !name.starts_with(shorter) {
                return false;
            }
            let suffix = &name[shorter.len()..];
            // Must start with - followed by at least 4 digits (YYYY)
            suffix.starts_with('-')
                && suffix.len() >= 5
                && suffix[1..5].chars().all(|c| c.is_ascii_digit())
        });
        if !is_date_variant {
            result.push((name, pricing));
        }
    }
    result.sort_by(|(a, _), (b, _)| a.cmp(b));
    result
}

/// Get pricing for a specific model
pub fn get_model_pricing(provider: ProviderKind, model: &str) -> ModelPricing {
    if provider.is_free() {
        return FREE_PRICING;
    }

    let pricing = match provider {
        ProviderKind::Claude => CLAUDE_PRICING.get(model),
        ProviderKind::OpenAI => OPENAI_PRICING.get(model),
        ProviderKind::Mistral => MISTRAL_PRICING.get(model),
        ProviderKind::Groq => GROQ_PRICING.get(model),
        ProviderKind::DeepSeek => DEEPSEEK_PRICING.get(model),
        ProviderKind::Gemini => GEMINI_PRICING.get(model),
        ProviderKind::XAi => XAI_PRICING.get(model),
        ProviderKind::Native => return FREE_PRICING,
    };

    pricing.copied().unwrap_or(DEFAULT_PRICING)
}

/// Calculate cost for a given number of tokens
///
/// # Arguments
///
/// * `provider` - The provider kind
/// * `model` - The model identifier
/// * `input_tokens` - Number of input tokens
/// * `output_tokens` - Number of output tokens
///
/// # Returns
///
/// Cost in USD
pub fn calculate_cost(
    provider: ProviderKind,
    model: &str,
    input_tokens: u64,
    output_tokens: u64,
) -> f64 {
    let pricing = get_model_pricing(provider, model);
    pricing.calculate(input_tokens, output_tokens)
}

/// Calculate cost with cached token discount.
pub fn calculate_cost_with_cache(
    provider: ProviderKind,
    model: &str,
    input_tokens: u64,
    output_tokens: u64,
    cached_tokens: u64,
) -> f64 {
    let pricing = get_model_pricing(provider, model);
    pricing.calculate_with_cache(input_tokens, output_tokens, cached_tokens)
}

/// Estimate cost before execution based on estimated tokens
///
/// # Arguments
///
/// * `provider` - The provider kind
/// * `model` - The model identifier
/// * `estimated_input` - Estimated input tokens
/// * `estimated_output` - Estimated output tokens
///
/// # Returns
///
/// Estimated cost in USD
pub fn estimate_cost(
    provider: ProviderKind,
    model: &str,
    estimated_input: u64,
    estimated_output: u64,
) -> f64 {
    calculate_cost(provider, model, estimated_input, estimated_output)
}

/// Format cost as USD string with appropriate precision
pub fn format_cost(cost: f64) -> String {
    if cost < 0.0001 {
        format!("${:.6}", cost)
    } else if cost < 0.01 {
        format!("${:.4}", cost)
    } else if cost < 1.0 {
        format!("${:.3}", cost)
    } else {
        format!("${:.2}", cost)
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// TESTS
// ═══════════════════════════════════════════════════════════════════════════

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

    // ───────────────────────────────────────────────────────────────────────
    // ProviderKind tests
    // ───────────────────────────────────────────────────────────────────────

    #[test]
    fn provider_from_str_claude() {
        assert_eq!(ProviderKind::parse("claude"), Some(ProviderKind::Claude));
        assert_eq!(ProviderKind::parse("anthropic"), Some(ProviderKind::Claude));
        assert_eq!(ProviderKind::parse("CLAUDE"), Some(ProviderKind::Claude));
    }

    #[test]
    fn provider_from_str_openai() {
        assert_eq!(ProviderKind::parse("openai"), Some(ProviderKind::OpenAI));
        assert_eq!(ProviderKind::parse("gpt"), Some(ProviderKind::OpenAI));
    }

    #[test]
    fn provider_from_str_all() {
        assert!(ProviderKind::parse("mistral").is_some());
        assert!(ProviderKind::parse("groq").is_some());
        assert!(ProviderKind::parse("deepseek").is_some());
        assert!(ProviderKind::parse("gemini").is_some());
        assert!(ProviderKind::parse("native").is_some());
    }

    #[test]
    fn provider_from_str_unknown() {
        assert_eq!(ProviderKind::parse("unknown"), None);
        assert_eq!(ProviderKind::parse(""), None);
    }

    #[test]
    fn provider_is_free() {
        assert!(ProviderKind::Native.is_free());
        assert!(!ProviderKind::Claude.is_free());
        assert!(!ProviderKind::OpenAI.is_free());
    }

    // ───────────────────────────────────────────────────────────────────────
    // ModelPricing tests
    // ───────────────────────────────────────────────────────────────────────

    #[test]
    fn pricing_calculate_simple() {
        let pricing = ModelPricing::new(10.0, 30.0); // $10/M input, $30/M output
        let cost = pricing.calculate(1_000_000, 1_000_000);
        assert!((cost - 40.0).abs() < 0.0001);
    }

    #[test]
    fn pricing_calculate_fractional() {
        let pricing = ModelPricing::new(3.0, 15.0); // Claude Sonnet
        let cost = pricing.calculate(1000, 500);
        // 1000 * 3/1M + 500 * 15/1M = 0.003 + 0.0075 = 0.0105
        assert!((cost - 0.0105).abs() < 0.0001);
    }

    #[test]
    fn pricing_calculate_zero_tokens() {
        let pricing = ModelPricing::new(10.0, 30.0);
        let cost = pricing.calculate(0, 0);
        assert!((cost - 0.0).abs() < 0.0001);
    }

    // ───────────────────────────────────────────────────────────────────────
    // Cost calculation tests
    // ───────────────────────────────────────────────────────────────────────

    #[test]
    fn calculate_cost_claude_sonnet() {
        let cost = calculate_cost(ProviderKind::Claude, "claude-sonnet-4-6", 10_000, 5_000);
        // 10000 * 3/1M + 5000 * 15/1M = 0.03 + 0.075 = 0.105
        assert!((cost - 0.105).abs() < 0.0001);
    }

    #[test]
    fn calculate_cost_openai_gpt4o() {
        let cost = calculate_cost(ProviderKind::OpenAI, "gpt-4o", 10_000, 5_000);
        // 10000 * 2.5/1M + 5000 * 10/1M = 0.025 + 0.05 = 0.075
        assert!((cost - 0.075).abs() < 0.0001);
    }

    #[test]
    fn calculate_cost_native_free() {
        let cost = calculate_cost(ProviderKind::Native, "llama3.2-q4", 1_000_000, 1_000_000);
        assert!((cost - 0.0).abs() < 0.0001);
    }

    #[test]
    fn calculate_cost_unknown_model() {
        let cost = calculate_cost(ProviderKind::Claude, "unknown-model", 1_000_000, 1_000_000);
        // Should use default pricing (5, 15)
        assert!((cost - 20.0).abs() < 0.0001);
    }

    #[test]
    fn calculate_cost_groq() {
        let cost = calculate_cost(
            ProviderKind::Groq,
            "llama-3.3-70b-versatile",
            100_000,
            50_000,
        );
        // 100000 * 0.59/1M + 50000 * 0.79/1M = 0.059 + 0.0395 = 0.0985
        assert!((cost - 0.0985).abs() < 0.0001);
    }

    #[test]
    fn calculate_cost_deepseek() {
        let cost = calculate_cost(ProviderKind::DeepSeek, "deepseek-chat", 100_000, 50_000);
        // 100000 * 0.14/1M + 50000 * 0.28/1M = 0.014 + 0.014 = 0.028
        assert!((cost - 0.028).abs() < 0.0001);
    }

    #[test]
    fn calculate_cost_gemini() {
        let cost = calculate_cost(ProviderKind::Gemini, "gemini-2.0-flash", 100_000, 50_000);
        // 100000 * 0.1/1M + 50000 * 0.4/1M = 0.01 + 0.02 = 0.03
        assert!((cost - 0.03).abs() < 0.0001);
    }

    // ───────────────────────────────────────────────────────────────────────
    // Format cost tests
    // ───────────────────────────────────────────────────────────────────────

    #[test]
    fn format_cost_tiny() {
        assert_eq!(format_cost(0.00001), "$0.000010");
    }

    #[test]
    fn format_cost_small() {
        assert_eq!(format_cost(0.005), "$0.0050");
    }

    #[test]
    fn format_cost_medium() {
        assert_eq!(format_cost(0.105), "$0.105");
    }

    #[test]
    fn format_cost_large() {
        assert_eq!(format_cost(5.50), "$5.50");
    }

    // ───────────────────────────────────────────────────────────────────────
    // Pricing table coverage
    // ───────────────────────────────────────────────────────────────────────

    #[test]
    fn claude_pricing_coverage() {
        assert!(CLAUDE_PRICING.contains_key("claude-sonnet-4-6"));
        assert!(CLAUDE_PRICING.contains_key("claude-opus-4"));
        assert!(CLAUDE_PRICING.contains_key("claude-3-5-haiku-latest"));
    }

    #[test]
    fn openai_pricing_coverage() {
        assert!(OPENAI_PRICING.contains_key("gpt-4o"));
        assert!(OPENAI_PRICING.contains_key("gpt-4o-mini"));
        assert!(OPENAI_PRICING.contains_key("o1"));
    }

    #[test]
    fn mistral_pricing_coverage() {
        assert!(MISTRAL_PRICING.contains_key("mistral-large-latest"));
        assert!(MISTRAL_PRICING.contains_key("mistral-small-latest"));
    }

    #[test]
    fn all_providers_have_pricing() {
        // Each paid provider should have at least one model
        assert!(!CLAUDE_PRICING.is_empty());
        assert!(!OPENAI_PRICING.is_empty());
        assert!(!MISTRAL_PRICING.is_empty());
        assert!(!GROQ_PRICING.is_empty());
        assert!(!DEEPSEEK_PRICING.is_empty());
        assert!(!GEMINI_PRICING.is_empty());
    }

    // ───────────────────────────────────────────────────────────────────────
    // list_provider_models tests
    // ───────────────────────────────────────────────────────────────────────

    #[test]
    fn list_provider_models_all_cloud_providers_non_empty() {
        let providers = [
            ProviderKind::Claude,
            ProviderKind::OpenAI,
            ProviderKind::Mistral,
            ProviderKind::Groq,
            ProviderKind::DeepSeek,
            ProviderKind::Gemini,
            ProviderKind::XAi,
        ];
        for provider in providers {
            let models = list_provider_models(provider);
            assert!(
                !models.is_empty(),
                "{} should return at least 1 model",
                provider.name()
            );
        }
    }

    #[test]
    fn list_provider_models_native_returns_empty() {
        let models = list_provider_models(ProviderKind::Native);
        assert!(models.is_empty(), "Native provider should return no models");
    }

    #[test]
    fn list_provider_models_claude_deduplicates_date_variants() {
        let models = list_provider_models(ProviderKind::Claude);
        let names: Vec<&str> = models.iter().map(|(n, _)| *n).collect();
        // The base alias should survive dedup
        assert!(
            names.contains(&"claude-sonnet-4"),
            "claude-sonnet-4 should be in the deduplicated list"
        );
        // Date-suffixed variant should be filtered out
        assert!(
            !names.contains(&"claude-sonnet-4-20250514"),
            "claude-sonnet-4-20250514 should be deduplicated away"
        );
        // The -6 variant is also treated as a date variant of claude-sonnet-4
        // (prefix + -DIGIT pattern), so both it and its own date variant are removed
        assert!(
            !names.contains(&"claude-sonnet-4-6-20250514"),
            "claude-sonnet-4-6-20250514 should be deduplicated away"
        );
    }

    #[test]
    fn list_provider_models_openai_deduplicates_date_variants() {
        let models = list_provider_models(ProviderKind::OpenAI);
        let names: Vec<&str> = models.iter().map(|(n, _)| *n).collect();
        // The short alias should be present
        assert!(
            names.contains(&"gpt-4o"),
            "gpt-4o should be in the deduplicated list"
        );
        // The date-suffixed variant should be filtered out
        assert!(
            !names.contains(&"gpt-4o-2024-11-20"),
            "gpt-4o-2024-11-20 should be deduplicated away"
        );
        // Same for GPT-4.1
        assert!(
            names.contains(&"gpt-4.1"),
            "gpt-4.1 should be in the deduplicated list"
        );
        assert!(
            !names.contains(&"gpt-4.1-2025-04-14"),
            "gpt-4.1-2025-04-14 should be deduplicated away"
        );
    }

    #[test]
    fn list_provider_models_no_duplicates() {
        let providers = [
            ProviderKind::Claude,
            ProviderKind::OpenAI,
            ProviderKind::Mistral,
            ProviderKind::Groq,
            ProviderKind::DeepSeek,
            ProviderKind::Gemini,
            ProviderKind::XAi,
        ];
        for provider in providers {
            let models = list_provider_models(provider);
            let names: Vec<&str> = models.iter().map(|(n, _)| *n).collect();
            let mut seen = std::collections::HashSet::new();
            for name in &names {
                assert!(
                    seen.insert(name),
                    "{} has duplicate model: {}",
                    provider.name(),
                    name
                );
            }
        }
    }

    #[test]
    fn list_provider_models_pricing_positive() {
        // All returned models should have positive pricing, except known free previews
        let free_previews: &[&str] = &["gemini-2.0-flash-exp", "gemini-2.0-flash-thinking"];

        let providers = [
            ProviderKind::Claude,
            ProviderKind::OpenAI,
            ProviderKind::Mistral,
            ProviderKind::Groq,
            ProviderKind::DeepSeek,
            ProviderKind::Gemini,
            ProviderKind::XAi,
        ];
        for provider in providers {
            let models = list_provider_models(provider);
            for (name, pricing) in &models {
                if free_previews.contains(name) {
                    continue;
                }
                assert!(
                    pricing.input_per_million > 0.0,
                    "{}/{} should have input_per_million > 0, got {}",
                    provider.name(),
                    name,
                    pricing.input_per_million
                );
                assert!(
                    pricing.output_per_million > 0.0,
                    "{}/{} should have output_per_million > 0, got {}",
                    provider.name(),
                    name,
                    pricing.output_per_million
                );
            }
        }
    }

    #[test]
    fn list_provider_models_results_are_sorted() {
        let providers = [
            ProviderKind::Claude,
            ProviderKind::OpenAI,
            ProviderKind::Mistral,
            ProviderKind::Groq,
            ProviderKind::DeepSeek,
            ProviderKind::Gemini,
            ProviderKind::XAi,
        ];
        for provider in providers {
            let models = list_provider_models(provider);
            let names: Vec<&str> = models.iter().map(|(n, _)| *n).collect();
            let mut sorted = names.clone();
            sorted.sort();
            assert_eq!(
                names,
                sorted,
                "{} models should be sorted alphabetically",
                provider.name()
            );
        }
    }
}