wh40kdc 0.4.13

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
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
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
//! 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::scoring::{
    add_to_hand, empty_player_game, player_primary, player_secondary, player_total, remove_score,
    score_cap, score_primary_event, score_secondary, score_secondary_event, score_turn,
    set_primary, wtc_result, AssertedAward, ScoringMode,
};
use wh40kdc::{describe_scoring_card, normalize_name, Dataset, Phase, SecondaryCard};

// ---------------------------------------------------------------------------
// 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(),
            ))
        }
        "wargear_options_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.wargear_options_of(unit)
                    .into_iter()
                    .map(|o| Value::String(o.id.to_string()))
                    .collect(),
            ))
        }
        "maximal_loadout" => {
            let id = str_arg("unitId");
            let Some(unit) = ds.units.get(id) else {
                return err_value(
                    ErrorKind::UnknownEntity,
                    Some(json!({ "kind": "unit", "id": id })),
                );
            };
            let model_count: u64 = str_arg("modelCount").parse().unwrap_or(0);
            let lo = wh40kdc::maximal_loadout(unit, model_count, &ds.wargear_options_of(unit));
            let mut encoded: Vec<Value> = lo
                .counts
                .iter()
                .map(|(k, v)| Value::String(format!("{k}:{v}")))
                .collect();
            encoded.sort_by(|a, b| a.as_str().unwrap_or("").cmp(b.as_str().unwrap_or("")));
            ok_value(Value::Array(encoded))
        }
        "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,
            })
        }
        "base_size_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 &unit.base_size_mm {
                Some(b) => Value::String(encode_base(b)),
                None => Value::Null,
            })
        }
        "model_bases_of" => {
            let id = str_arg("unitId");
            if ds.units.get(id).is_none() {
                return err_value(
                    ErrorKind::UnknownEntity,
                    Some(json!({ "kind": "unit", "id": id })),
                );
            }
            let comp = ds
                .unit_compositions
                .iter()
                .find(|c| c.unit_id.as_str() == id);
            let pairs: Vec<Value> = comp
                .map(|c| {
                    c.models
                        .iter()
                        .map(|m| {
                            let base = m
                                .base_size_mm
                                .as_ref()
                                .map(encode_base)
                                .unwrap_or_else(|| "none".to_string());
                            Value::String(format!("{}={}", m.name.as_str(), base))
                        })
                        .collect()
                })
                .unwrap_or_default();
            ok_value(Value::Array(pairs))
        }
        "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",
    }
}

use wh40kdc::encode_base_size as encode_base;

/// 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() })),
        ),
    }
}

fn handle_translate_scoring(state: &mut RunnerState, args: &Value) -> Value {
    let Some(card_id) = args.get("cardId").and_then(Value::as_str) else {
        return err_value(
            ErrorKind::InvalidInput,
            Some(json!({ "detail": "translate_scoring.cardId must be a string" })),
        );
    };
    let ds = state.dataset();
    match ds.mission_cards.get(card_id) {
        Some(card) => ok_value(json!({ "awards": describe_scoring_card(card) })),
        None => err_value(
            ErrorKind::UnknownEntity,
            Some(json!({ "kind": "secondary-card", "id": card_id })),
        ),
    }
}

// ---------------------------------------------------------------------------
// Scoring engine ops. Awards are referenced by index into a card's `awards`
// array (never serialized over the wire); both impls reconstruct the same
// `AssertedAward` from the shared embedded dataset.
// ---------------------------------------------------------------------------

fn parse_mode(s: &str) -> Option<ScoringMode> {
    match s {
        "fixed" => Some(ScoringMode::Fixed),
        "tactical" => Some(ScoringMode::Tactical),
        _ => None,
    }
}

/// Resolve `[{index, count?}]` against a card's `awards`, or a typed error. The
/// index addresses the full `awards` array (approach affects only the cap).
fn resolve_asserted(card: &SecondaryCard, asserted: &Value) -> Result<Vec<AssertedAward>, Value> {
    let Some(arr) = asserted.as_array() else {
        return Err(err_value(
            ErrorKind::InvalidInput,
            Some(json!({ "detail": "asserted must be an array" })),
        ));
    };
    let n = card.awards.len();
    let mut out = Vec::with_capacity(arr.len());
    for raw in arr {
        let Some(idx) = raw.get("index").and_then(Value::as_u64) else {
            return Err(err_value(
                ErrorKind::InvalidInput,
                Some(json!({ "detail": "asserted.index must be a number" })),
            ));
        };
        let idx = idx as usize;
        if idx >= n {
            return Err(err_value(
                ErrorKind::InvalidInput,
                Some(json!({ "detail": format!("asserted.index out of range: {idx}") })),
            ));
        }
        out.push(AssertedAward {
            award: card.awards[idx].clone(),
            count: raw.get("count").and_then(Value::as_u64),
        });
    }
    Ok(out)
}

