calnexus 0.2.0

A command-line math expression evaluator with 11 core and 3 optional (time/unit/fx) computation domains plus a numerical-linalg feature, symbolic calculus, REPL, batch processing, HTTP and MCP servers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: MIT

//! FX 场景化工具:`fx_budget` + `fx_pricing`(`#[forge]` 双协议端点)。
//! 基于 math::fx_scenario 纯函数 + FrankfurterProvider 汇率缓存;feature = "fx"。
//! `spawn_blocking` 隔离同步 `RateProvider::rates()` 调用。

use crate::domains::fx_provider::{FxProviderConfig, RateProvider, build_provider};
use crate::math::fx_scenario::{budget_calculation, pricing_calculation};
use crate::server::evaluate::REQUEST_TIMEOUT_SECS;
use sdforge::error::ApiError;
use sdforge::forge;
use std::sync::{Arc, OnceLock};
use std::time::Duration;

// ============================================================
// Request / Response DTOs
// ============================================================

/// `POST /api/v1/fx_budget` + MCP `fx_budget` tool 请求。
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct FxBudgetRequest {
    /// 学费金额(外币,必须 > 0)。
    pub tuition: f64,
    /// 学费货币代码(ISO 4217,如 "USD")。
    pub tuition_currency: String,
    /// 月均生活费(外币),可选。
    #[serde(default)]
    pub living_cost_monthly: Option<f64>,
    /// 留学年限(1..=10)。
    pub duration_years: u32,
    /// 本币代码(ISO 4217,如 "CNY")。
    pub home_currency: String,
    /// 响应语言(BCP-47;缺省/未知回退英文;仅影响文案,协议字段保持英文)。
    #[serde(default)]
    pub lang: Option<String>,
}

/// `fx_budget` 响应。
#[derive(Debug, Clone, serde::Serialize)]
pub struct FxBudgetResponse {
    pub tuition_foreign: f64,
    pub tuition_currency: String,
    pub tuition_home: f64,
    pub home_currency: String,
    pub rate: f64,
    pub duration_years: u32,
    pub annual_tuition_home: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub living_monthly_home: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub total_living_home: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub total_cost_home: Option<f64>,
    pub exchange_risk: ExchangeRiskResponse,
    /// 汇率快照日期(跨实例结果可审计)。
    pub rate_date: Option<String>,
    /// 汇率数据源名称(来源可观测,恒为单源:取自 RateTable.source,"frankfurter" / "erapi")。
    pub rate_source: String,
}

/// 汇率风险区间响应。
#[derive(Debug, Clone, serde::Serialize)]
pub struct ExchangeRiskResponse {
    pub range: String,
    pub note: String,
}

/// `POST /api/v1/fx_pricing` + MCP `fx_pricing` tool 请求。
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct FxPricingRequest {
    /// 产品成本(人民币,必须 > 0)。
    pub cost_cny: f64,
    /// 目标利润率(0 < rate < 1,如 0.3 = 30%)。
    pub target_profit_rate: f64,
    /// 目标币种列表(逗号分隔,如 "USD,EUR,GBP",1..=10 种)。
    pub currencies: String,
    /// 平台综合费率(0 <= rate < 1,如 0.15 = 15%)。
    #[serde(default = "default_platform_rate")]
    pub platform_rate: f64,
    /// 汇率安全缓冲(0 <= buffer <= 0.5,如 0.05 = 5%)。
    #[serde(default = "default_safety_buffer")]
    pub safety_buffer: f64,
    /// 响应语言(BCP-47;缺省/未知回退英文;仅影响文案,协议字段保持英文)。
    #[serde(default)]
    pub lang: Option<String>,
}

fn default_platform_rate() -> f64 {
    0.15
}

fn default_safety_buffer() -> f64 {
    0.05
}

/// `fx_pricing` 响应。
#[derive(Debug, Clone, serde::Serialize)]
pub struct FxPricingResponse {
    pub cost_cny: f64,
    pub target_profit_rate: f64,
    pub platform_rate: f64,
    pub safety_buffer: f64,
    pub pricing: Vec<PricingItemResponse>,
    /// 汇率快照日期(跨实例结果可审计)。
    pub rate_date: Option<String>,
    /// 汇率数据源名称(来源可观测,恒为单源:取自 RateTable.source,"frankfurter" / "erapi")。
    pub rate_source: String,
}

