hojicha-core 0.2.2

Core Elm Architecture abstractions for terminal UIs in Rust
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
//! Unified test harness combining event and time control
//!
//! This module provides a single, configurable test harness that unifies
//! the functionality of EventTestHarness and TimeControlledHarness.
//!
//! ## Overview
//!
//! The `UnifiedTestHarness` provides comprehensive testing capabilities for Hojicha
//! applications, including:
//!
//! - Deterministic event processing
//! - Time control for testing timers and delays
//! - Message history tracking
//! - Command execution tracking
//! - Scenario-based testing with `ScenarioBuilder`
//!
//! ## Examples
//!
//! ### Basic Event Testing
//!
//! ```rust
//! use hojicha_core::testing::UnifiedTestHarness;
//! use hojicha_core::{Model, Cmd, Event};
//!
//! # struct MyApp { counter: i32 }
//! # impl Model for MyApp {
//! #     type Message = i32;
//! #     fn init(&mut self) -> Cmd<i32> { Cmd::noop() }
//! #     fn update(&mut self, event: Event<i32>) -> Cmd<i32> {
//! #         if let Event::User(n) = event {
//! #             self.counter += n;
//! #         }
//! #         Cmd::noop()
//! #     }
//! #     fn view(&self) -> String { format!("Counter: {}", self.counter) }
//! # }
//! let mut harness = UnifiedTestHarness::new(MyApp { counter: 0 });
//!
//! // Send a message
//! harness.send_message(5);
//! harness.process_all();
//!
//! // Check the state
//! assert_eq!(harness.model().counter, 5);
//! ```
//!
//! ### Time-Controlled Testing
//!
//! ```rust,ignore
//! use hojicha_core::testing::{UnifiedTestHarness, HarnessConfig};
//! use hojicha_core::{Model, Cmd, Event, commands};
//! use std::time::Duration;
//!
//! # struct MyApp { timer_fired: bool }
//! # #[derive(Clone, Debug)]
//! # enum Msg { TimerFired }
//! # impl Model for MyApp {
//! #     type Message = Msg;
//! #     fn init(&mut self) -> Cmd<Msg> {
//! #         commands::tick(Duration::from_secs(1), || Msg::TimerFired)
//! #     }
//! #     fn update(&mut self, event: Event<Msg>) -> Cmd<Msg> {
//! #         if let Event::User(Msg::TimerFired) = event {
//! #             self.timer_fired = true;
//! #         }
//! #         Cmd::noop()
//! #     }
//! #     fn view(&self) -> String { format!("Counter: {}", self.counter) }
//! # }
//! let config = HarnessConfig {
//!     time_controlled: true,
//!     start_paused: true,
//!     ..Default::default()
//! };
//!
//! let mut harness = UnifiedTestHarness::with_config(
//!     MyApp { timer_fired: false },
//!     config
//! );
//!
//!
//! // Timer hasn't fired yet
//! assert!(!harness.model().timer_fired);
//!
//! // Advance time to trigger the timer
//! harness.advance_time(Duration::from_secs(1));
//! harness.process_all();
//!
//! // Timer should have fired
//! assert!(harness.model().timer_fired);
//! ```
//!
//! ### Scenario-Based Testing
//!
//! ```rust
//! use hojicha_core::testing::ScenarioBuilder;
//! use hojicha_core::event::Key;
//!
//! # struct MyApp { selected: usize }
//! # #[derive(Clone, Debug)]
//! # enum Msg { Up, Down }
//! # impl hojicha_core::Model for MyApp {
//! #     type Message = Msg;
//! #     fn init(&mut self) -> hojicha_core::Cmd<Msg> { hojicha_core::Cmd::noop() }
//! #     fn update(&mut self, event: hojicha_core::Event<Msg>) -> hojicha_core::Cmd<Msg> {
//! #         match event {
//! #             hojicha_core::Event::Key(k) if k.key == Key::Up => {
//! #                 self.selected = self.selected.saturating_sub(1);
//! #             }
//! #             hojicha_core::Event::Key(k) if k.key == Key::Down => {
//! #                 self.selected = self.selected.saturating_add(1);
//! #             }
//! #             _ => {}
//! #         }
//! #         hojicha_core::Cmd::noop()
//! #     }
//! #     fn view(&self) -> String { String::new() }
//! # }
//! use hojicha_core::event::KeyModifiers;
//! ScenarioBuilder::new(MyApp { selected: 0 })
//!     .send_event(hojicha_core::Event::Key(hojicha_core::event::KeyEvent::new(Key::Down, KeyModifiers::empty())))
//!     .send_event(hojicha_core::Event::Key(hojicha_core::event::KeyEvent::new(Key::Down, KeyModifiers::empty())))
//!     .send_event(hojicha_core::Event::Key(hojicha_core::event::KeyEvent::new(Key::Up, KeyModifiers::empty())))
//!     .process_all()
//!     .assert_model(|model| model.selected == 1, "selected should be 1")
//!     .run();
//! ```

