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
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
//! Command utilities for handling side effects
//!
//! This module provides functions for creating commands that perform side effects
//! in your Hojicha application. Commands are the Elm Architecture's way of handling
//! operations that interact with the outside world.
//!
//! ## Core Command Types
//!
//! - **Synchronous**: Simple functions that return messages
//! - **Asynchronous**: Futures that eventually produce messages
//! - **Timed**: Commands that execute after delays or at intervals
//! - **Composite**: Batch and sequence commands for complex flows
//!
//! ## Common Patterns
//!
//! ### No-op Command
//! ```
//! # use hojicha_core::commands::noop;
//! # use hojicha_core::{Model, Cmd, Event};
//! # struct MyModel;
//! # impl Model for MyModel {
//! #     type Message = ();
//! #     fn update(&mut self, event: Event<Self::Message>) -> Cmd<Self::Message> {
//!         // Handle event but don't trigger side effects
//!         noop()
//! #     }
//! #     fn view(&self) -> String { String::new() }
//! # }
//! ```
//!
//! ### Concurrent Commands
//! ```
//! # use hojicha_core::commands::{batch, tick};
//! # use hojicha_core::Cmd;
//! # use std::time::Duration;
//! # enum Msg { Tick1, Tick2 }
//! let cmd: Cmd<Msg> = batch(vec![
//!     tick(Duration::from_secs(1), || Msg::Tick1),
//!     tick(Duration::from_secs(2), || Msg::Tick2),
//! ]);
//! ```
//!
//! ### Sequential Commands
//! ```
//! # use hojicha_core::commands::sequence;
//! # use hojicha_core::Cmd;
//! # enum Msg { First, Second }
//! let cmd: Cmd<Msg> = sequence(vec![
//!     Cmd::new(|| Some(Msg::First)),
//!     Cmd::new(|| Some(Msg::Second)),
//! ]);
//! ```

use crate::core::{Cmd, Message};
use crate::event::WindowSize;
use std::process::Command;
use std::time::Duration;

// Import panic recovery utilities from runtime crate
// These are used to wrap Model methods for safe execution
// Note: These are always available, not feature-gated

/// Default maximum batch size
///
/// Batches larger than this will trigger a warning in debug mode.
/// This is a soft limit - the batch will still be created.
#[cfg(debug_assertions)]
const DEFAULT_MAX_BATCH_SIZE: usize = 100;

/// Hard maximum batch size
///
/// Batches larger than this will be automatically chunked.
/// This prevents accidental memory exhaustion from massive batches.
const HARD_MAX_BATCH_SIZE: usize = 1000;

/// Special message types for terminal control
#[derive(Debug, Clone)]
pub enum TerminalControlMsg {
    /// Hide the terminal cursor from view
    HideCursor,
    /// Show the terminal cursor
    ShowCursor,
    /// Enter the alternate screen buffer (like vim/less use)
    EnterAltScreen,
    /// Exit the alternate screen buffer and return to main screen
    ExitAltScreen,
    /// Set the terminal window title to the given string
    SetWindowTitle(String),
    /// Enable mouse tracking for cell motion (only when button pressed)
    EnableMouseCellMotion,
    /// Enable mouse tracking for all motion events (including hover)
    EnableMouseAllMotion,
    /// Disable all mouse tracking
    DisableMouse,
    /// Clear the entire screen
    ClearScreen,
    /// Clear the current line
    ClearLine,
}

/// Create a no-op command
///
/// This is the most common command return value, indicating that the program
/// should continue running without performing any side effects.
///
/// # Returns
/// A command that does nothing but allows the program to continue.
///
/// # Example
/// ```
/// use hojicha_core::{Model, Cmd, Event, commands::noop};
///
/// #[derive(Debug)]
/// enum AppMessage {
///     DoNothing,
/// }
///
/// struct MyApp;
///
/// impl Model for MyApp {
///     type Message = AppMessage;
///     
///     fn update(&mut self, event: Event<Self::Message>) -> Cmd<Self::Message> {
///         match event {
///             Event::User(AppMessage::DoNothing) => {
///                 // Just continue running without side effects
///                 noop()
///             }
///             _ => noop()
///         }
///     }
///     
///     fn view(&self) -> String {
///         "App running".to_string()
///     }
/// }
/// ```
#[must_use]
pub fn noop<M: Message>() -> Cmd<M> {
    Cmd::noop()
}

/// Create a no-op command
///
/// # Deprecated
/// This function is deprecated. Use `commands::noop()` instead for clearer intent.
/// The name "none" was confusing because it returns `Some(Cmd)` rather than `None`.
///
/// # Example
/// ```
/// # use hojicha_core::{Cmd, commands};
/// # enum Msg {}
/// // Old way (deprecated):
/// let cmd: Cmd<Msg> = commands::none();
///
/// // New way (preferred):
/// let cmd: Cmd<Msg> = commands::noop();
/// ```
#[deprecated(
    since = "0.2.1",
    note = "Use commands::noop() instead. The name 'none' was confusing."
)]
#[must_use]
pub fn none<M: Message>() -> Cmd<M> {
    noop()
}

