behaviorsim-rs 0.7.0

Domain-agnostic specification for modeling individual psychology and social dynamics
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
//! Mental health state based on Joiner's Interpersonal Theory of Suicide.
//!
//! This module implements the ITS model with:
//! - Thwarted Belongingness (TB): Computed from loneliness and perceived reciprocal caring
//! - Perceived Burdensomeness (PB): Computed from perceived liability and self-hate
//! - Acquired Capability (AC): Habituation to pain/fear; NEVER DECAYS
//! - Interpersonal Hopelessness: Perceived permanence of TB/PB (not general hopelessness)
//!
//! ITS Formulas:
//! - TB = loneliness * (1 - perceived_reciprocal_caring)^g
//! - PB = perceived_liability * self_hate
//! - Suicidal Desire = TB * PB (when both TB and PB are above threshold AND hopelessness > threshold)
//! - Attempt Risk = Desire * Acquired Capability

use crate::state::{SocialCognition, StateValue};
use crate::types::Duration;
use serde::{Deserialize, Serialize};

/// Threshold above which Thwarted Belongingness is considered present.
/// Per ITS, TB must be significantly elevated to contribute to suicidal desire.
pub const TB_PRESENT_THRESHOLD: f32 = 0.5;

/// Exponent for caring-based buffering of thwarted belongingness.
/// Values > 1.0 strengthen the protective effect of caring.
const CARING_BUFFER_EXPONENT: f32 = 3.0;

/// Threshold above which Perceived Burdensomeness is considered present.
/// Per ITS, PB must be significantly elevated to contribute to suicidal desire.
pub const PB_PRESENT_THRESHOLD: f32 = 0.5;

/// Threshold above which interpersonal hopelessness activates suicidal desire.
/// This represents the perceived permanence of TB/PB states.
pub const HOPELESSNESS_THRESHOLD: f32 = 0.5;

/// Threshold above which Acquired Capability is considered present.
/// Per ITS, capability must be meaningfully elevated to enable lethal action.
pub const AC_PRESENCE_THRESHOLD: f64 = 0.4;

/// Returns true when acquired capability is meaningfully elevated.
#[must_use]
pub fn is_ac_present(ac_score: f64) -> bool {
    ac_score >= AC_PRESENCE_THRESHOLD
}

/// ITS convergence snapshot showing which factors are simultaneously present.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct ITSConvergence {
    /// Thwarted belongingness above threshold.
    pub tb_present: bool,
    /// Perceived burdensomeness above threshold.
    pub pb_present: bool,
    /// Acquired capability above threshold.
    pub ac_present: bool,
    /// True only when TB, PB, and AC are all present.
    pub all_factors_present: bool,
}

/// Categorical ITS risk levels for clinical interpretability.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ITSRiskLevel {
    /// No desire and no capability.
    NoRisk,
    /// Suicidal desire present, capability absent.
    DesireOnly,
    /// Capability present, desire absent.
    CapabilityOnly,
    /// TB and PB present with capability, but hopelessness is absent.
    BothPresentButNotConvergent,
    /// Desire and capability present at the same time.
    HighestRisk,
}

/// Mental health state with ITS (Interpersonal Theory of Suicide) factors.
///
/// The ITS model states that suicidal desire requires:
/// 1. Thwarted Belongingness (TB) - feeling disconnected from others
/// 2. Perceived Burdensomeness (PB) - feeling like a burden to others
/// 3. Interpersonal Hopelessness - believing these states are permanent
///
/// The capability for lethal self-harm is separate from desire and
/// represented by Acquired Capability (AC), which never decays.
///
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MentalHealth {
    /// Depression severity.
    /// Range: 0 (not depressed) to 1 (severe depression)
    /// Default decay half-life: 1 week
    depression: StateValue,

    /// Sense of personal value.
    /// Range: 0 (worthless) to 1 (high self-worth)
    /// Default decay half-life: 3 days
    self_worth: StateValue,

    /// Cognitive belief about future (general hopelessness).
    /// Range: 0 (hopeful) to 1 (hopeless)
    /// Default decay half-life: 3 days
    hopelessness: StateValue,

    /// Perceived permanence of interpersonal pain (TB/PB states).
    /// This is distinct from general hopelessness - it's specifically
    /// about whether the person believes their interpersonal situation
    /// can ever improve.
    /// Range: 0 (changeable) to 1 (permanent)
    /// Default decay half-life: 2 days
    interpersonal_hopelessness: StateValue,

    /// Habituation to pain and fear of death.
    /// This is a trait-like accumulation that NEVER DECAYS.
    /// Range: 0 (fearful of pain/death) to 1 (habituated)
    /// Decay: None (permanent)
    acquired_capability: StateValue,
}

impl MentalHealth {
    /// Default decay half-life for depression (1 week).
    const DEPRESSION_DECAY_HALF_LIFE: Duration = Duration::weeks(1);

