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
//! Entity builder for fluent construction.
//!
//! The EntityBuilder provides a fluent API for constructing entities
//! with proper validation. Species is required; other fields have defaults.

use crate::context::EcologicalContext;
use crate::enums::{LifeStage, PersonalityProfile, Species};
use crate::state::{
    Disposition, Hexaco, IndividualState, MentalHealth, Mood, Needs, PersonCharacteristics,
    SocialCognition,
};
// Note: Mood::from_personality is used below to derive baseline affect from HEXACO
use crate::types::{Duration, EntityId, Timestamp};

use super::Entity;

/// Error type for entity build failures.
///
/// This error is returned when `EntityBuilder::build()` fails validation.
///
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EntityBuildError {
    /// Species is required but was not set.
    MissingSpecies,

    /// Age is required but was not set.
    MissingAge,

    /// The entity ID is invalid (empty string).
    InvalidId(String),
}

impl std::fmt::Display for EntityBuildError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EntityBuildError::MissingSpecies => write!(f, "Species is required but was not set"),
            EntityBuildError::MissingAge => write!(f, "Age is required but was not set"),
            EntityBuildError::InvalidId(reason) => write!(f, "Invalid entity ID: {}", reason),
        }
    }
}

impl std::error::Error for EntityBuildError {}

/// Builder for constructing Entity instances.
///
/// The builder provides a fluent API for setting entity properties.
/// Species and age are required; all other properties have sensible defaults.
///
/// # Required Fields
///
/// - `species` - Must be set before calling `build()`
/// - `age` - Must be set before calling `build()`
///
/// # Optional Fields with Defaults
///
/// - `id` - Auto-generated UUID if not set
/// - `life_stage` - Derived from age and species if not set
/// - `personality` - Neutral HEXACO (Balanced profile) if not set
/// - `person_characteristics` - Neutral (0.5, 0.5, 0.5) if not set
///
#[derive(Debug, Clone, Default)]
pub struct EntityBuilder {
    id: Option<String>,
    species: Option<Species>,
    age: Option<Duration>,
    birth_date: Option<Timestamp>,
    life_stage: Option<LifeStage>,
    personality: Option<PersonalityProfile>,
    hexaco: Option<Hexaco>,
    person_characteristics: Option<PersonCharacteristics>,
    mood: Option<Mood>,
    needs: Option<Needs>,
    mental_health: Option<MentalHealth>,
    social_cognition: Option<SocialCognition>,
    disposition: Option<Disposition>,
    context: Option<EcologicalContext>,
}

impl EntityBuilder {
    /// Creates a new entity builder with no fields set.
    ///
    #[must_use]
    pub fn new() -> Self {
        EntityBuilder::default()
    }

    /// Sets the entity ID.
    ///
    /// If not set, a UUID will be generated.
    ///
    #[must_use]
    pub fn id(mut self, id: impl Into<String>) -> Self {
        self.id = Some(id.into());
        self
    }

    /// Sets the species (required).
    ///
    /// Species determines time scaling, lifespan, and which subsystems
    /// are active.
    ///
    #[must_use]
    pub fn species(mut self, species: Species) -> Self {
        self.species = Some(species);
        self
    }

    /// Sets the entity's age.
    ///
    /// Age affects life stage determination if life_stage is not
    /// explicitly set.
    ///
    #[must_use]
    pub fn age(mut self, age: Duration) -> Self {
        self.age = Some(age);
        self
    }

    /// Sets the entity's birth date.
    ///
    /// When set, age at any timestamp can be computed as:
    /// `query_timestamp - birth_date`
    ///
    /// Note: If both `age()` and `birth_date()` are set, the explicit `age()`
    /// is used as the anchor age. The birth_date is stored separately for
    /// timestamp-based age computation.
    ///
    #[must_use]
    pub fn birth_date(mut self, birth_date: Timestamp) -> Self {
        self.birth_date = Some(birth_date);
        self
    }

    /// Sets the life stage explicitly.
    ///
    /// If not set, the life stage is derived from age and species.
    ///
    #[must_use]
    pub fn life_stage(mut self, stage: LifeStage) -> Self {
        self.life_stage = Some(stage);
        self
    }