/// Batch multiple commands to run concurrently
///
/// All commands in the batch will execute simultaneously. Use this when you need
/// multiple independent operations to happen at the same time.
///
/// Note: For performance optimization:
/// - Empty vectors return `Cmd::noop()`
/// - Single-element vectors return the element directly
/// - Use `batch_strict()` if you need guaranteed batch semantics
///
/// # Safety
/// - Batches larger than 100 commands will trigger a debug warning
/// - Batches larger than 1000 commands will be automatically chunked
///
/// # Panics
/// Panics if the input vector has exactly one element but that element cannot be retrieved.
/// This should never happen in practice as we check the length beforehand.
///
/// # Returns
/// A command that runs all input commands concurrently.
///
/// # Example
/// ```
/// use hojicha_core::{Model, Cmd, Event, commands::{batch, tick, spawn}};
/// use std::time::Duration;
///
/// #[derive(Debug, Clone)]
/// enum AppMessage {
///     ConfigLoaded(String),
///     TimerExpired,
///     DataFetched(String),
/// }
///
/// struct MyApp {
///     config: String,
///     data: String,
/// }
///
/// impl Model for MyApp {
///     type Message = AppMessage;
///     
///     fn init(&mut self) -> Cmd<Self::Message> {
///         // Start multiple operations simultaneously
///         batch(vec![
///             // Load config file
///             Cmd::new(|| {
///                 let config = std::fs::read_to_string("config.json")
///                     .unwrap_or_else(|_| "default".to_string());
///                 Some(AppMessage::ConfigLoaded(config))
///             }),
///             // Start a 5-second timer
///             tick(Duration::from_secs(5), || AppMessage::TimerExpired),
///             // Fetch data asynchronously
///             spawn(async {
///                 tokio::time::sleep(Duration::from_secs(2)).await;
///                 Some(AppMessage::DataFetched("async data".to_string()))
///             }),
///         ])
///     }
///     
///     fn update(&mut self, event: Event<Self::Message>) -> Cmd<Self::Message> {
///         match event {
///             Event::User(AppMessage::ConfigLoaded(config)) => {
///                 self.config = config;
///                 Cmd::noop()
///             }
///             Event::User(AppMessage::TimerExpired) => {
///                 println!("Timer expired!");
///                 Cmd::noop()
///             }
///             Event::User(AppMessage::DataFetched(data)) => {
///                 self.data = data;
///                 Cmd::noop()
///             }
///             _ => Cmd::noop()
///         }
///     }
///     
///     fn view(&self) -> String {
///         format!("Config: {}, Data: {}", self.config, self.data)
///     }
/// }
/// ```
#[must_use]
pub fn batch<M: Message>(cmds: Vec<Cmd<M>>) -> Cmd<M> {
    match cmds.len() {
        0 => Cmd::noop(),
        1 => cmds.into_iter().next().unwrap(),
        n if n > HARD_MAX_BATCH_SIZE => {
            // Chunk very large batches to prevent memory issues
            eprintln!("Warning: Batch of {n} commands exceeds hard limit of {HARD_MAX_BATCH_SIZE}. Chunking into smaller batches.");
            batch_chunked(cmds, HARD_MAX_BATCH_SIZE)
        }
        n => {
            #[cfg(debug_assertions)]
            if n > DEFAULT_MAX_BATCH_SIZE {
                eprintln!(
                    "Warning: Large batch of {n} commands (recommended max: {DEFAULT_MAX_BATCH_SIZE})"
                );
            }
            let _ = n; // Suppress unused variable warning in release builds
            Cmd::batch(cmds)
        }
    }
}

/// Sequence commands to run one after another
///
/// Note: For performance optimization:
/// - Empty vectors return `Cmd::noop()`
/// - Single-element vectors return the element directly
/// - Use `sequence_strict()` if you need guaranteed sequence semantics
///
/// # Panics
/// Panics if the input vector has exactly one element but that element cannot be retrieved.
/// This should never happen in practice as we check the length beforehand.
///
/// # Example
/// ```
/// # use hojicha_core::{Cmd, commands::sequence};
/// # enum Msg { Save, Notify }
/// # fn save_to_disk() -> Cmd<Msg> { Cmd::noop() }
/// # fn show_notification() -> Cmd<Msg> { Cmd::noop() }
/// // Sequence commands to run one after another
/// let cmd: Cmd<Msg> = sequence(vec![
///     save_to_disk(),
///     show_notification(),
/// ]);
/// ```
#[must_use]
pub fn sequence<M: Message>(cmds: Vec<Cmd<M>>) -> Cmd<M> {
    match cmds.len() {
        0 => Cmd::noop(),
        1 => cmds.into_iter().next().unwrap(),
        _ => Cmd::sequence(cmds),
    }
}

/// Create a batch command with strict semantics
///
/// Unlike `batch()`, this always returns a batch command regardless of the
/// number of elements. Use this when you need guaranteed batch behavior.
///
/// # Example
/// ```no_run
/// # use hojicha_core::{Cmd, commands::batch_strict};
/// # enum Msg { Action }
/// # fn maybe_cmd() -> Cmd<Msg> { Cmd::noop() }
/// // Always returns a batch, even with 0 or 1 elements
/// batch_strict(vec![maybe_cmd()])
/// # ;
/// ```
#[must_use]
pub fn batch_strict<M: Message>(cmds: Vec<Cmd<M>>) -> Cmd<M> {
    Cmd::batch(cmds)
}