use crate::{
    core::{Cmd, Model},
    event::Event,
    testing::time_control::{PausedTimeGuard, TimeController},
};
use std::collections::VecDeque;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};

/// Configuration for the unified test harness
#[derive(Debug, Clone)]
pub struct HarnessConfig {
    /// Whether to use manual time control
    pub time_controlled: bool,
    /// Whether to start with paused time
    pub start_paused: bool,
    /// Maximum number of events to process automatically
    pub max_auto_events: Option<usize>,
    /// Whether to enable debug logging
    pub debug_logging: bool,
    /// Timeout for async operations (when time controlled)
    pub async_timeout: Duration,
}

impl Default for HarnessConfig {
    fn default() -> Self {
        Self {
            time_controlled: false,
            start_paused: true,
            max_auto_events: Some(1000),
            debug_logging: false,
            async_timeout: Duration::from_secs(30),
        }
    }
}

/// A unified test harness that combines event processing and time control
///
/// This allows testing both synchronous event processing and time-dependent
/// async operations in a deterministic way.
pub struct UnifiedTestHarness<M: Model> {
    model: M,
    /// Queue of events to process
    event_queue: VecDeque<Event<M::Message>>,
    /// Events that have been processed
    processed_events: Vec<Event<M::Message>>,
    /// Commands that have been executed
    executed_commands: Vec<String>, // String description of commands
    /// Number of update calls
    update_count: AtomicUsize,
    /// Whether the model has quit
    has_quit: bool,
    /// Time controller (if time controlled)
    time_controller: Option<TimeController>,
    /// RAII guard for paused time
    _time_guard: Option<PausedTimeGuard>,
    /// Configuration
    config: HarnessConfig,
    /// Start time for measurements
    start_time: Instant,
    /// Messages generated during execution
    generated_messages: Vec<M::Message>,
}