fn optional_caps(op: &Value) -> (Option<u64>, Option<u64>) {
    (
        op.get("roundCap").and_then(Value::as_u64),
        op.get("gameCap").and_then(Value::as_u64),
    )
}

fn handle_score_event(state: &mut RunnerState, args: &Value) -> Value {
    let Some(card_id) = args.get("cardId").and_then(Value::as_str) else {
        return err_value(
            ErrorKind::InvalidInput,
            Some(json!({ "detail": "score_event.cardId must be a string" })),
        );
    };
    let Some(approach) = args
        .get("approach")
        .and_then(Value::as_str)
        .and_then(parse_mode)
    else {
        return err_value(
            ErrorKind::InvalidInput,
            Some(json!({ "detail": "score_event.approach must be 'fixed' or 'tactical'" })),
        );
    };
    let ds = state.dataset();
    let Some(card) = ds.mission_cards.get(card_id) else {
        return err_value(
            ErrorKind::UnknownEntity,
            Some(json!({ "kind": "secondary-card", "id": card_id })),
        );
    };
    let asserted = match resolve_asserted(card, args.get("asserted").unwrap_or(&Value::Null)) {
        Ok(a) => a,
        Err(e) => return e,
    };
    let turn = score_turn(&asserted);
    let cap = score_cap(card, approach);
    let banked = score_secondary_event(&asserted, card, approach);
    let mut value = serde_json::Map::new();
    value.insert("turn".into(), json!(turn));
    // Infinity (uncapped fixed) has no JSON form — null means "no cap".
    value.insert("cap".into(), cap.map(|c| json!(c)).unwrap_or(Value::Null));
    value.insert("banked".into(), json!(banked));
    if let Some(round_cap) = args.get("roundCap").and_then(Value::as_u64) {
        value.insert(
            "primaryBanked".into(),
            json!(score_primary_event(&asserted, round_cap)),
        );
    }
    ok_value(Value::Object(value))
}

fn handle_score_state(state: &mut RunnerState, args: &Value) -> Value {
    let Some(approach) = args
        .get("approach")
        .and_then(Value::as_str)
        .and_then(parse_mode)
    else {
        return err_value(
            ErrorKind::InvalidInput,
            Some(json!({ "detail": "score_state.approach must be 'fixed' or 'tactical'" })),
        );
    };
    let Some(ops) = args.get("ops").and_then(Value::as_array) else {
        return err_value(
            ErrorKind::InvalidInput,
            Some(json!({ "detail": "score_state.ops must be an array" })),
        );
    };
    let ds = state.dataset();
    let mut pg = empty_player_game(approach);
    for op in ops {
        let kind = op.get("kind").and_then(Value::as_str).unwrap_or("");
        match kind {
            "draw" => {
                let Some(cid) = op.get("cardId").and_then(Value::as_str) else {
                    return err_value(
                        ErrorKind::InvalidInput,
                        Some(json!({ "detail": "draw.cardId must be a string" })),
                    );
                };
                pg = add_to_hand(&pg, cid);
            }
            "score-secondary" | "score-primary" => {
                let (Some(cid), Some(round)) = (
                    op.get("cardId").and_then(Value::as_str),
                    op.get("round").and_then(Value::as_u64),
                ) else {
                    return err_value(
                        ErrorKind::InvalidInput,
                        Some(json!({ "detail": format!("{kind} needs cardId and round") })),
                    );
                };
                let Some(card) = ds.mission_cards.get(cid) else {
                    return err_value(
                        ErrorKind::UnknownEntity,
                        Some(json!({ "kind": "secondary-card", "id": cid })),
                    );
                };
                let asserted =
                    match resolve_asserted(card, op.get("asserted").unwrap_or(&Value::Null)) {
                        Ok(a) => a,
                        Err(e) => return e,
                    };
                if kind == "score-secondary" {
                    let vp = score_secondary_event(&asserted, card, pg.approach);
                    pg = score_secondary(&pg, round, cid, vp);
                } else {
                    // The app path: compute the round's raw total, then clamp on store.
                    let (rc, gc) = optional_caps(op);
                    pg = set_primary(&pg, round, score_turn(&asserted), rc, gc);
                }
            }
            "set-primary" => {
                let (Some(round), Some(vp)) = (
                    op.get("round").and_then(Value::as_u64),
                    op.get("vp").and_then(Value::as_u64),
                ) else {
                    return err_value(
                        ErrorKind::InvalidInput,
                        Some(json!({ "detail": "set-primary needs round and vp" })),
                    );
                };
                let (rc, gc) = optional_caps(op);
                pg = set_primary(&pg, round, vp, rc, gc);
            }
            "remove-score" => {
                let Some(index) = op.get("index").and_then(Value::as_u64) else {
                    return err_value(
                        ErrorKind::InvalidInput,
                        Some(json!({ "detail": "remove-score needs index" })),
                    );
                };
                pg = remove_score(&pg, index as usize);
            }
            other => {
                return err_value(
                    ErrorKind::InvalidInput,
                    Some(json!({ "detail": format!("unknown score_state op kind: {other}") })),
                );
            }
        }
    }
    ok_value(json!({
        "rounds": pg.rounds,
        "handIds": pg.hand_ids,
        "log": pg.log,
        "primary": player_primary(&pg),
        "secondary": player_secondary(&pg),
        "total": player_total(&pg),
    }))
}

