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
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: MIT

//! CalNexus CLI:命令行数学表达式求值器。
//! 退出码:0=成功,1=计算/解析错误,2=用法错误,3=超时。
use crate::core::evaluate;
use crate::domains::format_bigrational;
use crate::output::{format_canonical, format_latex, generate_steps};
use crate::{AstCanonicalizer, CacheManager, CalcError, EvalContext, EvalResult, parse};
use sdforge::clap::{self, CommandFactory, FromArgMatches, Parser};
use std::io::{self, IsTerminal, Read};

#[derive(Parser)]
#[command(
    name = "calnexus",
    version,
    about = "CalNexus: math expression evaluator",
    long_about = None
)]
struct Cli {
    /// Expression to evaluate (reads from stdin if omitted and piped)
    expression: Option<String>,

    /// Variable binding: --var NAME=VALUE (can be repeated)
    #[arg(long = "var")]
    vars: Vec<String>,

    /// Output result as JSON with domain and cache metadata
    #[arg(long, conflicts_with_all = ["latex", "canonical", "steps"])]
    json: bool,

    /// Output detailed error explanation
    #[arg(long, conflicts_with_all = ["json"])]
    explain: bool,

    /// Language for error messages: en or zh (default: auto-detect from system locale)
    #[arg(long, value_parser = clap::builder::PossibleValuesParser::new(["en", "zh"]))]
    lang: Option<String>,

    /// Arbitrary precision mode: format result to N decimal places using BigRational arithmetic
    #[arg(long, conflicts_with_all = ["canonical", "batch"])]
    precision: Option<usize>,

    /// Start interactive REPL mode (read-eval-print loop)
    #[arg(long, conflicts_with_all = ["canonical", "latex", "steps", "batch"])]
    repl: bool,

    /// Batch evaluate expressions from file ('-' for stdin), one expression per line
    #[arg(long, conflicts_with_all = ["canonical", "latex", "steps", "precision", "repl"])]
    batch: Option<String>,

    /// Render result as LaTeX (e.g., matrices as `\begin{pmatrix}...`)
    #[arg(long, conflicts_with_all = ["json", "canonical"])]
    latex: bool,

    /// Display step-by-step evaluation (e.g., `2+9=11` for `(2+9)*7-6`)
    #[arg(long, conflicts_with_all = ["json", "canonical"])]
    steps: bool,

    /// Print canonical S-expression form (e.g., `(+ 2 3)` for `3+2`), skip evaluation
    #[arg(long, conflicts_with_all = ["json", "latex", "steps", "precision", "repl", "batch"])]
    canonical: bool,

    /// Evaluation timeout in seconds (0.1-3600, default 5; env: CALNEXUS_TIMEOUT)
    #[arg(long)]
    timeout: Option<f64>,

    /// Cache entry budget, approximate (entries x 4KB byte cap; env: CALNEXUS_CACHE_SIZE)
    #[arg(long)]
    cache_size: Option<u64>,

    /// HTTP server bind address (default 127.0.0.1:3000; env: CALNEXUS_BIND_ADDR)
    #[cfg(feature = "server")]
    #[arg(long)]
    bind: Option<String>,

    /// List all available functions grouped by domain, then exit
    #[arg(long)]
    list_functions: bool,

    /// Start HTTP server mode (POST /api/v1/evaluate). Requires `server` feature.
    #[cfg(feature = "server")]
    #[arg(long, conflicts_with_all = ["repl", "batch", "canonical", "latex", "steps", "json", "explain", "precision", "serve_mcp"])]
    serve_http: bool,

    /// Start MCP server mode (evaluate tool, stdio transport). Requires `server` feature.
    #[cfg(feature = "server")]
    #[arg(long, conflicts_with_all = ["repl", "batch", "canonical", "latex", "steps", "json", "explain", "precision", "serve_http"])]
    serve_mcp: bool,
}