/// 单币种定价明细。
#[derive(Debug, Clone, serde::Serialize)]
pub struct PricingItemResponse {
    pub currency: String,
    pub recommended_price: f64,
    pub actual_profit_rate: f64,
    pub profit_cny: f64,
    pub platform_fee_cny: f64,
}

// ============================================================
// Provider 单例
// ============================================================

/// 进程级汇率 provider 单例(与 FxDomain 独立,共享底层缓存文件)。
fn shared_provider() -> Arc<dyn RateProvider> {
    static PROVIDER: OnceLock<Arc<dyn RateProvider>> = OnceLock::new();
    Arc::clone(PROVIDER.get_or_init(|| Arc::new(build_provider(&FxProviderConfig::from_env()))))
}

// ============================================================
// Request 校验
// ============================================================

impl FxBudgetRequest {
    /// 校验请求参数约束。
    fn validate(&self) -> Result<(), ApiError> {
        if self.tuition <= 0.0 {
            return Err(ApiError::validation("tuition", "tuition must be positive"));
        }
        if self.duration_years == 0 || self.duration_years > 10 {
            return Err(ApiError::validation(
                "duration_years",
                "duration_years must be between 1 and 10",
            ));
        }
        if self.tuition_currency.len() != 3
            || !self
                .tuition_currency
                .chars()
                .all(|c| c.is_ascii_alphabetic())
        {
            return Err(ApiError::validation(
                "tuition_currency",
                "must be a 3-letter ISO 4217 currency code",
            ));
        }
        if self.home_currency.len() != 3
            || !self.home_currency.chars().all(|c| c.is_ascii_alphabetic())
        {
            return Err(ApiError::validation(
                "home_currency",
                "must be a 3-letter ISO 4217 currency code",
            ));
        }
        if let Some(living) = self.living_cost_monthly
            && living < 0.0
        {
            return Err(ApiError::validation(
                "living_cost_monthly",
                "living_cost_monthly must be non-negative",
            ));
        }
        Ok(())
    }
}

impl FxPricingRequest {
    /// 校验请求参数约束。
    fn validate(&self) -> Result<(), ApiError> {
        if self.cost_cny <= 0.0 {
            return Err(ApiError::validation(
                "cost_cny",
                "cost_cny must be positive",
            ));
        }
        if self.target_profit_rate <= 0.0 || self.target_profit_rate >= 1.0 {
            return Err(ApiError::validation(
                "target_profit_rate",
                "target_profit_rate must be between 0 and 1 (exclusive)",
            ));
        }
        if self.platform_rate < 0.0 || self.platform_rate >= 1.0 {
            return Err(ApiError::validation(
                "platform_rate",
                "platform_rate must be in [0, 1)",
            ));
        }
        if self.safety_buffer < 0.0 || self.safety_buffer > 0.5 {
            return Err(ApiError::validation(
                "safety_buffer",
                "safety_buffer must be in [0, 0.5]",
            ));
        }
        let currencies: Vec<&str> = self
            .currencies
            .split(',')
            .map(|s| s.trim())
            .filter(|s| !s.is_empty())
            .collect();
        if currencies.is_empty() {
            return Err(ApiError::validation(
                "currencies",
                "currencies list must not be empty",
            ));
        }
        if currencies.len() > 10 {
            return Err(ApiError::validation(
                "currencies",
                "currencies list must not exceed 10 items",
            ));
        }
        for cur in &currencies {
            if cur.len() != 3 || !cur.chars().all(|c| c.is_ascii_alphabetic()) {
                return Err(ApiError::validation(
                    "currencies",
                    format!("'{}' is not a valid 3-letter ISO 4217 currency code", cur),
                ));
            }
        }
        Ok(())
    }
}

// ============================================================
// #[forge] handlers
// ============================================================