/// Create a batch command with a specific size limit
///
/// Batches larger than the limit will be automatically chunked.
///
/// # Example
/// ```no_run
/// # use hojicha_core::{Cmd, commands::batch_with_limit};
/// # enum Msg { Action }
/// # let large_vec_of_commands: Vec<Cmd<Msg>> = vec![];
/// // Create batches with max 50 commands each
/// batch_with_limit(large_vec_of_commands, 50)
/// # ;
/// ```
#[must_use]
pub fn batch_with_limit<M: Message>(cmds: Vec<Cmd<M>>, limit: usize) -> Cmd<M> {
    if cmds.len() <= limit {
        batch(cmds)
    } else {
        batch_chunked(cmds, limit)
    }
}

/// Internal helper to chunk large batches
#[doc(hidden)]
pub(crate) fn batch_chunked<M: Message>(mut cmds: Vec<Cmd<M>>, chunk_size: usize) -> Cmd<M> {
    let mut chunks = Vec::new();

    while !cmds.is_empty() {
        let chunk: Vec<Cmd<M>> = cmds.drain(..chunk_size.min(cmds.len())).collect();
        chunks.push(Cmd::batch(chunk));
    }

    // Batch the batches - this creates a two-level batch
    // This ensures all commands still run concurrently
    Cmd::batch(chunks)
}

/// Create a sequence command with strict semantics
///
/// Unlike `sequence()`, this always returns a sequence command regardless of the
/// number of elements. Use this when you need guaranteed sequence behavior.
///
/// # Example
/// ```no_run
/// # use hojicha_core::{Cmd, commands::sequence_strict};
/// # enum Msg { Action }
/// # fn maybe_cmd() -> Cmd<Msg> { Cmd::noop() }
/// // Always returns a sequence, even with 0 or 1 elements
/// sequence_strict(vec![maybe_cmd()])
/// # ;
/// ```
#[must_use]
pub fn sequence_strict<M: Message>(cmds: Vec<Cmd<M>>) -> Cmd<M> {
    Cmd::sequence(cmds)
}

/// Create a command that sends a message after a delay
///
/// This command waits for the specified duration, then executes the callback
/// and sends the resulting message to your update function.
///
/// # Parameters
/// - `duration`: How long to wait before executing
/// - `f`: Function that creates the message to send
///
/// # Returns
/// A command that will send a message after the specified delay.
///
/// # Example
/// ```
/// use hojicha_core::{Model, Cmd, Event, commands::tick};
/// use std::time::Duration;
///
/// #[derive(Debug, Clone)]
/// enum AppMessage {
///     StartTimeout,
///     TimeoutExpired,
///     CustomTimeout(String),
/// }
///
/// struct TimeoutApp {
///     status: String,
/// }
///
/// impl Model for TimeoutApp {
///     type Message = AppMessage;
///     
///     fn update(&mut self, event: Event<Self::Message>) -> Cmd<Self::Message> {
///         match event {
///             Event::User(AppMessage::StartTimeout) => {
///                 self.status = "Timer started...".to_string();
///                 // Wait 3 seconds, then send TimeoutExpired message
///                 tick(Duration::from_secs(3), || AppMessage::TimeoutExpired)
///             }
///             Event::User(AppMessage::TimeoutExpired) => {
///                 self.status = "Timeout completed!".to_string();
///                 // Chain another timer with custom data
///                 tick(Duration::from_secs(1), || {
///                     AppMessage::CustomTimeout("Custom data".to_string())
///                 })
///             }
///             Event::User(AppMessage::CustomTimeout(data)) => {
///                 self.status = format!("Got custom timeout: {}", data);
///                 Cmd::noop()
///             }
///             _ => Cmd::noop()
///         }
///     }
///     
///     fn view(&self) -> String {
///         format!("Status: {}", self.status)
///     }
/// }
/// ```
pub fn tick<M, F>(duration: Duration, f: F) -> Cmd<M>
where
    M: Message,
    F: FnOnce() -> M + Send + 'static,
{
    #[allow(deprecated)]
    Cmd::tick(duration, f)
}