/// CLI 入口:解析参数、分发到对应模式处理函数,返回退出码。
pub fn run() -> i32 {
    // --help 本地化:clap derive 只接受静态 help 字符串,故在解析前预读 --lang
    // 构造 I18n 覆盖 about/help;运行时语言仍以解析出的 cli.lang 为准。
    let about_i18n = peek_lang_i18n();
    let matches = localized_command(&about_i18n).get_matches();
    let cli = Cli::from_arg_matches(&matches).unwrap_or_else(|e| e.exit());
    // 语言优先级:--lang 显式指定 > 系统语言检测链;--lang 无默认值,缺省即检测。
    let i18n = match cli.lang.as_deref() {
        Some(lang) => crate::i18n::I18n::from_str(lang),
        None => crate::i18n::I18n::from_detected(),
    };

    // 配置面:timeout / cache-size 统一解析
    // (优先级 flag > env > default;非法 env 值显性报错而非静默回退)
    let timeout_secs = match resolve_timeout(&i18n, cli.timeout) {
        Ok(t) => t,
        Err(msg) => {
            eprintln!("calnexus: {}", msg);
            return 2;
        }
    };
    let cache_budget = match cache_budget_bytes(&i18n, cli.cache_size) {
        Ok(b) => b,
        Err(msg) => {
            eprintln!("calnexus: {}", msg);
            return 2;
        }
    };

    // --serve-http / --serve-mcp 模式:启动 server(阻塞运行,内部创建 tokio runtime)
    #[cfg(feature = "server")]
    if cli.serve_http || cli.serve_mcp {
        return run_server_mode(&cli, &i18n);
    }

    // --list-functions:运行时函数目录
    if cli.list_functions {
        return run_list_functions();
    }

    // --repl 模式:启动交互式 REPL
    if cli.repl {
        return run_repl_mode(&cli, &i18n, timeout_secs, cache_budget);
    }

    // --batch 模式:批量求值
    if let Some(path) = &cli.batch {
        return run_batch_mode(path, &cli, &i18n, timeout_secs, cache_budget);
    }

    // 以下模式需要表达式(位置参数或 stdin)
    let expr = match get_expression(&cli, &i18n) {
        Ok(e) => e,
        Err(e) => return handle_error(&e, &cli, &i18n),
    };

    let mut ctx = match parse_vars(&cli.vars) {
        Ok(ctx) => ctx,
        Err(e) => return handle_error(&e, &cli, &i18n),
    };
    ctx.precision = cli.precision;
    ctx.timeout = std::time::Duration::from_secs_f64(timeout_secs);

    if cli.canonical {
        run_canonical_mode(&expr, &cli, &i18n)
    } else if cli.latex || cli.steps {
        run_latex_steps_mode(&expr, &ctx, &cli, &i18n)
    } else {
        run_default_mode(&expr, &ctx, &cli, &i18n, cache_budget)
    }
}

/// 预读原始参数中的 `--lang`,构造用于 `--help` 文案的 I18n。
///
/// 无 `--lang` 时走系统语言检测链(与运行时语言选择一致)。
fn peek_lang_i18n() -> crate::i18n::I18n {
    let mut args = std::env::args_os().skip(1);
    while let Some(arg) = args.next() {
        let arg = arg.to_string_lossy();
        if let Some(value) = arg.strip_prefix("--lang=") {
            return crate::i18n::I18n::from_str(value);
        }
        if arg == "--lang"
            && let Some(value) = args.next()
        {
            return crate::i18n::I18n::from_str(&value.to_string_lossy());
        }
    }
    crate::i18n::I18n::from_detected()
}

/// 本地化 help 的 clap Command:derive 只收静态字符串,用 mut_arg 按语言覆盖各参数 help。
fn localized_command(i18n: &crate::i18n::I18n) -> clap::Command {
    const ARG_HELP: &[(&str, &str)] = &[
        ("expression", "cli.help_expression"),
        ("vars", "cli.help_var"),
        ("json", "cli.help_json"),
        ("explain", "cli.help_explain"),
        ("lang", "cli.help_lang"),
        ("precision", "cli.help_precision"),
        ("repl", "cli.help_repl"),
        ("batch", "cli.help_batch"),
        ("latex", "cli.help_latex"),
        ("steps", "cli.help_steps"),
        ("canonical", "cli.help_canonical"),
        ("timeout", "cli.help_timeout"),
        ("cache_size", "cli.help_cache_size"),
        ("list_functions", "cli.help_list_functions"),
    ];
    let mut cmd = Cli::command().about(i18n.t("cli.about"));
    for (id, key) in ARG_HELP {
        let text = i18n.t(key);
        cmd = cmd.mut_arg(*id, move |arg| arg.help(text));
    }
    #[cfg(feature = "server")]
    {
        cmd = cmd.mut_arg("bind", |arg| arg.help(i18n.t("cli.help_bind")));
        cmd = cmd.mut_arg("serve_http", |arg| arg.help(i18n.t("cli.help_serve_http")));
        cmd = cmd.mut_arg("serve_mcp", |arg| arg.help(i18n.t("cli.help_serve_mcp")));
    }
    cmd
}

/// --list-functions:按域分组打印函数目录,退出码 0。
fn run_list_functions() -> i32 {
    for (domain, functions) in crate::function_catalog::DOMAIN_FUNCTIONS {
        println!("{}:", domain);
        for f in *functions {
            println!("  {}", f);
        }
    }
    0
}

/// 启动 HTTP/MCP server 模式。
#[cfg(feature = "server")]
fn run_server_mode(cli: &Cli, i18n: &crate::i18n::I18n) -> i32 {
    // server 模式同样消费配置面
    let cache_budget = match cache_budget_bytes(i18n, cli.cache_size) {
        Ok(b) => b,
        Err(msg) => {
            eprintln!("calnexus: {}", msg);
            return 2;
        }
    };
    crate::server::init_shared_cache(cache_budget);

    let server_result = if cli.serve_http {
        let bind = match resolve_bind(i18n, cli.bind.clone()) {
            Ok(addr) => addr,
            Err(msg) => {
                eprintln!("calnexus: {}", msg);
                return 2;
            }
        };
        crate::server::HttpServer::new().with_addr(bind).run()
    } else {
        crate::server::McpServer::new().run()
    };
    match server_result {
        Ok(()) => 0,
        Err(e) => {
            eprintln!("{}", e);
            1
        }
    }
}

