zzstat 0.5.0

A deterministic, hardcode-free stat calculation engine designed for MMORPGs
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
//! Stat resolver module.
//!
//! Provides the `StatResolver` type, which is the main entry point
//! for stat resolution. It manages sources, transforms, dependency
//! graphs, and caching.

use crate::context::StatContext;
use crate::error::StatError;
use crate::graph::StatGraph;
use crate::numeric::{StatNumeric, StatValue};
use crate::resolved::ResolvedStat;
use crate::source::StatSource;
use crate::stat_id::StatId;
use crate::transform::{StackRule, StatTransform, TransformEntry, TransformPhase};
use rustc_hash::FxHashMap;

use crate::registry::StatRegistry;
use std::sync::Arc;

/// Scope for stat resolution.
///
/// Determines which stats should be resolved and how the dependency graph
/// should be constructed.
enum ResolveScope {
    /// Resolve a single stat and its dependencies.
    Single(StatId),
    /// Resolve all registered stats.
    All,
    /// Resolve specific stats and their dependencies (batch).
    Batch(Vec<StatId>),
}

/// Cached dependency graph.
struct GraphCache {
    graph: StatGraph,
    toposort: Vec<StatId>,
}

pub struct StatResolver {
    registry: Arc<std::sync::RwLock<StatRegistry>>,
    graph_cache: Option<GraphCache>,

    /// Cache of resolved stats (per-instance, not shared).
    cache: FxHashMap<StatId, ResolvedStat>,
}

impl StatResolver {
    /// Create a new empty resolver.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use zzstat::StatResolver;
    ///
    /// let resolver = StatResolver::new();
    /// ```
    pub fn new() -> Self {
        Self {
            registry: Arc::new(std::sync::RwLock::new(StatRegistry::new())),
            graph_cache: None,
            cache: FxHashMap::default(),
        }
    }

    /// Fork this resolver, creating a new resolver that shares base data.
    ///
    /// The forked resolver starts with an empty overlay and cache.
    /// Modifications to the fork only affect the fork (copy-on-write).
    /// The original resolver is unaffected.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use zzstat::*;
    /// use zzstat::source::ConstantSource;
    /// use zzstat::numeric::StatNumeric;
    ///
    /// let mut base = StatResolver::new();
    /// let hp_id = StatId::from("HP");
    /// base.register_source(hp_id.clone(), Box::new(ConstantSource(100.0)));
    ///
    /// // Fork the resolver
    /// let mut fork = base.fork();
    ///
    /// // Modify the fork (doesn't affect base)
    /// fork.register_source(hp_id.clone(), Box::new(ConstantSource(50.0)));
    ///
    /// let context = StatContext::new();
    /// let base_resolved = base.resolve(&hp_id, &context).unwrap();
    /// let fork_resolved = fork.resolve(&hp_id, &context).unwrap();
    ///
    /// assert_eq!(base_resolved.value.to_f64(), 100.0);
    /// assert_eq!(fork_resolved.value.to_f64(), 150.0); // 100 + 50
    /// ```
    pub fn fork(&self) -> Self {
        let parent_registry = Arc::clone(&self.registry);
        let child_registry = StatRegistry::fork_with_parent(parent_registry);
        Self {
            registry: Arc::new(std::sync::RwLock::new(child_registry)),
            graph_cache: None,
            cache: FxHashMap::default(),
        }
    }

    /// Register a source for a stat.
    ///
    /// Multiple sources for the same stat are summed (additive).
    /// Registering a source automatically invalidates the cache for that stat.
    ///
    /// Uses copy-on-write semantics: if this resolver is a fork, the source
    /// is added to the overlay. Otherwise, it's added to the base data.
    ///
    /// # Arguments
    ///
    /// * `stat_id` - The stat to register a source for
    /// * `source` - The source to register
    ///
    /// # Examples
    ///
    /// ```rust
    /// use zzstat::*;
    /// use zzstat::source::ConstantSource;
    ///
    /// let mut resolver = StatResolver::new();
    /// let hp_id = StatId::from("HP");
    ///
    /// resolver.register_source(hp_id.clone(), Box::new(ConstantSource(100.0)));
    /// resolver.register_source(hp_id.clone(), Box::new(ConstantSource(50.0)));
    /// // HP will be 150.0 (100 + 50)
    /// ```
    pub fn register_source(&mut self, stat_id: StatId, source: Box<dyn StatSource>) {
        let stat_id_clone = stat_id.clone();
        {
            let mut guard = self.registry.write().unwrap();
            guard.get_mut_sources(stat_id).push(Arc::new(source));
        }
        // Invalidate cache for this stat and all dependents
        self.graph_cache = None;
        self.cache.remove(&stat_id_clone);
        self.invalidate_downstream(&stat_id_clone);
    }