/// Create a command that ticks at regular intervals
///
/// This command creates a recurring timer that sends messages at regular intervals.
/// Unlike `tick()` which only fires once, `every()` continues indefinitely.
///
/// Similar to Bubbletea's Every command, this aligns with system clock
/// boundaries. For example, `every(Duration::from_secs(1))` will tick
/// at the start of each second.
///
/// # Parameters
/// - `duration`: Interval between ticks
/// - `f`: Function that creates messages, receives the current timestamp
///
/// # Returns
/// A command that sends messages at regular intervals until the program exits.
///
/// # Example
/// ```
/// use hojicha_core::{Model, Cmd, Event, commands::every};
/// use std::time::{Duration, Instant};
///
/// #[derive(Debug, Clone)]
/// enum ClockMessage {
///     StartClock,
///     Tick(Instant),
///     StopClock,
/// }
///
/// struct ClockApp {
///     running: bool,
///     last_tick: Option<Instant>,
///     tick_count: u32,
/// }
///
/// impl Model for ClockApp {
///     type Message = ClockMessage;
///     
///     fn init(&mut self) -> Cmd<Self::Message> {
///         // Start ticking every second
///         every(Duration::from_secs(1), |instant| ClockMessage::Tick(instant))
///     }
///     
///     fn update(&mut self, event: Event<Self::Message>) -> Cmd<Self::Message> {
///         match event {
///             Event::User(ClockMessage::StartClock) => {
///                 self.running = true;
///                 // Start a new ticker
///                 every(Duration::from_secs(1), |instant| ClockMessage::Tick(instant))
///             }
///             Event::User(ClockMessage::Tick(instant)) => {
///                 if self.running {
///                     self.last_tick = Some(instant);
///                     self.tick_count += 1;
///                 }
///                 Cmd::noop()
///             }
///             Event::User(ClockMessage::StopClock) => {
///                 self.running = false;
///                 Cmd::noop()
///             }
///             _ => Cmd::noop()
///         }
///     }
///     
///     fn view(&self) -> String {
///         let status = if self.running { "Running" } else { "Stopped" };
///         format!(
///             "Clock: {} | Ticks: {} | Last: {:?}",
///             status, self.tick_count, self.last_tick
///         )
///     }
/// }
/// ```
pub fn every<M, F>(duration: Duration, f: F) -> Cmd<M>
where
    M: Message,
    F: FnOnce(std::time::Instant) -> M + Send + 'static,
{
    #[allow(deprecated)]
    Cmd::every(duration, f)
}

/// Query the terminal for its current size
///
/// This command returns a `WindowSize` message with the current terminal dimensions.
/// Note that resize events are automatically delivered when the terminal size changes,
/// so you typically won't need to use this command directly.
///
/// # Example
/// ```
/// # use hojicha_core::{Cmd, commands::window_size, event::WindowSize};
/// # enum Msg { GotSize(WindowSize) }
/// // Query the terminal size
/// let cmd: Cmd<Msg> = window_size(|size| Msg::GotSize(size));
/// ```
pub fn window_size<M, F>(f: F) -> Cmd<M>
where
    M: Message,
    F: Fn(WindowSize) -> M + Send + Sync + 'static,
{
    Cmd::new(move || {
        // Query the actual terminal size using crossterm
        match crossterm::terminal::size() {
            Ok((width, height)) => Some(f(WindowSize { width, height })),
            Err(_) => {
                // Fall back to reasonable defaults if we can't query the terminal
                Some(f(WindowSize {
                    width: 80,
                    height: 24,
                }))
            }
        }
    })
}

/// Set the terminal window title
///
/// # Example
/// ```
/// # use hojicha_core::{Cmd, commands::set_window_title};
/// # enum Msg {}
/// // Set the terminal window title
/// let cmd: Cmd<Msg> = set_window_title("My Awesome App");
/// ```
pub fn set_window_title<M: Message>(title: impl Into<String>) -> Cmd<M> {
    let title = title.into();
    Cmd::new(move || {
        use crossterm::{execute, terminal::SetTitle};
        let _ = execute!(std::io::stdout(), SetTitle(&title));
        None
    })
}

/// Send an interrupt signal (simulates Ctrl+C)
///
/// This is useful for graceful shutdown or interrupting long-running operations.
///
/// # Example
/// ```
/// # use hojicha_core::{Cmd, commands::interrupt};
/// # enum Msg {}
/// // Send an interrupt signal (simulates Ctrl+C)
/// let cmd: Cmd<Msg> = interrupt();
/// ```
#[must_use]
pub fn interrupt<M: Message>() -> Cmd<M> {
    Cmd::new(|| {
        #[cfg(unix)]
        {
            // Send SIGINT to current process
            unsafe {
                libc::kill(libc::getpid(), libc::SIGINT);
            }
        }
        None
    })
}

