workshop-rs 1.21.0

Canonical multi-locale Overwatch Workshop semantic core: catalog, parser, WIR, validation, emitter.
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
//! The canonical Workshop catalog.
//!
//! The catalog is the locale-independent semantic identity layer between
//! textual Workshop spellings and WIR. Every builtin has a canonical `id` and
//! a [`Kind`]; locale tables map canonical identities to client spellings and
//! back, so parser, emitter, analyzer, and tooling never embed
//! locale-specific strings as identity.
//!
//! Locale coverage is data ([ADR-0001](https://github.com/wrightkit/workshop-rs/blob/main/docs/adr/0001-catalog-boundaries.md)):
//! the primary locale (the first declared one, `en-US`) is complete — every
//! entry and enum member carries a primary-locale alias — while additional
//! declared locales may be partially covered. Missing target-locale mappings
//! fail explicitly at conversion/emission time; the catalog reports exact
//! per-locale coverage machine-readably ([`Catalog::locale_coverage`],
//! [`Catalog::identity`]).
//!
//! The catalog dataset declares its own `version` and a deterministic content
//! `digest` (sha256) recomputed by the catalog pipeline
//! (`workshop-catalog-gen build`); [`Catalog::load`] rejects a digest
//! mismatch, so dataset changes are deliberate and reproducible.

pub mod descriptions;
pub mod detect;

use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};

use serde::{Deserialize, Deserializer, Serialize};

use crate::core::signatures::ExpectedDomain;

/// The embedded catalog data.
pub const CATALOG_DATA: &str = include_str!("data/catalog.json");

/// A normalized Workshop client locale, e.g. `en-US`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
pub struct Locale(String);

impl Locale {
    /// Build a locale from a client spelling, normalized to lowercase.
    pub fn new(value: &str) -> Locale {
        Locale(value.trim().to_ascii_lowercase())
    }

    /// The normalized locale string.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl<'de> Deserialize<'de> for Locale {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Ok(Self::new(&value))
    }
}

impl std::fmt::Display for Locale {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

/// The kind of a catalog builtin.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Kind {
    /// A structural keyword (If, End, Set Global Variable, …).
    Structural = 0,
    /// An action function.
    Action = 1,
    /// A value function.
    Value = 2,
    /// An event.
    Event = 3,
    /// An operator token (comparison operators).
    Operator = 4,
    /// An enumerated value domain.
    Enum = 5,
    /// A settings entry.
    Setting = 6,
}

impl Kind {
    pub const NUM_KINDS: usize = 7;

    pub const fn as_index(self) -> usize {
        self as usize
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Kind::Structural => "structural",
            Kind::Action => "action",
            Kind::Value => "value",
            Kind::Event => "event",
            Kind::Operator => "operator",
            Kind::Enum => "enum",
            Kind::Setting => "setting",
        }
    }
}

/// Literal substitutions accepted at one parameter position. The authored
/// literal is kept in WIR; these facts only decide acceptance.
///
/// These are deliberately per-parameter facts. They do not establish a
/// global relationship between Workshop booleans, numbers, arrays, strings,
/// vectors, or null.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ParamCoercions {
    /// Accept `False` as numeric zero.
    #[serde(default)]
    pub false_as_number: bool,
    /// Accept `True` as numeric one.
    #[serde(default)]
    pub true_as_number: bool,
    /// Accept numeric zero as `Null`.
    #[serde(default)]
    pub zero_as_null: bool,
    /// Accept `Vector(0, 0, 0)` as `Null`.
    #[serde(default)]
    pub null_vector_as_null: bool,
    /// Accept `Empty Array` as an empty string.
    #[serde(default)]
    pub empty_array_as_string: bool,
}

/// `rule-content-v1` facts for one parameter position, declared when the
/// surface parameter list and the structured document's argument list
/// differ. Absent elements and entries without the array map their
/// parameters one-to-one to plain content arguments.
///
/// These are deliberately per-parameter facts describing the emitted
/// document's layout; they do not change the surface signature, which
/// follows the Workshop call syntax.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ParamContent {
    /// The folded variable-target call this parameter contributes to, when
    /// the call's variable target folds surface parameters into one
    /// `globalVariable`/`playerVariable` content argument.
    #[serde(default)]
    pub fold: Option<ParamContentFold>,
    /// The modify-operator call ids accepted at this position (`add`,
    /// `removeFromArrayByIndex`, …). In `rule-content-v1` the operand is a
    /// zero-argument call node named by one of these ids — not an enum
    /// member, so the position declares no enum domain.
    #[serde(default)]
    pub operations: Vec<String>,
}