    /// Register a transform for a stat.
    ///
    /// Transforms are applied in registration order within each phase.
    /// The stack rule is inferred from the transform's phase.
    /// Registering a transform automatically invalidates the cache for that stat.
    ///
    /// # Arguments
    ///
    /// * `stat_id` - The stat to register a transform for
    /// * `transform` - The transform to register
    ///
    /// # Examples
    ///
    /// ```rust
    /// use zzstat::*;
    /// use zzstat::source::ConstantSource;
    /// use zzstat::transform::MultiplicativeTransform;
    ///
    /// let mut resolver = StatResolver::new();
    /// let atk_id = StatId::from("ATK");
    ///
    /// resolver.register_source(atk_id.clone(), Box::new(ConstantSource(100.0)));
    /// resolver.register_transform(atk_id.clone(), Box::new(MultiplicativeTransform::new(1.5)));
    /// // ATK will be 150.0 (100 * 1.5)
    /// ```
    pub fn register_transform(&mut self, stat_id: StatId, transform: Box<dyn StatTransform>) {
        let phase = transform.phase();
        let rule = crate::transform::infer_stack_rule(transform.as_ref());
        let entry = TransformEntry {
            phase,
            rule,
            transform,
        };
        self.register_transform_entry(stat_id, entry);
    }

    /// Register a transform with explicit phase and inferred stack rule.
    ///
    /// The stack rule is inferred from the transform's type and phase.
    /// This is a convenience method for registering transforms in a specific phase.
    ///
    /// # Arguments
    ///
    /// * `stat_id` - The stat to register a transform for
    /// * `phase` - The phase to register the transform in
    /// * `transform` - The transform to register
    ///
    /// # Examples
    ///
    /// ```rust
    /// use zzstat::*;
    /// use zzstat::source::ConstantSource;
    /// use zzstat::transform::{AdditiveTransform, TransformPhase};
    ///
    /// let mut resolver = StatResolver::new();
    /// let atk_id = StatId::from("ATK");
    ///
    /// resolver.register_source(atk_id.clone(), Box::new(ConstantSource(100.0)));
    /// resolver.register_transform_in_phase(
    ///     atk_id.clone(),
    ///     TransformPhase::Additive,
    ///     Box::new(AdditiveTransform::new(50.0)),
    /// );
    /// ```
    pub fn register_transform_in_phase(
        &mut self,
        stat_id: StatId,
        phase: TransformPhase,
        transform: Box<dyn StatTransform>,
    ) {
        let rule = crate::transform::infer_stack_rule(transform.as_ref());
        let entry = TransformEntry {
            phase,
            rule,
            transform,
        };
        self.register_transform_entry(stat_id, entry);
    }

    /// Register a transform with explicit phase and stack rule.
    ///
    /// This method provides full control over how the transform is registered
    /// and how it stacks with other transforms in the same phase.
    ///
    /// # Arguments
    ///
    /// * `stat_id` - The stat to register a transform for
    /// * `phase` - The phase to register the transform in
    /// * `rule` - The stack rule for combining with other transforms
    /// * `transform` - The transform to register
    ///
    /// # Examples
    ///
    /// ```rust
    /// use zzstat::*;
    /// use zzstat::source::ConstantSource;
    /// use zzstat::transform::{AdditiveTransform, StackRule, TransformPhase};
    ///
    /// let mut resolver = StatResolver::new();
    /// let atk_id = StatId::from("ATK");
    ///
    /// resolver.register_source(atk_id.clone(), Box::new(ConstantSource(100.0)));
    /// resolver.register_transform_with_rule(
    ///     atk_id.clone(),
    ///     TransformPhase::Additive,
    ///     StackRule::Additive,
    ///     Box::new(AdditiveTransform::new(50.0)),
    /// );
    /// ```
    pub fn register_transform_with_rule(
        &mut self,
        stat_id: StatId,
        phase: TransformPhase,
        rule: StackRule,
        transform: Box<dyn StatTransform>,
    ) {
        let entry = TransformEntry {
            phase,
            rule,
            transform,
        };
        self.register_transform_entry(stat_id, entry);
    }

    /// Internal method to register a transform entry.
    ///
    /// Uses copy-on-write semantics: if this resolver is a fork, the transform
    /// is added to the overlay. Otherwise, it's added to the base data.
    fn register_transform_entry(&mut self, stat_id: StatId, entry: TransformEntry) {
        let stat_id_clone = stat_id.clone();
        {
            let mut guard = self.registry.write().unwrap();
            guard.get_mut_transforms(stat_id).push(Arc::new(entry));
        }
        // Invalidate cache for this stat and potentially dependent stats
        self.graph_cache = None;
        self.cache.remove(&stat_id_clone);
        self.invalidate_downstream(&stat_id_clone);
    }

