wh40kdc 0.2.0

Warhammer 40K dataset for the 40kdc-data schema layer: generated types, an embedded dataset behind a linked typed API, plus ListForge + NewRecruit roster importers and exporters.
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
//! NDJSON conformance runner — the Rust implementation of the wire protocol
//! in `conformance/RUNNER_PROTOCOL.md`. Each line on stdin is a JSON request
//! `{op, args?}`; each line on stdout is a JSON response `{ok: true, value}`
//! or `{ok: false, error_kind, error_payload?}`.
//!
//! Structurally parallel to `tools/src/runner.ts`. Library consumers should
//! call the public API directly; this runner exists so the cross-impl differ
//! in `tooling/parity/` has a uniform interface across language ports.

use std::io::{self, BufRead, Write};
use std::path::PathBuf;

use serde::Serialize;
use serde_json::{json, Value};

use wh40kdc::cruncher::{
    attribute_stages, crunch, AttackProfileRef, AttributedStage, Buff, BuffSource, EngineContext,
    EngineInput, StageLift, StageName, TargetProfileRef,
};
use wh40kdc::export::{export_roster, ExportFormat};
use wh40kdc::import::{
    import_roster, try_import_roster, AdapterTrial, ImportFailureReason, ImportResult, Roster,
    RosterFormat,
};
use wh40kdc::{normalize_name, Dataset, Phase};

// ---------------------------------------------------------------------------
// Spec version + impl identity.
// ---------------------------------------------------------------------------

const IMPL_NAME: &str = "rust";
const IMPL_VERSION: &str = env!("CARGO_PKG_VERSION");

/// Walk up from `CARGO_MANIFEST_DIR` to find the `conformance/SPEC_VERSION`
/// file in the source tree. Mirrors the TS runner's parent-walk; lets the
/// binary work both from `cargo run` (manifest-relative) and a built artifact
/// (parent-relative, when the conformance dir is shipped alongside).
fn load_spec_version() -> i64 {
    let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    for ancestor in manifest.ancestors() {
        let candidate = ancestor.join("conformance").join("SPEC_VERSION");
        if let Ok(s) = std::fs::read_to_string(&candidate) {
            if let Ok(n) = s.trim().parse::<i64>() {
                return n;
            }
        }
    }
    panic!("could not locate conformance/SPEC_VERSION");
}

// ---------------------------------------------------------------------------
// Response envelope (hand-serialized to keep the JSON shape exactly matching
// the TS runner: ok-tagged with optional error_payload).
// ---------------------------------------------------------------------------

#[derive(Clone, Copy)]
enum ErrorKind {
    InvalidInput,
    UnknownOp,
    UnknownEntity,
    ImportFailed,
    ExportFailed,
    #[allow(dead_code)] // Reserved for a future Rust validator.
    ValidationError,
    CrunchError,
    #[allow(dead_code)]
    InternalError,
}

impl ErrorKind {
    fn as_str(self) -> &'static str {
        match self {
            ErrorKind::InvalidInput => "INVALID_INPUT",
            ErrorKind::UnknownOp => "UNKNOWN_OP",
            ErrorKind::UnknownEntity => "UNKNOWN_ENTITY",
            ErrorKind::ImportFailed => "IMPORT_FAILED",
            ErrorKind::ExportFailed => "EXPORT_FAILED",
            ErrorKind::ValidationError => "VALIDATION_ERROR",
            ErrorKind::CrunchError => "CRUNCH_ERROR",
            ErrorKind::InternalError => "INTERNAL_ERROR",
        }
    }
}

fn ok_value(value: Value) -> Value {
    json!({ "ok": true, "value": value })
}

fn err_value(kind: ErrorKind, payload: Option<Value>) -> Value {
    match payload {
        Some(p) => json!({ "ok": false, "error_kind": kind.as_str(), "error_payload": p }),
        None => json!({ "ok": false, "error_kind": kind.as_str() }),
    }
}

// ---------------------------------------------------------------------------
// Runner state. Init must come first; ops error with INVALID_INPUT before
// init. Dataset is &'static; no lifetime juggling needed.
// ---------------------------------------------------------------------------

struct RunnerState {
    initialized: bool,
    spec_version: i64,
    dataset: Option<&'static Dataset>,
}

impl RunnerState {
    fn new(spec_version: i64) -> Self {
        Self {
            initialized: false,
            spec_version,
            dataset: None,
        }
    }