    /// Default decay half-life for self-worth (3 days).
    const SELF_WORTH_DECAY_HALF_LIFE: Duration = Duration::days(3);

    /// Default decay half-life for hopelessness (3 days).
    const HOPELESSNESS_DECAY_HALF_LIFE: Duration = Duration::days(3);

    /// Default decay half-life for interpersonal hopelessness (2 weeks).
    const INTERPERSONAL_HOPELESSNESS_DECAY_HALF_LIFE: Duration = Duration::weeks(2);

    /// Creates a new MentalHealth with healthy defaults.
    ///
    #[must_use]
    pub fn new() -> Self {
        MentalHealth {
            depression: StateValue::new(0.1)
                .with_bounds(0.0, 1.0)
                .with_decay_half_life(Self::DEPRESSION_DECAY_HALF_LIFE),
            self_worth: StateValue::new(0.6)
                .with_bounds(0.0, 1.0)
                .with_decay_half_life(Self::SELF_WORTH_DECAY_HALF_LIFE),
            hopelessness: StateValue::new(0.1)
                .with_bounds(0.0, 1.0)
                .with_decay_half_life(Self::HOPELESSNESS_DECAY_HALF_LIFE),
            interpersonal_hopelessness: StateValue::new(0.1)
                .with_bounds(0.0, 1.0)
                .with_decay_half_life(Self::INTERPERSONAL_HOPELESSNESS_DECAY_HALF_LIFE),
            // AC never decays - uses new_no_decay
            acquired_capability: StateValue::new_no_decay(0.0).with_bounds(0.0, 1.0),
        }
    }

    // ITS Compute Methods

    /// Computes Thwarted Belongingness from social cognition.
    ///
    /// Formula: TB = loneliness * (1 - perceived_reciprocal_caring)^g
    ///
    /// High loneliness only produces TB when perceived caring is low.
    /// High caring buffers TB even if loneliness is elevated.
    ///
    /// # Arguments
    ///
    /// * `social` - The social cognition state containing loneliness and perceived_reciprocal_caring
    ///
    /// # Returns
    ///
    /// TB value from 0.0 to 1.0
    #[must_use]
    pub fn compute_thwarted_belongingness(&self, social: &SocialCognition) -> f32 {
        let loneliness = social.loneliness_effective();
        let caring = social.perceived_reciprocal_caring_effective();

        // TB = loneliness * (1 - caring)^g
        let tb = loneliness * (1.0 - caring).powf(CARING_BUFFER_EXPONENT);
        tb.clamp(0.0, 1.0)
    }

    /// Computes Perceived Burdensomeness from social cognition.
    ///
    /// Formula: PB = perceived_liability * self_hate
    ///
    /// This is a multiplicative formula, meaning BOTH liability perception
    /// AND self-hate are required for PB to be present. Liability alone
    /// is insufficient without self-hate, and vice versa.
    ///
    /// # Arguments
    ///
    /// * `social` - The social cognition state containing perceived_liability and self_hate
    ///
    /// # Returns
    ///
    /// PB value from 0.0 to 1.0
    #[must_use]
    pub fn compute_perceived_burdensomeness(&self, social: &SocialCognition) -> f32 {
        let liability = social.perceived_liability_effective();
        let self_hate = social.self_hate_effective();

        // PB = liability * self_hate (multiplicative)
        let pb = liability * self_hate;
        pb.clamp(0.0, 1.0)
    }

    /// Computes suicidal desire from TB, PB, and interpersonal hopelessness.
    ///
    /// Per ITS, suicidal desire requires:
    /// 1. Thwarted Belongingness above threshold
    /// 2. Perceived Burdensomeness above threshold
    /// 3. Interpersonal hopelessness above threshold (belief that TB/PB are permanent)
    ///
    /// If any condition is not met, desire is zero.
    ///
    /// # Arguments
    ///
    /// * `social` - The social cognition state for computing TB and PB
    ///
    /// # Returns
    ///
    /// Suicidal desire from 0.0 to 1.0
    #[must_use]
    pub fn compute_suicidal_desire(&self, social: &SocialCognition) -> f32 {
        let hopelessness = self.interpersonal_hopelessness.effective();
        let tb = self.compute_thwarted_belongingness(social);
        let pb = self.compute_perceived_burdensomeness(social);

        if !self.is_tb_present(social)
            || !self.is_pb_present(social)
            || hopelessness < HOPELESSNESS_THRESHOLD
        {
            return 0.0;
        }

        let desire = tb * pb;
        desire.clamp(0.0, 1.0)
    }