    /// Resolve a single stat.
    ///
    /// This will resolve the requested stat and all of its dependencies
    /// in the correct order. Results are cached until invalidated.
    ///
    /// This method shares its core implementation with `resolve_all()` and
    /// `resolve_batch()` via the internal `resolve_internal()` method.
    ///
    /// # Arguments
    ///
    /// * `stat_id` - The stat to resolve
    /// * `context` - The stat context for conditional calculations
    ///
    /// # Returns
    ///
    /// * `Ok(ResolvedStat)` - The resolved stat with full breakdown
    /// * `Err(StatError)` - If resolution fails (cycle, missing dependency, etc.)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use zzstat::*;
    /// use zzstat::source::ConstantSource;
    ///
    /// let mut resolver = StatResolver::new();
    /// let hp_id = StatId::from("HP");
    ///
    /// resolver.register_source(hp_id.clone(), Box::new(ConstantSource(100.0)));
    ///
    /// let context = StatContext::new();
    /// let resolved = resolver.resolve(&hp_id, &context).unwrap();
    /// assert_eq!(resolved.value, 100.0);
    /// ```
    pub fn resolve(
        &mut self,
        stat_id: &StatId,
        context: &StatContext,
    ) -> Result<ResolvedStat, StatError> {
        let results = self.resolve_internal(ResolveScope::Single(stat_id.clone()), context)?;
        results
            .into_iter()
            .next()
            .map(|(_, resolved)| resolved)
            .ok_or_else(|| StatError::MissingSource(stat_id.clone()))
    }

    /// Resolve all registered stats.
    ///
    /// Resolves all stats that have been registered (have sources or transforms).
    /// Stats are resolved in dependency order, and results are cached.
    ///
    /// This method shares its core implementation with `resolve()` and
    /// `resolve_batch()` via the internal `resolve_internal()` method.
    ///
    /// # Arguments
    ///
    /// * `context` - The stat context for conditional calculations
    ///
    /// # Returns
    ///
    /// * `Ok(HashMap<StatId, ResolvedStat>)` - Map of all resolved stats
    /// * `Err(StatError)` - If resolution fails (cycle, missing dependency, etc.)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use zzstat::*;
    /// use zzstat::source::ConstantSource;
    ///
    /// let mut resolver = StatResolver::new();
    /// resolver.register_source(StatId::from("HP"), Box::new(ConstantSource(100.0)));
    /// resolver.register_source(StatId::from("MP"), Box::new(ConstantSource(50.0)));
    ///
    /// let context = StatContext::new();
    /// let results = resolver.resolve_all(&context).unwrap();
    /// assert_eq!(results.len(), 2);
    /// ```
    pub fn resolve_all(
        &mut self,
        context: &StatContext,
    ) -> Result<FxHashMap<StatId, ResolvedStat>, StatError> {
        self.resolve_internal(ResolveScope::All, context)
    }

    /// Resolve multiple target stats and their dependencies in a single batch.
    ///
    /// More efficient than calling `resolve()` multiple times, as it only resolves
    /// the dependency subgraph needed for the specified targets.
    ///
    /// This method shares its core implementation with `resolve()` and
    /// `resolve_all()` via the internal `resolve_internal()` method.
    ///
    /// # Arguments
    ///
    /// * `targets` - The stat IDs to resolve
    /// * `context` - The stat context for conditional calculations
    ///
    /// # Returns
    ///
    /// * `Ok(HashMap<StatId, ResolvedStat>)` - Map of resolved stats (targets and dependencies)
    /// * `Err(StatError)` - If resolution fails (cycle, missing dependency, etc.)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use zzstat::*;
    /// use zzstat::source::ConstantSource;
    ///
    /// let mut resolver = StatResolver::new();
    /// let str_id = StatId::from("STR");
    /// let atk_id = StatId::from("ATK");
    /// let hp_id = StatId::from("HP");
    ///
    /// resolver.register_source(str_id.clone(), Box::new(ConstantSource(10.0)));
    /// resolver.register_source(atk_id.clone(), Box::new(ConstantSource(50.0)));
    /// resolver.register_source(hp_id.clone(), Box::new(ConstantSource(100.0)));
    ///
    /// let context = StatContext::new();
    /// let results = resolver.resolve_batch(&[atk_id.clone(), hp_id.clone()], &context)?;
    /// assert!(results.contains_key(&atk_id));
    /// assert!(results.contains_key(&hp_id));
    /// // STR may or may not be included depending on dependencies
    /// # Ok::<(), zzstat::StatError>(())
    /// ```
    pub fn resolve_batch(
        &mut self,
        targets: &[StatId],
        context: &StatContext,
    ) -> Result<FxHashMap<StatId, ResolvedStat>, StatError> {
        self.resolve_internal(ResolveScope::Batch(targets.to_vec()), context)
    }

    /// Invalidate the cache for a specific stat.
    ///
    /// The next time this stat is resolved, it will be recalculated
    /// instead of using the cached value.
    ///
    /// # Arguments
    ///
    /// * `stat_id` - The stat to invalidate
    ///
    /// # Examples
    ///
    /// ```rust
    /// use zzstat::*;
    /// use zzstat::source::ConstantSource;
    ///
    /// let mut resolver = StatResolver::new();
    /// let hp_id = StatId::from("HP");
    ///
    /// resolver.register_source(hp_id.clone(), Box::new(ConstantSource(100.0)));
    /// let context = StatContext::new();
    /// let _ = resolver.resolve(&hp_id, &context).unwrap();
    ///
    /// // Invalidate and add new source
    /// resolver.invalidate(&hp_id);
    /// resolver.register_source(hp_id.clone(), Box::new(ConstantSource(50.0)));
    /// ```
    pub fn invalidate(&mut self, stat_id: &StatId) {
        self.cache.remove(stat_id);
        self.invalidate_downstream(stat_id);
    }