    fn dataset(&mut self) -> &'static Dataset {
        let ds = self.dataset.get_or_insert_with(Dataset::embedded);
        *ds
    }
}

// ---------------------------------------------------------------------------
// Op handlers.
// ---------------------------------------------------------------------------

fn handle_init(state: &mut RunnerState, args: &Value) -> Value {
    if state.initialized {
        return err_value(
            ErrorKind::InvalidInput,
            Some(json!({ "detail": "init called twice" })),
        );
    }
    if !args.is_object() {
        return err_value(
            ErrorKind::InvalidInput,
            Some(json!({ "detail": "init args must be an object" })),
        );
    }
    let spec_version = args.get("spec_version").and_then(Value::as_i64);
    if spec_version != Some(state.spec_version) {
        return err_value(
            ErrorKind::InvalidInput,
            Some(json!({
                "detail": format!(
                    "spec_version mismatch: runner={}, request={}",
                    state.spec_version,
                    spec_version.map(|n| n.to_string()).unwrap_or_else(|| "null".to_string()),
                ),
            })),
        );
    }
    let locale = args.get("locale").and_then(Value::as_str);
    if locale != Some("C") {
        return err_value(
            ErrorKind::InvalidInput,
            Some(json!({
                "detail": format!(
                    "unsupported locale: {} (only \"C\")",
                    locale.unwrap_or("null"),
                ),
            })),
        );
    }
    let tz = args.get("tz").and_then(Value::as_str);
    if tz != Some("UTC") {
        return err_value(
            ErrorKind::InvalidInput,
            Some(json!({
                "detail": format!("unsupported tz: {} (only \"UTC\")", tz.unwrap_or("null")),
            })),
        );
    }
    if !args.get("seed").map(Value::is_number).unwrap_or(false) {
        return err_value(
            ErrorKind::InvalidInput,
            Some(json!({ "detail": "seed must be a number" })),
        );
    }
    state.initialized = true;
    ok_value(json!({
        "impl": IMPL_NAME,
        "spec_version": state.spec_version,
        "impl_version": IMPL_VERSION,
    }))
}

fn handle_normalize(args: &Value) -> Value {
    let Some(input) = args.get("input").and_then(Value::as_str) else {
        return err_value(
            ErrorKind::InvalidInput,
            Some(json!({ "detail": "normalize.input must be a string" })),
        );
    };
    ok_value(Value::String(normalize_name(input)))
}

/// Mirror the TS runner's import-decode behavior: if the input string looks
/// like JSON (starts with `{` or `[`), parse it; otherwise wrap the raw
/// string. `import_roster` then dispatches on the resulting Value (text
/// adapters match `Value::String`; JSON adapters match `Object`/`Array`).
fn handle_import(state: &mut RunnerState, args: &Value) -> Value {
    let Some(input) = args.get("input").and_then(Value::as_str) else {
        return err_value(
            ErrorKind::InvalidInput,
            Some(json!({ "detail": "import.input must be a string" })),
        );
    };
    let trimmed = input.trim_start();
    let decoded: Value = if trimmed.starts_with('{') || trimmed.starts_with('[') {
        serde_json::from_str(input).unwrap_or_else(|_| Value::String(input.to_string()))
    } else {
        Value::String(input.to_string())
    };
    match import_roster(&decoded, state.dataset()) {
        Ok(roster) => match serde_json::to_value(&roster) {
            Ok(v) => ok_value(v),
            Err(e) => err_value(
                ErrorKind::ImportFailed,
                Some(json!({ "detail": e.to_string() })),
            ),
        },
        Err(e) => err_value(
            ErrorKind::ImportFailed,
            Some(json!({
                "detail": e.to_string(),
                "format": args.get("format").cloned().unwrap_or(Value::Null),
            })),
        ),
    }
}

fn handle_try_import(state: &mut RunnerState, args: &Value) -> Value {
    let Some(input) = args.get("input").and_then(Value::as_str) else {
        return err_value(
            ErrorKind::InvalidInput,
            Some(json!({ "detail": "try_import.input must be a string" })),
        );
    };
    let ds = state.dataset();
    match try_import_roster(input, ds) {
        ImportResult::Ok { roster, format } => {
            let roster_v = serde_json::to_value(&roster).unwrap_or(Value::Null);
            let format_s = roster_format_str(format);
            ok_value(json!({ "format": format_s, "roster": roster_v }))
        }
        ImportResult::Err {
            reason,
            message,
            trials,
        } => err_value(
            ErrorKind::ImportFailed,
            Some(json!({
                "reason": import_failure_reason_str(&reason),
                "message": message,
                "trials": trials.into_iter().map(adapter_trial_to_value).collect::<Vec<_>>(),
            })),
        ),
    }
}