impl<M: Model + 'static> UnifiedTestHarness<M>
where
    M::Message: Clone + std::fmt::Debug,
{
    /// Create a new unified test harness with default config
    pub fn new(model: M) -> Self {
        Self::with_config(model, HarnessConfig::default())
    }

    /// Create a new unified test harness with custom config
    pub fn with_config(mut model: M, config: HarnessConfig) -> Self {
        let time_controller = if config.time_controlled {
            Some(if config.start_paused {
                TimeController::new_paused()
            } else {
                TimeController::new_real()
            })
        } else {
            None
        };

        let time_guard = if config.time_controlled && config.start_paused {
            Some(PausedTimeGuard::new())
        } else {
            None
        };

        // Call init and process any initial commands
        let init_cmd = model.init();
        let mut harness = Self {
            model,
            event_queue: VecDeque::new(),
            processed_events: Vec::new(),
            executed_commands: Vec::new(),
            update_count: AtomicUsize::new(0),
            has_quit: false,
            time_controller,
            _time_guard: time_guard,
            config,
            start_time: Instant::now(),
            generated_messages: Vec::new(),
        };

        if !init_cmd.is_noop() {
            harness.execute_command(init_cmd);
        }

        harness
    }

    /// Create a new harness with paused time
    pub fn new_with_paused_time(model: M) -> Self {
        let config = HarnessConfig {
            time_controlled: true,
            start_paused: true,
            ..Default::default()
        };
        Self::with_config(model, config)
    }

    /// Create a new harness for testing async operations
    pub fn new_for_async(model: M) -> Self {
        let config = HarnessConfig {
            time_controlled: true,
            start_paused: false,
            ..Default::default()
        };
        Self::with_config(model, config)
    }

    /// Get a reference to the model
    pub fn model(&self) -> &M {
        &self.model
    }

    /// Get a mutable reference to the model
    pub fn model_mut(&mut self) -> &mut M {
        &mut self.model
    }

    /// Queue an event for processing
    pub fn send_event(&mut self, event: Event<M::Message>) {
        if self.config.debug_logging {
            eprintln!("[HARNESS] Queuing event: {:?}", event);
        }
        self.event_queue.push_back(event);
    }

    /// Queue a user message
    pub fn send_message(&mut self, message: M::Message) {
        self.send_event(Event::User(message));
    }

    /// Queue multiple events
    pub fn send_events(&mut self, events: impl IntoIterator<Item = Event<M::Message>>) {
        for event in events {
            self.send_event(event);
        }
    }

    /// Queue multiple messages
    pub fn send_messages(&mut self, messages: impl IntoIterator<Item = M::Message>) {
        for message in messages {
            self.send_message(message);
        }
    }

    /// Process a single event from the queue
    pub fn process_one(&mut self) -> Option<Event<M::Message>> {
        if self.has_quit {
            return None;
        }

        if let Some(event) = self.event_queue.pop_front() {
            self.update_count.fetch_add(1, Ordering::SeqCst);
            let event_clone = event.clone();

            if self.config.debug_logging {
                eprintln!("[HARNESS] Processing event: {:?}", event);
                eprintln!(
                    "[HARNESS] Model state before: {:?}",
                    std::any::type_name::<M>()
                );
            }

            // Process the event
            let cmd = self.model.update(event);
            self.execute_command(cmd);

            self.processed_events.push(event_clone.clone());

            if self.config.debug_logging {
                eprintln!(
                    "[HARNESS] Event processed. Queue length: {}",
                    self.event_queue.len()
                );
            }

            Some(event_clone)
        } else {
            None
        }
    }

    /// Process all queued events
    pub fn process_all(&mut self) -> Vec<Event<M::Message>> {
        let mut processed = Vec::new();
        let max_events = self.config.max_auto_events.unwrap_or(usize::MAX);
        let mut count = 0;

        while let Some(event) = self.process_one() {
            processed.push(event);
            count += 1;

            if count >= max_events {
                if self.config.debug_logging {
                    eprintln!(
                        "[HARNESS] Hit max auto events limit ({}), stopping",
                        max_events
                    );
                }
                break;
            }
        }
        processed
    }

    /// Process events until a condition is met
    pub fn process_until<F>(&mut self, mut condition: F) -> bool
    where
        F: FnMut(&M) -> bool,
    {
        let max_events = self.config.max_auto_events.unwrap_or(usize::MAX);
        let mut count = 0;

        while !self.has_quit && !self.event_queue.is_empty() && count < max_events {
            if condition(&self.model) {
                return true;
            }

            if self.process_one().is_none() {
                break;
            }
            count += 1;
        }

        condition(&self.model)
    }

    /// Process events for a specific duration (requires time control)
    pub fn process_for_duration(&mut self, duration: Duration) -> Vec<Event<M::Message>> {
        if self.time_controller.is_none() {
            panic!("process_for_duration requires time_controlled=true");
        }

        let start_time = self.now();
        let mut processed = Vec::new();

        loop {
            let current_time = self.now();
            if current_time - start_time >= duration {
                break;
            }

            if let Some(event) = self.process_one() {
                processed.push(event);
            } else {
                // No more events, advance time manually
                let remaining = duration - (current_time - start_time);
                if remaining > Duration::ZERO {
                    self.advance_time(remaining.min(Duration::from_millis(100)));
                } else {
                    break;
                }
            }
        }

        processed
    }

    /// Execute a command and handle any resulting messages
    fn execute_command(&mut self, cmd: Cmd<M::Message>) {
        if cmd.is_quit() {
            self.has_quit = true;
            self.executed_commands.push("quit".to_string());
            return;
        }

        if cmd.is_noop() {
            return;
        }

        // Check command type before consuming it
        let is_batch = cmd.is_batch();
        let is_sequence = cmd.is_sequence();

        // For testing purposes, we try to execute the command
        // In a real implementation, this would be handled by the runtime
        match cmd.test_execute() {
            Ok(Some(message)) => {
                if self.config.debug_logging {
                    eprintln!("[HARNESS] Command generated message: {:?}", message);
                }
                self.generated_messages.push(message.clone());
                self.send_message(message);
                self.executed_commands.push("sync_command".to_string());
            }
            Ok(None) => {
                // Command executed but produced no message
                self.executed_commands
                    .push("sync_command_no_message".to_string());
            }
            Err(_) => {
                // Command failed or is async
                self.executed_commands
                    .push("async_or_failed_command".to_string());
            }
        }

        // Handle special command types
        if is_batch {
            self.executed_commands.push("batch_command".to_string());
        } else if is_sequence {
            self.executed_commands.push("sequence_command".to_string());
        }
    }

    /// Get the number of events processed
    pub fn processed_count(&self) -> usize {
        self.update_count.load(Ordering::SeqCst)
    }

    /// Get the number of events still queued
    pub fn queued_count(&self) -> usize {
        self.event_queue.len()
    }

    /// Check if the model has quit
    pub fn has_quit(&self) -> bool {
        self.has_quit
    }

    /// Get all processed events
    pub fn processed_events(&self) -> &[Event<M::Message>] {
        &self.processed_events
    }

    /// Get all executed commands (as descriptions)
    pub fn executed_commands(&self) -> &[String] {
        &self.executed_commands
    }

    /// Get messages generated by commands
    pub fn generated_messages(&self) -> &[M::Message] {
        &self.generated_messages
    }

    /// Clear the event queue
    pub fn clear_queue(&mut self) {
        self.event_queue.clear();
    }

    /// Clear processed events history
    pub fn clear_history(&mut self) {
        self.processed_events.clear();
        self.executed_commands.clear();
        self.generated_messages.clear();
    }

    /// Get elapsed time since harness creation
    pub fn elapsed(&self) -> Duration {
        if let Some(controller) = &self.time_controller {
            controller.now()
        } else {
            self.start_time.elapsed()
        }
    }

    // Time control methods (require time_controlled=true)

    /// Pause time (requires time control)
    pub fn pause_time(&self) {
        if let Some(controller) = &self.time_controller {
            controller.pause();
        } else {
            panic!("pause_time requires time_controlled=true");
        }
    }

    /// Resume time (requires time control)
    pub fn resume_time(&self) {
        if let Some(controller) = &self.time_controller {
            controller.resume();
        } else {
            panic!("resume_time requires time_controlled=true");
        }
    }

    /// Advance time by the given duration (requires paused time)
    pub fn advance_time(&self, duration: Duration) {
        if let Some(controller) = &self.time_controller {
            controller
                .advance(duration)
                .expect("Time must be paused to advance manually");
        } else {
            panic!("advance_time requires time_controlled=true");
        }
    }

    /// Set time scale (requires time control)
    pub fn set_time_scale(&self, scale: f64) {
        if let Some(controller) = &self.time_controller {
            controller.set_scale(scale);
        } else {
            panic!("set_time_scale requires time_controlled=true");
        }
    }

    /// Get current virtual time (requires time control)
    pub fn now(&self) -> Duration {
        if let Some(controller) = &self.time_controller {
            controller.now()
        } else {
            panic!("now requires time_controlled=true");
        }
    }

    // Assertion helpers

    /// Assert that the model is in a specific state
    pub fn assert_model<F>(&self, predicate: F, message: &str)
    where
        F: FnOnce(&M) -> bool,
    {
        assert!(predicate(&self.model), "{}", message);
    }

    /// Assert that a specific number of events were processed
    pub fn assert_processed_count(&self, expected: usize) {
        assert_eq!(
            self.processed_count(),
            expected,
            "Expected {} processed events, got {}",
            expected,
            self.processed_count()
        );
    }

    /// Assert that a specific message was generated
    pub fn assert_message_generated(&self, message: &M::Message)
    where
        M::Message: PartialEq,
    {
        assert!(
            self.generated_messages.contains(message),
            "Expected message {:?} was not generated",
            message
        );
    }

    /// Assert that no events are queued
    pub fn assert_queue_empty(&self) {
        assert_eq!(
            self.queued_count(),
            0,
            "Expected empty queue, but {} events are queued",
            self.queued_count()
        );
    }

    /// Create a scenario builder for declarative testing
    pub fn scenario(model: M) -> ScenarioBuilder<M> {
        ScenarioBuilder::new(model)
    }
}