/// Membership in a folded variable-target call: this surface parameter
/// supplies one argument of the `globalVariable`/`playerVariable` call the
/// `rule-content-v1` target renders as. All members of a fold group share
/// the same `call` and are contiguous surface parameters; the folded call
/// occupies the content-argument position of the group's first member.
///
/// The member's node form follows its declared parameter type: a
/// `Variable`-typed parameter supplies the tagged `{"variable": "<name>"}`
/// node bound to the declared variable name, and any other parameter
/// supplies a normal value node.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ParamContentFold {
    /// The reserved target call id (`globalVariable` or `playerVariable`).
    pub call: String,
    /// The argument index inside the folded call this parameter supplies.
    pub arg: usize,
}

/// One catalog builtin.
#[derive(Debug, Clone)]
pub struct CatalogEntry {
    pub id: String,
    pub kind: Kind,
    /// Whether `lookup` reports the entry's call signature and
    /// `lookup_within` scopes to its parameters. Every action and value is
    /// callable; a structural entry is callable only when the data declares
    /// its parameter list (`"params": []` on the zero-argument `else`/`end`
    /// constructs). Events, operators, and section keywords are not.
    pub(crate) callable: bool,
    /// Parameter names, when the catalog documents them.
    pub(crate) params: Vec<String>,
    /// Reviewed semantic names when they differ from the catalog parameters.
    pub(crate) param_names: Option<Vec<String>>,
    /// Reviewed localized spellings for each parameter, parallel to `params`.
    pub(crate) param_aliases: Vec<HashMap<Locale, Vec<String>>>,
    /// The localized parameter display name the Workshop editor shows for
    /// each position, parallel to `params` — the catalog's own
    /// `paramDisplayNames` section, separate from `paramAliases` (accepted
    /// parse spellings) and `paramDefaults` (the value applied when an
    /// argument is omitted). `None` at an index marks a position without a
    /// source-confirmed name; such positions are recorded explicitly in
    /// the catalog's `paramDisplayNameGaps` list.
    pub(crate) param_display_names: Vec<Option<HashMap<Locale, String>>>,
    /// The canonical enum domain expected at each parameter position, when
    /// the parameter takes an enumerated value (parallel to `params`).
    /// `None` for non-enum parameters and for parameters whose accepted
    /// values span multiple canonical domains. In particular, a filtered
    /// rule event's `Player` parameter accepts `EventPlayer` members or
    /// canonical `Hero` members; the WIR [`crate::wir::EventTarget`] carries
    /// that union explicitly.
    pub(crate) param_domains: Vec<Option<String>>,
    /// Default value per parameter position (parallel to `params`),
    /// resolved when a call omits the argument. See the catalog data
    /// provenance for the value syntax and source.
    pub(crate) param_defaults: Vec<Option<String>>,
    /// Source-backed semantic type per parameter position. `None` means
    /// the available sources do not establish a narrower type.
    pub(crate) param_types: Vec<Option<String>>,
    /// Contextual literal substitutions per parameter position.
    pub(crate) param_coercions: Vec<Option<ParamCoercions>>,
    /// `rule-content-v1` argument facts per parameter position (parallel to
    /// `params`), declared where the surface parameter list and the content
    /// argument list differ — folded variable targets and modify-operator
    /// positions.
    pub(crate) param_content: Vec<Option<ParamContent>>,
    /// Source-backed return type for Value entries. Actions must leave this
    /// unset; an absent value remains unresolved.
    pub(crate) return_type: Option<String>,
    /// Reevaluation coverage for the action's `*Reeval` parameter, keyed by
    /// enum member id: which parameter positions the selected reevaluation
    /// member keeps re-evaluating. `None` when the action has no `*Reeval`
    /// parameter or coverage is not reviewed. Members absent from the map
    /// are unknown, not empty — an empty vector is a reviewed "reevaluates
    /// nothing" claim.
    pub(crate) reevaluation_coverage: Option<BTreeMap<String, Vec<usize>>>,
    /// Whether the final declared parameter repeats for additional arguments.
    pub(crate) variadic: bool,
    pub(crate) aliases: HashMap<Locale, Vec<String>>,
}

/// A locale-independent identity for a preset used by the Workshop `String`
/// value. Unlike a custom `Value::String`, this identity must resolve through
/// reviewed client-locale aliases before it can be parsed or emitted.
#[derive(Debug, Clone)]
pub struct LocalizedStringEntry {
    pub id: String,
    pub(crate) aliases: HashMap<Locale, Vec<String>>,
}

fn spelling<'a>(aliases: &'a HashMap<Locale, Vec<String>>, locale: &Locale) -> Option<&'a str> {
    aliases
        .get(locale)
        .and_then(|spellings| spellings.first())
        .map(String::as_str)
}