    /// Sets personality using a preset profile.
    ///
    /// This sets HEXACO values based on the profile. If both
    /// `personality()` and `hexaco()` are called, the later call wins.
    ///
    #[must_use]
    pub fn personality(mut self, profile: PersonalityProfile) -> Self {
        self.personality = Some(profile);
        self.hexaco = None; // Profile overrides raw HEXACO
        self
    }

    /// Sets HEXACO personality values directly.
    ///
    /// This allows fine-grained control over personality dimensions.
    /// If both `personality()` and `hexaco()` are called, the later call wins.
    ///
    #[must_use]
    pub fn hexaco(mut self, hexaco: Hexaco) -> Self {
        self.hexaco = Some(hexaco);
        self.personality = None; // Raw HEXACO overrides profile
        self
    }

    /// Sets person characteristics (PPCT model).
    ///
    /// Person characteristics include demand, resource, and force factors
    /// that influence proximal processes.
    ///
    #[must_use]
    pub fn person_characteristics(mut self, pc: PersonCharacteristics) -> Self {
        self.person_characteristics = Some(pc);
        self
    }

    /// Sets the initial mood state.
    ///
    /// Mood contains the PAD (Pleasure-Arousal-Dominance) dimensions.
    ///
    #[must_use]
    pub fn mood(mut self, mood: Mood) -> Self {
        self.mood = Some(mood);
        self
    }

    /// Sets the initial needs state.
    ///
    /// Needs includes fatigue, stress, purpose, and other physiological/psychological needs.
    ///
    #[must_use]
    pub fn needs(mut self, needs: Needs) -> Self {
        self.needs = Some(needs);
        self
    }

    /// Sets the initial mental health state.
    ///
    /// Mental health includes ITS factors (depression, hopelessness,
    /// acquired capability, etc.).
    ///
    #[must_use]
    pub fn mental_health(mut self, mental_health: MentalHealth) -> Self {
        self.mental_health = Some(mental_health);
        self
    }

    /// Sets the initial social cognition state.
    ///
    /// Social cognition includes loneliness, perceived caring/liability,
    /// self-hate, and other interpersonal beliefs.
    ///
    #[must_use]
    pub fn social_cognition(mut self, social_cognition: SocialCognition) -> Self {
        self.social_cognition = Some(social_cognition);
        self
    }

    /// Sets the initial disposition state.
    ///
    /// Disposition includes behavioral tendencies like empathy, aggression,
    /// grievance, and prosocial behavior.
    ///
    #[must_use]
    pub fn disposition(mut self, disposition: Disposition) -> Self {
        self.disposition = Some(disposition);
        self
    }

    /// Sets the initial ecological context.
    ///
    /// Allows pre-populating the entity's ecological context with
    /// microsystems, exosystem, macrosystem, and chronosystem values.
    ///
    #[must_use]
    pub fn with_context(mut self, context: EcologicalContext) -> Self {
        self.context = Some(context);
        self
    }

