lemma 0.8.19

A language that means business.
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
use anyhow::{Context, Result};
use chrono::NaiveDate;
use inquire::validator::Validation;
use inquire::{DateSelect, MultiSelect, Select, Text};
use lemma::{DateTimeValue, LemmaRepository, LemmaSpec};
use lemma::{EffectiveDate, Engine, LemmaType, LiteralValue, TypeSpecification, ValueKind};
use rust_decimal::Decimal;
use std::collections::HashMap;
use std::sync::Arc;

pub(crate) fn repo_label(repository: &LemmaRepository) -> String {
    match &repository.name {
        Some(name) => name.clone(),
        None => "(workspace)".to_string(),
    }
}

/// Repository qualifier, spec name, selected rules, merged data (CLI + prompts).
pub type InteractiveResult = (
    Option<String>,
    String,
    Option<Vec<String>>,
    HashMap<String, String>,
);

#[derive(Clone, Debug)]
struct TextConstraints {
    length: Option<usize>,
    help: String,
}

#[derive(Clone, Debug)]
struct NumericConstraints {
    minimum: Option<Decimal>,
    maximum: Option<Decimal>,
    decimals: Option<u8>,
    help: String,
}

fn get_plan_for_interactive<'a>(
    engine: &'a Engine,
    repo: Option<&str>,
    name: &str,
    now: &DateTimeValue,
) -> Result<&'a lemma::ExecutionPlan> {
    engine
        .get_plan(repo, name, Some(now))
        .map_err(|e| anyhow::anyhow!("{}", e))
}

pub fn run_interactive(
    engine: &Engine,
    spec_name: Option<String>,
    rule_names: Option<Vec<String>>,
    provided_data: &HashMap<String, String>,
    now: &DateTimeValue,
    cli_repository_qualifier: Option<&str>,
) -> Result<InteractiveResult> {
    let (repository_qualifier, specification_name) = match spec_name {
        Some(name) => {
            // Validate the spec exists (will error on ambiguity when repository is None).
            get_plan_for_interactive(engine, cli_repository_qualifier, &name, now)?;
            (cli_repository_qualifier.map(String::from), name)
        }
        None => select_spec(engine, now, cli_repository_qualifier)?,
    };

    let rules = match rule_names {
        Some(names) => Some(names),
        None => select_rules(
            engine,
            repository_qualifier.as_deref(),
            &specification_name,
            now,
        )?,
    };

    let data = prompt_data(
        engine,
        repository_qualifier.as_deref(),
        &specification_name,
        &rules,
        provided_data,
        now,
    )?;

    Ok((repository_qualifier, specification_name, rules, data))
}

fn select_spec(
    engine: &Engine,
    now: &DateTimeValue,
    cli_repository_qualifier: Option<&str>,
) -> Result<(Option<String>, String)> {
    let effective_instant = EffectiveDate::DateTimeValue(now.clone());
    let mut pairs: Vec<(Arc<LemmaRepository>, Arc<LemmaSpec>)> = engine
        .list()
        .iter()
        .flat_map(|repo| {
            let repo_arc = Arc::clone(&repo.repository);
            let instant = effective_instant.clone();
            repo.specs.iter().filter_map(move |ss| {
                ss.spec_at(&instant)
                    .map(|spec| (Arc::clone(&repo_arc), spec))
            })
        })
        .collect();
    if let Some(q) = cli_repository_qualifier {
        let resolved = engine
            .get_repository(q)
            .map_err(|e| anyhow::anyhow!("{}", e))?;
        pairs.retain(|(repo, _)| Arc::ptr_eq(repo, &resolved.repository));
    }

    if pairs.is_empty() {
        anyhow::bail!("No specs found in workspace. Add .lemma files to get started.");
    }

    let needs_repo_qualifier = {
        let mut names: Vec<&str> = pairs.iter().map(|(_, s)| s.name.as_str()).collect();
        names.sort();
        names.windows(2).any(|w| w[0] == w[1])
    };

    let display_options: Vec<String> = pairs
        .iter()
        .map(|(repo, spec)| {
            let label = repo_label(repo);
            let rq = if needs_repo_qualifier {
                Some(label.as_str())
            } else {
                cli_repository_qualifier
            };
            let (data_count, rules_count) = get_plan_for_interactive(engine, rq, &spec.name, now)
                .ok()
                .map(|p| (p.data.len(), p.rules.len()))
                .unwrap_or((0, 0));
            format!(
                "{} ({}) — {} data, {} rules",
                spec.name, label, data_count, rules_count
            )
        })
        .collect();

    let selected = Select::new("Select a spec:", display_options.clone())
        .with_help_message("Use arrow keys to navigate, Enter to select")
        .prompt()
        .context("Failed to get spec selection")?;

    let spec_index = display_options
        .iter()
        .position(|d| d == &selected)
        .context("Failed to find selected spec index")?;

    let (r, s) = pairs
        .into_iter()
        .nth(spec_index)
        .context("Failed to match selected spec")?;
    let rq = if needs_repo_qualifier {
        Some(repo_label(&r))
    } else {
        cli_repository_qualifier.map(String::from)
    };
    Ok((rq, s.name.clone()))
}