    /// Computes attempt risk from desire and acquired capability.
    ///
    /// Risk = Desire * Acquired Capability, but only when AC is above threshold.
    ///
    /// High desire with low capability means ideation without means.
    /// High capability with low desire is "dormant" risk - capability
    /// that could become dangerous if desire increases.
    ///
    /// # Arguments
    ///
    /// * `social` - The social cognition state for computing desire
    ///
    /// # Returns
    ///
    /// Attempt risk from 0.0 to 1.0
    #[must_use]
    pub fn compute_attempt_risk(&self, social: &SocialCognition) -> f32 {
        let desire = self.compute_suicidal_desire(social);
        if desire <= 0.0 {
            return 0.0;
        }

        let convergence = self.its_convergence(social);
        if !convergence.all_factors_present {
            return 0.0;
        }

        let capability = self.acquired_capability.effective();

        let risk = desire * capability;
        risk.clamp(0.0, 1.0)
    }

    /// Computes dormant escalation risk.
    ///
    /// High acquired capability with low desire indicates latent risk if desire increases.
    /// Returns 0.0-1.0 where higher values indicate greater dormant risk.
    #[must_use]
    pub fn compute_dormant_risk(&self, social: &SocialCognition) -> f32 {
        let desire = self.compute_suicidal_desire(social);
        let capability = self.acquired_capability.effective();
        let dormant_risk = capability * (1.0 - desire);
        dormant_risk.clamp(0.0, 1.0)
    }

    /// Checks if Thwarted Belongingness is above the present threshold.
    #[must_use]
    pub fn is_tb_present(&self, social: &SocialCognition) -> bool {
        self.compute_thwarted_belongingness(social) >= TB_PRESENT_THRESHOLD
    }

    /// Checks if Perceived Burdensomeness is above the present threshold.
    #[must_use]
    pub fn is_pb_present(&self, social: &SocialCognition) -> bool {
        let liability = social.perceived_liability_effective();
        let self_hate = social.self_hate_effective();

        if liability < PB_PRESENT_THRESHOLD || self_hate < PB_PRESENT_THRESHOLD {
            return false;
        }

        self.compute_perceived_burdensomeness(social) >= PB_PRESENT_THRESHOLD
    }

    /// Checks if interpersonal hopelessness is above the threshold.
    #[must_use]
    pub fn is_interpersonal_hopelessness_present(&self) -> bool {
        self.interpersonal_hopelessness.effective() >= HOPELESSNESS_THRESHOLD
    }

    /// Computes ITS convergence across TB, PB, and AC.
    ///
    /// This is the gating mechanism for lethal risk: all three factors
    /// must be simultaneously present above thresholds.
    #[must_use]
    pub fn its_convergence(&self, social: &SocialCognition) -> ITSConvergence {
        let tb_present = self.is_tb_present(social);
        let pb_present = self.is_pb_present(social);
        let ac_present = is_ac_present(self.acquired_capability.effective() as f64);
        let all_factors_present = tb_present && pb_present && ac_present;

        ITSConvergence {
            tb_present,
            pb_present,
            ac_present,
            all_factors_present,
        }
    }

    /// Computes categorical ITS risk level from current social cognition.
    #[must_use]
    pub fn its_risk_level(&self, social: &SocialCognition) -> ITSRiskLevel {
        let tb_present = self.is_tb_present(social);
        let pb_present = self.is_pb_present(social);
        let hopelessness_present = self.interpersonal_hopelessness.effective() >= HOPELESSNESS_THRESHOLD;
        let ac_present = is_ac_present(self.acquired_capability.effective() as f64);
        let desire_present = tb_present && pb_present && hopelessness_present;

        match (desire_present, ac_present) {
            (true, true) => ITSRiskLevel::HighestRisk,
            (true, false) => ITSRiskLevel::DesireOnly,
            (false, true) if tb_present && pb_present => ITSRiskLevel::BothPresentButNotConvergent,
            (false, true) => ITSRiskLevel::CapabilityOnly,
            (false, false) => ITSRiskLevel::NoRisk,
        }
    }

    // Builder methods

    /// Sets the base depression.
    #[must_use]
    pub fn with_depression_base(mut self, value: f32) -> Self {
        self.depression.set_base(value);
        self
    }

    /// Sets the base self-worth.
    #[must_use]
    pub fn with_self_worth_base(mut self, value: f32) -> Self {
        self.self_worth.set_base(value);
        self
    }

    /// Sets the base hopelessness.
    #[must_use]
    pub fn with_hopelessness_base(mut self, value: f32) -> Self {
        self.hopelessness.set_base(value);
        self
    }

    /// Sets the base interpersonal hopelessness.
    #[must_use]
    pub fn with_interpersonal_hopelessness_base(mut self, value: f32) -> Self {
        self.interpersonal_hopelessness.set_base(value);
        self
    }

    /// Sets the base acquired capability.
    #[must_use]
    pub fn with_acquired_capability_base(mut self, value: f32) -> Self {
        self.acquired_capability.set_base(value);
        self
    }