/// --repl 模式:解析变量绑定并启动交互式 REPL。
fn run_repl_mode(cli: &Cli, i18n: &crate::i18n::I18n, timeout_secs: f64, cache_budget: u64) -> i32 {
    let mut ctx = match parse_vars(&cli.vars) {
        Ok(ctx) => ctx,
        Err(e) => return handle_error(&e, cli, i18n),
    };
    ctx.precision = cli.precision;
    ctx.timeout = std::time::Duration::from_secs_f64(timeout_secs);
    let cache = crate::CacheManager::with_capacity_bytes(cache_budget);
    crate::repl::ReplSession::with_cache(ctx, i18n.clone(), cache).run()
}

/// --batch 模式:解析变量绑定并批量求值。
fn run_batch_mode(
    path: &str,
    cli: &Cli,
    i18n: &crate::i18n::I18n,
    timeout_secs: f64,
    cache_budget: u64,
) -> i32 {
    let mut ctx = match parse_vars(&cli.vars) {
        Ok(ctx) => ctx,
        Err(e) => return handle_error(&e, cli, i18n),
    };
    ctx.timeout = std::time::Duration::from_secs_f64(timeout_secs);
    let cache = crate::CacheManager::with_capacity_bytes(cache_budget);
    crate::batch::BatchProcessor::run_with_cache(path, &ctx, cli.json, i18n, cache)
}

/// --canonical 模式:parse → canonicalize_no_fold → 输出 S-expr,跳过求值。
fn run_canonical_mode(expr: &str, cli: &Cli, i18n: &crate::i18n::I18n) -> i32 {
    let ast = match parse(expr) {
        Ok(ast) => ast,
        Err(e) => return handle_error(&e, cli, i18n),
    };
    match AstCanonicalizer::canonicalize_no_fold(&ast) {
        Ok((_canonical_ast, cf)) => {
            println!("{}", format_canonical(&cf));
            0
        }
        Err(e) => handle_error(&e, cli, i18n),
    }
}

/// --latex 和/或 --steps 模式:解析 + 规范化 + 求值 + 格式化输出。
fn run_latex_steps_mode(expr: &str, ctx: &EvalContext, cli: &Cli, i18n: &crate::i18n::I18n) -> i32 {
    let ast = match parse(expr) {
        Ok(ast) => ast,
        Err(e) => return handle_error(&e, cli, i18n),
    };
    let (canonical_ast, _cf) = match AstCanonicalizer::canonicalize(&ast) {
        Ok(pair) => pair,
        Err(e) => return handle_error(&e, cli, i18n),
    };

    // --steps 先输出步骤(基于原始 AST,避免常量折叠后无步骤可显示)
    if cli.steps {
        match generate_steps(&ast, ctx) {
            Ok(step_lines) => {
                for line in &step_lines {
                    println!("{}", line);
                }
            }
            Err(e) => return handle_error(&e, cli, i18n),
        }
    }

    if cli.latex {
        let cache = CacheManager::with_capacity_bytes(crate::core::DEFAULT_MAX_WEIGHT_BYTES);
        match evaluate(expr, ctx, cli.precision, &cache) {
            Ok((result, _domain, _cache_hit, fmt_prec)) => {
                let latex_str = format_latex(&result, &canonical_ast, expr, fmt_prec);
                println!("{}", latex_str);
            }
            Err(e) => return handle_error(&e, cli, i18n),
        }
    }
    0
}

/// 默认模式:求值 + 输出(JSON 或文本)。
fn run_default_mode(
    expr: &str,
    ctx: &EvalContext,
    cli: &Cli,
    i18n: &crate::i18n::I18n,
    cache_budget: u64,
) -> i32 {
    let cache = CacheManager::with_capacity_bytes(cache_budget);
    match evaluate(expr, ctx, cli.precision, &cache) {
        Ok((result, domain, cache_hit, fmt_prec)) => {
            if cli.json {
                println!(
                    "{}",
                    format_json_output(&result, &domain, cache_hit, fmt_prec)
                );
            } else {
                println!("{}", format_result(&result, fmt_prec));
            }
            0
        }
        Err(e) => handle_error(&e, cli, i18n),
    }
}

/// 格式化 EvalResult 为 JSON 输出字符串(代码见 v1 契约 docs/schema/result-v1.json)。
fn format_json_output(
    result: &EvalResult,
    domain: &str,
    cache_hit: bool,
    fmt_prec: Option<usize>,
) -> String {
    // serde_json 统一构造 + 契约版本字段 "v":1。
    // result 类型判别:Scalar 为数值、Complex 为 {re,im}、Steps 为字符串数组,
    // 其余变体为文本形态字符串。契约详见 docs/schema/result-v1.json。
    let cache_str = if cache_hit { "hit" } else { "miss" };
    let result_value = match result {
        EvalResult::Scalar(v) => serde_json::json!(*v),
        EvalResult::Complex(re, im) => serde_json::json!({ "re": re, "im": im }),
        EvalResult::Steps(v) => serde_json::json!(v),
        _ => serde_json::json!(format_result(result, fmt_prec)),
    };
    crate::core::sort_json_keys(serde_json::json!({
        "v": 1,
        "result": result_value,
        "domain": domain,
        "cache": cache_str,
    }))
    .to_string()
}