    /// Internal method to invalidate cache for all stats that depend on the given stat.
    fn invalidate_downstream(&mut self, stat_id: &StatId) {
        if self.cache.is_empty() {
            return;
        }

        // Build the current graph to find dependents.
        if let Ok(graph) = self.build_graph() {
            let dependents = graph.get_all_dependents(stat_id);
            for dep in dependents {
                self.cache.remove(&dep);
            }
        }
    }

    /// Invalidate the entire cache.
    ///
    /// All cached stats will be recalculated on the next resolution.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use zzstat::*;
    /// use zzstat::source::ConstantSource;
    ///
    /// let mut resolver = StatResolver::new();
    /// resolver.register_source(StatId::from("HP"), Box::new(ConstantSource(100.0)));
    ///
    /// let context = StatContext::new();
    /// let _ = resolver.resolve_all(&context).unwrap();
    ///
    /// // Clear all caches
    /// resolver.invalidate_all();
    /// ```
    pub fn invalidate_all(&mut self) {
        self.cache.clear();
    }

    /// Get the breakdown for a stat (if it's been resolved).
    ///
    /// Returns the cached `ResolvedStat` if it exists, or `None` if
    /// the stat hasn't been resolved yet.
    ///
    /// # Arguments
    ///
    /// * `stat_id` - The stat to get the breakdown for
    ///
    /// # Returns
    ///
    /// * `Some(&ResolvedStat)` - The resolved stat with breakdown
    /// * `None` - If the stat hasn't been resolved
    ///
    /// # Examples
    ///
    /// ```rust
    /// use zzstat::*;
    /// use zzstat::source::ConstantSource;
    ///
    /// let mut resolver = StatResolver::new();
    /// let hp_id = StatId::from("HP");
    ///
    /// resolver.register_source(hp_id.clone(), Box::new(ConstantSource(100.0)));
    /// let context = StatContext::new();
    ///
    /// // Not resolved yet
    /// assert!(resolver.get_breakdown(&hp_id).is_none());
    ///
    /// // Resolve
    /// let _ = resolver.resolve(&hp_id, &context).unwrap();
    ///
    /// // Now available
    /// let breakdown = resolver.get_breakdown(&hp_id).unwrap();
    /// assert_eq!(breakdown.value, 100.0);
    /// ```
    pub fn get_breakdown(&self, stat_id: &StatId) -> Option<&ResolvedStat> {
        self.cache.get(stat_id)
    }

    /// Internal method to resolve stats based on scope.
    ///
    /// This is the unified implementation for all resolve methods.
    /// It handles graph building, topological sorting, and the resolution loop.
    fn resolve_internal(
        &mut self,
        scope: ResolveScope,
        context: &StatContext,
    ) -> Result<FxHashMap<StatId, ResolvedStat>, StatError> {
        let (single_stat_id, batch_targets, is_all) = match &scope {
            ResolveScope::Single(stat_id) => {
                if let Some(cached) = self.cache.get(stat_id) {
                    let mut result = FxHashMap::default();
                    result.insert(stat_id.clone(), cached.clone());
                    return Ok(result);
                }
                (Some(stat_id.clone()), None, false)
            }
            ResolveScope::All => (None, None, true),
            ResolveScope::Batch(targets) => {
                if targets.is_empty() {
                    return Ok(FxHashMap::default());
                }
                (None, Some(targets.clone()), false)
            }
        };

        if self.graph_cache.is_none() {
            let graph = self.build_graph()?;
            let toposort = graph.topological_sort()?;
            self.graph_cache = Some(GraphCache { graph, toposort });
        }

        let graph_cache = self.graph_cache.as_ref().unwrap();

        let resolution_order = if let Some(targets) = batch_targets.as_ref() {
            let subgraph = graph_cache.graph.subgraph_for_targets(targets.as_slice());
            subgraph.topological_sort()?
        } else {
            graph_cache.toposort.clone()
        };

        for stat_id in &resolution_order {
            if !self.cache.contains_key(stat_id) {
                let resolved = self.resolve_stat_internal(stat_id, context, &graph_cache.graph)?;
                self.cache.insert(stat_id.clone(), resolved);
            }
        }

        let mut results = FxHashMap::default();
        if let Some(stat_id) = single_stat_id {
            if let Some(resolved) = self.cache.get(&stat_id) {
                results.insert(stat_id, resolved.clone());
            }
        } else if is_all {
            results = self.cache.clone();
        } else {
            for stat_id in &resolution_order {
                if let Some(resolved) = self.cache.get(stat_id) {
                    results.insert(stat_id.clone(), resolved.clone());
                }
            }
        }

        Ok(results)
    }