fn roster_format_str(f: RosterFormat) -> &'static str {
    match f {
        RosterFormat::Listforge => "listforge",
        RosterFormat::NewrecruitJson => "newrecruit-json",
        RosterFormat::NewrecruitWtcCompact => "newrecruit-wtc-compact",
        RosterFormat::NewrecruitWtcFull => "newrecruit-wtc-full",
        RosterFormat::NewrecruitSimple => "newrecruit-simple",
        RosterFormat::Rosterizer => "rosterizer",
        RosterFormat::Gw => "gw",
    }
}

fn import_failure_reason_str(r: &ImportFailureReason) -> &'static str {
    match r {
        ImportFailureReason::EmptyInput => "empty-input",
        ImportFailureReason::DecodeFailed => "decode-failed",
        ImportFailureReason::NoAdapterMatched => "no-adapter-matched",
        ImportFailureReason::ParseFailed => "parse-failed",
    }
}

fn adapter_trial_to_value(t: AdapterTrial) -> Value {
    let mut obj = serde_json::Map::new();
    obj.insert(
        "id".to_string(),
        Value::String(roster_format_str(t.id).to_string()),
    );
    obj.insert("matched".to_string(), Value::Bool(t.matched));
    if let Some(r) = t.reason {
        obj.insert("reason".to_string(), Value::String(r));
    }
    Value::Object(obj)
}

fn handle_export(state: &mut RunnerState, args: &Value) -> Value {
    let Some(format_s) = args.get("format").and_then(Value::as_str) else {
        return err_value(
            ErrorKind::InvalidInput,
            Some(json!({ "detail": "export.format must be a string" })),
        );
    };
    let format = match format_s {
        "newrecruit-json" => ExportFormat::NewrecruitJson,
        "newrecruit-wtc-compact" => ExportFormat::NewrecruitWtcCompact,
        "newrecruit-wtc-full" => ExportFormat::NewrecruitWtcFull,
        "newrecruit-simple" => ExportFormat::NewrecruitSimple,
        "roster-json" => ExportFormat::RosterJson,
        "rosterizer" => ExportFormat::Rosterizer,
        other => {
            return err_value(
                ErrorKind::InvalidInput,
                Some(json!({ "detail": format!("unknown export format: {other}") })),
            );
        }
    };
    let Some(roster_v) = args.get("roster") else {
        return err_value(
            ErrorKind::InvalidInput,
            Some(json!({ "detail": "export.roster must be present" })),
        );
    };
    let roster: Roster = match serde_json::from_value(roster_v.clone()) {
        Ok(r) => r,
        Err(e) => {
            return err_value(
                ErrorKind::InvalidInput,
                Some(json!({ "detail": format!("export.roster is not a valid Roster: {e}") })),
            );
        }
    };
    let _ = state; // dataset not needed for export — kept for handler symmetry
    match std::panic::catch_unwind(|| export_roster(&roster, format)) {
        Ok(s) => ok_value(Value::String(s)),
        Err(_) => err_value(
            ErrorKind::ExportFailed,
            Some(json!({ "detail": "exporter panicked" })),
        ),
    }
}