/// 根据 CLI 配置输出 CalcError 并返回退出码(JSON/解释/友好提示三态)。
fn handle_error(e: &CalcError, cli: &Cli, i18n: &crate::i18n::I18n) -> i32 {
    // caret 渲染需要原始表达式:位置参数场景直接可得(stdin 场景为 None,无 caret)
    handle_error_with_expr(e, cli.expression.as_deref(), cli, i18n)
}

/// 错误渲染:JSON / 教育模式 / 文本三态;`undefined_symbol` 的 hint 按上下文分发
/// (CLI 给 `--var`,REPL 给 `:let`)。
fn handle_error_with_expr(
    e: &CalcError,
    expr: Option<&str>,
    cli: &Cli,
    i18n: &crate::i18n::I18n,
) -> i32 {
    if cli.json {
        // to_json() 已返回 {"error":{...}} 完整结构,无需再包装
        println!("{}", e.to_json());
        return e.kind.exit_code();
    }

    // undefined_symbol hint 上下文化:CLI 语境给 --var(REPL 语境保留 :let)
    let mut contextual = e.clone();
    let is_undefined_symbol = contextual.kind == CalcError::undefined_symbol("").kind
        || contextual.i18n_key == Some("msg.unbound_variable");
    if is_undefined_symbol {
        // 变量名优先取 i18n 参数,其次兼容两种 message 前缀
        // (undefined_symbol() 前缀 / mathexpr "Unbound variable: x")
        let name = contextual
            .i18n_args
            .iter()
            .find(|(k, _)| k == "name")
            .map(|(_, v)| v.clone())
            .or_else(|| {
                contextual
                    .message
                    .strip_prefix("undefined symbol: ")
                    .or_else(|| contextual.message.strip_prefix("Unbound variable: "))
                    .map(str::to_string)
            });
        if let Some(name) = name {
            // hint 双轨:raw hint 保持英文原文(机器契约,to_json() 输出),同时附上
            // 键控 hint(hint.define_via_var)供 friendly()/to_explain() 本地化渲染。
            // 注意需覆盖 undefined_symbol() 构造时预设的 hint.undefined_symbol 键。
            contextual.hint = Some(format!("define it via --var {name}=<value>"));
            contextual = contextual.with_hint_i18n(
                "hint.define_via_var",
                vec![("name".to_string(), name.clone())],
            );
        }
    }
    let e = &contextual;

    if cli.explain {
        eprintln!("{}", e.to_explain(i18n));
    } else {
        eprintln!("{}: {}", i18n.t("cli.error_prefix"), e.friendly(i18n));
    }

    // caret 位置指示(仅文本模式;span 指向原始输入)
    if let (Some(expr_text), Some(span)) = (expr, &e.span) {
        let chars: Vec<char> = expr_text.chars().collect();
        let start = span.start.min(chars.len());
        let end = span.end.min(chars.len()).max(start).max(start + 1);
        eprintln!("  | {}", expr_text);
        eprint!("  | ");
        for _ in 0..start {
            eprint!(" ");
        }
        for _ in start..end {
            eprint!("^");
        }
        eprintln!();
    }

    e.kind.exit_code()
}

/// 从位置参数或 stdin 获取表达式;错误附加 i18n 键供调用方本地化渲染。
fn get_expression(cli: &Cli, i18n: &crate::i18n::I18n) -> Result<String, CalcError> {
    if let Some(expr) = &cli.expression {
        return Ok(expr.clone());
    }
    // 无位置参数:检查 stdin
    if io::stdin().is_terminal() {
        // TTY stdin:显示 help 并退出(about 与参数 help 均与 run() 同源本地化)
        localized_command(i18n)
            .try_get_matches_from(["calnexus", "--help"])
            .unwrap_or_else(|e| e.exit());
        return Err(CalcError::usage(String::new())); // unreachable:clap 会先退出
    }
    // 管道 stdin:读取表达式
    let mut input = String::new();
    if io::stdin().read_to_string(&mut input).is_err() {
        return Err(CalcError::usage("failed to read from stdin")
            .with_i18n("cli.stdin_read_failed", vec![]));
    }
    let trimmed = input.trim().to_string();
    if trimmed.is_empty() {
        return Err(
            CalcError::usage("empty expression on stdin").with_i18n("cli.empty_stdin", vec![])
        );
    }
    Ok(trimmed)
}

/// 解析求值超时(秒),优先级 flag > env(`CALNEXUS_TIMEOUT`) > 默认 5.0。
fn resolve_timeout(i18n: &crate::i18n::I18n, cli_value: Option<f64>) -> Result<f64, String> {
    const DEFAULT_TIMEOUT_SECS: f64 = 5.0;
    const MIN: f64 = 0.1;
    const MAX: f64 = 3600.0;
    let raw = match cli_value {
        Some(v) => v,
        None => match std::env::var("CALNEXUS_TIMEOUT") {
            // 注意:'{s}' 报告原始(未 trim)环境变量值,与历史文案一致
            Ok(s) => s
                .trim()
                .parse::<f64>()
                .map_err(|_| i18n.tf("cli.invalid_timeout_env", &[("value", s.as_str())]))?,
            Err(_) => DEFAULT_TIMEOUT_SECS,
        },
    };
    if !(MIN..=MAX).contains(&raw) {
        return Err(i18n.tf(
            "cli.timeout_out_of_range",
            &[
                ("value", raw.to_string().as_str()),
                ("min", MIN.to_string().as_str()),
                ("max", MAX.to_string().as_str()),
            ],
        ));
    }
    Ok(raw)
}