    /// Build the dependency graph from all registered transforms.
    fn build_graph(&self) -> Result<StatGraph, StatError> {
        let mut graph = StatGraph::new();
        let guard = self.registry.read().unwrap();

        // Add all stats that have sources or transforms
        for stat_id in guard.get_all_stat_ids() {
            graph.add_node(stat_id.clone());
        }

        // Add edges from transform dependencies (check overlay first, then base)
        for stat_id in guard.get_all_stat_ids() {
            for entry in guard.get_transforms(&stat_id) {
                for dep in entry.transform.depends_on() {
                    // dep must be resolved before stat_id
                    graph.add_edge(stat_id.clone(), dep);
                }
            }
        }

        Ok(graph)
    }

    /// Export the stat dependency graph and active modifiers as a Mermaid JS flowchart.
    ///
    /// This generates a `graph TD` Mermaid diagram that visualizes:
    /// - All registered stats as nodes
    /// - Dependency relationships (arrows from dependency to dependent stat)
    /// - Active sources contributing to the base value
    /// - Active transforms modifying the stat
    ///
    /// # Returns
    ///
    /// A string containing the Mermaid diagram syntax.
    pub fn export_mermaid(&self) -> String {
        let mut out = String::new();
        out.push_str("graph TD\n");

        let guard = self.registry.read().unwrap();
        let stat_ids = guard.get_all_stat_ids();

        // Add all stats as main nodes
        for stat_id in &stat_ids {
            out.push_str(&format!("    {}[(\"{}\")]\n", stat_id, stat_id));

            // Add sources
            for (source_count, src) in guard.get_sources(stat_id).iter().enumerate() {
                let src_id = format!("{}_src_{}", stat_id, source_count);
                let desc = format!("{:?}", src).replace("\"", "'");
                out.push_str(&format!("    {}>\"{}\"]\n", src_id, desc));
                out.push_str(&format!("    {} -.-> {}\n", src_id, stat_id));
            }

            // Add transforms
            for (transform_count, entry) in guard.get_transforms(stat_id).iter().enumerate() {
                let tr_id = format!("{}_tr_{}", stat_id, transform_count);
                let desc = entry.transform.description().replace("\"", "'");
                out.push_str(&format!("    {}[/\"{}\"/]\n", tr_id, desc));
                out.push_str(&format!("    {} -.-> {}\n", tr_id, stat_id));
            }
        }

        // Add dependency edges
        if let Ok(graph) = self.build_graph() {
            for stat_id in graph.nodes() {
                for entry in guard.get_transforms(&stat_id) {
                    for dep in entry.transform.depends_on() {
                        // dep is required for stat_id. Thus data flows from dep -> stat_id
                        out.push_str(&format!("    {} ==> {}\n", dep, stat_id));
                    }
                }
            }
        }

        out
    }

    /// Internal method to resolve a single stat.
    fn resolve_stat_internal(
        &self,
        stat_id: &StatId,
        context: &StatContext,
        _graph: &StatGraph,
    ) -> Result<ResolvedStat, StatError> {
        let mut resolved = ResolvedStat::new(stat_id.clone(), StatValue::zero());
        let guard = self.registry.read().unwrap();

        // Step 1: Collect all source values (additive)
        let mut base_value = StatValue::zero();
        let mut source_count = 0;

        // Collect sources
        for source in guard.get_sources(stat_id) {
            let value = source.get_value(stat_id, context);
            base_value += value;
            source_count += 1;
            resolved.add_source(format!("Source #{}", source_count), value);
        }

        // If no sources at all, create a default source entry
        if source_count == 0 {
            resolved.add_source("Default", StatValue::zero());
        }

        // Step 2: Apply transforms grouped by phase, then by stack rule
        let mut current_value = base_value;

        // Collect all transforms
        let all_transforms = guard.get_transforms(stat_id);

        if !all_transforms.is_empty() {
            // Group transforms by phase
            let mut transforms_by_phase: std::collections::BTreeMap<u8, Vec<&TransformEntry>> =
                std::collections::BTreeMap::new();

            for entry in &all_transforms {
                let phase_value = entry.phase.value();
                transforms_by_phase
                    .entry(phase_value)
                    .or_default()
                    .push(entry.as_ref());
            }

            // Apply transforms in phase order, with stack rules applied within each phase
            for (_phase_value, phase_entries) in transforms_by_phase {
                current_value = self.apply_transforms_with_stack_rules(
                    current_value,
                    phase_entries,
                    stat_id,
                    context,
                    &mut resolved,
                )?;
            }
        }

        resolved.value = current_value;
        Ok(resolved)
    }