fn handle_linked_query(state: &mut RunnerState, args: &Value) -> Value {
    let Some(query) = args.get("query").and_then(Value::as_str) else {
        return err_value(
            ErrorKind::InvalidInput,
            Some(json!({ "detail": "linked_query.query must be a string" })),
        );
    };
    let input = args.get("input").cloned().unwrap_or_else(|| json!({}));
    let str_arg = |k: &str| -> &str { input.get(k).and_then(Value::as_str).unwrap_or("") };
    let ds = state.dataset();
    match query {
        "find_unit" => ok_value(match ds.find_unit(str_arg("query")) {
            Some(u) => Value::String(u.id.to_string()),
            None => Value::Null,
        }),
        "find_weapon" => ok_value(match ds.find_weapon(str_arg("query")) {
            Some(w) => Value::String(w.id.to_string()),
            None => Value::Null,
        }),
        "find_faction" => ok_value(match ds.find_faction(str_arg("query")) {
            Some(f) => Value::String(f.id.to_string()),
            None => Value::Null,
        }),
        "find_ability" => ok_value(match ds.find_ability(str_arg("query")) {
            Some(a) => Value::String(a.ability_id.to_string()),
            None => Value::Null,
        }),
        "abilities_of" => {
            let id = str_arg("unitId");
            let Some(unit) = ds.units.get(id) else {
                return err_value(
                    ErrorKind::UnknownEntity,
                    Some(json!({ "kind": "unit", "id": id })),
                );
            };
            ok_value(Value::Array(
                ds.abilities_of(unit)
                    .into_iter()
                    .map(|a| Value::String(a.ability_id.to_string()))
                    .collect(),
            ))
        }
        "weapons_of" => {
            let id = str_arg("unitId");
            let Some(unit) = ds.units.get(id) else {
                return err_value(
                    ErrorKind::UnknownEntity,
                    Some(json!({ "kind": "unit", "id": id })),
                );
            };
            ok_value(Value::Array(
                ds.weapons_of(unit)
                    .into_iter()
                    .map(|w| Value::String(w.id.to_string()))
                    .collect(),
            ))
        }
        "phases_of" => {
            let id = str_arg("abilityId");
            let Some(ability) = ds.abilities.get(id) else {
                return err_value(
                    ErrorKind::UnknownEntity,
                    Some(json!({ "kind": "ability", "id": id })),
                );
            };
            ok_value(Value::Array(
                ds.phases_of(ability)
                    .iter()
                    .map(|p| Value::String(phase_str(*p).to_string()))
                    .collect(),
            ))
        }
        "faction_of" => {
            let id = str_arg("unitId");
            let Some(unit) = ds.units.get(id) else {
                return err_value(
                    ErrorKind::UnknownEntity,
                    Some(json!({ "kind": "unit", "id": id })),
                );
            };
            ok_value(match ds.faction_of(unit) {
                Some(f) => Value::String(f.id.to_string()),
                None => Value::Null,
            })
        }
        "abilities_of_faction" => {
            let id = str_arg("factionId");
            ok_value(Value::Array(
                ds.abilities_of_faction(id)
                    .into_iter()
                    .map(|a| Value::String(a.ability_id.to_string()))
                    .collect(),
            ))
        }
        "weapons_of_faction" => {
            let id = str_arg("factionId");
            if ds.factions.get(id).is_none() {
                return err_value(
                    ErrorKind::UnknownEntity,
                    Some(json!({ "kind": "faction", "id": id })),
                );
            }
            ok_value(Value::Array(
                ds.weapons_of_faction(id)
                    .into_iter()
                    .map(|w| Value::String(w.id.to_string()))
                    .collect(),
            ))
        }
        other => err_value(
            ErrorKind::InvalidInput,
            Some(json!({ "detail": format!("unknown linked_query: {other}") })),
        ),
    }
}

fn phase_str(p: Phase) -> &'static str {
    match p {
        Phase::Command => "command",
        Phase::Movement => "movement",
        Phase::Shooting => "shooting",
        Phase::Charge => "charge",
        Phase::Fight => "fight",
    }
}

/// Rust has no validator yet (the crate exposes `BUNDLED_SCHEMA` as a string
/// constant but no validation function). Return UNKNOWN_OP so the differ can
/// negotiate the area off; do not silently succeed.
fn handle_validate(_args: &Value) -> Value {
    err_value(
        ErrorKind::UnknownOp,
        Some(json!({
            "op": "validate",
            "detail": "validator not implemented in this impl",
        })),
    )
}

/// Wire shape for the `crunch` and `attribution` args. Both ops take the same
/// envelope (`buildEngineInput` in TS); separating it keeps each handler thin.
#[derive(serde::Deserialize)]
struct CrunchArgs {
    attacker: Option<AttackerSpec>,
    #[serde(rename = "modelsFiring")]
    models_firing: Option<u64>,
    target: Option<TargetSpec>,
    context: Option<EngineContext>,
    #[serde(default)]
    buffs: Vec<Buff>,
    #[serde(default)]
    epsilon: Option<f64>,
}

#[derive(serde::Deserialize)]
struct AttackerSpec {
    #[serde(rename = "weaponId")]
    weapon_id: String,
    #[serde(rename = "profileIndex")]
    profile_index: usize,
}