/// Macro to generate simple terminal control commands
///
/// This reduces code duplication for commands that just signal
/// the runtime to perform a terminal operation.
macro_rules! terminal_cmd {
    ($(
        $(#[$attr:meta])*
        $vis:vis fn $name:ident() -> $doc:literal;
    )+) => {
        $(
            $(#[$attr])*
            #[doc = $doc]
            #[doc = ""]
            #[doc = "This command signals the runtime to perform the operation."]
            $vis fn $name<M: Message>() -> Cmd<M> {
                Cmd::new(|| None)
            }
        )+
    };
}

// Generate all the simple terminal control commands
terminal_cmd! {
    /// Hide the terminal cursor
    pub fn hide_cursor() -> "Hide the terminal cursor from view";

    /// Show the terminal cursor
    pub fn show_cursor() -> "Show the terminal cursor";

    /// Enter alternate screen buffer
    pub fn enter_alt_screen() -> "Enter the alternate screen buffer (like vim/less use)";

    /// Exit alternate screen buffer
    pub fn exit_alt_screen() -> "Exit the alternate screen buffer and return to main screen";
}

/// Create a custom command from an async function
///
/// This allows you to create commands that perform async operations like
/// HTTP requests, database queries, or other I/O operations.
///
/// # Example
/// ```
/// # use hojicha_core::{Cmd, commands::custom_async};
/// # enum Message { DataFetched(String) }
/// // Create an async command
/// let cmd: Cmd<Message> = custom_async(|| async {
///     // Perform async operation
///     let data = "example data".to_string();
///     Some(Message::DataFetched(data))
/// });
/// ```
pub fn custom_async<M, F, Fut>(f: F) -> Cmd<M>
where
    M: Message,
    F: FnOnce() -> Fut + Send + 'static,
    Fut: std::future::Future<Output = Option<M>> + Send + 'static,
{
    Cmd::async_cmd(f())
}

/// Spawn a simple async task
///
/// This command spawns an async task on the shared runtime managed by the program.
/// Unlike `custom_async`, this uses the existing runtime rather than creating a new one.
///
/// # Example
/// ```
/// # use hojicha_core::{Cmd, commands::spawn};
/// # use std::time::Duration;
/// # enum Message { TimerComplete }
/// // Spawn an async task
/// let cmd: Cmd<Message> = spawn(async {
///     tokio::time::sleep(Duration::from_secs(1)).await;
///     Some(Message::TimerComplete)
/// });
/// ```
pub fn spawn<M, Fut>(fut: Fut) -> Cmd<M>
where
    M: Message,
    Fut: std::future::Future<Output = Option<M>> + Send + 'static,
{
    Cmd::async_cmd(fut)
}

/// Create a custom command from a blocking function
///
/// This is a convenience wrapper for creating simple custom commands.
///
/// # Example
/// ```
/// # use hojicha_core::{Cmd, commands::custom};
/// # enum Message { ComputationComplete(i32) }
/// # fn expensive_computation() -> i32 { 42 }
/// // Create a custom command
/// let cmd: Cmd<Message> = custom(|| {
///     // Perform some custom logic
///     let result = expensive_computation();
///     Some(Message::ComputationComplete(result))
/// });
/// ```
pub fn custom<M, F>(f: F) -> Cmd<M>
where
    M: Message,
    F: FnOnce() -> Option<M> + Send + 'static,
{
    Cmd::new(f)
}

/// Create a custom fallible command
///
/// This allows you to create commands that can fail and handle errors gracefully.
///
/// # Example
/// ```
/// # use hojicha_core::{Cmd, commands::custom_fallible};
/// # enum Message { ConfigLoaded(String) }
/// // Create a fallible command
/// let cmd: Cmd<Message> = custom_fallible(|| {
///     // Perform operation that might fail
///     let data = std::fs::read_to_string("config.json")?;
///     Ok(Some(Message::ConfigLoaded(data)))
/// });
/// ```
pub fn custom_fallible<M, F>(f: F) -> Cmd<M>
where
    M: Message,
    F: FnOnce() -> crate::Result<Option<M>> + Send + 'static,
{
    Cmd::fallible(f)
}

/// Create a fallible command that converts errors to messages
///
/// This allows errors to be handled by the model's update method rather than
/// just being logged.
///
/// # Example
/// ```
/// # use hojicha_core::{Cmd, commands::fallible_with_error};
/// # enum Msg { DataLoaded(String), ErrorOccurred(String) }
/// // Create a fallible command with error handling
/// let cmd: Cmd<Msg> = fallible_with_error(
///     || {
///         let data = std::fs::read_to_string("data.json")?;
///         Ok(Some(Msg::DataLoaded(data)))
///     },
///     |err| Msg::ErrorOccurred(err.to_string())
/// );
/// ```
pub fn fallible_with_error<M, F, E>(f: F, error_handler: E) -> Cmd<M>
where
    M: Message,
    F: FnOnce() -> crate::Result<Option<M>> + Send + 'static,
    E: FnOnce(crate::error::Error) -> M + Send + 'static,
{
    Cmd::new(move || match f() {
        Ok(msg) => msg,
        Err(err) => Some(error_handler(err)),
    })
}

/// Execute a command in a subprocess, releasing the terminal while it runs
///
/// This is useful for running interactive programs like editors or shells.
/// The terminal will be restored after the command completes.
///
/// # Example
/// ```
/// # use hojicha_core::{Cmd, commands::exec};
/// # enum Msg { EditorClosed(Option<i32>) }
/// // Execute an external program
/// let cmd: Cmd<Msg> = exec("vim", vec!["file.txt"], |exit_status| {
///     Msg::EditorClosed(exit_status)
/// });
/// ```
pub fn exec<M, F>(program: impl Into<String>, args: Vec<impl Into<String>>, callback: F) -> Cmd<M>
where
    M: Message,
    F: Fn(Option<i32>) -> M + Send + 'static,
{
    let program = program.into();
    let args: Vec<String> = args.into_iter().map(Into::into).collect();

    Cmd::exec_process(program, args, callback)
}

/// Execute a shell command, releasing the terminal while it runs
///
/// # Example
/// ```
/// # use hojicha_core::{Cmd, commands::exec_command};
/// # enum Msg { CommandFinished(Option<i32>) }
/// // Execute a shell command
/// let cmd: Cmd<Msg> = exec_command("ls -la", |exit_status| {
///     Msg::CommandFinished(exit_status)
/// });
/// ```
pub fn exec_command<M, F>(command: impl Into<String>, callback: F) -> Cmd<M>
where
    M: Message,
    F: Fn(Option<i32>) -> M + Send + 'static,
{
    let command = command.into();

    Cmd::new(move || {
        let output = if cfg!(target_os = "windows") {
            Command::new("cmd").args(["/C", &command]).status()
        } else {
            Command::new("sh").args(["-c", &command]).status()
        };

        let exit_code = output.ok().and_then(|status| status.code());
        Some(callback(exit_code))
    })
}

// Generate mouse and screen control commands
terminal_cmd! {
    /// Enable mouse cell motion tracking
    ///
    /// This enables mouse events only when a button is pressed.
    pub fn enable_mouse_cell_motion() -> "Enable mouse tracking for cell motion (only when button pressed)";

    /// Enable mouse all motion tracking
    ///
    /// This enables mouse movement events regardless of whether a button is pressed,
    /// allowing for hover interactions.
    pub fn enable_mouse_all_motion() -> "Enable mouse tracking for all motion events (including hover)";

    /// Disable mouse tracking
    pub fn disable_mouse() -> "Disable all mouse tracking";

    /// Clear the entire screen
    pub fn clear_screen() -> "Clear the entire screen";

    /// Clear the current line
    pub fn clear_line() -> "Clear the current line";

    /// Suspend the program (Ctrl+Z)
    ///
    /// This will suspend the program and return control to the shell.
    /// When the program is resumed, a Resume event will be sent.
    pub fn suspend() -> "Suspend the program (Ctrl+Z)";
}

/// Quit the program gracefully
///
/// This command signals the program to exit cleanly. When this command is executed,
/// the event loop will stop and the program will terminate. All cleanup operations
/// (like restoring terminal state) will be performed automatically.
///
/// # Returns
/// A command that terminates the program when executed.
///
/// # Example
///
/// ```
/// use hojicha_core::{Model, Event, Cmd, Key, commands::quit};
///
/// #[derive(Debug, Clone)]
/// enum AppMessage {
///     RequestQuit,
///     ConfirmQuit,
/// }
///
/// struct MyApp {
///     quit_requested: bool,
/// }
///
/// impl Model for MyApp {
///     type Message = AppMessage;
///     
///     fn update(&mut self, event: Event<Self::Message>) -> Cmd<Self::Message> {
///         match event {
///             // Handle keyboard input
///             Event::Key(key) => match key.key {
///                 Key::Char('q') | Key::Esc => {
///                     // Quit immediately on 'q' or Escape
///                     quit()
///                 }
///                 Key::Char('c') if key.modifiers.contains(crossterm::event::KeyModifiers::CONTROL) => {
///                     // Handle Ctrl+C gracefully
///                     quit()
///                 }
///                 _ => Cmd::noop()
///             },
///             
///             // Handle application messages
///             Event::User(AppMessage::RequestQuit) => {
///                 if self.quit_requested {
///                     // Second request - quit immediately
///                     quit()
///                 } else {
///                     // First request - ask for confirmation
///                     self.quit_requested = true;
///                     Cmd::noop()
///                 }
///             }
///             Event::User(AppMessage::ConfirmQuit) => {
///                 // Confirmed - quit the application
///                 quit()
///             }
///             
///             _ => Cmd::noop()
///         }
///     }
///     
///     fn view(&self) -> String {
///         if self.quit_requested {
///             "Are you sure you want to quit? Press 'q' again to confirm.".to_string()
///         } else {
///             "Press 'q' to quit, Ctrl+C to exit immediately".to_string()
///         }
///     }
/// }
/// ```
#[must_use]
pub fn quit<M: Message>() -> Cmd<M> {
    #[allow(deprecated)]
    Cmd::quit()
}

/// Macro to generate crossterm commands that execute terminal sequences
///
/// This reduces duplication for commands that use crossterm to send
/// control sequences to the terminal.
macro_rules! crossterm_cmd {
    ($(
        $(#[$attr:meta])*
        $vis:vis fn $name:ident($cmd_type:path) -> $doc:literal;
    )+) => {
        $(
            $(#[$attr])*
            #[doc = $doc]
            #[doc = ""]
            #[doc = "This command sends a control sequence to the terminal."]
            $vis fn $name<M: Message>() -> Cmd<M> {
                Cmd::new(|| {
                    use crossterm::execute;
                    use std::io;
                    let _ = execute!(io::stdout(), $cmd_type);
                    None
                })
            }
        )+
    };
}

// Generate crossterm-based commands
crossterm_cmd! {
    /// Enable bracketed paste mode
    ///
    /// When enabled, pasted text will be delivered as a single `Event::Paste(String)`
    /// instead of individual key events. This prevents pasted text from
    /// accidentally triggering keyboard shortcuts.
    pub fn enable_bracketed_paste(crossterm::event::EnableBracketedPaste) -> "Enable bracketed paste mode";

    /// Disable bracketed paste mode
    pub fn disable_bracketed_paste(crossterm::event::DisableBracketedPaste) -> "Disable bracketed paste mode";

    /// Enable focus change reporting
    ///
    /// When enabled, the program will receive `Event::Focus` when the terminal
    /// gains focus and `Event::Blur` when it loses focus.
    pub fn enable_focus_change(crossterm::event::EnableFocusChange) -> "Enable focus change reporting";

    /// Disable focus change reporting
    pub fn disable_focus_change(crossterm::event::DisableFocusChange) -> "Disable focus change reporting";
}

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

    #[derive(Debug, PartialEq)]
    enum TestMsg {
        One,
        Two,
        Three,
    }

    #[test]
    fn test_batch_empty() {
        let result: Cmd<TestMsg> = batch(vec![]);
        assert!(!result.is_quit());
    }

    #[test]
    fn test_batch_single() {
        let cmd = Cmd::new(|| Some(TestMsg::One));
        let result = batch(vec![cmd]);
        assert!(!result.is_quit());
    }

    #[test]
    fn test_batch_multiple() {
        let cmds = vec![
            Cmd::new(|| Some(TestMsg::One)),
            Cmd::new(|| Some(TestMsg::Two)),
            Cmd::new(|| Some(TestMsg::Three)),
        ];
        let result = batch(cmds);
        assert!(!result.is_quit());
    }

    #[test]
    fn test_sequence_executes_in_order() {
        let cmd = sequence(vec![Cmd::new(|| Some(TestMsg::One))]);
        let msg = cmd.execute().unwrap();
        assert_eq!(msg, Some(TestMsg::One));
    }

    #[test]
    fn test_tick_command() {
        let cmd = tick(Duration::from_millis(10), || TestMsg::One);
        // Tick commands are now async and handled by the executor
        // They return None from execute() since they need async handling
        let msg = cmd.execute().unwrap();
        assert_eq!(msg, None);
    }

    #[test]
    fn test_every_command() {
        let cmd: Cmd<TestMsg> = every(Duration::from_millis(1), |_| TestMsg::One);
        // Every commands are now async and handled by the executor
        // They return None from execute() since they need async handling
        let result = cmd.test_execute().unwrap();
        assert_eq!(result, None);
    }

    #[test]
    fn test_window_size_command() {
        // Test that window_size returns a valid WindowSize
        #[derive(Debug, PartialEq)]
        enum SizeMsg {
            Size(WindowSize),
        }

        let cmd: Cmd<SizeMsg> = window_size(SizeMsg::Size);
        let result = cmd.test_execute().unwrap();

        // Verify we got a size message
        assert!(matches!(result, Some(SizeMsg::Size(_))));

        // The actual dimensions will vary based on terminal, but should be positive
        if let Some(SizeMsg::Size(size)) = result {
            assert!(size.width > 0);
            assert!(size.height > 0);
        }
    }

    #[test]
    fn test_cursor_commands() {
        let hide_cmd: Cmd<TestMsg> = hide_cursor();
        let show_cmd: Cmd<TestMsg> = show_cursor();

        assert!(hide_cmd.test_execute().is_ok());
        assert!(show_cmd.test_execute().is_ok());
    }

    #[test]
    fn test_alt_screen_commands() {
        let enter_cmd: Cmd<TestMsg> = enter_alt_screen();
        let exit_cmd: Cmd<TestMsg> = exit_alt_screen();

        assert!(enter_cmd.test_execute().is_ok());
        assert!(exit_cmd.test_execute().is_ok());
    }

    #[test]
    fn test_custom_command() {
        let cmd = custom::<TestMsg, _>(|| Some(TestMsg::One));
        let result = cmd.execute();
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), Some(TestMsg::One));
    }

    #[test]
    fn test_custom_fallible_success() {
        let cmd = custom_fallible::<TestMsg, _>(|| Ok(Some(TestMsg::Two)));
        let result = cmd.execute();
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), Some(TestMsg::Two));
    }

    #[test]
    fn test_custom_fallible_error() {
        use std::io;
        let cmd = custom_fallible::<TestMsg, _>(|| {
            Err(crate::error::Error::Io(io::Error::other("test error")))
        });
        let result = cmd.execute();
        assert!(result.is_err());
    }

    #[test]
    fn test_custom_async_command() {
        let cmd = custom_async::<TestMsg, _, _>(|| async { Some(TestMsg::Three) });
        let result = cmd.execute();
        assert!(result.is_ok());
        // Now async commands return None since they use shared runtime
        assert_eq!(result.unwrap(), None);
    }

    #[test]
    fn test_window_title_command() {
        let cmd: Cmd<TestMsg> = set_window_title("Test Title");
        assert!(cmd.test_execute().is_ok());

        let cmd_empty: Cmd<TestMsg> = set_window_title("");
        assert!(cmd_empty.test_execute().is_ok());
    }

    #[test]
    fn test_exec_command() {
        let cmd: Cmd<TestMsg> = exec("echo", vec!["hello"], |_| TestMsg::One);
        assert!(cmd.is_exec_process());

        let process_info = cmd.take_exec_process();
        assert!(process_info.is_some());
    }

    #[test]
    fn test_mouse_commands() {
        let cell_motion: Cmd<TestMsg> = enable_mouse_cell_motion();
        let all_motion: Cmd<TestMsg> = enable_mouse_all_motion();
        let disable: Cmd<TestMsg> = disable_mouse();

        assert!(cell_motion.test_execute().is_ok());
        assert!(all_motion.test_execute().is_ok());
        assert!(disable.test_execute().is_ok());
    }

    #[test]
    fn test_clear_commands() {
        let clear_screen: Cmd<TestMsg> = clear_screen();
        let clear_line: Cmd<TestMsg> = clear_line();

        assert!(clear_screen.test_execute().is_ok());
        assert!(clear_line.test_execute().is_ok());
    }

    #[test]
    fn test_suspend_command() {
        let cmd: Cmd<TestMsg> = suspend();
        assert!(cmd.test_execute().is_ok());
    }

    #[test]
    fn test_crossterm_commands() {
        let enable_paste: Cmd<TestMsg> = enable_bracketed_paste();
        let disable_paste: Cmd<TestMsg> = disable_bracketed_paste();
        let enable_focus: Cmd<TestMsg> = enable_focus_change();
        let disable_focus: Cmd<TestMsg> = disable_focus_change();

        assert!(enable_paste.test_execute().is_ok());
        assert!(disable_paste.test_execute().is_ok());
        assert!(enable_focus.test_execute().is_ok());
        assert!(disable_focus.test_execute().is_ok());
    }

    #[test]
    fn test_batch_with_mixed_types() {
        let cmds = vec![
            Cmd::new(|| Some(TestMsg::One)),
            Cmd::new(|| Some(TestMsg::Two)),
        ];

        let batch_cmd = batch(cmds);
        // Batch commands should be recognized as batch type
        assert!(batch_cmd.is_batch());
    }

    #[test]
    fn test_sequence_execution_order() {
        let cmds = vec![
            Cmd::new(|| Some(TestMsg::One)),
            Cmd::new(|| Some(TestMsg::Two)),
        ];

        let seq_cmd = sequence(cmds);
        // Sequence commands should be recognized as sequence type
        assert!(seq_cmd.is_sequence());
    }

    // Property-based tests
    mod property_tests {
        use super::*;
        use proptest::prelude::*;

        proptest! {
            #[test]
            fn prop_batch_command_properties(cmd_count in 0usize..50) {
                let cmds: Vec<Cmd<TestMsg>> = (0..cmd_count)
                    .map(|_| Cmd::new(|| Some(TestMsg::One)))
                    .collect();

                let batch_cmd = batch(cmds);

                // Batch commands should never be quit commands
                prop_assert!(!batch_cmd.is_quit());

                // Empty batches should be recognized as no-ops
                if cmd_count == 0 {
                    prop_assert!(batch_cmd.is_noop());
                } else if cmd_count >= 2 {
                    // Only multi-command batches are considered "batch" type
                    prop_assert!(batch_cmd.is_batch());
                }
                // Single commands may be optimized and not be recognized as batch
            }
        }

        proptest! {
            #[test]
            fn prop_sequence_command_properties(cmd_count in 1usize..20) {
                let cmds: Vec<Cmd<TestMsg>> = (0..cmd_count)
                    .map(|i| Cmd::new(move || match i % 3 {
                        0 => Some(TestMsg::One),
                        1 => Some(TestMsg::Two),
                        _ => Some(TestMsg::Three),
                    }))
                    .collect();

                let seq_cmd = sequence(cmds);

                // Sequence commands should never be quit commands
                prop_assert!(!seq_cmd.is_quit());

                // Only multi-command sequences are considered "sequence" type
                if cmd_count >= 2 {
                    prop_assert!(seq_cmd.is_sequence());
                }
                // Single commands may be optimized and not be recognized as sequence
            }
        }

        proptest! {
            #[test]
            fn prop_batch_with_limit_properties(
                cmd_count in 2usize..50, // Start at 2 to avoid single-command optimization
                limit in 1usize..20
            ) {
                let cmds: Vec<Cmd<TestMsg>> = (0..cmd_count)
                    .map(|_| Cmd::new(|| Some(TestMsg::One)))
                    .collect();

                let batch_cmd = batch_with_limit(cmds, limit);

                // Batch with limit should preserve basic properties
                prop_assert!(!batch_cmd.is_quit());

                // Should be recognized as batch for multi-command inputs
                prop_assert!(batch_cmd.is_batch());
            }
        }
    }

    // Additional behavioral tests
    mod behavioral_tests {
        use super::*;

        /// Behavioral test: fallible commands with error handlers
        #[test]
        fn test_fallible_with_error_behavior() {
            use crate::error::Error;

            let fallible_cmd = fallible_with_error(
                || Err(Error::Custom("test error".to_string().into())),
                |_| TestMsg::Three,
            );

            assert!(!fallible_cmd.is_quit());
            assert!(!fallible_cmd.is_noop());

            // Should execute and handle the error
            let result = fallible_cmd.execute().unwrap();
            assert_eq!(result, Some(TestMsg::Three));
        }
    }
}