fn handle_wtc_result(args: &Value) -> Value {
    let (Some(a), Some(b)) = (
        args.get("a").and_then(Value::as_u64),
        args.get("b").and_then(Value::as_u64),
    ) else {
        return err_value(
            ErrorKind::InvalidInput,
            Some(json!({ "detail": "wtc_result needs numeric a and b" })),
        );
    };
    let r = wtc_result(a, b);
    ok_value(json!({ "a": r.a, "b": r.b }))
}

fn handle_resolve_terrain(args: &Value) -> Value {
    let Some(layout_val) = args.get("layout") else {
        return err_value(
            ErrorKind::InvalidInput,
            Some(json!({ "detail": "resolve_terrain.layout must be an object" })),
        );
    };
    let templates_val = args.get("templates").cloned().unwrap_or_else(|| json!([]));
    if !templates_val.is_array() {
        return err_value(
            ErrorKind::InvalidInput,
            Some(json!({ "detail": "resolve_terrain.templates must be an array" })),
        );
    }
    let layout: wh40kdc::terrain::TerrainLayout = match serde_json::from_value(layout_val.clone()) {
        Ok(l) => l,
        Err(e) => {
            return err_value(
                ErrorKind::InvalidInput,
                Some(json!({ "detail": format!("resolve_terrain.layout: {e}") })),
            )
        }
    };
    let templates: Vec<wh40kdc::terrain::TerrainTemplate> =
        match serde_json::from_value(templates_val) {
            Ok(t) => t,
            Err(e) => {
                return err_value(
                    ErrorKind::InvalidInput,
                    Some(json!({ "detail": format!("resolve_terrain.templates: {e}") })),
                )
            }
        };
    match wh40kdc::resolve_layout(&layout, &templates) {
        Ok(pieces) => ok_value(json!({ "pieces": pieces })),
        Err(e) => err_value(
            ErrorKind::InvalidInput,
            Some(json!({ "detail": e.to_string() })),
        ),
    }
}

fn handle_keystones(args: &Value) -> Value {
    let Some(layout_val) = args.get("layout") else {
        return err_value(
            ErrorKind::InvalidInput,
            Some(json!({ "detail": "keystones.layout must be an object" })),
        );
    };
    let templates_val = args.get("templates").cloned().unwrap_or_else(|| json!([]));
    if !templates_val.is_array() {
        return err_value(
            ErrorKind::InvalidInput,
            Some(json!({ "detail": "keystones.templates must be an array" })),
        );
    }
    let layout: wh40kdc::terrain::TerrainLayout = match serde_json::from_value(layout_val.clone()) {
        Ok(l) => l,
        Err(e) => {
            return err_value(
                ErrorKind::InvalidInput,
                Some(json!({ "detail": format!("keystones.layout: {e}") })),
            )
        }
    };
    let templates: Vec<wh40kdc::terrain::TerrainTemplate> =
        match serde_json::from_value(templates_val) {
            Ok(t) => t,
            Err(e) => {
                return err_value(
                    ErrorKind::InvalidInput,
                    Some(json!({ "detail": format!("keystones.templates: {e}") })),
                )
            }
        };
    let board: wh40kdc::terrain::BoardExtents = match args.get("board") {
        None => wh40kdc::terrain::BOARD_INCHES,
        Some(b) => match serde_json::from_value(b.clone()) {
            Ok(b) => b,
            Err(e) => {
                return err_value(
                    ErrorKind::InvalidInput,
                    Some(json!({ "detail": format!("keystones.board: {e}") })),
                )
            }
        },
    };
    match wh40kdc::terrain::keystone_measurements(&layout, &templates, board) {
        Ok(measurements) => ok_value(json!({ "measurements": measurements })),
        Err(e) => err_value(
            ErrorKind::InvalidInput,
            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),
        "translate_scoring" => handle_translate_scoring(state, args),
        "score_event" => handle_score_event(state, args),
        "score_state" => handle_score_state(state, args),
        "wtc_result" => handle_wtc_result(args),
        "resolve_terrain" => handle_resolve_terrain(args),
        "keystones" => handle_keystones(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}");
    }
}