fn select_rules(
    engine: &Engine,
    repo: Option<&str>,
    spec_name: &str,
    now: &DateTimeValue,
) -> Result<Option<Vec<String>>> {
    let plan = get_plan_for_interactive(engine, repo, spec_name, now)
        .context(format!("Spec '{}' not found", spec_name))?;
    let rule_names: Vec<String> = plan
        .schema(&lemma::DataOverlay::default())
        .rules
        .keys()
        .cloned()
        .collect();

    if rule_names.is_empty() {
        return Ok(None);
    }

    let selected = MultiSelect::new("Select rules to evaluate:", rule_names.clone())
        .with_default(&(0..rule_names.len()).collect::<Vec<_>>())
        .prompt()
        .context("Failed to get rule selection")?;

    if selected.is_empty() || selected.len() == rule_names.len() {
        Ok(None)
    } else {
        Ok(Some(selected))
    }
}

fn prompt_data(
    engine: &Engine,
    repo: Option<&str>,
    spec_name: &str,
    rule_names: &Option<Vec<String>>,
    provided_data: &HashMap<String, String>,
    now: &DateTimeValue,
) -> Result<HashMap<String, String>> {
    let base_plan = get_plan_for_interactive(engine, repo, spec_name, now)
        .context(format!("Spec '{}' not found", spec_name))?;

    let mut collected: HashMap<String, String> = HashMap::new();
    let mut header_printed = false;

    loop {
        let trial_values: HashMap<String, lemma::DataValueInput> = provided_data
            .iter()
            .chain(collected.iter())
            .map(|(k, v)| (k.clone(), lemma::DataValueInput::convenience(v.clone())))
            .collect();

        let overlay = lemma::DataOverlay::resolve(base_plan, trial_values, engine.limits())
            .map_err(|e| anyhow::anyhow!("{}", e))
            .context("Failed to apply collected values to plan")?;

        let schema = match rule_names {
            Some(names) if !names.is_empty() => base_plan
                .schema_for_rules(names, &overlay)
                .map_err(|e| anyhow::anyhow!("{}", e))
                .context("Failed to build schema for selected rules")?,
            _ => base_plan.schema(&overlay),
        };

        // Find the next data field that still needs a value from the user.
        // Fields that are bound (provided_data or collected) appear as bound_value.is_some().
        let next = schema
            .data
            .iter()
            .find(|(_, entry)| entry.bound_value.is_none());

        let (name, entry) = match next {
            Some(pair) => pair,
            None => break,
        };
        let name = name.clone();
        let entry = entry.clone();

        if !header_printed {
            println!("\nEnter values for data (press Enter to accept defaults):");
            header_printed = true;
        }

        loop {
            let input_value =
                prompt_value_for_type(&name, &entry.lemma_type, entry.default.as_ref())?;

            let mut validation_trial = provided_data.clone();
            validation_trial.extend(collected.clone());
            validation_trial.insert(name.clone(), input_value.clone());
            match engine.run_plan(
                base_plan,
                Some(now),
                validation_trial
                    .into_iter()
                    .map(|(k, v)| (k, lemma::DataValueInput::convenience(v)))
                    .collect(),
                false,
                rule_names.as_deref(),
            ) {
                Ok(_) => {
                    collected.insert(name.clone(), input_value);
                    break;
                }
                Err(e) => {
                    eprintln!("  {}\n", e);
                }
            }
        }
    }

    Ok(collected)
}