fn spellings_for<'a>(aliases: &'a HashMap<Locale, Vec<String>>, locale: &Locale) -> &'a [String] {
    aliases.get(locale).map(Vec::as_slice).unwrap_or_default()
}

impl LocalizedStringEntry {
    /// The deterministic emitted spelling in `locale`, when mapped.
    pub fn spelling(&self, locale: &Locale) -> Option<&str> {
        spelling(&self.aliases, locale)
    }

    /// All reviewed spellings accepted for this locale.
    pub fn spellings(&self, locale: &Locale) -> &[String] {
        spellings_for(&self.aliases, locale)
    }
}

impl CatalogEntry {
    /// The localized spelling of this builtin in `locale`, when declared.
    pub fn spelling(&self, locale: &Locale) -> Option<&str> {
        spelling(&self.aliases, locale)
    }

    /// Every reviewed localized spelling of this builtin, with the first
    /// spelling reserved for deterministic emission.
    pub fn spellings(&self, locale: &Locale) -> &[String] {
        spellings_for(&self.aliases, locale)
    }

    /// Resolve a canonical or reviewed localized parameter spelling to its
    /// unambiguous declared position.
    pub fn resolve_param(&self, locale: &Locale, spelling: &str) -> Option<usize> {
        let mut matches = self
            .params
            .iter()
            .enumerate()
            .filter(|(index, canonical)| {
                canonical == &spelling
                    || self
                        .param_aliases
                        .get(*index)
                        .and_then(|aliases| aliases.get(locale))
                        .is_some_and(|aliases| aliases.iter().any(|alias| alias == spelling))
            })
            .map(|(index, _)| index);
        let first = matches.next()?;
        matches.next().is_none().then_some(first)
    }

    /// The canonical parameter names in declaration order.
    pub fn params(&self) -> &[String] {
        &self.params
    }

    /// The number of declared arguments for this builtin.
    pub fn param_count(&self) -> usize {
        self.params.len()
    }

    /// The reviewed semantic name for an argument position, when declared.
    pub fn param_name(&self, index: usize) -> Option<&str> {
        let names = self.param_names.as_deref().unwrap_or(&self.params);
        param_at(names, index, self.variadic).map(String::as_str)
    }

    /// The localized parameter display name the Workshop editor shows for
    /// the argument at `index` in `locale`, when the catalog records one.
    /// This is a reviewed editor-presentation fact only — it does not
    /// affect parsing or emission — and it stays separate from
    /// [`param_name`], `paramAliases`, and `paramDefaults`.
    ///
    /// [`param_name`]: Self::param_name
    pub fn param_display_name(&self, locale: &Locale, index: usize) -> Option<&str> {
        param_at(&self.param_display_names, index, self.variadic)
            .and_then(Option::as_ref)
            .and_then(|names| names.get(locale))
            .map(String::as_str)
    }

    /// The number of arguments that must be present when trailing defaults
    /// are applied. A missing default in the middle of a signature remains a
    /// required position; defaults only make the suffix optional.
    pub fn required_param_count(&self) -> usize {
        (0..self.params.len())
            .rev()
            .find(|index| {
                self.param_defaults
                    .get(*index)
                    .and_then(Option::as_ref)
                    .is_none()
            })
            .map_or(0, |index| index + 1)
    }

    /// Whether any declared parameter has a default value.
    pub fn has_param_defaults(&self) -> bool {
        self.param_defaults.iter().any(Option::is_some)
    }

    /// The default value for an argument position, when declared.
    pub fn param_default(&self, index: usize) -> Option<&str> {
        param_at(&self.param_defaults, index, self.variadic).and_then(Option::as_deref)
    }

    /// The declared enum domain for an argument position, when one exists.
    pub fn param_domain(&self, index: usize) -> Option<&str> {
        param_at(&self.param_domains, index, self.variadic).and_then(Option::as_deref)
    }

    /// The parameter positions the given `*Reeval` enum member keeps
    /// re-evaluating on this action, when the action declares reviewed
    /// reevaluation coverage. `Some(&[])` means the member re-evaluates no
    /// parameter of this action; `None` means the member's coverage is
    /// unknown for this action and callers must stay conservative.
    ///
    /// `member` is the canonical enum member id (e.g. `COLOR`), the same
    /// spelling a parsed `Value::Enum` carries.
    pub fn reevaluation_coverage(&self, member: &str) -> Option<&[usize]> {
        self.reevaluation_coverage
            .as_ref()
            .and_then(|coverage| coverage.get(member).map(Vec::as_slice))
    }