/// `POST /api/v1/fx_budget` + MCP `fx_budget`:留学预算换算本币并给出 ±3% 汇率风险区间。
#[forge(
    name = "fx_budget",
    version = 1,
    path = "/fx_budget",
    method = "POST",
    tool_name = "fx_budget",
    description = "Calculate study abroad budget with currency conversion. Args MUST be wrapped in a req object with fields: tuition, tuition_currency, home_currency, optional living_cost_monthly, duration_years, optional lang (response language, BCP-47 tag, 'en' default, 'zh' supported). Returns tuition/living/total in home currency plus a 3-percent exchange-rate risk range and rate_date (snapshot date). Errors: 400 InvalidInput (unknown currency), 503 ServiceUnavailable (FX upstream unreachable)."
)]
pub(crate) async fn fx_budget(req: FxBudgetRequest) -> Result<FxBudgetResponse, ApiError> {
    fx_budget_with_timeout(req, Duration::from_secs(REQUEST_TIMEOUT_SECS)).await
}

/// 带超时的 fx_budget 实现(可测试入口):超时→503,spawn_blocking panic→500。
pub(crate) async fn fx_budget_with_timeout(
    req: FxBudgetRequest,
    timeout: Duration,
) -> Result<FxBudgetResponse, ApiError> {
    run_fx_budget(req, timeout, shared_provider()).await
}

async fn run_fx_budget(
    req: FxBudgetRequest,
    timeout: Duration,
    provider: Arc<dyn RateProvider>,
) -> Result<FxBudgetResponse, ApiError> {
    req.validate()?;

    // 语言协商:请求级 lang → I18n(缺省/未知回退英文)
    let i18n = super::lang::resolve_i18n(req.lang.as_deref());
    let tuition = req.tuition;
    let tuition_currency = req.tuition_currency.clone();
    let living_cost = req.living_cost_monthly;
    let duration = req.duration_years;
    let home_currency = req.home_currency.clone();

    // spawn_blocking 隔离同步 RateProvider 调用
    let i18n_in_task = i18n.clone();
    let join_handle = tokio::task::spawn_blocking(move || {
        let table = provider.rates().map_err(|e| {
            // 保留底层错误源(503 语义)
            ApiError::service_unavailable_with_source(
                "fx_budget",
                Some(5),
                std::io::Error::other(e.to_string()),
            )
        })?;
        let rate_date = Some(table.date.clone());
        let rate_source = table.source.clone();
        budget_calculation(
            tuition,
            &tuition_currency,
            living_cost,
            duration,
            &home_currency,
            &table,
        )
        .map(|result| (result, rate_date, rate_source))
        // CalcError 携 i18n_key 时按协商语言渲染 detail(en 逐字节不变)
        .map_err(|e| {
            ApiError::invalid_input(
                super::evaluate::localized_error_detail(&e, &i18n_in_task),
                None,
                None,
            )
        })
    });

    // 请求级超时兜底:先向调用方返回 503(与 evaluate 同模式);阻塞池线程本身由
    // 上游 HTTP_TIMEOUT(5s,auto 链最坏两轮 ≈10s)自了结,本 timeout 不终止它
    let (result, rate_date, rate_source) = match tokio::time::timeout(timeout, join_handle).await {
        Ok(Ok(r)) => r?,
        Ok(Err(join_err)) => {
            return Err(ApiError::internal_with_source(
                "fx_budget task failed",
                "spawn_blocking",
                join_err,
            ));
        }
        Err(_) => {
            return Err(ApiError::service_unavailable(
                "fx_budget",
                Some(timeout.as_secs()),
            ));
        }
    };

    Ok(FxBudgetResponse {
        tuition_foreign: result.tuition_foreign,
        tuition_currency: result.tuition_currency,
        tuition_home: result.tuition_home,
        home_currency: result.home_currency,
        rate: result.rate,
        duration_years: result.duration_years,
        annual_tuition_home: result.annual_tuition_home,
        living_monthly_home: result.living_monthly_home,
        total_living_home: result.total_living_home,
        total_cost_home: result.total_cost_home,
        exchange_risk: ExchangeRiskResponse {
            range: format!(
                "{:.0}~{:.0} {}",
                result.exchange_risk.low, result.exchange_risk.high, result.exchange_risk.currency
            ),
            // 用户可见文案经 i18n 目录 + 请求级语言协商
            note: i18n.t("msg.fx.budget_risk_note").to_string(),
        },
        rate_date,
        rate_source,
    })
}