fn prompt_value_for_type(
    data_name: &str,
    lemma_type: &LemmaType,
    schema_default: Option<&LiteralValue>,
) -> Result<String> {
    let type_str = lemma_type.to_string();

    match &lemma_type.specifications {
        TypeSpecification::Boolean { .. } => prompt_boolean_data(data_name, schema_default),
        TypeSpecification::Text {
            options,
            length,
            help,
            ..
        } => {
            if !options.is_empty() {
                if options.len() == 1 {
                    return Ok(options[0].clone());
                }
                let prompt_message = format!("{} [{}]", data_name, type_str);
                let mut prompt =
                    Select::new(&prompt_message, options.clone()).with_help_message(help.as_str());
                if let Some(lit) = schema_default {
                    if let ValueKind::Text(s) = &lit.value {
                        if let Some(idx) = options.iter().position(|o| o == s) {
                            prompt = prompt.with_starting_cursor(idx);
                        }
                    }
                }
                prompt
                    .prompt()
                    .context(format!("Failed to get option for {}", data_name))
            } else {
                let constraints = TextConstraints {
                    length: *length,
                    help: help.clone(),
                };
                prompt_text_data_with_constraints(
                    data_name,
                    &type_str,
                    lemma_type,
                    schema_default,
                    &constraints,
                )
            }
        }
        TypeSpecification::Quantity {
            minimum,
            maximum,
            decimals,
            units,
            help,
            traits,
            decomposition,
            ..
        } => {
            let quantity_spec = TypeSpecification::Quantity {
                minimum: minimum.clone(),
                maximum: maximum.clone(),
                decimals: *decimals,
                units: units.clone(),
                traits: traits.clone(),
                decomposition: decomposition.clone(),
                help: help.clone(),
            };
            let constraints = NumericConstraints {
                minimum: quantity_spec.minimum_decimal(),
                maximum: quantity_spec.maximum_decimal(),
                decimals: *decimals,
                help: help.clone(),
            };
            prompt_quantity_data(data_name, &type_str, schema_default, units, &constraints)
        }
        TypeSpecification::Number {
            minimum,
            maximum,
            decimals,
            help,
            ..
        } => {
            let number_spec = TypeSpecification::Number {
                minimum: minimum.clone(),
                maximum: maximum.clone(),
                decimals: *decimals,
                help: help.clone(),
            };
            let constraints = NumericConstraints {
                minimum: number_spec.minimum_decimal(),
                maximum: number_spec.maximum_decimal(),
                decimals: *decimals,
                help: help.clone(),
            };
            prompt_number_data(data_name, &type_str, schema_default, &constraints)
        }
        TypeSpecification::Ratio {
            minimum,
            maximum,
            decimals,
            units,
            help,
            ..
        } => {
            let ratio_spec = TypeSpecification::Ratio {
                minimum: minimum.clone(),
                maximum: maximum.clone(),
                decimals: *decimals,
                units: units.clone(),
                help: help.clone(),
            };
            prompt_ratio_data(
                data_name,
                &type_str,
                schema_default,
                units,
                ratio_spec.minimum_decimal(),
                ratio_spec.maximum_decimal(),
                help.as_str(),
            )
        }
        TypeSpecification::Date { .. } => prompt_date_data(data_name, schema_default),
        TypeSpecification::Time { help, .. } => {
            let def = schema_default
                .filter(|l| matches!(l.value, ValueKind::Time(_)))
                .map(|l| l.to_string());
            prompt_simple_text(data_name, &type_str, def.as_deref(), help.as_str(), "12:34:56")
        }
        TypeSpecification::NumberRange { help, .. }
        | TypeSpecification::DateRange { help, .. }
        | TypeSpecification::TimeRange { help, .. }
        | TypeSpecification::QuantityRange { help, .. }
        | TypeSpecification::RatioRange { help, .. } => {
            prompt_range_data(data_name, &type_str, lemma_type, schema_default, help.as_str())
        }
        TypeSpecification::Veto { .. } => {
            anyhow::bail!("Data '{}' has veto type which is not promptable", data_name)
        }
        TypeSpecification::Undetermined => unreachable!(
            "BUG: prompt_value_for_type called with Error sentinel type; this type must never reach interactive mode"
        ),
    }
}