    /// Whether this action declares reviewed per-parameter reevaluation
    /// coverage for its `*Reeval` parameter.
    pub fn has_reevaluation_coverage(&self) -> bool {
        self.reevaluation_coverage.is_some()
    }

    /// The source-backed semantic type for an argument position, when
    /// available. Enum domains remain exposed separately by `param_domain`.
    pub fn param_type(&self, index: usize) -> Option<&str> {
        param_at(&self.param_types, index, self.variadic).and_then(Option::as_deref)
    }

    /// The contextual literal substitutions for an argument position.
    pub fn param_coercions(&self, index: usize) -> Option<&ParamCoercions> {
        param_at(&self.param_coercions, index, self.variadic).and_then(Option::as_ref)
    }

    /// The `rule-content-v1` facts for an argument position: how the
    /// parameter appears in the structured document when the surface
    /// signature and the content layout differ.
    pub fn param_content(&self, index: usize) -> Option<&ParamContent> {
        param_at(&self.param_content, index, self.variadic).and_then(Option::as_ref)
    }

    /// The source-backed return type of a Value, when available.
    pub fn return_type(&self) -> Option<&str> {
        self.return_type.as_deref()
    }

    /// Whether the final declared parameter repeats for additional arguments.
    pub fn is_variadic(&self) -> bool {
        self.variadic
    }

    /// Whether the surface signature's leading `(player, variable)`
    /// parameters fold into one `PlayerVariable` WIR argument. The declared
    /// shape is a `Player|Array` parameter directly followed by a `Variable`
    /// parameter (`stopChasingPlayerVariable`, `chasePlayerVariableAtRate`,
    /// `chasePlayerVariableOverTime`, `setPlayerVariableAtIndex`,
    /// `modifyPlayerVariableAtIndex`).
    pub(crate) fn folds_player_variable_pair(&self) -> bool {
        self.param_type(0) == Some("Player|Array") && self.param_type(1) == Some("Variable")
    }

    /// Whether `args`, a WIR argument list for this entry, actually carries
    /// the folded pair: the signature is foldable and WIR arg 0 is a
    /// `PlayerVariable` value. An unparseable or hand-built argument list
    /// that never folded still positions its arguments one-to-one.
    pub(crate) fn wir_args_folded(
        &self,
        program: &crate::wir::Program,
        args: &[crate::wir::ValueId],
    ) -> bool {
        self.folds_player_variable_pair()
            && matches!(
                args.first()
                    .and_then(|arg| program.values.get(*arg))
                    .map(|node| &node.value),
                Some(crate::wir::Value::PlayerVariable { .. })
            )
    }

    /// The surface parameter index that `args[wir_index]` supplies for this
    /// entry's signature. Positions map one-to-one unless `args` carries the
    /// folded `(player, variable)` pair ([`wir_args_folded`]): the folded
    /// `PlayerVariable` then sits at the `Variable` position and supplies
    /// the `Player` position through its inner `player` field, and every
    /// later WIR argument maps to param `wir_index + 1`.
    pub(crate) fn wir_arg_param_index(
        &self,
        program: &crate::wir::Program,
        args: &[crate::wir::ValueId],
        wir_index: usize,
    ) -> usize {
        wir_index + usize::from(self.wir_args_folded(program, args))
    }
}

fn param_at<T>(values: &[T], index: usize, variadic: bool) -> Option<&T> {
    values
        .get(index)
        .or_else(|| variadic.then(|| values.last()).flatten())
}

/// One enum member within a domain.
#[derive(Debug, Clone)]
pub struct EnumMember {
    pub member: String,
    pub(crate) aliases: HashMap<Locale, Vec<String>>,
}

impl EnumMember {
    /// The localized spelling of this member in `locale`, when declared.
    pub fn spelling(&self, locale: &Locale) -> Option<&str> {
        spelling(&self.aliases, locale)
    }

    /// Every reviewed localized spelling of this enum member, with the first
    /// spelling reserved for deterministic emission.
    pub fn spellings(&self, locale: &Locale) -> &[String] {
        spellings_for(&self.aliases, locale)
    }
}

/// One enum value domain (e.g. `Color`, `Beam`).
#[derive(Debug, Clone)]
pub struct EnumDomain {
    pub domain: String,
    pub(crate) aliases: HashMap<Locale, Vec<String>>,
    pub members: Vec<EnumMember>,
}

impl EnumDomain {
    pub fn spelling(&self, locale: &Locale) -> Option<&str> {
        spelling(&self.aliases, locale)
    }
}