    // Effective value accessors

    /// Returns the effective depression (base + delta).
    #[must_use]
    pub fn depression_effective(&self) -> f32 {
        self.depression.effective()
    }

    /// Returns the effective self-worth (base + delta).
    #[must_use]
    pub fn self_worth_effective(&self) -> f32 {
        self.self_worth.effective()
    }

    /// Returns the effective hopelessness (base + delta).
    #[must_use]
    pub fn hopelessness_effective(&self) -> f32 {
        self.hopelessness.effective()
    }

    /// Returns the effective interpersonal hopelessness (base + delta).
    #[must_use]
    pub fn interpersonal_hopelessness_effective(&self) -> f32 {
        self.interpersonal_hopelessness.effective()
    }

    /// Returns the effective acquired capability (base + delta).
    #[must_use]
    pub fn acquired_capability_effective(&self) -> f32 {
        self.acquired_capability.effective()
    }

    // StateValue references

    /// Returns a reference to the depression StateValue.
    #[must_use]
    pub fn depression(&self) -> &StateValue {
        &self.depression
    }

    /// Returns a reference to the self_worth StateValue.
    #[must_use]
    pub fn self_worth(&self) -> &StateValue {
        &self.self_worth
    }

    /// Returns a reference to the hopelessness StateValue.
    #[must_use]
    pub fn hopelessness(&self) -> &StateValue {
        &self.hopelessness
    }

    /// Returns a reference to the interpersonal_hopelessness StateValue.
    #[must_use]
    pub fn interpersonal_hopelessness(&self) -> &StateValue {
        &self.interpersonal_hopelessness
    }

    /// Returns a reference to the acquired_capability StateValue.
    #[must_use]
    pub fn acquired_capability(&self) -> &StateValue {
        &self.acquired_capability
    }

    /// Returns a mutable reference to the depression StateValue.
    pub fn depression_mut(&mut self) -> &mut StateValue {
        &mut self.depression
    }

    /// Returns a mutable reference to the self_worth StateValue.
    pub fn self_worth_mut(&mut self) -> &mut StateValue {
        &mut self.self_worth
    }

    /// Returns a mutable reference to the hopelessness StateValue.
    pub fn hopelessness_mut(&mut self) -> &mut StateValue {
        &mut self.hopelessness
    }

    /// Returns a mutable reference to the interpersonal_hopelessness StateValue.
    pub fn interpersonal_hopelessness_mut(&mut self) -> &mut StateValue {
        &mut self.interpersonal_hopelessness
    }

    /// Returns a mutable reference to the acquired_capability StateValue.
    pub fn acquired_capability_mut(&mut self) -> &mut StateValue {
        &mut self.acquired_capability
    }

    // Base shifters (for permanent changes)

    /// Shifts the base self-worth by adding an amount.
    ///
    /// This is used for permanent changes from events.
    pub fn shift_self_worth_base(&mut self, amount: f32) {
        self.self_worth.shift_base(amount);
    }

    /// Shifts the base interpersonal hopelessness by adding an amount.
    ///
    /// This is used for permanent changes from events.
    pub fn shift_interpersonal_hopelessness_base(&mut self, amount: f32) {
        self.interpersonal_hopelessness.shift_base(amount);
    }

    /// Shifts the base acquired capability by adding an amount.
    ///
    /// AC is always 100% permanent, so all AC changes go to base.
    pub fn shift_acquired_capability_base(&mut self, amount: f32) {
        self.acquired_capability.shift_base(amount);
    }

    // Delta modifiers

    /// Adds to the depression delta.
    pub fn add_depression_delta(&mut self, amount: f32) {
        self.depression.add_delta(amount);
    }

    /// Adds to the self-worth delta.
    pub fn add_self_worth_delta(&mut self, amount: f32) {
        self.self_worth.add_delta(amount);
    }

    /// Adds to the hopelessness delta.
    pub fn add_hopelessness_delta(&mut self, amount: f32) {
        self.hopelessness.add_delta(amount);
    }

    /// Adds to the interpersonal hopelessness delta.
    pub fn add_interpersonal_hopelessness_delta(&mut self, amount: f32) {
        self.interpersonal_hopelessness.add_delta(amount);
    }

    /// Adds to the acquired capability delta.
    ///
    /// Note: AC never decays, so delta additions are permanent.
    pub fn add_acquired_capability_delta(&mut self, amount: f32) {
        self.acquired_capability.add_delta(amount);
    }

    // Chronic delta modifiers

    /// Adds to the self-worth chronic delta.
    pub fn add_self_worth_chronic_delta(&mut self, amount: f32) {
        self.self_worth.add_chronic_delta(amount);
    }