fn prompt_date_data(data_name: &str, schema_default: Option<&LiteralValue>) -> Result<String> {
    let help_message = if schema_default.is_some() {
        "Use arrow keys to navigate, Enter to select (or accept default)"
    } else {
        "Use arrow keys to navigate, Enter to select"
    };

    let prompt_title = format!("{} [date]", data_name);
    let mut ds = DateSelect::new(&prompt_title).with_help_message(help_message);

    if let Some(lit) = schema_default {
        if let ValueKind::Date(d) = &lit.value {
            if let Some(naive) = NaiveDate::from_ymd_opt(d.year, d.month, d.day) {
                ds = ds.with_default(naive);
            }
        }
    }

    let date = ds
        .prompt()
        .context(format!("Failed to get date for {}", data_name))?;

    Ok(format!("{}T00:00:00Z", date.format("%Y-%m-%d")))
}

fn prompt_boolean_data(data_name: &str, schema_default: Option<&LiteralValue>) -> Result<String> {
    let options = vec!["true", "false"];

    let default_index = match schema_default.and_then(|lit| match &lit.value {
        ValueKind::Boolean(b) => Some(*b),
        _ => None,
    }) {
        Some(true) => 0,
        Some(false) => 1,
        None => 0,
    };

    let help_message = if schema_default.is_some() {
        format!(
            "Default: {} - Use arrow keys to change, Enter to confirm",
            options[default_index]
        )
    } else {
        "Use arrow keys to select, Enter to confirm".to_string()
    };

    let selected = Select::new(&format!("{} [boolean]", data_name), options)
        .with_help_message(&help_message)
        .with_starting_cursor(default_index)
        .prompt()
        .context(format!("Failed to get boolean value for {}", data_name))?;

    Ok(selected.to_string())
}

fn prompt_text_data_with_constraints(
    data_name: &str,
    type_str: &str,
    lemma_type: &LemmaType,
    schema_default: Option<&LiteralValue>,
    constraints: &TextConstraints,
) -> Result<String> {
    let default_str = schema_default.map(|l| l.to_string());
    let prompt_message = format!("{} [{}]", data_name, type_str);
    let example = lemma_type.example_value();

    let TextConstraints { length, help } = constraints.clone();

    let validator = move |input: &str| {
        let s = input.trim();
        if s.is_empty() {
            return Ok(Validation::Invalid("Value is required".into()));
        }
        if let Some(len) = length {
            if s.chars().count() != len {
                return Ok(Validation::Invalid(
                    format!("Must be exactly {} characters", len).into(),
                ));
            }
        }
        Ok(Validation::Valid)
    };

    let mut prompt = Text::new(&prompt_message).with_validator(validator);
    let help_message = if help.is_empty() {
        format!("Example: {}", example)
    } else {
        help.clone()
    };
    prompt = prompt.with_help_message(&help_message);

    if let Some(default) = default_str.as_deref() {
        prompt = prompt.with_default(default);
    }

    prompt
        .prompt()
        .context(format!("Failed to get value for {}", data_name))
}