/// Target-format metadata recorded in the catalog.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[non_exhaustive]
pub struct TargetMeta {
    pub game: String,
    pub format: String,
    pub surface: String,
}

/// Provenance of the catalog data.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Provenance {
    pub generator: String,
    pub generator_version: String,
    pub source: String,
    pub license: String,
    pub reviewed: bool,
    /// Additional immutable observations that qualify the dataset source,
    /// including reviewed spelling conflicts retained as parse aliases.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub source_notes: Vec<String>,
}

/// Per-locale mapping coverage: how many canonical entries (builtins,
/// localized preset identities, and enum members) carry a mapping for the
/// locale out of the declared total.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[non_exhaustive]
pub struct LocaleCoverage {
    pub locale: Locale,
    /// Canonical entries with a declared mapping in this locale.
    pub mapped: usize,
    /// Canonical entries (builtins and enum members) declared by the catalog.
    pub total: usize,
}

/// The machine-readable catalog identity (ADR-0001 Decision 5): the four
/// identities that evolve independently — implementation version, catalog
/// dataset version plus content digest, locale coverage, and target evidence
/// — plus the data provenance record. Serialized with the ADR's kebab-case
/// identity names.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub struct CatalogIdentity {
    /// The `workshop-rs` package version (semver); bumped by code changes.
    pub implementation_version: String,
    /// The catalog dataset version; bumped by any dataset change.
    pub catalog_version: String,
    /// The deterministic content digest (sha256 hex) computed by the
    /// pipeline; `None` when the data does not declare one.
    pub catalog_digest: Option<String>,
    /// Declared locales with per-locale mapping counts.
    pub locale_coverage: Vec<LocaleCoverage>,
    /// The declared target surface.
    pub target: TargetMeta,
    /// The provenance record of the catalog data.
    pub provenance: Provenance,
}

pub(crate) type MemberIndexMap = HashMap<String, HashMap<String, (usize, usize)>>;

/// domain -> normalized member spelling -> member index, for
/// `NormalizedIndex::enum_alias_to_member`.
type EnumMemberAliasMap = HashMap<String, HashMap<String, Option<(usize, usize)>>>;

/// Whitespace-collapsed secondary spelling indexes (#448).
///
/// Reviewed export spellings carry whitespace the lexer cannot reproduce
/// inside a token stream — trailing spaces (`ヒーロー: `,
/// `Élévation à une puissance `), leading spaces, and spacing variants the
/// client itself normalizes (`66号公路`/`66 号公路`, `1팀`/`1 팀`). Every
/// verbatim index is mirrored here keyed by [`normalize_spelling`]; the
/// verbatim index is always consulted first, and a normalized key shared
/// by distinct targets (`None` after a collision) resolves nothing rather
/// than guessing.
#[derive(Debug, Clone, Default)]
pub(crate) struct NormalizedIndex {
    pub(crate) alias_to_entry: HashMap<Locale, [HashMap<String, Option<usize>>; Kind::NUM_KINDS]>,
    pub(crate) localized_string_alias: HashMap<Locale, HashMap<String, Option<usize>>>,
    pub(crate) enum_alias_to_domain: HashMap<Locale, HashMap<String, Option<String>>>,
    pub(crate) enum_alias_to_member: HashMap<Locale, EnumMemberAliasMap>,
    pub(crate) bare_member: HashMap<Locale, HashMap<String, Vec<(String, String)>>>,
}

/// The whitespace-collapsed comparison form of a catalog spelling: all
/// Unicode whitespace removed, characters otherwise unchanged (#448).
pub(crate) fn normalize_spelling(spelling: &str) -> Cow<'_, str> {
    if spelling.chars().any(char::is_whitespace) {
        Cow::Owned(spelling.chars().filter(|c| !c.is_whitespace()).collect())
    } else {
        Cow::Borrowed(spelling)
    }
}

/// The unambiguous target of `spelling` in a normalized index: a key shared
/// by distinct targets is stored as `None` and resolves nothing.
fn lookup_normalized<'a, V>(
    index: &'a HashMap<String, Option<V>>,
    spelling: &str,
) -> Option<&'a V> {
    index.get(normalize_spelling(spelling).as_ref())?.as_ref()
}