    /// Apply transforms in a phase with stack rule semantics.
    ///
    /// Groups transforms by stack rule priority and applies them in order:
    /// Override → Additive → Multiplicative → Diminishing → Min → Max → MinMax
    ///
    /// Stack rule semantics:
    /// - Additive: base + sum(all additive deltas) where delta = transform.apply(0)
    /// - Multiplicative: base × product(all multipliers) where multiplier = transform.apply(1.0)
    /// - Override: last transform wins (deterministic order)
    /// - Diminishing: value × (1 - exp(-k × stacks)) where stacks = number of transforms
    /// - Min: clamp to maximum of all min bounds (most restrictive)
    /// - Max: clamp to minimum of all max bounds (most restrictive)
    /// - MinMax: collect all min/max bounds, compute effective_min = max(all mins),
    ///   effective_max = min(all maxes), then clamp(value, effective_min, effective_max)
    fn apply_transforms_with_stack_rules(
        &self,
        base_value: StatValue,
        entries: Vec<&TransformEntry>,
        stat_id: &StatId,
        context: &StatContext,
        resolved: &mut ResolvedStat,
    ) -> Result<StatValue, StatError> {
        // Group entries by stack rule (sorted by priority)
        let mut by_rule: std::collections::BTreeMap<u8, Vec<&TransformEntry>> =
            std::collections::BTreeMap::new();

        for entry in entries {
            let priority = entry.rule.priority();
            by_rule.entry(priority).or_default().push(entry);
        }

        let mut current_value = base_value;

        // Apply stack rules in priority order
        for (_priority, rule_entries) in by_rule {
            if rule_entries.is_empty() {
                continue;
            }

            // All entries in this group have the same stack rule
            let stack_rule = rule_entries[0].rule;

            match stack_rule {
                StackRule::Override => {
                    // Last transform wins (deterministic order - use last entry)
                    if let Some(last_entry) = rule_entries.last() {
                        let dependencies =
                            self.collect_dependencies(last_entry.transform.depends_on(), stat_id)?;
                        let new_value =
                            last_entry
                                .transform
                                .apply(current_value, &dependencies, context)?;
                        resolved.add_transform(last_entry.transform.description(), new_value);
                        current_value = new_value;
                    }
                }
                StackRule::Additive => {
                    // Additive stacking: base + sum(all additive deltas)
                    // Extract delta by applying each transform to zero
                    let mut sum_delta = StatValue::zero();
                    for entry in &rule_entries {
                        let dependencies =
                            self.collect_dependencies(entry.transform.depends_on(), stat_id)?;
                        // Apply to zero to extract the additive delta
                        let zero = StatValue::zero();
                        let delta = entry.transform.apply(zero, &dependencies, context)?;
                        sum_delta += delta;
                    }
                    // Apply the sum of deltas to the current value
                    current_value += sum_delta;
                    resolved.add_transform(
                        format!("+{:.2} (additive stack)", sum_delta.to_f64()),
                        current_value,
                    );
                }
                StackRule::Multiplicative => {
                    // Multiplicative stacking: base × product(all multipliers)
                    // Extract multiplier by applying each transform to 1.0
                    let mut product_multiplier = StatValue::from_f64(1.0);
                    for entry in &rule_entries {
                        let dependencies =
                            self.collect_dependencies(entry.transform.depends_on(), stat_id)?;
                        // Apply to 1.0 to extract the multiplier
                        let one = StatValue::from_f64(1.0);
                        let multiplier = entry.transform.apply(one, &dependencies, context)?;
                        product_multiplier *= multiplier;
                    }
                    // Apply the product of multipliers to the current value
                    current_value *= product_multiplier;
                    resolved.add_transform(
                        format!("×{:.4} (multiplicative stack)", product_multiplier.to_f64()),
                        current_value,
                    );
                }
                StackRule::Diminishing { k } => {
                    // Diminishing returns: value × (1 - exp(-k × stacks))
                    // Count the number of stacks (transforms)
                    let stacks = rule_entries.len() as f64;
                    let k_f64 = k.to_f64();
                    let multiplier = 1.0 - (-k_f64 * stacks).exp();
                    current_value *= StatValue::from_f64(multiplier);
                    resolved.add_transform(
                        format!(
                            "×{:.4} (diminishing k={:.2}, stacks={:.0})",
                            multiplier, k_f64, stacks
                        ),
                        current_value,
                    );
                }
                StackRule::Min => {
                    // Min clamping: clamp to maximum of all min bounds (most restrictive)
                    let mut min_bound = None;
                    for entry in &rule_entries {
                        let bound = self.extract_min_bound(entry, stat_id, context)?;
                        if let Some(bound_value) = bound {
                            // Take the maximum of all min bounds (most restrictive)
                            min_bound = Some(
                                min_bound.map_or(bound_value, |m: StatValue| m.max(bound_value)),
                            );
                        }
                    }
                    if let Some(min) = min_bound {
                        current_value = current_value.max(min);
                        resolved.add_transform(format!("min({:.2})", min.to_f64()), current_value);
                    }
                }
                StackRule::Max => {
                    // Max clamping: clamp to minimum of all max bounds (most restrictive)
                    let mut max_bound = None;
                    for entry in &rule_entries {
                        let bound = self.extract_max_bound(entry, stat_id, context)?;
                        if let Some(bound_value) = bound {
                            // Take the minimum of all max bounds (most restrictive)
                            max_bound = Some(
                                max_bound.map_or(bound_value, |m: StatValue| m.min(bound_value)),
                            );
                        }
                    }
                    if let Some(max) = max_bound {
                        current_value = current_value.min(max);
                        resolved.add_transform(format!("max({:.2})", max.to_f64()), current_value);
                    }
                }
                StackRule::MinMax => {
                    // MinMax clamping: collect all min/max bounds and apply most restrictive
                    // effective_min = max(all mins), effective_max = min(all maxes)
                    let mut min_bounds = Vec::new();
                    let mut max_bounds = Vec::new();

                    for entry in &rule_entries {
                        // Extract bounds using helper methods
                        if let Some(min) = self.extract_min_bound(entry, stat_id, context)? {
                            min_bounds.push(min);
                        }
                        if let Some(max) = self.extract_max_bound(entry, stat_id, context)? {
                            max_bounds.push(max);
                        }
                    }

                    // Compute effective bounds (most restrictive)
                    let effective_min =
                        min_bounds.iter().fold(None, |acc: Option<StatValue>, &m| {
                            Some(acc.map_or(m, |a: StatValue| a.max(m)))
                        });
                    let effective_max =
                        max_bounds.iter().fold(None, |acc: Option<StatValue>, &m| {
                            Some(acc.map_or(m, |a: StatValue| a.min(m)))
                        });

                    // Apply clamping
                    if let Some(min) = effective_min {
                        current_value = current_value.max(min);
                    }
                    if let Some(max) = effective_max {
                        current_value = current_value.min(max);
                    }

                    // Update resolved stat description
                    match (effective_min, effective_max) {
                        (Some(min), Some(max)) => {
                            resolved.add_transform(
                                format!("clamp({:.2}, {:.2})", min.to_f64(), max.to_f64()),
                                current_value,
                            );
                        }
                        (Some(min), None) => {
                            resolved.add_transform(
                                format!("clamp_min({:.2})", min.to_f64()),
                                current_value,
                            );
                        }
                        (None, Some(max)) => {
                            resolved.add_transform(
                                format!("clamp_max({:.2})", max.to_f64()),
                                current_value,
                            );
                        }
                        (None, None) => {
                            // No bounds, no-op
                        }
                    }
                }
            }
        }

        Ok(current_value)
    }