fn prompt_simple_text(
    data_name: &str,
    type_str: &str,
    default_value: Option<&str>,
    help: &str,
    example: &str,
) -> Result<String> {
    let prompt_message = format!("{} [{}]", data_name, type_str);
    let validator = |input: &str| {
        if input.trim().is_empty() {
            Ok(Validation::Invalid("Value is required".into()))
        } else {
            Ok(Validation::Valid)
        }
    };
    let mut prompt = Text::new(&prompt_message).with_validator(validator);
    let help_message = if help.is_empty() {
        format!("Example: {}", example)
    } else {
        help.to_string()
    };
    prompt = prompt.with_help_message(&help_message);
    if let Some(default) = default_value {
        prompt = prompt.with_default(default);
    }
    prompt
        .prompt()
        .context(format!("Failed to get value for {}", data_name))
}

fn prompt_range_data(
    data_name: &str,
    type_str: &str,
    lemma_type: &LemmaType,
    schema_default: Option<&LiteralValue>,
    help: &str,
) -> Result<String> {
    let (left_default, right_default) = match schema_default {
        Some(LiteralValue {
            value: ValueKind::Range(left, right),
            ..
        }) => (Some(left.display_value()), Some(right.display_value())),
        _ => (None, None),
    };

    let endpoint_example = match &lemma_type.specifications {
        TypeSpecification::DateRange { .. } => "2024-01-01",
        TypeSpecification::TimeRange { .. } => "09:00",
        TypeSpecification::NumberRange { .. } => "0",
        TypeSpecification::QuantityRange { .. } => "30 kilogram",
        TypeSpecification::RatioRange { .. } => "10%",
        _ => unreachable!("BUG: prompt_range_data called with non-range type"),
    };

    let left_value = prompt_simple_text(
        &format!("{}.start", data_name),
        type_str,
        left_default.as_deref(),
        help,
        endpoint_example,
    )?;
    let right_value = prompt_simple_text(
        &format!("{}.end", data_name),
        type_str,
        right_default.as_deref(),
        help,
        endpoint_example,
    )?;

    Ok(format!("{}...{}", left_value.trim(), right_value.trim()))
}

fn prompt_number_data(
    data_name: &str,
    type_str: &str,
    schema_default: Option<&LiteralValue>,
    constraints: &NumericConstraints,
) -> Result<String> {
    let default_str = schema_default.map(|l| l.to_string());
    let prompt_message = format!("{} [{}]", data_name, type_str);
    prompt_decimal_input(&prompt_message, default_str.as_deref(), constraints, "10")
}

fn prompt_quantity_data(
    data_name: &str,
    type_str: &str,
    schema_default: Option<&LiteralValue>,
    units: &lemma::QuantityUnits,
    constraints: &NumericConstraints,
) -> Result<String> {
    let parsed = schema_default.and_then(|lit| match &lit.value {
        ValueKind::Quantity(n, signature) => Some((
            n.clone(),
            signature.first().map(|(n, _)| n.as_str()).unwrap_or(""),
        )),
        _ => None,
    });

    let prompt_message = format!("{} [{}]", data_name, type_str);

    if units.is_empty() {
        let default_str = schema_default.and_then(|lit| lit.magnitude_default_for_decimal_prompt());
        return prompt_decimal_input(&prompt_message, default_str.as_deref(), constraints, "7.65");
    }

    let unit_names: Vec<String> = units.iter().map(|u| u.name.clone()).collect();
    let unit = if unit_names.len() == 1 {
        unit_names[0].clone()
    } else {
        let prompt_msg = format!("Select unit for {}", data_name);
        let mut select = Select::new(&prompt_msg, unit_names);
        if let Some((_, def_unit)) = parsed {
            if let Some(idx) = units.iter().position(|u| u.name == def_unit) {
                select = select.with_starting_cursor(idx);
            }
        }
        select
            .prompt()
            .context(format!("Failed to get unit for {}", data_name))?
    };

    let numeric_default = schema_default.and_then(|lit| lit.magnitude_default_for_decimal_prompt());

    let value_constraints = NumericConstraints {
        help: if constraints.help.is_empty() {
            format!("Enter numeric value (unit: {})", unit)
        } else {
            constraints.help.clone()
        },
        ..constraints.clone()
    };
    let value = prompt_decimal_input(
        &format!("Enter value for {} ({})", data_name, unit),
        numeric_default.as_deref(),
        &value_constraints,
        "7.65",
    )?;

    Ok(format!("{} {}", value, unit))
}