/// The validated canonical Workshop catalog.
#[derive(Debug, Clone)]
pub struct Catalog {
    detection_index: Option<detect::AliasIndex>,
    pub(crate) schema_version: u32,
    /// The declared locales, normalized; the first one is the primary
    /// locale and must be fully covered.
    pub(crate) locales: Vec<Locale>,
    pub(crate) target: TargetMeta,
    pub(crate) provenance: Provenance,
    /// The catalog dataset version (ADR-0001 `catalog-version`).
    pub(crate) catalog_version: String,
    /// The declared content digest (sha256 hex), verified at load when
    /// present (ADR-0001 `catalog-version`).
    pub(crate) catalog_digest: Option<String>,
    pub(crate) entries: Vec<CatalogEntry>,
    pub(crate) localized_strings: Vec<LocalizedStringEntry>,
    pub(crate) enums: Vec<EnumDomain>,
    pub(crate) by_id: [HashMap<String, usize>; Kind::NUM_KINDS],
    pub(crate) alias_to_entry: HashMap<Locale, [HashMap<String, usize>; Kind::NUM_KINDS]>,
    pub(crate) localized_string_by_id: HashMap<String, usize>,
    pub(crate) localized_string_alias: HashMap<Locale, HashMap<String, usize>>,
    pub(crate) enum_by_domain: HashMap<String, usize>,
    pub(crate) enum_alias_to_domain: HashMap<Locale, HashMap<String, String>>,
    pub(crate) enum_alias_to_member: HashMap<Locale, MemberIndexMap>,
    pub(crate) bare_member_index: HashMap<Locale, HashMap<String, Vec<(String, String)>>>,
    /// Whitespace-collapsed mirrors of the verbatim indexes; see
    /// [`NormalizedIndex`].
    pub(crate) normalized: NormalizedIndex,
    /// The attached localized description dataset (`descriptions.json`),
    /// empty until [`Catalog::load_descriptions`] attaches one.
    pub(crate) descriptions: descriptions::Descriptions,
}

mod load;

pub use load::{build_canonical, canonicalize, content_digest};

impl Catalog {
    pub(crate) fn schema_version(&self) -> u32 {
        self.schema_version
    }

    /// The declared locales, normalized; the first one is the primary locale.
    pub fn locales(&self) -> &[Locale] {
        &self.locales
    }

    /// The primary locale: the first declared one, whose mapping surface is
    /// complete (`en-US` in the committed catalog).
    pub fn primary_locale(&self) -> &Locale {
        &self.locales[0]
    }

    /// Whether a locale is declared by the catalog.
    pub fn supports(&self, locale: &Locale) -> bool {
        self.locales.contains(locale)
    }

    /// The catalog dataset version (ADR-0001 `catalog-version`).
    pub fn catalog_version(&self) -> &str {
        &self.catalog_version
    }

    /// The declared content digest (sha256 hex) of the catalog dataset,
    /// verified at load; `None` for data that declares none.
    pub fn catalog_digest(&self) -> Option<&str> {
        self.catalog_digest.as_deref()
    }