    /// Adds to the interpersonal hopelessness chronic delta.
    pub fn add_interpersonal_hopelessness_chronic_delta(&mut self, amount: f32) {
        self.interpersonal_hopelessness.add_chronic_delta(amount);
    }

    // Decay

    /// Applies decay to mental health dimensions over the specified duration.
    ///
    /// Note: Acquired Capability NEVER decays.
    pub fn apply_decay(&mut self, elapsed: Duration) {
        self.depression.apply_decay(elapsed);
        self.self_worth.apply_decay(elapsed);
        self.hopelessness.apply_decay(elapsed);
        self.interpersonal_hopelessness.apply_decay(elapsed);
        // acquired_capability intentionally not decayed
    }

    /// Resets deltas for decaying dimensions only.
    ///
    /// Note: AC delta is not reset as it's permanent.
    pub fn reset_deltas(&mut self) {
        self.depression.reset_delta();
        self.self_worth.reset_delta();
        self.hopelessness.reset_delta();
        self.interpersonal_hopelessness.reset_delta();
        // acquired_capability intentionally not reset
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::state::SocialCognition;

    #[test]
    fn thwarted_belongingness_multiplicative_buffer() {
        // TB = loneliness * (1 - perceived_reciprocal_caring)^g
        let mh = MentalHealth::new();

        // High loneliness, low caring
        let social = SocialCognition::new()
            .with_loneliness_base(0.8)
            .with_perceived_reciprocal_caring_base(0.2);
        let tb = mh.compute_thwarted_belongingness(&social);
        // TB = 0.8 * (1 - 0.2)^3 = 0.4096
        assert!((tb - 0.4096).abs() < 0.01);

        // Low loneliness, high caring
        let social2 = SocialCognition::new()
            .with_loneliness_base(0.2)
            .with_perceived_reciprocal_caring_base(0.8);
        let tb2 = mh.compute_thwarted_belongingness(&social2);
        // TB = 0.2 * (1 - 0.8)^3 = 0.0016
        assert!((tb2 - 0.0016).abs() < 0.01);
    }

    #[test]
    fn perceived_burdensomeness_multiplicative_formula() {
        // PB = perceived_liability * self_hate
        let mh = MentalHealth::new();

        // High liability, high self-hate
        let social = SocialCognition::new()
            .with_perceived_liability_base(0.8)
            .with_self_hate_base(0.8);
        let pb = mh.compute_perceived_burdensomeness(&social);
        // PB = 0.8 * 0.8 = 0.64
        assert!((pb - 0.64).abs() < 0.01);

        // High liability, low self-hate - PB should be low
        let social2 = SocialCognition::new()
            .with_perceived_liability_base(0.8)
            .with_self_hate_base(0.1);
        let pb2 = mh.compute_perceived_burdensomeness(&social2);
        // PB = 0.8 * 0.1 = 0.08
        assert!((pb2 - 0.08).abs() < 0.01);
    }

    #[test]
    fn acquired_capability_never_decays() {
        let mut mh = MentalHealth::new();
        mh.add_acquired_capability_delta(0.5);

        // Apply decay over a very long time
        mh.apply_decay(Duration::years(100));

        // AC delta should remain unchanged
        assert!((mh.acquired_capability().delta() - 0.5).abs() < f32::EPSILON);
        assert!(!mh.acquired_capability().decays());
    }

    #[test]
    fn desire_requires_tb_pb_hopelessness() {
        let mut mh = MentalHealth::new().with_interpersonal_hopelessness_base(0.6); // Above threshold

        // High TB and PB inputs
        let social = SocialCognition::new()
            .with_loneliness_base(0.9)
            .with_perceived_reciprocal_caring_base(0.1)
            .with_perceived_liability_base(0.9)
            .with_self_hate_base(0.9);

        // With all conditions met, desire should be non-zero
        let desire = mh.compute_suicidal_desire(&social);
        assert!(desire > 0.0);

        // Now remove hopelessness - desire should be zero
        mh = MentalHealth::new().with_interpersonal_hopelessness_base(0.2); // Below threshold
        let desire2 = mh.compute_suicidal_desire(&social);
        assert!((desire2 - 0.0).abs() < f32::EPSILON);
    }

    #[test]
    fn interpersonal_hopelessness_measures_permanence() {
        // Test that interpersonal hopelessness is about TB/PB permanence
        let mh = MentalHealth::new().with_interpersonal_hopelessness_base(0.8);

        assert!(mh.is_interpersonal_hopelessness_present());

        // General hopelessness is separate
        let mh2 = MentalHealth::new()
            .with_hopelessness_base(0.8)
            .with_interpersonal_hopelessness_base(0.2);

        assert!(!mh2.is_interpersonal_hopelessness_present());
    }

    #[test]
    fn attempt_risk_requires_desire_and_capability() {
        let mh = MentalHealth::new()
            .with_interpersonal_hopelessness_base(0.7)
            .with_acquired_capability_base(0.8);

        // High TB, PB, hopelessness, capability
        let social = SocialCognition::new()
            .with_loneliness_base(0.9)
            .with_perceived_reciprocal_caring_base(0.1)
            .with_perceived_liability_base(0.9)
            .with_self_hate_base(0.9);

        let risk = mh.compute_attempt_risk(&social);
        assert!(risk > 0.0);

        // Zero capability means zero risk even with desire
        let mh2 = MentalHealth::new()
            .with_interpersonal_hopelessness_base(0.7)
            .with_acquired_capability_base(0.0);
        let risk2 = mh2.compute_attempt_risk(&social);
        assert!((risk2 - 0.0).abs() < f32::EPSILON);
    }

    #[test]
    fn dormant_risk_high_ac_low_desire() {
        let mh = MentalHealth::new()
            .with_interpersonal_hopelessness_base(0.2)
            .with_acquired_capability_base(0.9);

        let low_desire_social = SocialCognition::new()
            .with_loneliness_base(0.1)
            .with_perceived_reciprocal_caring_base(0.9)
            .with_perceived_liability_base(0.1)
            .with_self_hate_base(0.1);

        let risk = mh.compute_dormant_risk(&low_desire_social);
        assert!(risk > 0.7);
    }

    #[test]
    fn dormant_risk_high_desire_low_latent_risk() {
        let mh = MentalHealth::new()
            .with_interpersonal_hopelessness_base(0.8)
            .with_acquired_capability_base(0.9);

        let high_desire_social = SocialCognition::new()
            .with_loneliness_base(1.0)
            .with_perceived_reciprocal_caring_base(0.0)
            .with_perceived_liability_base(1.0)
            .with_self_hate_base(1.0);

        let risk = mh.compute_dormant_risk(&high_desire_social);
        assert!(risk < 0.3);
    }

    #[test]
    fn dormant_risk_low_ac_remains_low() {
        let mh = MentalHealth::new()
            .with_interpersonal_hopelessness_base(0.8)
            .with_acquired_capability_base(0.1);

        let high_desire_social = SocialCognition::new()
            .with_loneliness_base(0.9)
            .with_perceived_reciprocal_caring_base(0.1)
            .with_perceived_liability_base(0.9)
            .with_self_hate_base(0.9);

        let risk = mh.compute_dormant_risk(&high_desire_social);
        assert!(risk < 0.2);
    }

    #[test]
    fn attempt_risk_requires_ac_threshold() {
        let mh = MentalHealth::new()
            .with_interpersonal_hopelessness_base(0.8)
            .with_acquired_capability_base((AC_PRESENCE_THRESHOLD - 0.05) as f32);

        let social = SocialCognition::new()
            .with_loneliness_base(0.9)
            .with_perceived_reciprocal_caring_base(0.1)
            .with_perceived_liability_base(0.9)
            .with_self_hate_base(0.9);

        let risk = mh.compute_attempt_risk(&social);
        assert!((risk - 0.0).abs() < f32::EPSILON);
    }

    #[test]
    fn its_convergence_reports_presence() {
        let mh = MentalHealth::new()
            .with_interpersonal_hopelessness_base(0.7)
            .with_acquired_capability_base((AC_PRESENCE_THRESHOLD + 0.1) as f32);

        let social = SocialCognition::new()
            .with_loneliness_base(0.9)
            .with_perceived_reciprocal_caring_base(0.1)
            .with_perceived_liability_base(0.9)
            .with_self_hate_base(0.9);

        let convergence = mh.its_convergence(&social);
        assert!(convergence.tb_present);
        assert!(convergence.pb_present);
        assert!(convergence.ac_present);
        assert!(convergence.all_factors_present);
    }

    #[test]
    fn tb_threshold_check() {
        let mh = MentalHealth::new();

        let low_tb_social = SocialCognition::new()
            .with_loneliness_base(0.2)
            .with_perceived_reciprocal_caring_base(0.8);
        assert!(!mh.is_tb_present(&low_tb_social));

        let high_tb_social = SocialCognition::new()
            .with_loneliness_base(0.9)
            .with_perceived_reciprocal_caring_base(0.1);
        assert!(mh.is_tb_present(&high_tb_social));
    }

    #[test]
    fn pb_threshold_check() {
        let mh = MentalHealth::new();

        let low_pb_social = SocialCognition::new()
            .with_perceived_liability_base(0.2)
            .with_self_hate_base(0.2);
        assert!(!mh.is_pb_present(&low_pb_social));

        let imbalanced_liability_social = SocialCognition::new()
            .with_perceived_liability_base(0.9)
            .with_self_hate_base(0.2);
        assert!(!mh.is_pb_present(&imbalanced_liability_social));

        let imbalanced_self_hate_social = SocialCognition::new()
            .with_perceived_liability_base(0.2)
            .with_self_hate_base(0.9);
        assert!(!mh.is_pb_present(&imbalanced_self_hate_social));

        let high_pb_social = SocialCognition::new()
            .with_perceived_liability_base(0.8)
            .with_self_hate_base(0.8);
        assert!(mh.is_pb_present(&high_pb_social));
    }

    #[test]
    fn new_creates_healthy_defaults() {
        let mh = MentalHealth::new();

        assert!(mh.depression_effective() < 0.3);
        assert!(mh.self_worth_effective() > 0.5);
        assert!(mh.hopelessness_effective() < 0.3);
        assert!(mh.interpersonal_hopelessness_effective() < 0.3);
        assert!(mh.acquired_capability_effective() < 0.1);
    }

    #[test]
    fn builder_methods_work() {
        let mh = MentalHealth::new()
            .with_depression_base(0.5)
            .with_self_worth_base(0.3)
            .with_hopelessness_base(0.4)
            .with_interpersonal_hopelessness_base(0.6)
            .with_acquired_capability_base(0.2);

        assert!((mh.depression().base() - 0.5).abs() < f32::EPSILON);
        assert!((mh.self_worth().base() - 0.3).abs() < f32::EPSILON);
        assert!((mh.hopelessness().base() - 0.4).abs() < f32::EPSILON);
        assert!((mh.interpersonal_hopelessness().base() - 0.6).abs() < f32::EPSILON);
        assert!((mh.acquired_capability().base() - 0.2).abs() < f32::EPSILON);
    }

    #[test]
    fn delta_modifiers_work() {
        let mut mh = MentalHealth::new();

        mh.add_depression_delta(0.3);
        assert!((mh.depression().delta() - 0.3).abs() < f32::EPSILON);

        mh.add_self_worth_delta(-0.2);
        assert!((mh.self_worth().delta() - (-0.2)).abs() < f32::EPSILON);
    }

    #[test]
    fn decay_does_not_affect_ac() {
        let mut mh = MentalHealth::new();
        mh.add_depression_delta(0.5);
        mh.add_acquired_capability_delta(0.5);

        mh.apply_decay(Duration::weeks(4));

        // Depression should have decayed significantly
        assert!(mh.depression().delta() < 0.3);

        // AC should not have decayed at all
        assert!((mh.acquired_capability().delta() - 0.5).abs() < f32::EPSILON);
    }

    #[test]
    fn reset_deltas_does_not_affect_ac() {
        let mut mh = MentalHealth::new();
        mh.add_depression_delta(0.5);
        mh.add_acquired_capability_delta(0.5);

        mh.reset_deltas();

        assert!(mh.depression().delta().abs() < f32::EPSILON);
        // AC delta should remain
        assert!((mh.acquired_capability().delta() - 0.5).abs() < f32::EPSILON);
    }

    #[test]
    fn default_is_new() {
        let mh = MentalHealth::default();
        assert!(mh.depression_effective() < 0.3);
    }

    #[test]
    fn clone_and_equality() {
        let mh1 = MentalHealth::new().with_depression_base(0.5);
        let mh2 = mh1.clone();
        assert_eq!(mh1, mh2);
    }

    #[test]
    fn debug_format() {
        let mh = MentalHealth::new();
        let debug = format!("{:?}", mh);
        assert!(debug.contains("MentalHealth"));
    }

    #[test]
    fn mutable_references_work() {
        let mut mh = MentalHealth::new();
        mh.depression_mut().add_delta(0.2);
        assert!((mh.depression().delta() - 0.2).abs() < f32::EPSILON);
    }

    #[test]
    fn threshold_constants_defined() {
        // Verify constants are accessible and reasonable
        assert!(TB_PRESENT_THRESHOLD > 0.0 && TB_PRESENT_THRESHOLD <= 1.0);
        assert!(PB_PRESENT_THRESHOLD > 0.0 && PB_PRESENT_THRESHOLD <= 1.0);
        assert!(HOPELESSNESS_THRESHOLD > 0.0 && HOPELESSNESS_THRESHOLD <= 1.0);
        assert!(AC_PRESENCE_THRESHOLD > 0.0 && AC_PRESENCE_THRESHOLD <= 1.0);
    }

    #[test]
    fn ac_presence_helper_uses_threshold() {
        assert!(!is_ac_present(AC_PRESENCE_THRESHOLD - 0.01));
        assert!(is_ac_present(AC_PRESENCE_THRESHOLD));
    }

    #[test]
    fn its_risk_level_distinguishes_desire_and_capability() {
        let social = SocialCognition::new()
            .with_loneliness_base(0.9)
            .with_perceived_reciprocal_caring_base(0.1)
            .with_perceived_liability_base(0.9)
            .with_self_hate_base(0.9);

        let desire_only = MentalHealth::new()
            .with_interpersonal_hopelessness_base(0.8)
            .with_acquired_capability_base(0.1);
        assert_eq!(
            desire_only.its_risk_level(&social),
            ITSRiskLevel::DesireOnly
        );

        let low_desire_social = SocialCognition::new()
            .with_loneliness_base(0.2)
            .with_perceived_reciprocal_caring_base(0.8)
            .with_perceived_liability_base(0.2)
            .with_self_hate_base(0.2);

        let capability_only = MentalHealth::new()
            .with_interpersonal_hopelessness_base(0.2)
            .with_acquired_capability_base(0.8);
        assert_eq!(
            capability_only.its_risk_level(&low_desire_social),
            ITSRiskLevel::CapabilityOnly
        );
    }

    #[test]
    fn its_risk_level_detects_non_convergent_state() {
        let social = SocialCognition::new()
            .with_loneliness_base(0.9)
            .with_perceived_reciprocal_caring_base(0.1)
            .with_perceived_liability_base(0.9)
            .with_self_hate_base(0.9);

        let mh = MentalHealth::new()
            .with_interpersonal_hopelessness_base(0.1)
            .with_acquired_capability_base(0.9);

        assert_eq!(
            mh.its_risk_level(&social),
            ITSRiskLevel::BothPresentButNotConvergent
        );
    }

    #[test]
    fn its_risk_level_handles_highest_and_no_risk_states() {
        let high_risk_social = SocialCognition::new()
            .with_loneliness_base(0.9)
            .with_perceived_reciprocal_caring_base(0.1)
            .with_perceived_liability_base(0.9)
            .with_self_hate_base(0.9);
        let highest_risk = MentalHealth::new()
            .with_interpersonal_hopelessness_base(0.9)
            .with_acquired_capability_base(0.9);

        assert_eq!(
            highest_risk.its_risk_level(&high_risk_social),
            ITSRiskLevel::HighestRisk
        );

        let low_risk_social = SocialCognition::new()
            .with_loneliness_base(0.1)
            .with_perceived_reciprocal_caring_base(0.9)
            .with_perceived_liability_base(0.1)
            .with_self_hate_base(0.1);
        let no_risk = MentalHealth::new()
            .with_interpersonal_hopelessness_base(0.1)
            .with_acquired_capability_base(0.1);

        assert_eq!(no_risk.its_risk_level(&low_risk_social), ITSRiskLevel::NoRisk);
    }

    #[test]
    fn all_mutable_refs() {
        let mut mh = MentalHealth::new();

        mh.self_worth_mut().add_delta(-0.2);
        mh.hopelessness_mut().add_delta(0.3);
        mh.interpersonal_hopelessness_mut().add_delta(0.4);

        assert!((mh.self_worth().delta() - (-0.2)).abs() < f32::EPSILON);
        assert!((mh.hopelessness().delta() - 0.3).abs() < f32::EPSILON);
        assert!((mh.interpersonal_hopelessness().delta() - 0.4).abs() < f32::EPSILON);
    }

    #[test]
    fn add_interpersonal_hopelessness_delta_test() {
        let mut mh = MentalHealth::new();
        mh.add_interpersonal_hopelessness_delta(0.5);
        assert!((mh.interpersonal_hopelessness().delta() - 0.5).abs() < f32::EPSILON);
    }

    #[test]
    fn add_hopelessness_delta_test() {
        let mut mh = MentalHealth::new();
        mh.add_hopelessness_delta(0.4);
        assert!((mh.hopelessness().delta() - 0.4).abs() < f32::EPSILON);
    }

    #[test]
    fn base_shift_and_chronic_delta_helpers_work() {
        let mut mh = MentalHealth::new();

        let initial_self_worth = mh.self_worth().base();
        let initial_interpersonal = mh.interpersonal_hopelessness().base();
        let initial_ac = mh.acquired_capability().base();

        mh.shift_self_worth_base(-0.2);
        mh.shift_interpersonal_hopelessness_base(0.3);
        mh.shift_acquired_capability_base(0.4);

        assert!(
            (mh.self_worth().base() - (initial_self_worth - 0.2)).abs() < f32::EPSILON
        );
        assert!(
            (mh.interpersonal_hopelessness().base() - (initial_interpersonal + 0.3)).abs()
                < f32::EPSILON
        );
        assert!(
            (mh.acquired_capability().base() - (initial_ac + 0.4)).abs() < f32::EPSILON
        );

        mh.add_self_worth_chronic_delta(0.15);
        mh.add_interpersonal_hopelessness_chronic_delta(-0.25);

        assert!(
            (mh.self_worth().chronic_delta() - 0.15).abs() < f32::EPSILON
        );
        assert!(
            (mh.interpersonal_hopelessness().chronic_delta() - (-0.25)).abs() < f32::EPSILON
        );
    }
}