fn prompt_ratio_data(
    data_name: &str,
    type_str: &str,
    schema_default: Option<&LiteralValue>,
    units: &lemma::RatioUnits,
    minimum: Option<Decimal>,
    maximum: Option<Decimal>,
    help: &str,
) -> Result<String> {
    // Ratio types typically support percent/permille; offer a unit selector.
    let prompt_message = format!("{} [{}]", data_name, type_str);
    let default_decimal = schema_default.and_then(|lit| lit.magnitude_default_for_decimal_prompt());
    let selected_unit = if units.len() == 1 {
        units
            .iter()
            .next()
            .map(|u| u.name.clone())
            .unwrap_or_else(|| "(none)".to_string())
    } else {
        let mut unit_choices: Vec<String> = vec!["(none)".to_string()];
        unit_choices.extend(units.iter().map(|u| u.name.clone()));
        Select::new(
            &format!("Select ratio unit for {}", data_name),
            unit_choices,
        )
        .prompt()
        .context(format!("Failed to get ratio unit for {}", data_name))?
    };

    let value = prompt_decimal_input(
        &prompt_message,
        default_decimal.as_deref(),
        &NumericConstraints {
            minimum,
            maximum,
            decimals: None,
            help: help.to_string(),
        },
        "0.10",
    )?;

    match selected_unit.as_str() {
        "(none)" => Ok(value),
        "percent" => Ok(format!("{}%", value)),
        "permille" => Ok(format!("{}%%", value)),
        other => Ok(format!("{} {}", value, other)),
    }
}

fn prompt_decimal_input(
    prompt_message: &str,
    default_value: Option<&str>,
    constraints: &NumericConstraints,
    example: &str,
) -> Result<String> {
    let NumericConstraints {
        minimum: min,
        maximum: max,
        decimals: decs,
        help,
    } = constraints.clone();

    let validator = move |input: &str| {
        let raw = input.trim();
        if raw.is_empty() {
            return Ok(Validation::Invalid("Value is required".into()));
        }
        let clean = raw.replace(['_', ','], "");
        let provided_decimals = clean
            .split_once('.')
            .map(|(_, frac)| frac.len())
            .unwrap_or(0);
        if let Some(d) = decs {
            if provided_decimals > d as usize {
                return Ok(Validation::Invalid(
                    format!("Too many decimals (max {})", d).into(),
                ));
            }
        }
        let value = match Decimal::from_str_exact(&clean) {
            Ok(v) => v,
            Err(_) => {
                return Ok(Validation::Invalid(
                    format!("Invalid number: '{}'", raw).into(),
                ))
            }
        };
        if let Some(min) = min {
            if value < min {
                return Ok(Validation::Invalid(format!("Must be >= {}", min).into()));
            }
        }
        if let Some(max) = max {
            if value > max {
                return Ok(Validation::Invalid(format!("Must be <= {}", max).into()));
            }
        }
        Ok(Validation::Valid)
    };

    let mut prompt = Text::new(prompt_message).with_validator(validator);
    let help_message = if help.is_empty() {
        format!("Example: {}", example)
    } else {
        help.clone()
    };
    prompt = prompt.with_help_message(&help_message);

    if let Some(default) = default_value {
        prompt = prompt.with_default(default);
    }

    let raw = prompt.prompt().context(format!(
        "Failed to get numeric value for {}",
        prompt_message
    ))?;
    Ok(raw.trim().replace(['_', ','], ""))
}