/// 解析缓存条目预算并换算为字节权重上限(条目 × 4KB,近似语义)。
fn cache_budget_bytes(i18n: &crate::i18n::I18n, cli_value: Option<u64>) -> Result<u64, String> {
    const DEFAULT_CACHE_SIZE: u64 = 10_000;
    const BYTES_PER_ENTRY: u64 = 4096;
    let entries = match cli_value {
        Some(n) => n,
        None => match std::env::var("CALNEXUS_CACHE_SIZE") {
            // 注意:'{s}' 报告原始(未 trim)环境变量值,与历史文案一致
            Ok(s) => s
                .trim()
                .parse::<u64>()
                .map_err(|_| i18n.tf("cli.invalid_cache_size_env", &[("value", s.as_str())]))?,
            Err(_) => DEFAULT_CACHE_SIZE,
        },
    };
    if entries == 0 {
        return Err(i18n.t("cli.cache_size_invalid").to_string());
    }
    Ok(entries.saturating_mul(BYTES_PER_ENTRY).max(BYTES_PER_ENTRY))
}

/// 解析 HTTP 绑定地址,优先级 flag > env(`CALNEXUS_BIND_ADDR`) > 默认 127.0.0.1:3000。
#[cfg(feature = "server")]
fn resolve_bind(i18n: &crate::i18n::I18n, cli_value: Option<String>) -> Result<String, String> {
    const DEFAULT_BIND: &str = "127.0.0.1:3000";
    match cli_value {
        Some(addr) => Ok(addr),
        None => match std::env::var("CALNEXUS_BIND_ADDR") {
            Ok(s) if !s.trim().is_empty() => Ok(s.trim().to_string()),
            Ok(_) => Err(i18n.tf("cli.invalid_bind_addr", &[("reason", "empty value")])),
            Err(_) => Ok(DEFAULT_BIND.to_string()),
        },
    }
}

fn parse_vars(vars: &[String]) -> Result<EvalContext, CalcError> {
    let mut ctx = EvalContext::new();
    for v in vars {
        let parts: Vec<&str> = v.splitn(2, '=').collect();
        if parts.len() != 2 {
            return Err(
                CalcError::usage(format!("invalid --var '{}', expected NAME=VALUE", v))
                    .with_i18n("cli.invalid_var", vec![("value".to_string(), v.clone())]),
            );
        }
        let value: f64 = parts[1].parse::<f64>().map_err(|e| {
            CalcError::usage(format!("invalid --var value '{}': {}", parts[1], e)).with_i18n(
                "cli.invalid_var_value",
                vec![
                    ("value".to_string(), parts[1].to_string()),
                    ("error".to_string(), e.to_string()),
                ],
            )
        })?;
        ctx = ctx.with_var(parts[0], value);
    }
    Ok(ctx)
}

/// 格式化 EvalResult 为人类可读字符串(非 JSON 模式),CLI 与 REPL 共用。
pub(crate) fn format_result(result: &EvalResult, fmt_prec: Option<usize>) -> String {
    match result {
        EvalResult::Scalar(v) => v.to_string(),
        EvalResult::Complex(re, im) => format_complex(*re, *im),
        EvalResult::Matrix(m) => format_matrix(m),
        EvalResult::BigInt(b) => b.to_string(),
        EvalResult::BigRational(r) => format_bigrational(r, fmt_prec),
        EvalResult::Vector(v) => format_vector(v),
        EvalResult::Polynomial(p) => format_polynomial(p),
        EvalResult::ComplexList(c) => format_complex_list(c),
        EvalResult::Symbolic(s) => s.clone(),
        EvalResult::LaTeX(s) => s.clone(),
        EvalResult::Steps(v) => v.join("\n"),
        EvalResult::Json(v) => v.to_string(),
        // DateTime:RFC3339 字符串直接输出
        EvalResult::DateTime(s) => s.clone(),
    }
}

/// 格式化复数为 `re+imi` 形式(如 `3+4i`、`-2-3i`、`5+0i`)。
fn format_complex(re: f64, im: f64) -> String {
    if im >= 0.0 {
        format!("{}+{}i", re, im)
    } else {
        format!("{}{}i", re, im)
    }
}

/// 格式化矩阵为 `[[a,b],[c,d]]` 形式。
fn format_matrix(m: &[Vec<f64>]) -> String {
    let rows: Vec<String> = m
        .iter()
        .map(|row| {
            let elems: Vec<String> = row.iter().map(|v| v.to_string()).collect();
            format!("[{}]", elems.join(","))
        })
        .collect();
    format!("[{}]", rows.join(","))
}

/// 格式化向量为 `[a,b,c]` 形式。
fn format_vector(v: &[f64]) -> String {
    let elems: Vec<String> = v.iter().map(|x| x.to_string()).collect();
    format!("[{}]", elems.join(","))
}

/// 格式化多项式系数向量(升幂存储)为降幂字符串形式(如 `[1,2,1]` → `x^2+2x+1`)。
fn format_polynomial(p: &[f64]) -> String {
    if p.is_empty() {
        return "0".to_string();
    }
    let terms: Vec<String> = p
        .iter()
        .enumerate()
        .rev()
        .filter_map(|(i, &coef)| format_polynomial_term(coef, i))
        .collect();
    if terms.is_empty() {
        return "0".to_string();
    }
    join_polynomial_terms(&terms)
}