    /// Collect dependency values for a transform.
    fn collect_dependencies(
        &self,
        dep_ids: Vec<StatId>,
        _stat_id: &StatId,
    ) -> Result<FxHashMap<StatId, StatValue>, StatError> {
        let mut dependencies = FxHashMap::default();
        for dep_id in dep_ids {
            let dep_value = self
                .cache
                .get(&dep_id)
                .map(|r| r.value)
                .ok_or_else(|| StatError::MissingDependency(dep_id.clone()))?;
            dependencies.insert(dep_id, dep_value);
        }
        Ok(dependencies)
    }

    /// Extract minimum bound from a transform entry.
    ///
    /// Applies the transform to a very negative value to infer the minimum bound.
    /// For ClampTransform, this will return the min parameter.
    fn extract_min_bound(
        &self,
        entry: &TransformEntry,
        stat_id: &StatId,
        context: &StatContext,
    ) -> Result<Option<StatValue>, StatError> {
        let dependencies = self.collect_dependencies(entry.transform.depends_on(), stat_id)?;
        let very_negative = StatValue::from_f64(-1e10);
        let bound_result = entry
            .transform
            .apply(very_negative, &dependencies, context)?;

        // If the result differs from input, it's a bound
        if bound_result > very_negative {
            Ok(Some(bound_result))
        } else {
            Ok(None)
        }
    }

    /// Extract maximum bound from a transform entry.
    ///
    /// Applies the transform to a very large value to infer the maximum bound.
    /// For ClampTransform, this will return the max parameter.
    fn extract_max_bound(
        &self,
        entry: &TransformEntry,
        stat_id: &StatId,
        context: &StatContext,
    ) -> Result<Option<StatValue>, StatError> {
        let dependencies = self.collect_dependencies(entry.transform.depends_on(), stat_id)?;
        let very_large = StatValue::from_f64(1e10);
        let bound_result = entry.transform.apply(very_large, &dependencies, context)?;

        // If the result differs from input, it's a bound
        if bound_result < very_large {
            Ok(Some(bound_result))
        } else {
            Ok(None)
        }
    }
}

impl Default for StatResolver {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::source::ConstantSource;
    use crate::transform::{MultiplicativeTransform, ScalingTransform};

    #[test]
    fn test_resolve_simple_source() {
        let mut resolver = StatResolver::new();
        let hp_id = StatId::from("HP");

        resolver.register_source(hp_id.clone(), Box::new(ConstantSource(100.0)));

        let context = StatContext::new();
        let resolved = resolver.resolve(&hp_id, &context).unwrap();

        assert_eq!(resolved.value, StatValue::from_f64(100.0));
        assert_eq!(resolved.stat_id, hp_id);
    }