/// Builder for creating declarative test scenarios
pub struct ScenarioBuilder<M: Model> {
    model: M,
    config: HarnessConfig,
    events: Vec<ScenarioStep<M::Message>>,
}

/// Type alias for condition predicates used in testing
pub type ConditionPredicate = Box<dyn Fn(&dyn std::any::Any) -> bool>;

/// A step in a test scenario
pub enum ScenarioStep<Msg> {
    /// Send an event
    SendEvent(Event<Msg>),
    /// Send a message
    SendMessage(Msg),
    /// Advance time
    AdvanceTime(Duration),
    /// Wait for a condition
    WaitFor(ConditionPredicate),
    /// Assert a condition
    Assert(ConditionPredicate, String),
    /// Process all queued events
    ProcessAll,
    /// Process events for a duration
    ProcessFor(Duration),
}

impl<Msg> std::fmt::Debug for ScenarioStep<Msg> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ScenarioStep::SendEvent(_) => write!(f, "SendEvent"),
            ScenarioStep::SendMessage(_) => write!(f, "SendMessage"),
            ScenarioStep::AdvanceTime(d) => write!(f, "AdvanceTime({:?})", d),
            ScenarioStep::WaitFor(_) => write!(f, "WaitFor(<closure>)"),
            ScenarioStep::Assert(_, msg) => write!(f, "Assert(<closure>, {})", msg),
            ScenarioStep::ProcessAll => write!(f, "ProcessAll"),
            ScenarioStep::ProcessFor(d) => write!(f, "ProcessFor({:?})", d),
        }
    }
}