/// 格式化多项式单项:零系数返回 None,i=0 常数项 / i=1 一次项 / i≥2 高次项。
fn format_polynomial_term(coef: f64, i: usize) -> Option<String> {
    if coef == 0.0 {
        return None;
    }
    let term = match i {
        0 => format!("{}", coef),
        1 => {
            if coef == 1.0 {
                "x".to_string()
            } else if coef == -1.0 {
                "-x".to_string()
            } else {
                format!("{}x", coef)
            }
        }
        _ => {
            if coef == 1.0 {
                format!("x^{}", i)
            } else if coef == -1.0 {
                format!("-x^{}", i)
            } else {
                format!("{}x^{}", coef, i)
            }
        }
    };
    Some(term)
}

/// 合并多项式单项为字符串:首项不加正号,后续正项加 `+`,负项直接拼接。
fn join_polynomial_terms(terms: &[String]) -> String {
    let mut result = terms[0].clone();
    for term in &terms[1..] {
        if term.starts_with('-') {
            result.push_str(term);
        } else {
            result.push('+');
            result.push_str(term);
        }
    }
    result
}

/// 格式化复数列表为 `[a+bi,c+di]` 形式。
fn format_complex_list(c: &[(f64, f64)]) -> String {
    let elems: Vec<String> = c.iter().map(|(re, im)| format_complex(*re, *im)).collect();
    format!("[{}]", elems.join(","))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{AstNode, BinaryOp};
    /// locales 文案引用的每个 `--flag` 必须在 clap 定义中存在(防 hint 指向不存在旗标)。
    #[test]
    fn locale_hint_flags_exist_in_clap_definition() {
        use clap::CommandFactory;
        let mut seen: Vec<String> = Vec::new();
        let cmd = Cli::command();
        let long_flags: Vec<String> = cmd
            .get_arguments()
            .filter_map(|a| a.get_long().map(|l| l.to_string()))
            .collect();

        for locale in ["en", "zh"] {
            let path = format!("locales/{locale}/messages.ftl");
            let raw = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {path}: {e}"));
            collect_ftl_values(&raw, &mut seen);
        }

        let flag_re = regex::Regex::new(r"--[a-z][a-z0-9_-]*").unwrap();
        // `--features` 是 cargo 构建旗标(非 CLI 旗标),合法出现于特性提示
        let external_flags = ["features"];
        let mut violations: Vec<String> = Vec::new();
        for text in &seen {
            for m in flag_re.find_iter(text) {
                let flag = m.as_str().trim_start_matches('-').to_string();
                if !long_flags.contains(&flag) && !external_flags.contains(&flag.as_str()) {
                    violations.push(format!("{text:?} 引用不存在的 --{flag}"));
                }
            }
        }
        assert!(
            violations.is_empty(),
            "locales 中存在指向不存在旗标的 hint:\n{}",
            violations.join("\n")
        );
    }

    /// CLI 不可达变体(Steps/LaTeX/Json/DateTime)经 format_json_output 输出合法 JSON。
    #[test]
    fn test_json_contract_non_cli_reachable_variants() {
        let variants: Vec<(EvalResult, &str)> = vec![
            (
                EvalResult::Steps(vec!["2+9=11".into(), "11*3=33".into()]),
                "steps",
            ),
            (EvalResult::LaTeX(r"\frac{1}{2}".into()), "latex"),
            (
                EvalResult::Json(serde_json::json!({"U": [[1.0]], "S": [1.0]})),
                "json",
            ),
            (
                EvalResult::DateTime("2026-09-14T00:00:00Z".into()),
                "datetime",
            ),
        ];
        for (result, name) in variants {
            let out = format_json_output(&result, "test", false, None);
            let parsed: serde_json::Value = serde_json::from_str(&out).unwrap_or_else(|e| {
                panic!(
                    "{name}: {}: {e}",
                    crate::i18n::global_t("panic.invalid_json")
                )
            });
            assert_eq!(parsed["v"], 1, "{name}: 契约版本必须为 1");
            assert!(
                parsed["result"].is_string() || parsed["result"].is_array(),
                "{name}: result 应为字符串或数组"
            );
        }
    }

    /// 从 FTL 文本提取全部消息值(`id = value` 行的 value 部分)。
    /// 引号字符串(保留首尾空白的值)与普通值一并收集。
    fn collect_ftl_values(ftl: &str, out: &mut Vec<String>) {
        for line in ftl.lines() {
            let trimmed = line.trim_start();
            if trimmed.is_empty() || trimmed.starts_with('#') {
                continue;
            }
            if let Some((_, value)) = line.split_once(" = ") {
                out.push(value.trim().to_string());
            }
        }
    }

    // ===== 配置面 i18n 键控文案测试(EN 渲染与历史硬编码逐字节一致) =====

    #[test]
    fn resolve_timeout_out_of_range_en_message_unchanged() {
        let i18n = crate::i18n::I18n::new(crate::i18n::Lang::En);
        let err = resolve_timeout(&i18n, Some(99999.0)).unwrap_err();
        assert_eq!(err, "--timeout 99999 out of range (0.1-3600 seconds)");
    }

    #[test]
    fn resolve_timeout_accepts_flag_value() {
        let i18n = crate::i18n::I18n::new(crate::i18n::Lang::En);
        assert_eq!(resolve_timeout(&i18n, Some(0.1)).unwrap(), 0.1);
        assert_eq!(resolve_timeout(&i18n, Some(3600.0)).unwrap(), 3600.0);
    }

    #[test]
    fn cache_budget_bytes_invalid_en_message_unchanged() {
        let i18n = crate::i18n::I18n::new(crate::i18n::Lang::En);
        let err = cache_budget_bytes(&i18n, Some(0)).unwrap_err();
        assert_eq!(err, "--cache-size must be a positive integer");
        assert_eq!(cache_budget_bytes(&i18n, Some(2)).unwrap(), 2 * 4096);
    }

    /// cli.about 已接入 clap `about`(--help 本地化):EN 覆盖文案与目录值一致。
    #[test]
    fn cli_about_override_matches_catalog_en() {
        let i18n = crate::i18n::I18n::new(crate::i18n::Lang::En);
        let cmd = Cli::command().about(i18n.t("cli.about"));
        assert_eq!(
            cmd.get_about().map(|s| s.to_string()).as_deref(),
            Some("CalNexus: math expression evaluator")
        );
    }

    /// localized_command 覆盖 about + 全部参数 help(clap help 本地化回归门)。
    #[test]
    fn localized_command_localizes_about_and_all_arg_helps() {
        let cases: [(&str, &str); 2] = [
            ("en", "CalNexus: math expression evaluator"),
            ("zh", "CalNexus: 数学表达式求值器"),
        ];
        for (lang_tag, about) in cases {
            let i18n = crate::i18n::I18n::from_str(lang_tag);
            let cmd = localized_command(&i18n);
            assert_eq!(
                cmd.get_about().map(|s| s.to_string()).as_deref(),
                Some(about),
                "lang {lang_tag}: about mismatch"
            );
            let arg_help: &[(&str, &str)] = &[
                ("expression", "cli.help_expression"),
                ("vars", "cli.help_var"),
                ("json", "cli.help_json"),
                ("explain", "cli.help_explain"),
                ("lang", "cli.help_lang"),
                ("precision", "cli.help_precision"),
                ("repl", "cli.help_repl"),
                ("batch", "cli.help_batch"),
                ("latex", "cli.help_latex"),
                ("steps", "cli.help_steps"),
                ("canonical", "cli.help_canonical"),
                ("timeout", "cli.help_timeout"),
                ("cache_size", "cli.help_cache_size"),
                ("list_functions", "cli.help_list_functions"),
            ];
            for (id, key) in arg_help {
                let arg = cmd
                    .get_arguments()
                    .find(|a| a.get_id() == *id)
                    .unwrap_or_else(|| panic!("arg {id} not found"));
                assert_eq!(
                    arg.get_help().map(|s| s.to_string()).as_deref(),
                    Some(i18n.t(key).as_str()),
                    "lang {lang_tag}: arg {id} help not localized"
                );
            }
            // zh 渲染必须含 CJK(本地化确实生效,而非回退英文原文)
            if lang_tag == "zh" {
                let vars_help = cmd
                    .get_arguments()
                    .find(|a| a.get_id() == "vars")
                    .and_then(|a| a.get_help().map(|s| s.to_string()))
                    .unwrap_or_default();
                assert!(
                    vars_help.chars().any(|c| c >= '\u{4e00}'),
                    "zh help should contain CJK, got {vars_help:?}"
                );
            }
        }
        // server 专属参数仅在 server feature 下覆盖
        #[cfg(feature = "server")]
        {
            let i18n = crate::i18n::I18n::new(crate::i18n::Lang::Zh);
            let cmd = localized_command(&i18n);
            for id in ["bind", "serve_http", "serve_mcp"] {
                let arg = cmd
                    .get_arguments()
                    .find(|a| a.get_id() == id)
                    .unwrap_or_else(|| panic!("arg {id} not found"));
                assert!(
                    arg.get_help()
                        .map(|s| s.to_string())
                        .is_some_and(|h| h.chars().any(|c| c >= '\u{4e00}')),
                    "server arg {id} help should be localized in zh"
                );
            }
        }
    }

    /// peek_lang_i18n 缺省路径:无 `--lang` 时须与系统检测链结果一致。
    #[test]
    fn peek_lang_i18n_without_flag_matches_detection() {
        assert_eq!(peek_lang_i18n().lang(), crate::i18n::detect_locale());
    }

    // ===== 新增 CLI 标志测试 =====

    #[test]
    fn test_canonicalize_no_fold_basic_addition() {
        // --canonical "3+2" → "(+ 2 3)"
        let ast = parse("3+2").unwrap();
        let (_, cf) = AstCanonicalizer::canonicalize_no_fold(&ast).unwrap();
        assert_eq!(cf.as_str(), "(+ 2 3)");
    }

    #[test]
    fn test_canonicalize_no_fold_equivalent_expressions() {
        let ast1 = parse("3+2").unwrap();
        let ast2 = parse("2+3").unwrap();
        let (_, cf1) = AstCanonicalizer::canonicalize_no_fold(&ast1).unwrap();
        let (_, cf2) = AstCanonicalizer::canonicalize_no_fold(&ast2).unwrap();
        assert_eq!(cf1.as_str(), cf2.as_str());
        assert_eq!(cf1.as_str(), "(+ 2 3)");
    }

    #[test]
    fn test_canonicalize_no_fold_multiplication() {
        let ast = parse("4*5").unwrap();
        let (_, cf) = AstCanonicalizer::canonicalize_no_fold(&ast).unwrap();
        assert_eq!(cf.as_str(), "(* 4 5)");
    }

    #[test]
    fn test_canonicalize_no_fold_does_not_constant_fold() {
        // 对比折叠版本:canonicalize_no_fold 保留 (+ 2 3)
        let ast = parse("2+3").unwrap();
        let (_, cf_fold) = AstCanonicalizer::canonicalize(&ast).unwrap();
        let (_, cf_no_fold) = AstCanonicalizer::canonicalize_no_fold(&ast).unwrap();
        assert_eq!(cf_fold.as_str(), "5", "folded version");
        assert_eq!(cf_no_fold.as_str(), "(+ 2 3)", "no-fold version");
    }

    #[test]
    fn test_canonicalize_no_fold_preserves_double_neg_elimination() {
        // 使用 -(2+3) 形式:保留外层 neg,内部 (+ 2 3) 排序
        let ast = parse("-(2+3)").unwrap();
        let (_, cf) = AstCanonicalizer::canonicalize_no_fold(&ast).unwrap();
        assert_eq!(cf.as_str(), "(- (+ 2 3))");
    }

    #[test]
    fn test_canonicalize_no_fold_does_not_fold_neg_number() {
        // -5 保留为 (- 5),不折叠;构造 -(5) 形式绕开 parser 对负数字面量的处理
        let ast = parse("0-5").unwrap();
        let (_, cf) = AstCanonicalizer::canonicalize_no_fold(&ast).unwrap();
        assert_eq!(cf.as_str(), "(- 0 5)");
    }

    #[test]
    fn test_canonicalize_no_fold_function_call() {
        let ast = parse("sin(x)+cos(y)").unwrap();
        let (_, cf) = AstCanonicalizer::canonicalize_no_fold(&ast).unwrap();
        // Add/Mul 规范串按条目排序:(cos y) 先于 (sin x)
        assert_eq!(cf.as_str(), "(+ (cos y) (sin x))");
    }

    #[test]
    fn test_format_canonical_wrapper() {
        use crate::CanonicalForm;
        use crate::output::format_canonical;
        let cf = CanonicalForm::new("(+ 2 3)");
        assert_eq!(format_canonical(&cf), "(+ 2 3)");
    }

    #[test]
    fn test_format_latex_dispatch_scalar() {
        use crate::output::format_latex;
        let r = EvalResult::Scalar(42.0);
        let ast = AstNode::Number(42.0);
        assert_eq!(format_latex(&r, &ast, "42", None), "42");
    }

    #[test]
    fn test_format_latex_dispatch_matrix() {
        use crate::output::format_latex;
        let r = EvalResult::Matrix(vec![vec![1.0, 2.0], vec![3.0, 4.0]]);
        let ast = AstNode::Number(0.0);
        assert_eq!(
            format_latex(&r, &ast, "[[1,2],[3,4]]", None),
            "\\begin{pmatrix}1 & 2 \\\\ 3 & 4\\end{pmatrix}"
        );
    }

    #[test]
    fn test_format_latex_dispatch_symbolic_diff() {
        use crate::output::format_latex;
        let r = EvalResult::Symbolic("2*x".to_string());
        let ast = AstNode::FunctionCall(
            "diff".to_string(),
            vec![
                AstNode::BinaryOp(
                    BinaryOp::Pow,
                    Box::new(AstNode::Variable("x".to_string())),
                    Box::new(AstNode::Number(2.0)),
                ),
                AstNode::Variable("x".to_string()),
            ],
        );
        let s = format_latex(&r, &ast, "diff(x^2,x)", None);
        assert_eq!(s, "\\frac{d}{dx}\\left(x^{2}\\right) = 2 \\cdot x");
    }

    #[test]
    fn test_generate_steps_basic() {
        use crate::output::generate_steps;
        // 步骤必须基于原始 AST(未折叠),否则常量折叠后无步骤可显示
        let ast = parse("(2+9)*7-6").unwrap();
        let ctx = EvalContext::new();
        let steps = generate_steps(&ast, &ctx).unwrap();
        // 2+9=11 → 11*7=77 → 77-6=71
        assert_eq!(steps, vec!["2+9=11", "11*7=77", "77-6=71"]);
    }

    #[test]
    fn test_format_result_handles_latex_variant() {
        let r = EvalResult::LaTeX("\\alpha".to_string());
        assert_eq!(format_result(&r, None), "\\alpha");
    }

    #[test]
    fn test_format_result_handles_steps_variant() {
        let r = EvalResult::Steps(vec!["1+1=2".to_string(), "2+2=4".to_string()]);
        assert_eq!(format_result(&r, None), "1+1=2\n2+2=4");
    }
}