    #[test]
    fn test_resolve_multiple_sources() {
        let mut resolver = StatResolver::new();
        let hp_id = StatId::from("HP");

        resolver.register_source(hp_id.clone(), Box::new(ConstantSource(100.0)));
        resolver.register_source(hp_id.clone(), Box::new(ConstantSource(50.0)));

        let context = StatContext::new();
        let resolved = resolver.resolve(&hp_id, &context).unwrap();

        assert_eq!(resolved.value, StatValue::from_f64(150.0));
        assert_eq!(resolved.sources.len(), 2);
    }

    #[test]
    fn test_resolve_with_transform() {
        let mut resolver = StatResolver::new();
        let atk_id = StatId::from("ATK");

        resolver.register_source(atk_id.clone(), Box::new(ConstantSource(100.0)));
        resolver.register_transform(atk_id.clone(), Box::new(MultiplicativeTransform::new(1.5)));

        let context = StatContext::new();
        let resolved = resolver.resolve(&atk_id, &context).unwrap();

        assert_eq!(resolved.value, StatValue::from_f64(150.0));
        assert_eq!(resolved.transforms.len(), 1);
    }

    #[test]
    fn test_resolve_with_dependency() {
        let mut resolver = StatResolver::new();
        let str_id = StatId::from("STR");
        let atk_id = StatId::from("ATK");

        resolver.register_source(str_id.clone(), Box::new(ConstantSource(10.0)));
        resolver.register_source(atk_id.clone(), Box::new(ConstantSource(50.0)));
        resolver.register_transform(
            atk_id.clone(),
            Box::new(ScalingTransform::new(str_id.clone(), 2.0)),
        );

        let context = StatContext::new();
        let resolved = resolver.resolve(&atk_id, &context).unwrap();

        // 50 (base) + 10 (STR) * 2 (scale) = 70
        assert_eq!(resolved.value, StatValue::from_f64(70.0));
    }

    #[test]
    fn test_resolve_missing_source() {
        let mut resolver = StatResolver::new();
        let hp_id = StatId::from("HP");

        let context = StatContext::new();
        let _result = resolver.resolve(&hp_id, &context);

        // Should return MissingSource error since no source is registered
        // This is expected behavior per the spec
    }

    #[test]
    fn test_cache_invalidation() {
        let mut resolver = StatResolver::new();
        let hp_id = StatId::from("HP");

        resolver.register_source(hp_id.clone(), Box::new(ConstantSource(100.0)));

        let context = StatContext::new();
        let resolved1 = resolver.resolve(&hp_id, &context).unwrap();
        assert_eq!(resolved1.value, StatValue::from_f64(100.0));

        // Should be cached
        let resolved2 = resolver.resolve(&hp_id, &context).unwrap();
        assert_eq!(resolved2.value, StatValue::from_f64(100.0));

        // Invalidate and add new source
        resolver.invalidate(&hp_id);
        resolver.register_source(hp_id.clone(), Box::new(ConstantSource(50.0)));

        let resolved3 = resolver.resolve(&hp_id, &context).unwrap();
        assert_eq!(resolved3.value, StatValue::from_f64(150.0)); // 100 + 50
    }

    #[test]
    fn test_cycle_detection() {
        let mut resolver = StatResolver::new();
        let a_id = StatId::from("A");
        let b_id = StatId::from("B");

        // Create a cycle: A depends on B, B depends on A
        resolver.register_source(a_id.clone(), Box::new(ConstantSource(1.0)));
        resolver.register_source(b_id.clone(), Box::new(ConstantSource(1.0)));

        resolver.register_transform(
            a_id.clone(),
            Box::new(ScalingTransform::new(b_id.clone(), 1.0)),
        );
        resolver.register_transform(
            b_id.clone(),
            Box::new(ScalingTransform::new(a_id.clone(), 1.0)),
        );

        let context = StatContext::new();
        let result = resolver.resolve(&a_id, &context);

        assert!(result.is_err());
        if let Err(StatError::Cycle { path: _ }) = result {
            // Good
        } else {
            panic!("Expected Cycle error");
        }
    }
    #[test]
    fn test_cache_invalidation_chain() {
        let mut resolver = StatResolver::new();
        let str_id = StatId::from("STR");
        let atk_id = StatId::from("ATK");

        // ATK depends on STR (ATK = STR * 2)
        resolver.register_source(str_id.clone(), Box::new(ConstantSource(10.0)));
        resolver.register_source(atk_id.clone(), Box::new(ConstantSource(0.0)));
        resolver.register_transform(
            atk_id.clone(),
            Box::new(ScalingTransform::new(str_id.clone(), 2.0)),
        );

        let context = StatContext::new();

        // Initial resolution
        let atk_resolved = resolver.resolve(&atk_id, &context).unwrap();
        assert_eq!(atk_resolved.value, StatValue::from_f64(20.0));

        // Now change STR by registering a new source (e.g., buff)
        // This should invalidate STR AND downstream ATK
        resolver.register_source(str_id.clone(), Box::new(ConstantSource(5.0))); // total STR = 15

        // Resolve ATK again
        let atk_resolved2 = resolver.resolve(&atk_id, &context).unwrap();
        // ATK should be 15 * 2 = 30
        assert_eq!(atk_resolved2.value, StatValue::from_f64(30.0));
    }
}