impl<M: Model + 'static> ScenarioBuilder<M>
where
    M::Message: Clone + std::fmt::Debug,
{
    /// Create a new scenario builder
    pub fn new(model: M) -> Self {
        Self {
            model,
            config: HarnessConfig::default(),
            events: Vec::new(),
        }
    }

    /// Configure the harness
    pub fn with_config(mut self, config: HarnessConfig) -> Self {
        self.config = config;
        self
    }

    /// Enable time control
    pub fn with_time_control(mut self) -> Self {
        self.config.time_controlled = true;
        self
    }

    /// Send an event
    pub fn send_event(mut self, event: Event<M::Message>) -> Self {
        self.events.push(ScenarioStep::SendEvent(event));
        self
    }

    /// Send a message
    pub fn send_message(mut self, message: M::Message) -> Self {
        self.events.push(ScenarioStep::SendMessage(message));
        self
    }

    /// Advance time
    pub fn advance_time(mut self, duration: Duration) -> Self {
        self.events.push(ScenarioStep::AdvanceTime(duration));
        self
    }

    /// Process all queued events
    pub fn process_all(mut self) -> Self {
        self.events.push(ScenarioStep::ProcessAll);
        self
    }

    /// Process events for a duration
    pub fn process_for(mut self, duration: Duration) -> Self {
        self.events.push(ScenarioStep::ProcessFor(duration));
        self
    }

    /// Assert a condition about the model
    pub fn assert_model<F>(mut self, predicate: F, message: impl Into<String>) -> Self
    where
        F: Fn(&M) -> bool + 'static,
    {
        let message = message.into();
        self.events.push(ScenarioStep::Assert(
            Box::new(move |model_any| {
                let model = model_any.downcast_ref::<M>().expect("Type mismatch");
                predicate(model)
            }),
            message,
        ));
        self
    }

    /// Execute the scenario
    pub fn run(self) -> UnifiedTestHarness<M> {
        let mut harness = UnifiedTestHarness::with_config(self.model, self.config);

        for step in self.events {
            match step {
                ScenarioStep::SendEvent(event) => harness.send_event(event),
                ScenarioStep::SendMessage(message) => harness.send_message(message),
                ScenarioStep::AdvanceTime(duration) => harness.advance_time(duration),
                ScenarioStep::ProcessAll => {
                    harness.process_all();
                }
                ScenarioStep::ProcessFor(duration) => {
                    harness.process_for_duration(duration);
                }
                ScenarioStep::Assert(predicate, message) => {
                    let model_any: &dyn std::any::Any = &harness.model;
                    assert!(predicate(model_any), "{}", message);
                }
                ScenarioStep::WaitFor(_predicate) => {
                    // TODO: Implement wait_for
                    unimplemented!("WaitFor not yet implemented");
                }
            }
        }

        harness
    }
}