#[derive(serde::Deserialize)]
struct TargetSpec {
    #[serde(rename = "unitId")]
    unit_id: String,
    #[serde(rename = "profileIndex")]
    profile_index: usize,
    #[serde(rename = "modelCount", default)]
    model_count: Option<u64>,
}

/// Build a borrowed [`EngineInput`] from the wire args. The returned input
/// borrows from the dataset, so callers consume it immediately. Returns the
/// pre-built error envelope on validation/lookup failures.
fn build_engine_input<'a>(
    ds: &'a Dataset,
    args: &Value,
    op_name: &str,
) -> Result<(EngineInput<'a>, Option<f64>), Value> {
    let parsed: CrunchArgs = serde_json::from_value(args.clone()).map_err(|e| {
        err_value(
            ErrorKind::InvalidInput,
            Some(json!({ "detail": format!("{op_name} args: {e}") })),
        )
    })?;
    let attacker = parsed.attacker.ok_or_else(|| {
        err_value(
            ErrorKind::InvalidInput,
            Some(json!({
                "detail": format!("{op_name}.attacker.weaponId/profileIndex required"),
            })),
        )
    })?;
    let target = parsed.target.ok_or_else(|| {
        err_value(
            ErrorKind::InvalidInput,
            Some(json!({
                "detail": format!("{op_name}.target.unitId/profileIndex required"),
            })),
        )
    })?;
    let models_firing = parsed.models_firing.ok_or_else(|| {
        err_value(
            ErrorKind::InvalidInput,
            Some(json!({ "detail": format!("{op_name}.modelsFiring required") })),
        )
    })?;
    let context = parsed.context.ok_or_else(|| {
        err_value(
            ErrorKind::InvalidInput,
            Some(json!({ "detail": format!("{op_name}.context required") })),
        )
    })?;
    let weapon = ds.weapons.get(&attacker.weapon_id).ok_or_else(|| {
        err_value(
            ErrorKind::UnknownEntity,
            Some(json!({ "kind": "weapon", "id": attacker.weapon_id })),
        )
    })?;
    let unit = ds.units.get(&target.unit_id).ok_or_else(|| {
        err_value(
            ErrorKind::UnknownEntity,
            Some(json!({ "kind": "unit", "id": target.unit_id })),
        )
    })?;
    let input = EngineInput {
        attacker: AttackProfileRef {
            weapon,
            profile_index: attacker.profile_index,
        },
        target: TargetProfileRef {
            unit,
            profile_index: target.profile_index,
            model_count: target.model_count,
        },
        models_firing,
        buffs: parsed.buffs,
        context,
    };
    Ok((input, parsed.epsilon))
}

/// Canonical wire shape for one stage: `{name, expected}`. Matches the TS
/// runner's trimmed crunch output — neither `detail` strings nor the
/// `resolved` modifier block are stable across implementations.
#[derive(Serialize)]
struct WireStage {
    name: StageName,
    expected: f64,
}

fn handle_crunch(state: &mut RunnerState, args: &Value) -> Value {
    let ds = state.dataset();
    let (input, _eps) = match build_engine_input(ds, args, "crunch") {
        Ok(x) => x,
        Err(e) => return e,
    };
    match crunch(&input, Some(ds)) {
        Ok(out) => {
            let stages: Vec<WireStage> = out
                .stages
                .iter()
                .map(|s| WireStage {
                    name: s.name,
                    expected: s.expected,
                })
                .collect();
            ok_value(json!({ "stages": stages }))
        }
        Err(e) => err_value(
            ErrorKind::CrunchError,
            Some(json!({ "detail": e.to_string() })),
        ),
    }
}

/// Wire-shape for `attribution`: drop `detail`, keep every numeric and the
/// kind-tagged BuffSource that's already serde-compatible.
#[derive(Serialize)]
struct WireAttributedStage<'a> {
    name: StageName,
    expected: f64,
    baseline: f64,
    lifts: Vec<WireLift<'a>>,
    residual: f64,
    intrinsics: &'a [String],
}

#[derive(Serialize)]
struct WireLift<'a> {
    source: &'a BuffSource,
    delta: f64,
}