    /// Builds the entity.
    ///
    /// # Errors
    ///
    /// Returns `EntityBuildError::MissingSpecies` if species was not set.
    /// Returns `EntityBuildError::MissingAge` if age was not set.
    /// Returns `EntityBuildError::InvalidId` if the ID is empty.
    ///
    pub fn build(self) -> Result<Entity, EntityBuildError> {
        // Validate required fields
        let species = self.species.ok_or(EntityBuildError::MissingSpecies)?;
        let age = self.age.ok_or(EntityBuildError::MissingAge)?;

        // Generate or validate ID
        let id_string = self.id.unwrap_or_else(generate_uuid);
        let id = match EntityId::new(id_string) {
            Ok(id) => id,
            Err(err) => return Err(EntityBuildError::InvalidId(err.reason)),
        };

        // Get birth_date (optional)
        let birth_date = self.birth_date;

        // Determine life stage: explicit > derived from age
        let life_stage = self
            .life_stage
            .unwrap_or_else(|| LifeStage::from_age_years_for_species(&species, age.as_years_f64()));

        // Build HEXACO: explicit hexaco > profile > default
        let hexaco = if let Some(h) = self.hexaco {
            h
        } else if let Some(profile) = self.personality {
            Hexaco::from_profile(profile)
        } else {
            Hexaco::from_profile(PersonalityProfile::Balanced)
        };

        // Build person characteristics
        let person_characteristics = self.person_characteristics.unwrap_or_default();

        // Build individual state with required components
        let mut individual_state = IndividualState::new()
            .with_hexaco(hexaco.clone())
            .with_person_characteristics(person_characteristics);

        // Apply mood: explicit mood overrides, otherwise derive from personality
        if let Some(mood) = self.mood {
            individual_state = individual_state.with_mood(mood);
        } else {
            // Derive baseline affect from personality traits
            individual_state = individual_state.with_mood(Mood::from_personality(&hexaco));
        }
        if let Some(needs) = self.needs {
            individual_state = individual_state.with_needs(needs);
        }
        if let Some(mental_health) = self.mental_health {
            individual_state = individual_state.with_mental_health(mental_health);
        }
        if let Some(social_cognition) = self.social_cognition {
            individual_state = individual_state.with_social_cognition(social_cognition);
        }
        if let Some(disposition) = self.disposition {
            individual_state = individual_state.with_disposition(disposition);
        }

        // Build entity with or without custom context
        if let Some(context) = self.context {
            Ok(Entity::new_with_context(
                id,
                species,
                age,
                birth_date,
                life_stage,
                individual_state,
                context,
            ))
        } else {
            Ok(Entity::new(
                id,
                species,
                age,
                birth_date,
                life_stage,
                individual_state,
            ))
        }
    }
}