/// Convenience macro for creating test scenarios
#[macro_export]
macro_rules! test_scenario {
    ($model:expr, $($step:expr),* $(,)?) => {{
        let mut builder = $crate::testing::unified_harness::ScenarioBuilder::new($model);
        $(
            builder = $step(builder);
        )*
        builder.run()
    }};
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{Cmd, Model};
    use crate::event::Event;

    #[derive(Debug, Clone, Default)]
    struct TestModel {
        counter: i32,
        messages: Vec<String>,
    }

    #[derive(Debug, Clone, PartialEq)]
    enum TestMessage {
        Increment,
        #[allow(dead_code)]
        Decrement,
        SetValue(i32),
        #[allow(dead_code)]
        AddMessage(String),
        Reset,
    }

    impl Model for TestModel {
        type Message = TestMessage;

        fn init(&mut self) -> Cmd<Self::Message> {
            Cmd::noop()
        }

        fn update(&mut self, event: Event<Self::Message>) -> Cmd<Self::Message> {
            match event {
                Event::User(TestMessage::Increment) => {
                    self.counter += 1;
                    Cmd::noop()
                }
                Event::User(TestMessage::Decrement) => {
                    self.counter -= 1;
                    Cmd::noop()
                }
                Event::User(TestMessage::SetValue(value)) => {
                    self.counter = value;
                    Cmd::noop()
                }
                Event::User(TestMessage::AddMessage(msg)) => {
                    self.messages.push(msg);
                    Cmd::noop()
                }
                Event::User(TestMessage::Reset) => {
                    self.counter = 0;
                    self.messages.clear();
                    Cmd::noop()
                }
                _ => Cmd::noop(),
            }
        }

        fn view(&self) -> String {
            format!("Counter: {}", self.counter)
        }
    }

    #[test]
    fn test_unified_harness_basic() {
        let model = TestModel::default();
        let mut harness = UnifiedTestHarness::new(model);

        harness.send_message(TestMessage::Increment);
        harness.send_message(TestMessage::Increment);
        harness.process_all();

        assert_eq!(harness.model().counter, 2);
        assert_eq!(harness.processed_count(), 2);
    }

    #[test]
    fn test_unified_harness_with_time_control() {
        let model = TestModel::default();
        let mut harness = UnifiedTestHarness::new_with_paused_time(model);

        // Time should start at zero
        assert_eq!(harness.now(), Duration::ZERO);

        // Advance time manually
        harness.advance_time(Duration::from_secs(5));
        assert_eq!(harness.now(), Duration::from_secs(5));

        // Send and process messages
        harness.send_message(TestMessage::SetValue(42));
        harness.process_all();

        assert_eq!(harness.model().counter, 42);
    }

    #[test]
    fn test_scenario_builder() {
        let model = TestModel::default();

        let harness = ScenarioBuilder::new(model)
            .with_time_control()
            .send_message(TestMessage::Increment)
            .send_message(TestMessage::Increment)
            .process_all()
            .assert_model(|m| m.counter == 2, "Counter should be 2")
            .send_message(TestMessage::Reset)
            .process_all()
            .assert_model(|m| m.counter == 0, "Counter should be reset")
            .run();

        assert_eq!(harness.model().counter, 0);
        assert_eq!(harness.processed_count(), 3);
    }

    #[test]
    fn test_harness_assertions() {
        let model = TestModel::default();
        let mut harness = UnifiedTestHarness::new(model);

        harness.send_message(TestMessage::Increment);
        harness.process_all();

        harness.assert_model(|m| m.counter == 1, "Counter should be 1");
        harness.assert_processed_count(1);
        harness.assert_queue_empty();
    }

    #[test]
    fn test_process_until() {
        let model = TestModel::default();
        let mut harness = UnifiedTestHarness::new(model);

        // Queue multiple events
        for i in 1..=5 {
            harness.send_message(TestMessage::SetValue(i));
        }

        // Process until counter reaches 3
        let result = harness.process_until(|m| m.counter == 3);
        assert!(result);
        assert_eq!(harness.model().counter, 3);

        // Should have 2 events left in queue
        assert_eq!(harness.queued_count(), 2);
    }

    #[test]
    fn test_harness_debug_logging() {
        let model = TestModel::default();
        let config = HarnessConfig {
            debug_logging: true,
            ..Default::default()
        };
        let mut harness = UnifiedTestHarness::with_config(model, config);

        harness.send_message(TestMessage::Increment);
        harness.process_all();

        // Just test that it doesn't panic with debug logging enabled
        assert_eq!(harness.model().counter, 1);
    }
}