fn project_attribution(stages: &[AttributedStage]) -> Vec<WireAttributedStage<'_>> {
    stages
        .iter()
        .map(|s| WireAttributedStage {
            name: s.name,
            expected: s.expected,
            baseline: s.baseline,
            lifts: s
                .lifts
                .iter()
                .map(|l: &StageLift| WireLift {
                    source: &l.source,
                    delta: l.delta,
                })
                .collect(),
            residual: s.residual,
            intrinsics: &s.intrinsics,
        })
        .collect()
}

fn handle_attribution(state: &mut RunnerState, args: &Value) -> Value {
    let ds = state.dataset();
    let (input, epsilon) = match build_engine_input(ds, args, "attribution") {
        Ok(x) => x,
        Err(e) => return e,
    };
    match attribute_stages(&input, Some(ds), epsilon) {
        Ok(stages) => {
            let wire = project_attribution(&stages);
            ok_value(serde_json::to_value(&wire).unwrap_or(Value::Null))
        }
        Err(e) => err_value(
            ErrorKind::CrunchError,
            Some(json!({ "detail": e.to_string() })),
        ),
    }
}

// ---------------------------------------------------------------------------
// Dispatcher.
// ---------------------------------------------------------------------------

/// Apply one decoded request to runner state and return the response. Used by
/// tests directly; the CLI loop wraps this with line parsing.
fn dispatch(state: &mut RunnerState, op: &str, args: &Value) -> Value {
    if !state.initialized && op != "init" {
        return err_value(
            ErrorKind::InvalidInput,
            Some(json!({ "detail": "must init before any other op" })),
        );
    }
    match op {
        "init" => handle_init(state, args),
        "version" => ok_value(json!({
            "impl": IMPL_NAME,
            "spec_version": state.spec_version,
            "impl_version": IMPL_VERSION,
        })),
        "normalize" => handle_normalize(args),
        "import" => handle_import(state, args),
        "try_import" => handle_try_import(state, args),
        "export" => handle_export(state, args),
        "linked_query" => handle_linked_query(state, args),
        "validate" => handle_validate(args),
        "crunch" => handle_crunch(state, args),
        "attribution" => handle_attribution(state, args),
        "shutdown" => ok_value(Value::Null),
        other => err_value(ErrorKind::UnknownOp, Some(json!({ "op": other }))),
    }
}

/// Process one stdin line and return the line that should be written to
/// stdout (without trailing `\n`). `None` on empty lines, which the CLI loop
/// silently ignores.
fn process_request(state: &mut RunnerState, line: &str) -> Option<String> {
    let trimmed = line.trim();
    if trimmed.is_empty() {
        return None;
    }
    let req: Value = match serde_json::from_str(trimmed) {
        Ok(v) => v,
        Err(e) => {
            return Some(
                err_value(
                    ErrorKind::InvalidInput,
                    Some(json!({ "detail": format!("not valid JSON: {e}") })),
                )
                .to_string(),
            );
        }
    };
    let Some(op) = req.get("op").and_then(Value::as_str) else {
        return Some(
            err_value(
                ErrorKind::InvalidInput,
                Some(json!({ "detail": "request must have a string `op` field" })),
            )
            .to_string(),
        );
    };
    let args = req.get("args").cloned().unwrap_or(Value::Null);
    Some(dispatch(state, op, &args).to_string())
}

// ---------------------------------------------------------------------------
// CLI: NDJSON stdin/stdout loop.
// ---------------------------------------------------------------------------

fn run_cli() -> ! {
    let spec_version = load_spec_version();
    let mut state = RunnerState::new(spec_version);
    let stdin = io::stdin();
    let stdout = io::stdout();
    let mut out = stdout.lock();
    for line_res in stdin.lock().lines() {
        let line = match line_res {
            Ok(l) => l,
            Err(_) => break,
        };
        if let Some(resp) = process_request(&mut state, &line) {
            // Honor `shutdown`: respond first, flush, then exit clean.
            let is_shutdown = serde_json::from_str::<Value>(line.trim())
                .ok()
                .and_then(|v| v.get("op").and_then(Value::as_str).map(str::to_string))
                .as_deref()
                == Some("shutdown");
            let _ = writeln!(out, "{resp}");
            let _ = out.flush();
            if is_shutdown {
                std::process::exit(0);
            }
        }
    }
    std::process::exit(0);
}

fn main() {
    run_cli();
}

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

    #[test]
    fn spec_version_loads() {
        let v = load_spec_version();
        assert!(v >= 1, "spec version: {v}");
    }
}