/// Generates a UUID-like unique identifier.
///
/// This uses a simple counter-based approach for determinism in tests.
/// In production, this could be replaced with actual UUID generation.
fn generate_uuid() -> String {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(1);
    let count = COUNTER.fetch_add(1, Ordering::Relaxed);
    format!("entity_{:016x}", count)
}

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

    #[test]
    fn builder_sets_species() {
        let entity = EntityBuilder::new()
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .build()
            .unwrap();

        assert_eq!(entity.species(), &Species::Human);
    }

    #[test]
    fn builder_sets_life_stage() {
        let entity = EntityBuilder::new()
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .life_stage(LifeStage::Adult)
            .build()
            .unwrap();

        assert_eq!(entity.life_stage(), LifeStage::Adult);
    }

    #[test]
    fn builder_sets_personality_profile() {
        let entity = EntityBuilder::new()
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .personality(PersonalityProfile::Leader)
            .build()
            .unwrap();

        // Leader has high extraversion
        assert!(entity.individual_state().hexaco().extraversion() > 0.5);
    }

    #[test]
    fn builder_sets_person_characteristics() {
        let pc = PersonCharacteristics::new().with_cognitive_ability_base(0.9);

        let entity = EntityBuilder::new()
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .person_characteristics(pc)
            .build()
            .unwrap();

        assert!(
            (entity
                .individual_state()
                .person_characteristics()
                .cognitive_ability()
                .base()
                - 0.9)
                .abs()
                < f32::EPSILON
        );
    }

    #[test]
    fn builder_produces_entity() {
        let result = EntityBuilder::new().species(Species::Human).age(crate::types::Duration::years(30)).build();

        assert!(result.is_ok());
        let entity = result.unwrap();
        assert_eq!(entity.species(), &Species::Human);
    }

    #[test]
    fn builder_requires_species() {
        let result = EntityBuilder::new().build();

        assert_eq!(result.unwrap_err(), EntityBuildError::MissingSpecies);
    }

    #[test]
    fn builder_defaults_life_stage() {
        // Age 30 -> YoungAdult for human (18-30 range)
        let entity = EntityBuilder::new()
            .species(Species::Human)
            .age(Duration::years(30))
            .build()
            .unwrap();

        assert_eq!(entity.life_stage(), LifeStage::YoungAdult);

        // Age 40 -> Adult for human (31-55 range)
        let adult = EntityBuilder::new()
            .species(Species::Human)
            .age(Duration::years(40))
            .build()
            .unwrap();

        assert_eq!(adult.life_stage(), LifeStage::Adult);

        // Age 8 -> Child for human
        let child = EntityBuilder::new()
            .species(Species::Human)
            .age(Duration::years(8))
            .build()
            .unwrap();

        assert_eq!(child.life_stage(), LifeStage::Child);
    }

    #[test]
    fn builder_sets_id() {
        let entity = EntityBuilder::new()
            .id("test_entity")
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .build()
            .unwrap();

        assert_eq!(entity.id().as_str(), "test_entity");
    }

    #[test]
    fn builder_generates_id_if_not_set() {
        let entity = EntityBuilder::new()
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .build()
            .unwrap();

        assert!(!entity.id().as_str().is_empty());
        assert!(entity.id().as_str().starts_with("entity_"));
    }

    #[test]
    fn builder_sets_age() {
        let entity = EntityBuilder::new()
            .species(Species::Human)
            .age(Duration::years(25))
            .build()
            .unwrap();

        assert_eq!(entity.age().as_years(), 25);
    }

    #[test]
    fn builder_requires_age() {
        let result = EntityBuilder::new().species(Species::Human).build();

        assert_eq!(result.unwrap_err(), EntityBuildError::MissingAge);
    }

    #[test]
    fn builder_sets_hexaco_directly() {
        let hexaco = Hexaco::new().with_openness(0.9).with_neuroticism(-0.8);

        let entity = EntityBuilder::new()
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .hexaco(hexaco)
            .build()
            .unwrap();

        assert!((entity.individual_state().hexaco().openness() - 0.9).abs() < f32::EPSILON);
        assert!((entity.individual_state().hexaco().neuroticism() - (-0.8)).abs() < f32::EPSILON);
    }

    #[test]
    fn hexaco_overrides_personality() {
        let hexaco = Hexaco::uniform(0.3);

        let entity = EntityBuilder::new()
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .personality(PersonalityProfile::Leader) // Would set high extraversion
            .hexaco(hexaco) // Overrides to 0.3
            .build()
            .unwrap();

        assert!((entity.individual_state().hexaco().extraversion() - 0.3).abs() < f32::EPSILON);
    }

    #[test]
    fn personality_overrides_hexaco() {
        let hexaco = Hexaco::uniform(0.3);

        let entity = EntityBuilder::new()
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .hexaco(hexaco)
            .personality(PersonalityProfile::Leader) // Overrides
            .build()
            .unwrap();

        // Leader has high extraversion (0.8 -> 0.6 in -1 to 1 range)
        assert!(entity.individual_state().hexaco().extraversion() > 0.5);
    }

    #[test]
    fn builder_clone() {
        let builder = EntityBuilder::new()
            .species(Species::Human)
            .age(Duration::years(30));

        let cloned = builder.clone();

        let entity1 = builder.build().unwrap();
        let entity2 = cloned.build().unwrap();

        assert_eq!(entity1.species(), entity2.species());
        assert_eq!(entity1.age(), entity2.age());
    }

    #[test]
    fn empty_id_returns_error() {
        let result = EntityBuilder::new().id("").species(Species::Human).age(crate::types::Duration::years(30)).build();

        assert_eq!(
            result.unwrap_err(),
            EntityBuildError::InvalidId("ID cannot be empty".to_string())
        );
    }

    #[test]
    fn builder_debug() {
        let builder = EntityBuilder::new().species(Species::Human);
        let debug = format!("{:?}", builder);
        assert!(debug.contains("EntityBuilder"));
    }

    #[test]
    fn error_display() {
        let err = EntityBuildError::MissingSpecies;
        let display = format!("{}", err);
        assert!(display.contains("Species"));

        let err_age = EntityBuildError::MissingAge;
        let display_age = format!("{}", err_age);
        assert!(display_age.contains("Age"));

        let err2 = EntityBuildError::InvalidId("test reason".to_string());
        let display2 = format!("{}", err2);
        assert!(display2.contains("test reason"));
    }

    #[test]
    fn error_debug() {
        let err = EntityBuildError::MissingSpecies;
        let debug = format!("{:?}", err);
        assert!(debug.contains("MissingSpecies"));

        let err_age = EntityBuildError::MissingAge;
        let debug_age = format!("{:?}", err_age);
        assert!(debug_age.contains("MissingAge"));
    }

    #[test]
    fn error_is_std_error() {
        use std::error::Error;

        let err: &dyn Error = &EntityBuildError::MissingSpecies;
        // Verify it's a valid std::error::Error
        assert!(err.source().is_none());

        let err_age: &dyn Error = &EntityBuildError::MissingAge;
        assert!(err_age.source().is_none());

        let err2: &dyn Error = &EntityBuildError::InvalidId("test".to_string());
        assert!(err2.source().is_none());
    }

    #[test]
    fn builder_new() {
        let builder = EntityBuilder::new();
        let debug = format!("{:?}", builder);
        assert!(debug.contains("EntityBuilder"));
    }

    #[test]
    fn dog_age_derives_life_stage() {
        // 2-year-old dog should be YoungAdult
        let dog = EntityBuilder::new()
            .species(Species::Dog)
            .age(Duration::years(2))
            .build()
            .unwrap();

        assert_eq!(dog.life_stage(), LifeStage::YoungAdult);
    }

    #[test]
    fn explicit_life_stage_overrides_age_derived() {
        let entity = EntityBuilder::new()
            .species(Species::Human)
            .age(Duration::years(30)) // Would be Adult
            .life_stage(LifeStage::Elder) // Override to Elder
            .build()
            .unwrap();

        assert_eq!(entity.life_stage(), LifeStage::Elder);
    }

    #[test]
    fn default_personality_is_balanced() {
        let entity = EntityBuilder::new()
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .build()
            .unwrap();

        // Balanced profile has 0.5 for all, which maps to 0.0 in -1 to 1 range
        assert!((entity.individual_state().hexaco().openness() - 0.0).abs() < 0.01);
    }

    #[test]
    fn default_person_characteristics_are_neutral() {
        let entity = EntityBuilder::new()
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .build()
            .unwrap();

        // Default PC has neutral values (around 0.5)
        let pc = entity.individual_state().person_characteristics();
        assert!(pc.resource() >= 0.3 && pc.resource() <= 0.7);
        assert!(pc.force() >= 0.3 && pc.force() <= 0.7);
    }

    #[test]
    fn builder_with_context() {
        use crate::context::{Microsystem, WorkContext};
        use crate::types::MicrosystemId;

        let mut context = EcologicalContext::default();
        let work_id = MicrosystemId::new("work_primary").unwrap();
        context.add_microsystem(work_id, Microsystem::new_work(WorkContext::default()));

        let entity = EntityBuilder::new()
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .with_context(context)
            .build()
            .unwrap();

        assert_eq!(entity.context().microsystem_count(), 1);
    }

    #[test]
    fn builder_without_context_uses_default() {
        let entity = EntityBuilder::new()
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .build()
            .unwrap();

        // Default context has no microsystems
        assert_eq!(entity.context().microsystem_count(), 0);
    }

    #[test]
    fn builder_sets_birth_date() {
        let birth = Timestamp::from_ymd_hms(1990, 6, 15, 0, 0, 0);
        let entity = EntityBuilder::new()
            .id("person_001")
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .birth_date(birth)
            .build()
            .unwrap();

        assert_eq!(entity.birth_date(), Some(birth));
    }

    #[test]
    fn builder_without_birth_date_returns_none() {
        let entity = EntityBuilder::new()
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .build()
            .unwrap();

        assert!(entity.birth_date().is_none());
    }

    #[test]
    fn builder_birth_date_can_be_used_with_age() {
        let birth = Timestamp::from_ymd_hms(1990, 6, 15, 0, 0, 0);
        let entity = EntityBuilder::new()
            .species(Species::Human)
            .birth_date(birth)
            .age(Duration::years(30))
            .build()
            .unwrap();

        // Both should be set independently
        assert_eq!(entity.birth_date(), Some(birth));
        assert_eq!(entity.age().as_years(), 30);
    }

    #[test]
    fn builder_sets_mood() {
        use crate::state::Mood;

        let mood = Mood::new().with_valence_base(0.6).with_arousal_base(-0.3);

        let entity = EntityBuilder::new()
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .mood(mood.clone())
            .build()
            .unwrap();

        assert_eq!(entity.individual_state().mood(), &mood);
    }

    #[test]
    fn builder_sets_needs() {
        use crate::state::Needs;

        let needs = Needs::new().with_fatigue_base(0.4).with_stress_base(0.2);

        let entity = EntityBuilder::new()
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .needs(needs.clone())
            .build()
            .unwrap();

        assert_eq!(entity.individual_state().needs(), &needs);
    }

    #[test]
    fn builder_sets_mental_health() {
        use crate::state::MentalHealth;

        let mh = MentalHealth::new()
            .with_depression_base(0.15)
            .with_hopelessness_base(0.1);

        let entity = EntityBuilder::new()
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .mental_health(mh.clone())
            .build()
            .unwrap();

        assert_eq!(entity.individual_state().mental_health(), &mh);
    }

    #[test]
    fn builder_sets_social_cognition() {
        use crate::state::SocialCognition;

        let sc = SocialCognition::new()
            .with_loneliness_base(0.25)
            .with_perceived_reciprocal_caring_base(0.7);

        let entity = EntityBuilder::new()
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .social_cognition(sc.clone())
            .build()
            .unwrap();

        assert_eq!(entity.individual_state().social_cognition(), &sc);
    }

    #[test]
    fn builder_sets_disposition() {
        use crate::state::Disposition;

        let disp = Disposition::new()
            .with_empathy_base(0.8)
            .with_impulse_control_base(0.7);

        let entity = EntityBuilder::new()
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .disposition(disp.clone())
            .build()
            .unwrap();

        assert_eq!(entity.individual_state().disposition(), &disp);
    }

    #[test]
    fn builder_without_optional_state_uses_defaults() {
        use crate::state::{Disposition, MentalHealth, Needs, SocialCognition};

        let entity = EntityBuilder::new()
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .build()
            .unwrap();

        // Mood is derived from personality (not default) - see builder_derives_mood_from_personality test
        // Other components should be default
        assert_eq!(entity.individual_state().needs(), &Needs::default());
        assert_eq!(
            entity.individual_state().mental_health(),
            &MentalHealth::default()
        );
        assert_eq!(
            entity.individual_state().social_cognition(),
            &SocialCognition::default()
        );
        assert_eq!(
            entity.individual_state().disposition(),
            &Disposition::default()
        );
    }

    #[test]
    fn builder_derives_mood_from_personality() {
        // Extraverted personality should produce positive baseline valence
        let entity = EntityBuilder::new()
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .personality(PersonalityProfile::Leader) // Leaders are extraverted
            .build()
            .unwrap();

        // Leader profile has high extraversion, so baseline valence should be positive
        let valence = entity.individual_state().mood().valence_base();
        assert!(valence > 0.0);
    }

    #[test]
    fn explicit_mood_overrides_personality_derived() {
        use crate::state::Mood;

        // Set explicit mood that differs from what personality would derive
        let explicit_mood = Mood::new()
            .with_valence_base(-0.5) // Negative valence despite personality
            .with_arousal_base(0.3);

        let entity = EntityBuilder::new()
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .personality(PersonalityProfile::Leader) // Would derive positive valence
            .mood(explicit_mood.clone()) // Override with explicit negative
            .build()
            .unwrap();

        // Explicit mood should override personality-derived mood
        assert_eq!(entity.individual_state().mood(), &explicit_mood);
        assert!((entity.individual_state().mood().valence_base() - (-0.5)).abs() < f32::EPSILON);
    }

    #[test]
    fn builder_sets_all_state_components_together() {
        use crate::state::{Disposition, MentalHealth, Mood, Needs, SocialCognition};

        let mood = Mood::new().with_valence_base(0.5);
        let needs = Needs::new().with_purpose_base(0.8);
        let mh = MentalHealth::new().with_depression_base(0.1);
        let sc = SocialCognition::new().with_loneliness_base(0.2);
        let disp = Disposition::new().with_empathy_base(0.9);

        let entity = EntityBuilder::new()
            .species(Species::Human)
            .age(crate::types::Duration::years(30))
            .mood(mood.clone())
            .needs(needs.clone())
            .mental_health(mh.clone())
            .social_cognition(sc.clone())
            .disposition(disp.clone())
            .build()
            .unwrap();

        assert_eq!(entity.individual_state().mood(), &mood);
        assert_eq!(entity.individual_state().needs(), &needs);
        assert_eq!(entity.individual_state().mental_health(), &mh);
        assert_eq!(entity.individual_state().social_cognition(), &sc);
        assert_eq!(entity.individual_state().disposition(), &disp);
    }
}