    /// The `workshop-rs` package version (ADR-0001 `implementation-version`).
    pub fn implementation_version() -> &'static str {
        env!("CARGO_PKG_VERSION")
    }

    /// The machine-readable catalog identity: implementation version, catalog
    /// version + digest, locale coverage, target evidence, and provenance.
    pub fn identity(&self) -> CatalogIdentity {
        CatalogIdentity {
            implementation_version: Self::implementation_version().to_string(),
            catalog_version: self.catalog_version.clone(),
            catalog_digest: self.catalog_digest.clone(),
            locale_coverage: self
                .locales
                .iter()
                .map(|locale| self.locale_coverage(locale))
                .collect(),
            target: self.target.clone(),
            provenance: self.provenance.clone(),
        }
    }

    /// The mapping coverage of one declared locale: mapped entries out of the
    /// declared total (builtins, localized preset identities, and enum members).
    /// The primary locale is
    /// always complete; other locales may be partially covered.
    pub fn locale_coverage(&self, locale: &Locale) -> LocaleCoverage {
        let member_total: usize = self.enums.iter().map(|domain| domain.members.len()).sum();
        let total = self.entries.len() + self.localized_strings.len() + member_total;
        let mapped = self
            .entries
            .iter()
            .filter(|entry| entry.aliases.contains_key(locale))
            .count()
            + self
                .localized_strings
                .iter()
                .filter(|entry| entry.aliases.contains_key(locale))
                .count()
            + self
                .enums
                .iter()
                .flat_map(|domain| &domain.members)
                .filter(|member| member.aliases.contains_key(locale))
                .count();
        LocaleCoverage {
            locale: locale.clone(),
            mapped,
            total,
        }
    }

    /// The mapping coverage of every declared locale, in declaration order.
    pub fn locale_coverage_all(&self) -> Vec<LocaleCoverage> {
        self.locales
            .iter()
            .map(|locale| self.locale_coverage(locale))
            .collect()
    }

    /// The builtin with the given canonical id and kind.
    pub fn entry(&self, kind: Kind, id: &str) -> Option<&CatalogEntry> {
        self.by_id[kind.as_index()]
            .get(id)
            .map(|i| &self.entries[*i])
    }

    /// Resolve a localized spelling to its canonical builtin. The verbatim
    /// index answers first; on a miss the whitespace-collapsed index
    /// answers a spelling whose declared form carries unwritable
    /// whitespace (`ヒーロー: `, `Élévation à une puissance `, #448).
    pub fn resolve(&self, kind: Kind, locale: &Locale, spelling: &str) -> Option<&CatalogEntry> {
        self.alias_to_entry
            .get(locale)
            .and_then(|by_kind| by_kind[kind.as_index()].get(spelling))
            .map(|i| &self.entries[*i])
            .or_else(|| {
                let index = &self.normalized.alias_to_entry.get(locale)?[kind.as_index()];
                lookup_normalized(index, spelling).map(|i| &self.entries[*i])
            })
    }

    /// The localized spelling of a canonical builtin id.
    pub fn spelling(&self, kind: Kind, locale: &Locale, id: &str) -> Option<&str> {
        self.entry(kind, id)?.spelling(locale)
    }

    /// Every entry of a kind, in catalog order.
    pub fn entries_of(&self, kind: Kind) -> impl Iterator<Item = &CatalogEntry> {
        self.entries.iter().filter(move |entry| entry.kind == kind)
    }

    /// Resolve a localized preset spelling to its stable identity.
    pub fn resolve_localized_string(
        &self,
        locale: &Locale,
        spelling: &str,
    ) -> Option<&LocalizedStringEntry> {
        self.localized_string_alias
            .get(locale)
            .and_then(|map| map.get(spelling))
            .map(|index| &self.localized_strings[*index])
            .or_else(|| {
                let index = self.normalized.localized_string_alias.get(locale)?;
                lookup_normalized(index, spelling).map(|i| &self.localized_strings[*i])
            })
    }

    /// Resolve the emitted spelling of a localized preset identity.
    pub fn localized_string_spelling(&self, locale: &Locale, id: &str) -> Option<&str> {
        self.localized_string_by_id
            .get(id)
            .and_then(|i| self.localized_strings.get(*i))
            .and_then(|entry| entry.spelling(locale))
    }

    /// Every reviewed localized preset identity, in catalog order.
    pub fn localized_strings(&self) -> impl Iterator<Item = &LocalizedStringEntry> {
        self.localized_strings.iter()
    }

    /// The total number of builtin entries.
    pub fn entry_count(&self) -> usize {
        self.entries.len()
    }

    /// The number of enum domains.
    pub fn enum_domains_count(&self) -> usize {
        self.enums.len()
    }

    /// The enum domain with the given name.
    pub fn enum_domain(&self, domain: &str) -> Option<&EnumDomain> {
        self.enum_by_domain.get(domain).map(|i| &self.enums[*i])
    }

    /// Resolve a localized enum-domain spelling to its canonical domain id.
    pub fn resolve_enum_domain(&self, locale: &Locale, spelling: &str) -> Option<&str> {
        self.enum_by_domain
            .get_key_value(spelling)
            .map(|(domain, _)| domain.as_str())
            .or_else(|| {
                self.enum_alias_to_domain
                    .get(locale)
                    .and_then(|map| map.get(spelling))
                    .map(String::as_str)
            })
            .or_else(|| {
                let index = self.normalized.enum_alias_to_domain.get(locale)?;
                lookup_normalized(index, spelling).map(String::as_str)
            })
    }

    /// Every enum domain, in catalog order.
    pub fn enum_domains(&self) -> impl Iterator<Item = &EnumDomain> {
        self.enums.iter()
    }

    /// Resolve a localized enum member spelling to `(domain, canonical member)`.
    pub fn resolve_enum_member(
        &self,
        domain: &str,
        locale: &Locale,
        spelling: &str,
    ) -> Option<(String, String)> {
        let indexes = self
            .enum_alias_to_member
            .get(locale)?
            .get(domain)?
            .get(spelling)
            .copied()
            .or_else(|| {
                let index = self
                    .normalized
                    .enum_alias_to_member
                    .get(locale)?
                    .get(domain)?;
                lookup_normalized(index, spelling).copied()
            })?;
        let (domain_index, member_index) = indexes;
        Some((
            domain.to_string(),
            self.enums[domain_index].members[member_index]
                .member
                .clone(),
        ))
    }

    /// The localized spelling of a canonical enum member.
    pub fn enum_spelling(&self, domain: &str, locale: &Locale, member: &str) -> Option<&str> {
        let domain_index = self.enum_by_domain.get(domain)?;
        let domain = &self.enums[*domain_index];
        domain
            .members
            .iter()
            .find(|candidate| candidate.member == member)?
            .spelling(locale)
    }

    /// Resolve a canonical enum member through the locale boundary, including
    /// reviewed partial locale spellings that are not yet part of the full
    /// catalog locale set.
    pub fn localized_enum_spelling(
        &self,
        domain: &str,
        locale: &Locale,
        member: &str,
    ) -> Option<&str> {
        self.enum_spelling(domain, locale, member).or_else(|| {
            (domain == "Color" && member == "WHITE").then_some(match locale.as_str() {
                "de-de" => "Weiß",
                "es-es" | "es-mx" => "Blanco",
                "fr-fr" => "Blanc",
                "it-it" => "Bianco",
                "ja-jp" => "白",
                "ko-kr" => "흰색",
                "pl-pl" => "Biały",
                "pt-br" => "Branco",
                "ru-ru" => "Белый",
                "th-th" => "สีขาว",
                "tr-tr" => "Beyaz",
                "zh-tw" => "白色",
                _ => return None,
            })
        })
    }

    /// Every `(domain, canonical member)` match for a bare (domain-less)
    /// localized member spelling. Returns all matches so callers can report
    /// ambiguity; a well-formed catalog has at most one meaningful match for
    /// a given spelling. The verbatim index answers first; a spelling that
    /// differs only in whitespace falls back to the collapsed index (#448).
    pub fn bare_member_matches(&self, locale: &Locale, spelling: &str) -> Vec<(String, String)> {
        if let Some(matches) = self
            .bare_member_index
            .get(locale)
            .and_then(|map| map.get(spelling))
        {
            return matches.clone();
        }
        self.normalized
            .bare_member
            .get(locale)
            .and_then(|map| map.get(normalize_spelling(spelling).as_ref()))
            .cloned()
            .unwrap_or_default()
    }

    /// The canonical ids and `locale` spellings of `kind` entries, for
    /// nearest-candidate diagnostics that reject in the canonical space
    /// (validation and emission, where the rejected name is an id or an
    /// authored spelling).
    pub(crate) fn canonical_spellings<'a>(
        &'a self,
        kind: Kind,
        locale: &'a Locale,
    ) -> impl Iterator<Item = &'a str> {
        self.entries_of(kind).flat_map(move |entry| {
            std::iter::once(entry.id.as_str())
                .chain(entry.spellings(locale).iter().map(String::as_str))
        })
    }

    /// The emitted form of `member_spelling` in `domain` under `locale`:
    /// constructor-form domains (`Hero`, `Button`, `Color`, `Map`) write
    /// `Domain(Member)` in every position and locale; every other domain
    /// writes the member bare (docs/wrapper-forms.md).
    pub(crate) fn enum_member_form(
        &self,
        domain: &str,
        member_spelling: &str,
        locale: &Locale,
    ) -> String {
        if matches!(domain, "Hero" | "Button" | "Color" | "Map") {
            let domain_display = self
                .enum_domain(domain)
                .and_then(|entry| entry.spelling(locale))
                .unwrap_or(domain);
            format!("{domain_display}({member_spelling})")
        } else {
            member_spelling.to_string()
        }
    }

    /// The canonical ids and `locale` spellings of `domain` members, for
    /// nearest-candidate diagnostics that reject in the canonical space.
    pub(crate) fn canonical_member_spellings<'a>(
        &'a self,
        domain: &'a str,
        locale: &'a Locale,
    ) -> impl Iterator<Item = &'a str> {
        self.enum_domain(domain)
            .into_iter()
            .flat_map(move |domain| {
                domain.members.iter().flat_map(move |member| {
                    std::iter::once(member.member.as_str())
                        .chain(member.spellings(locale).iter().map(String::as_str))
                })
            })
    }
}

/// The catalog is the canonical source of expected enum domains for the
/// Workshop surface it documents: `expected_domain(catalog_id, arg_index)`
/// answers the domain declared for that parameter position (e.g. `createHudText`
/// argument 9 is `HudReeval`), so the Workshop parser can resolve bare enum
/// members that are ambiguous across domains (e.g. `Visible To and String`).
/// Positions without a documented domain answer `None`.
impl ExpectedDomain for Catalog {
    fn expected_domain(&self, catalog_id: &str, arg_index: usize) -> Option<&str> {
        for kind in [Kind::Action, Kind::Value] {
            if let Some(entry) = self.entry(kind, catalog_id)
                && let Some(domain) = entry.param_domain(arg_index)
            {
                return Some(domain);
            }
        }
        None
    }
}