/// `POST /api/v1/fx_pricing` + MCP `fx_pricing`:按成本与目标利润率计算各币种安全售价。
#[forge(
    name = "fx_pricing",
    version = 1,
    path = "/fx_pricing",
    method = "POST",
    tool_name = "fx_pricing",
    description = "Cross-border e-commerce multi-currency pricing. Args MUST be wrapped in a req object with fields: cost_cny, target_profit_rate, currencies (comma separated), optional platform_rate, safety_buffer, optional lang (response language, BCP-47 tag, 'en' default, 'zh' supported). Returns per-currency recommended prices with platform fees, plus rate_date (snapshot date). Errors: 400 InvalidInput, 503 ServiceUnavailable (FX upstream unreachable)."
)]
pub(crate) async fn fx_pricing(req: FxPricingRequest) -> Result<FxPricingResponse, ApiError> {
    fx_pricing_with_timeout(req, Duration::from_secs(REQUEST_TIMEOUT_SECS)).await
}

/// 带超时的 fx_pricing 实现(可测试入口):超时→503,spawn_blocking panic→500。
pub(crate) async fn fx_pricing_with_timeout(
    req: FxPricingRequest,
    timeout: Duration,
) -> Result<FxPricingResponse, ApiError> {
    run_fx_pricing(req, timeout, shared_provider()).await
}

async fn run_fx_pricing(
    req: FxPricingRequest,
    timeout: Duration,
    provider: Arc<dyn RateProvider>,
) -> Result<FxPricingResponse, ApiError> {
    req.validate()?;

    // 语言协商:请求级 lang → I18n(缺省/未知回退英文)
    let i18n = super::lang::resolve_i18n(req.lang.as_deref());
    let cost = req.cost_cny;
    let profit_rate = req.target_profit_rate;
    let platform_rate = req.platform_rate;
    let safety_buffer = req.safety_buffer;
    let currencies: Vec<String> = req
        .currencies
        .split(',')
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect();

    let join_handle = tokio::task::spawn_blocking(move || {
        let table = provider.rates().map_err(|e| {
            // 保留底层错误源(503 语义)
            ApiError::service_unavailable_with_source(
                "fx_pricing",
                Some(5),
                std::io::Error::other(e.to_string()),
            )
        })?;
        let rate_date = Some(table.date.clone());
        let rate_source = table.source.clone();
        let cur_refs: Vec<&str> = currencies.iter().map(|s| s.as_str()).collect();
        pricing_calculation(
            cost,
            profit_rate,
            &cur_refs,
            platform_rate,
            safety_buffer,
            &table,
        )
        .map(|result| (result, rate_date, rate_source))
        // CalcError 携 i18n_key 时按协商语言渲染 detail(en 逐字节不变)
        .map_err(|e| {
            ApiError::invalid_input(
                super::evaluate::localized_error_detail(&e, &i18n),
                None,
                None,
            )
        })
    });

    // 请求级超时兜底:先向调用方返回 503(与 evaluate 同模式);阻塞池线程本身由
    // 上游 HTTP_TIMEOUT(5s,auto 链最坏两轮 ≈10s)自了结,本 timeout 不终止它
    let (result, rate_date, rate_source) = match tokio::time::timeout(timeout, join_handle).await {
        Ok(Ok(r)) => r?,
        Ok(Err(join_err)) => {
            return Err(ApiError::internal_with_source(
                "fx_pricing task failed",
                "spawn_blocking",
                join_err,
            ));
        }
        Err(_) => {
            return Err(ApiError::service_unavailable(
                "fx_pricing",
                Some(timeout.as_secs()),
            ));
        }
    };

    Ok(FxPricingResponse {
        cost_cny: result.cost_cny,
        target_profit_rate: profit_rate,
        platform_rate,
        safety_buffer,
        pricing: result
            .pricing
            .into_iter()
            .map(|item| PricingItemResponse {
                currency: item.currency,
                recommended_price: item.recommended_price,
                actual_profit_rate: item.actual_profit_rate,
                profit_cny: item.profit_cny,
                platform_fee_cny: item.platform_fee_cny,
            })
            .collect(),
        rate_date,
        rate_source,
    })
}

// ============================================================
// Tests
// ============================================================

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

    // === DTO 序列化/反序列化 ===

    #[test]
    fn test_fx_budget_request_deserialize() {
        let json = r#"{
            "tuition": 50000.0,
            "tuition_currency": "USD",
            "living_cost_monthly": 2000.0,
            "duration_years": 4,
            "home_currency": "CNY"
        }"#;
        let req: FxBudgetRequest = serde_json::from_str(json).unwrap();
        assert_eq!(req.tuition, 50000.0);
        assert_eq!(req.tuition_currency, "USD");
        assert_eq!(req.living_cost_monthly, Some(2000.0));
        assert_eq!(req.duration_years, 4);
        assert_eq!(req.home_currency, "CNY");
    }

    #[test]
    fn test_fx_budget_request_no_living() {
        let json = r#"{
            "tuition": 10000.0,
            "tuition_currency": "EUR",
            "duration_years": 2,
            "home_currency": "CNY"
        }"#;
        let req: FxBudgetRequest = serde_json::from_str(json).unwrap();
        assert_eq!(req.living_cost_monthly, None);
    }

    #[test]
    fn test_fx_pricing_request_deserialize() {
        let json = r#"{
            "cost_cny": 50.0,
            "target_profit_rate": 0.3,
            "currencies": "USD,EUR,GBP"
        }"#;
        let req: FxPricingRequest = serde_json::from_str(json).unwrap();
        assert_eq!(req.cost_cny, 50.0);
        assert_eq!(req.target_profit_rate, 0.3);
        assert_eq!(req.currencies, "USD,EUR,GBP");
        assert_eq!(req.platform_rate, 0.15); // default
        assert_eq!(req.safety_buffer, 0.05); // default
    }

    #[test]
    fn test_fx_pricing_request_custom_rates() {
        let json = r#"{
            "cost_cny": 100.0,
            "target_profit_rate": 0.25,
            "currencies": "USD",
            "platform_rate": 0.10,
            "safety_buffer": 0.03
        }"#;
        let req: FxPricingRequest = serde_json::from_str(json).unwrap();
        assert_eq!(req.platform_rate, 0.10);
        assert_eq!(req.safety_buffer, 0.03);
    }

    // === 校验测试 ===

    #[test]
    fn test_fx_budget_validate_accepts_valid() {
        let req = FxBudgetRequest {
            tuition: 50000.0,
            tuition_currency: "USD".into(),
            living_cost_monthly: Some(2000.0),
            duration_years: 4,
            home_currency: "CNY".into(),
            lang: None,
        };
        assert!(req.validate().is_ok());
    }

    #[test]
    fn test_fx_budget_validate_rejects_zero_tuition() {
        let req = FxBudgetRequest {
            tuition: 0.0,
            tuition_currency: "USD".into(),
            living_cost_monthly: None,
            duration_years: 2,
            home_currency: "CNY".into(),
            lang: None,
        };
        assert!(req.validate().is_err());
    }

    #[test]
    fn test_fx_budget_validate_rejects_zero_duration() {
        let req = FxBudgetRequest {
            tuition: 50000.0,
            tuition_currency: "USD".into(),
            living_cost_monthly: None,
            duration_years: 0,
            home_currency: "CNY".into(),
            lang: None,
        };
        assert!(req.validate().is_err());
    }

    #[test]
    fn test_fx_budget_validate_rejects_invalid_currency() {
        let req = FxBudgetRequest {
            tuition: 50000.0,
            tuition_currency: "USDX".into(), // 4 letters
            living_cost_monthly: None,
            duration_years: 2,
            home_currency: "CNY".into(),
            lang: None,
        };
        assert!(req.validate().is_err());
    }

    #[test]
    fn test_fx_pricing_validate_accepts_valid() {
        let req = FxPricingRequest {
            cost_cny: 50.0,
            target_profit_rate: 0.3,
            currencies: "USD,EUR".into(),
            platform_rate: 0.15,
            safety_buffer: 0.05,
            lang: None,
        };
        assert!(req.validate().is_ok());
    }

    #[test]
    fn test_fx_pricing_validate_rejects_empty_currencies() {
        let req = FxPricingRequest {
            cost_cny: 50.0,
            target_profit_rate: 0.3,
            currencies: "".into(),
            platform_rate: 0.15,
            safety_buffer: 0.05,
            lang: None,
        };
        assert!(req.validate().is_err());
    }

    #[test]
    fn test_fx_pricing_validate_rejects_too_many_currencies() {
        let req = FxPricingRequest {
            cost_cny: 50.0,
            target_profit_rate: 0.3,
            currencies: "USD,EUR,GBP,JPY,CNY,KRW,AUD,CAD,CHF,SGD,NZD".into(),
            platform_rate: 0.15,
            safety_buffer: 0.05,
            lang: None,
        };
        assert!(req.validate().is_err());
    }

    #[test]
    fn test_fx_pricing_validate_rejects_profit_rate_one() {
        let req = FxPricingRequest {
            cost_cny: 50.0,
            target_profit_rate: 1.0,
            currencies: "USD".into(),
            platform_rate: 0.15,
            safety_buffer: 0.05,
            lang: None,
        };
        assert!(req.validate().is_err());
    }

    #[test]
    fn test_fx_pricing_validate_rejects_negative_cost() {
        let req = FxPricingRequest {
            cost_cny: -10.0,
            target_profit_rate: 0.3,
            currencies: "USD".into(),
            platform_rate: 0.15,
            safety_buffer: 0.05,
            lang: None,
        };
        assert!(req.validate().is_err());
    }

    // === Response 序列化 ===

    #[test]
    fn test_fx_budget_response_serialize() {
        let resp = FxBudgetResponse {
            tuition_foreign: 50000.0,
            tuition_currency: "USD".into(),
            tuition_home: 362500.0,
            home_currency: "CNY".into(),
            rate: 7.25,
            duration_years: 4,
            annual_tuition_home: 90625.0,
            living_monthly_home: Some(14500.0),
            total_living_home: Some(696000.0),
            total_cost_home: Some(1058500.0),
            exchange_risk: ExchangeRiskResponse {
                range: "1027345~1089655 CNY".into(),
                note: "test".into(),
            },
            rate_date: Some("2026-09-13".into()),
            rate_source: "test-frankfurter".into(),
        };
        let json = serde_json::to_string(&resp).unwrap();
        assert!(json.contains(r#""tuition_foreign":50000.0"#));
        assert!(json.contains(r#""tuition_currency":"USD""#));
        assert!(json.contains(r#""exchange_risk""#));
        assert!(json.contains(r#""rate_source":"test-frankfurter""#));
    }

    #[test]
    fn test_fx_pricing_response_serialize() {
        let resp = FxPricingResponse {
            cost_cny: 50.0,
            target_profit_rate: 0.3,
            platform_rate: 0.15,
            safety_buffer: 0.05,
            pricing: vec![PricingItemResponse {
                currency: "USD".into(),
                recommended_price: 10.99,
                actual_profit_rate: 0.287,
                profit_cny: 14.35,
                platform_fee_cny: 1.65,
            }],
            rate_date: Some("2026-09-13".into()),
            rate_source: "test-frankfurter".into(),
        };
        let json = serde_json::to_string(&resp).unwrap();
        assert!(json.contains(r#""cost_cny":50.0"#));
        assert!(json.contains(r#""recommended_price":10.99"#));
        assert!(json.contains(r#""currency":"USD""#));
        assert!(json.contains(r#""rate_source":"test-frankfurter""#));
    }

    // === 成功响应 rate_source ===

    /// 测试用静态 provider:返回固定汇率表(source 可注入)。
    struct StaticProvider {
        table: crate::math::fx::RateTable,
    }

    impl RateProvider for StaticProvider {
        fn rates(&self) -> Result<crate::math::fx::RateTable, crate::core::CalcError> {
            Ok(self.table.clone())
        }

        fn name(&self) -> &'static str {
            "static"
        }
    }

    fn static_provider(source: &str) -> Arc<dyn RateProvider> {
        let mut rates = std::collections::HashMap::new();
        rates.insert("USD".to_string(), 1.08);
        rates.insert("CNY".to_string(), 7.85);
        Arc::new(StaticProvider {
            table: crate::math::fx::RateTable {
                base: "EUR".into(),
                date: "2026-09-13".into(),
                rates,
                source: source.into(),
            },
        })
    }

    #[tokio::test]
    async fn test_fx_budget_response_rate_source_from_table() {
        let req = FxBudgetRequest {
            tuition: 50000.0,
            tuition_currency: "USD".into(),
            living_cost_monthly: Some(2000.0),
            duration_years: 4,
            home_currency: "CNY".into(),
            lang: Some("en".into()),
        };
        let resp = run_fx_budget(
            req,
            Duration::from_secs(5),
            static_provider("test-frankfurter"),
        )
        .await
        .expect("static provider must succeed");
        assert_eq!(resp.rate_source, "test-frankfurter");
        assert_eq!(resp.rate_date.as_deref(), Some("2026-09-13"));
        let json = serde_json::to_string(&resp).unwrap();
        assert!(json.contains(r#""rate_source":"test-frankfurter""#));
    }

    #[tokio::test]
    async fn test_fx_pricing_response_rate_source_from_table() {
        let req = FxPricingRequest {
            cost_cny: 50.0,
            target_profit_rate: 0.3,
            currencies: "USD,EUR".into(),
            platform_rate: 0.15,
            safety_buffer: 0.05,
            lang: Some("en".into()),
        };
        let resp = run_fx_pricing(req, Duration::from_secs(5), static_provider("test-erapi"))
            .await
            .expect("static provider must succeed");
        assert_eq!(resp.rate_source, "test-erapi");
        assert_eq!(resp.rate_date.as_deref(), Some("2026-09-13"));
        let json = serde_json::to_string(&resp).unwrap();
        assert!(json.contains(r#""rate_source":"test-erapi""#));
    }

    // === 请求级超时 ===

    /// 测试用慢 provider:睡过超时窗口后返回错误(模拟上游卡死)。
    struct SlowProvider {
        delay: Duration,
    }

    impl RateProvider for SlowProvider {
        fn rates(&self) -> Result<crate::math::fx::RateTable, crate::core::CalcError> {
            std::thread::sleep(self.delay);
            Err(crate::core::CalcError::dependency_unavailable(
                "upstream stalled",
            ))
        }

        fn name(&self) -> &'static str {
            "slow"
        }
    }

    #[tokio::test]
    async fn test_fx_budget_timeout_returns_503() {
        let req = FxBudgetRequest {
            tuition: 50000.0,
            tuition_currency: "USD".into(),
            living_cost_monthly: None,
            duration_years: 4,
            home_currency: "CNY".into(),
            lang: None,
        };
        let provider: Arc<dyn RateProvider> = Arc::new(SlowProvider {
            delay: Duration::from_secs(5),
        });
        let err = run_fx_budget(req, Duration::from_secs(1), provider)
            .await
            .expect_err("slow provider must hit request timeout");
        match err {
            ApiError::ServiceUnavailable {
                service,
                retry_after,
                ..
            } => {
                assert_eq!(service, "fx_budget");
                assert_eq!(retry_after, Some(1));
            }
            other => panic!("期望 ServiceUnavailable,得到 {other:?}"),
        }
    }

    #[tokio::test]
    async fn test_fx_pricing_timeout_returns_503() {
        let req = FxPricingRequest {
            cost_cny: 50.0,
            target_profit_rate: 0.3,
            currencies: "USD,EUR".into(),
            platform_rate: 0.15,
            safety_buffer: 0.05,
            lang: None,
        };
        let provider: Arc<dyn RateProvider> = Arc::new(SlowProvider {
            delay: Duration::from_secs(5),
        });
        let err = run_fx_pricing(req, Duration::from_secs(1), provider)
            .await
            .expect_err("slow provider must hit request timeout");
        match err {
            ApiError::ServiceUnavailable {
                service,
                retry_after,
                ..
            } => {
                assert_eq!(service, "fx_pricing");
                assert_eq!(retry_after, Some(1));
            }
            other => panic!("期望 ServiceUnavailable,得到 {other:?}"),
        }
    }

    // === shared_provider 单例 ===

    #[test]
    fn test_shared_provider_returns_same_instance() {
        let p1 = shared_provider();
        let p2 = shared_provider();
        assert!(
            Arc::ptr_eq(&p1, &p2),
            "shared_provider should return same instance"
        );
    }
}