moosicbox_assert 0.2.0

MoosicBox assert package
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
//! Environment-controlled assertion macros for conditional debugging and testing.
//!
//! This crate provides assertion macros that can be toggled at runtime via the `ENABLE_ASSERT`
//! environment variable. When enabled, failed assertions exit the process with colorized error
//! messages and backtraces. When disabled, the macros have varying fallback behaviors:
//! returning errors, logging warnings, panicking, or becoming no-ops.
//!
//! # Use Cases
//!
//! * Development and debugging environments where you want strict checking
//! * Production environments where you want graceful degradation instead of process termination
//! * Testing scenarios where you need conditional assertion behavior
//! * Gradual migration from development assertions to production error handling
//!
//! # Environment Variables
//!
//! * `ENABLE_ASSERT` - Set to "1" to enable strict assertion mode (process exits on failure),
//!   any other value uses the fallback behavior of each macro
//!
//! # Examples
//!
//! Basic assertion that exits when enabled, does nothing when disabled:
//!
//! ```rust,no_run
//! use moosicbox_assert::assert;
//!
//! unsafe { std::env::set_var("ENABLE_ASSERT", "1"); }
//! let value = 42;
//! assert!(value > 0, "Value must be positive");
//! ```
//!
//! Assertion that returns an error when disabled:
//!
//! ```rust,no_run
//! use moosicbox_assert::assert_or_err;
//!
//! #[derive(Debug)]
//! enum Error { Invalid }
//!
//! fn validate(x: i32) -> Result<(), Error> {
//!     assert_or_err!(x >= 0, Error::Invalid, "Value must be non-negative");
//!     Ok(())
//! }
//! ```
//!
//! # Available Macros
//!
//! * [`assert!`] - Conditional assertion that exits or does nothing
//! * [`assert_or_err!`] - Returns an error when disabled
//! * [`assert_or_error!`] - Logs an error when disabled
//! * [`assert_or_panic!`] - Panics when disabled
//! * [`assert_or_unimplemented!`] - Calls `unimplemented!()` when disabled
//! * [`die!`] - Unconditional exit when enabled, no-op when disabled
//! * [`die_or_err!`] - Returns an error when disabled
//! * [`die_or_error!`] - Logs an error when disabled
//! * [`die_or_warn!`] - Logs a warning when disabled
//! * [`die_or_panic!`] - Panics when disabled
//! * [`die_or_propagate!`] - Propagates errors using `?` when disabled
//! * [`die_or_unimplemented!`] - Calls `unimplemented!()` when disabled

#![cfg_attr(feature = "fail-on-warnings", deny(warnings))]
#![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)]
#![allow(clippy::multiple_crate_versions)]

/// Re-export of the [`colored::Colorize`] trait for colorizing terminal output.
///
/// This trait is used internally by the assertion macros to format error messages
/// with colored backgrounds (red for errors, yellow for warnings). It's re-exported
/// to allow users to access colorization utilities without adding `colored` as a
/// separate dependency.
pub use colored::Colorize;

/// Re-export of the `moosicbox_env_utils` crate for environment variable utilities.
///
/// This module provides the `default_env!` macro used internally by assertion macros
/// to read the `ENABLE_ASSERT` environment variable. It's re-exported to allow users
/// to access environment utilities without adding `moosicbox_env_utils` as a separate
/// dependency.
pub use moosicbox_env_utils;

/// Conditional assertion that exits the process on failure when assertions are enabled.
///
/// When `ENABLE_ASSERT` environment variable is set to "1", this macro evaluates the condition
/// and exits the process with a colorized error message and stack trace if the condition is false.
/// When assertions are disabled, the condition is not evaluated and the macro becomes a no-op.
///
/// # Environment Variables
///
/// * `ENABLE_ASSERT` - Set to "1" to enable assertions, any other value disables them
///
/// # Examples
///
/// ```rust,no_run
/// use moosicbox_assert::assert;
///
/// unsafe { std::env::set_var("ENABLE_ASSERT", "1"); }
/// let value = 42;
/// assert!(value > 0);
/// assert!(value == 42, "Expected 42, got {}", value);
/// ```
///
/// # Panics
///
/// Exits the process (via `std::process::exit(1)`) when the condition is false and `ENABLE_ASSERT=1`.
#[macro_export]
macro_rules! assert {
    ($evaluate:expr $(,)?) => {
        if $crate::moosicbox_env_utils::default_env!("ENABLE_ASSERT", "false") == "1"
            && !($evaluate)
        {
            eprintln!(
                "{}",
                $crate::Colorize::on_red($crate::Colorize::white($crate::Colorize::bold(
                    format!(
                        "assert failed:\n{}",
                        std::backtrace::Backtrace::force_capture()
                    )
                    .as_str()
                )))
            );
            log::logger().flush();
            std::process::exit(1);
        }
    };
    ($evaluate:expr, $($message:tt)+) => {
        if $crate::moosicbox_env_utils::default_env!("ENABLE_ASSERT", "false") == "1"
            && !($evaluate)
        {
            eprintln!(
                "{}",
                $crate::Colorize::on_red($crate::Colorize::white($crate::Colorize::bold(
                    format!(
                        "assert failed: {}\n{}",
                        $crate::Colorize::underline(format!($($message)*).as_str()),
                        std::backtrace::Backtrace::force_capture()
                    )
                    .as_str()
                )))
            );
            log::logger().flush();
            std::process::exit(1);
        }
    };
}

/// Conditional assertion that returns an error on failure.
///
/// When `ENABLE_ASSERT` environment variable is set to "1" and the condition is false,
/// this macro exits the process with a colorized error message. When assertions are disabled
/// and the condition is false, it returns the specified error value instead.
///
/// # Environment Variables
///
/// * `ENABLE_ASSERT` - Set to "1" to enable assertions, any other value disables them
///
/// # Examples
///
/// ```rust,no_run
/// use moosicbox_assert::assert_or_err;
///
/// #[derive(Debug)]
/// enum MyError {
///     InvalidValue,
/// }
///
/// fn validate(value: i32) -> Result<(), MyError> {
///     assert_or_err!(value >= 0, MyError::InvalidValue, "Value must be non-negative");
///     assert_or_err!(value <= 100, MyError::InvalidValue, "Out of range: {}", value);
///     Ok(())
/// }
/// ```
///
/// # Errors
///
/// * Returns the specified error when the condition is false and `ENABLE_ASSERT` is not "1".
///
/// # Panics
///
/// Exits the process when the condition is false and `ENABLE_ASSERT=1`.
#[macro_export]
macro_rules! assert_or_err {
    ($evaluate:expr, $err:expr, $(,)?) => {
        if $crate::moosicbox_env_utils::default_env!("ENABLE_ASSERT", "false") == "1"
            && !($evaluate)
        {
            $crate::assert!($evaluate, "{:?}", $err)
        } else if !($evaluate) {
            return Err($err);
        }
    };
    ($evaluate:expr, $err:expr, $($message:tt)+) => {
        if $crate::moosicbox_env_utils::default_env!("ENABLE_ASSERT", "false") == "1"
            && !($evaluate)
        {
            $crate::assert!($evaluate, $($message)*)
        } else if !($evaluate) {
            return Err($err);
        }
    };
}

/// Conditional assertion that logs an error on failure.
///
/// When `ENABLE_ASSERT` environment variable is set to "1" and the condition is false,
/// this macro exits the process with a colorized error message. When assertions are disabled
/// and the condition is false, it logs an error message using the `log` crate instead.
///
/// # Environment Variables
///
/// * `ENABLE_ASSERT` - Set to "1" to enable assertions, any other value disables them
///
/// # Examples
///
/// ```rust,no_run
/// use moosicbox_assert::assert_or_error;
///
/// fn process_data(data: &[u8]) {
///     assert_or_error!(!data.is_empty(), "Cannot process empty data");
///     assert_or_error!(data.len() < 1024, "Data too large: {} bytes", data.len());
/// }
/// ```
///
/// # Panics
///
/// Exits the process when the condition is false and `ENABLE_ASSERT=1`.
#[macro_export]
macro_rules! assert_or_error {
    ($evaluate:expr, $($message:tt)+) => {
        if $crate::moosicbox_env_utils::default_env!("ENABLE_ASSERT", "false") == "1"
            && !($evaluate)
        {
            $crate::assert!($evaluate, $($message)*)
        } else if !($evaluate) {
            log::error!($($message)*);
        }
    };
}

/// Conditional assertion that calls `unimplemented!()` on failure.
///
/// When `ENABLE_ASSERT` environment variable is set to "1" and the condition is false,
/// this macro exits the process with a colorized error message. When assertions are disabled
/// and the condition is false, it calls `unimplemented!()` with a colorized message instead.
///
/// # Environment Variables
///
/// * `ENABLE_ASSERT` - Set to "1" to enable assertions, any other value disables them
///
/// # Examples
///
/// ```rust,no_run
/// use moosicbox_assert::assert_or_unimplemented;
///
/// fn experimental_feature(enabled: bool) {
///     assert_or_unimplemented!(enabled, "Feature not yet implemented");
///     println!("Running experimental feature");
/// }
/// ```
///
/// # Panics
///
/// * Exits the process when the condition is false and `ENABLE_ASSERT=1`
/// * Calls `unimplemented!()` when the condition is false and assertions are disabled
#[macro_export]
macro_rules! assert_or_unimplemented {
    ($evaluate:expr, $(,)?) => {
        let success = ($evaluate);
        if $crate::moosicbox_env_utils::default_env!("ENABLE_ASSERT", "false") == "1"
            && !success
        {
            $crate::assert!(success)
        } else if !success {
            unimplemented!(
                "{}",
                $crate::Colorize::on_red($crate::Colorize::white($crate::Colorize::bold(
                    format!(
                        "{}\n{}",
                        $crate::Colorize::underline(format!($($message)*).as_str()),
                        std::backtrace::Backtrace::force_capture()
                    )
                    .as_str()
                )))
            );
        }
    };
    ($evaluate:expr, $($message:tt)+) => {
        let success = ($evaluate);
        if $crate::moosicbox_env_utils::default_env!("ENABLE_ASSERT", "false") == "1"
            && !success
        {
            $crate::assert!(success, $($message)*)
        } else if !success {
            unimplemented!(
                "{}",
                $crate::Colorize::on_red($crate::Colorize::white($crate::Colorize::bold(
                    format!(
                        "{}\n{}",
                        $crate::Colorize::underline(format!($($message)*).as_str()),
                        std::backtrace::Backtrace::force_capture()
                    )
                    .as_str()
                )))
            );
        }
    };
}

/// Conditional assertion that panics on failure.
///
/// When `ENABLE_ASSERT` environment variable is set to "1" and the condition is false,
/// this macro exits the process with a colorized error message. When assertions are disabled
/// and the condition is false, it panics with a colorized message instead.
///
/// # Environment Variables
///
/// * `ENABLE_ASSERT` - Set to "1" to enable assertions, any other value disables them
///
/// # Examples
///
/// ```rust,no_run
/// use moosicbox_assert::assert_or_panic;
///
/// fn critical_operation(value: i32) {
///     assert_or_panic!(value > 0, "Value must be positive, got {}", value);
/// }
/// ```
///
/// # Panics
///
/// * Exits the process when the condition is false and `ENABLE_ASSERT=1`
/// * Panics when the condition is false and assertions are disabled
#[macro_export]
macro_rules! assert_or_panic {
    ($evaluate:expr, $(,)?) => {{
        let success = ($evaluate);
        if $crate::moosicbox_env_utils::default_env!("ENABLE_ASSERT", "false") == "1"
            && !success
        {
            $crate::assert!(success)
        } else if !success {
            panic!(
                "{}",
                $crate::Colorize::on_red($crate::Colorize::white($crate::Colorize::bold(
                    format!(
                        "{}\n{}",
                        $crate::Colorize::underline(format!($($message)*).as_str()),
                        std::backtrace::Backtrace::force_capture()
                    )
                    .as_str()
                )))
            );
        }
    }};
    ($evaluate:expr, $($message:tt)+) => {{
        let success = ($evaluate);
        if $crate::moosicbox_env_utils::default_env!("ENABLE_ASSERT", "false") == "1"
            && !success
        {
            $crate::assert!(success, $($message)*)
        } else if !success {
            panic!(
                "{}",
                $crate::Colorize::on_red($crate::Colorize::white($crate::Colorize::bold(
                    format!(
                        "{}\n{}",
                        $crate::Colorize::underline(format!($($message)*).as_str()),
                        std::backtrace::Backtrace::force_capture()
                    )
                    .as_str()
                )))
            );
        }
    }};
}

/// Unconditionally exits the process when assertions are enabled.
///
/// When `ENABLE_ASSERT` environment variable is set to "1", this macro exits the process
/// with a colorized error message and stack trace. When assertions are disabled,
/// this macro becomes a no-op.
///
/// # Environment Variables
///
/// * `ENABLE_ASSERT` - Set to "1" to enable assertions, any other value disables them
///
/// # Examples
///
/// ```rust,no_run
/// use moosicbox_assert::die;
///
/// fn check_value(value: i32) {
///     if value < 0 {
///         die!("Value cannot be negative: {}", value);
///     }
/// }
/// ```
///
/// # Panics
///
/// Exits the process (via `std::process::exit(1)`) when `ENABLE_ASSERT=1`.
#[macro_export]
macro_rules! die {
    () => {
        if $crate::moosicbox_env_utils::default_env!("ENABLE_ASSERT", "false") == "1" {
            eprintln!(
                "{}",
                $crate::Colorize::on_red($crate::Colorize::white($crate::Colorize::bold(
                    format!("{}", std::backtrace::Backtrace::force_capture()).as_str()
                )))
            );
            log::logger().flush();
            std::process::exit(1);
        }
    };
    ($($message:tt)+) => {
        if $crate::moosicbox_env_utils::default_env!("ENABLE_ASSERT", "false") == "1" {
            eprintln!(
                "{}",
                $crate::Colorize::on_red($crate::Colorize::white($crate::Colorize::bold(
                    format!(
                        "{}\n{}",
                        $crate::Colorize::underline(format!($($message)*).as_str()),
                        std::backtrace::Backtrace::force_capture()
                    )
                    .as_str()
                )))
            );
            log::logger().flush();
            std::process::exit(1);
        }
    };
}

/// Exits the process or logs a warning depending on assertion mode.
///
/// When `ENABLE_ASSERT` environment variable is set to "1", this macro exits the process
/// with a colorized error message (red background). When assertions are disabled,
/// it logs a warning message with yellow background instead.
///
/// # Environment Variables
///
/// * `ENABLE_ASSERT` - Set to "1" to enable assertions, any other value disables them
///
/// # Examples
///
/// ```rust,no_run
/// use moosicbox_assert::die_or_warn;
///
/// fn deprecated_function() {
///     die_or_warn!("This function is deprecated and will be removed");
/// }
/// ```
///
/// # Panics
///
/// Exits the process when `ENABLE_ASSERT=1`.
#[macro_export]
macro_rules! die_or_warn {
    ($($message:tt)+) => {
        if $crate::moosicbox_env_utils::default_env!("ENABLE_ASSERT", "false") == "1" {
            eprintln!(
                "{}",
                $crate::Colorize::on_yellow($crate::Colorize::white($crate::Colorize::bold(
                    format!(
                        "{}\n{}",
                        $crate::Colorize::underline(format!($($message)*).as_str()),
                        std::backtrace::Backtrace::force_capture()
                    )
                    .as_str()
                )))
            );
            log::logger().flush();
            std::process::exit(1);
        } else {
            log::warn!(
                "{}",
                $crate::Colorize::on_yellow($crate::Colorize::white($crate::Colorize::bold(
                    format!(
                        "{}\n{}",
                        $crate::Colorize::underline(format!($($message)*).as_str()),
                        std::backtrace::Backtrace::force_capture()
                    )
                    .as_str()
                )))
            );
        }
    };
}

/// Exits the process or returns an error depending on assertion mode.
///
/// When `ENABLE_ASSERT` environment variable is set to "1", this macro exits the process
/// with a colorized error message. When assertions are disabled, it returns the specified
/// error value instead.
///
/// # Environment Variables
///
/// * `ENABLE_ASSERT` - Set to "1" to enable assertions, any other value disables them
///
/// # Examples
///
/// ```rust,no_run
/// use moosicbox_assert::die_or_err;
///
/// #[derive(Debug)]
/// enum MyError {
///     Fatal,
/// }
///
/// fn critical_check() -> Result<(), MyError> {
///     die_or_err!(MyError::Fatal, "Critical condition failed");
/// }
/// ```
///
/// # Errors
///
/// * Returns the specified error when `ENABLE_ASSERT` is not "1".
///
/// # Panics
///
/// Exits the process when `ENABLE_ASSERT=1`.
#[macro_export]
macro_rules! die_or_err {
    ($err:expr, $($message:tt)+) => {
        if $crate::moosicbox_env_utils::default_env!("ENABLE_ASSERT", "false") == "1"
        {
            $crate::die!($($message)*);
            unreachable!();
        } else {
            return Err($err);
        }
    };
}

/// Exits the process or logs an error depending on assertion mode.
///
/// When `ENABLE_ASSERT` environment variable is set to "1", this macro exits the process
/// with a colorized error message. When assertions are disabled, it logs an error message
/// with red background instead using the `log` crate.
///
/// # Environment Variables
///
/// * `ENABLE_ASSERT` - Set to "1" to enable assertions, any other value disables them
///
/// # Examples
///
/// ```rust,no_run
/// use moosicbox_assert::die_or_error;
///
/// fn check_invariant(valid: bool) {
///     if !valid {
///         die_or_error!("Invariant violation detected");
///     }
/// }
/// ```
///
/// # Panics
///
/// Exits the process when `ENABLE_ASSERT=1`.
#[macro_export]
macro_rules! die_or_error {
    ($($message:tt)+) => {
        if $crate::moosicbox_env_utils::default_env!("ENABLE_ASSERT", "false") == "1" {
            eprintln!(
                "{}",
                $crate::Colorize::on_red($crate::Colorize::white($crate::Colorize::bold(
                    format!(
                        "{}\n{}",
                        $crate::Colorize::underline(format!($($message)*).as_str()),
                        std::backtrace::Backtrace::force_capture()
                    )
                    .as_str()
                )))
            );
            log::logger().flush();
            std::process::exit(1);
        } else {
            log::error!(
                "{}",
                $crate::Colorize::on_red($crate::Colorize::white($crate::Colorize::bold(
                    format!(
                        "{}\n{}",
                        $crate::Colorize::underline(format!($($message)*).as_str()),
                        std::backtrace::Backtrace::force_capture()
                    )
                    .as_str()
                )))
            );
        }
    };
}

/// Exits the process or propagates an error depending on assertion mode.
///
/// When `ENABLE_ASSERT` environment variable is set to "1" and the result is an error,
/// this macro exits the process with a colorized error message. When assertions are disabled,
/// it propagates the error using the `?` operator instead.
///
/// # Environment Variables
///
/// * `ENABLE_ASSERT` - Set to "1" to enable assertions, any other value disables them
///
/// # Examples
///
/// ```rust,no_run
/// use moosicbox_assert::die_or_propagate;
///
/// fn process_result() -> Result<(), String> {
///     die_or_propagate!(Ok::<(), String>(()), "Failed to process");
///     Ok(())
/// }
/// ```
///
/// # Errors
///
/// * Propagates the error from the evaluated `Result` when it is `Err` and `ENABLE_ASSERT` is not
///   "1".
///
/// # Panics
///
/// Exits the process when the result is `Err` and `ENABLE_ASSERT=1`.
#[macro_export]
macro_rules! die_or_propagate {
    ($evaluate:expr, $($message:tt)+) => {
        if $crate::moosicbox_env_utils::default_env!("ENABLE_ASSERT", "false") == "1" {
            match $evaluate {
                Ok(x) => x,
                Err(e) => $crate::die!($($message)*),
            }
        } else {
            $evaluate?
        }
    };

    ($evaluate:expr $(,)?) => {
        if $crate::moosicbox_env_utils::default_env!("ENABLE_ASSERT", "false") == "1" {
            match $evaluate {
                Ok(x) => x,
                Err(_e) => $crate::die!(),
            }
        } else {
            $evaluate?
        }
    };
}

/// Exits the process or panics depending on assertion mode.
///
/// When `ENABLE_ASSERT` environment variable is set to "1", this macro exits the process
/// with a colorized error message. When assertions are disabled, it panics with a
/// colorized message instead.
///
/// # Environment Variables
///
/// * `ENABLE_ASSERT` - Set to "1" to enable assertions, any other value disables them
///
/// # Examples
///
/// ```rust,no_run
/// use moosicbox_assert::die_or_panic;
///
/// fn critical_failure() {
///     die_or_panic!("Unrecoverable error occurred");
/// }
/// ```
///
/// # Panics
///
/// * Exits the process when `ENABLE_ASSERT=1`
/// * Panics when assertions are disabled
#[macro_export]
macro_rules! die_or_panic {
    ($($message:tt)+) => {
        if $crate::moosicbox_env_utils::default_env!("ENABLE_ASSERT", "false") == "1" {
            eprintln!(
                "{}",
                $crate::Colorize::on_red($crate::Colorize::white($crate::Colorize::bold(
                    format!(
                        "{}\n{}",
                        $crate::Colorize::underline(format!($($message)*).as_str()),
                        std::backtrace::Backtrace::force_capture()
                    )
                    .as_str()
                )))
            );
            log::logger().flush();
            std::process::exit(1);
        } else {
            panic!(
                "{}",
                $crate::Colorize::on_red($crate::Colorize::white($crate::Colorize::bold(
                    format!(
                        "{}\n{}",
                        $crate::Colorize::underline(format!($($message)*).as_str()),
                        std::backtrace::Backtrace::force_capture()
                    )
                    .as_str()
                )))
            );
        }
    };
}

/// Exits the process or calls `unimplemented!()` depending on assertion mode.
///
/// When `ENABLE_ASSERT` environment variable is set to "1", this macro exits the process
/// with a colorized error message. When assertions are disabled, it calls `unimplemented!()`
/// with a colorized message instead.
///
/// # Environment Variables
///
/// * `ENABLE_ASSERT` - Set to "1" to enable assertions, any other value disables them
///
/// # Examples
///
/// ```rust,no_run
/// use moosicbox_assert::die_or_unimplemented;
///
/// fn not_ready_yet() {
///     die_or_unimplemented!("This code path is not implemented");
/// }
/// ```
///
/// # Panics
///
/// * Exits the process when `ENABLE_ASSERT=1`
/// * Calls `unimplemented!()` when assertions are disabled
#[macro_export]
macro_rules! die_or_unimplemented {
    ($($message:tt)+) => {
        if $crate::moosicbox_env_utils::default_env!("ENABLE_ASSERT", "false") == "1" {
            eprintln!(
                "{}",
                $crate::Colorize::on_red($crate::Colorize::white($crate::Colorize::bold(
                    format!(
                        "{}\n{}",
                        $crate::Colorize::underline(format!($($message)*).as_str()),
                        std::backtrace::Backtrace::force_capture()
                    )
                    .as_str()
                )))
            );
            log::logger().flush();
            std::process::exit(1);
        } else {
            unimplemented!(
                "{}",
                $crate::Colorize::on_red($crate::Colorize::white($crate::Colorize::bold(
                    format!(
                        "{}\n{}",
                        $crate::Colorize::underline(format!($($message)*).as_str()),
                        std::backtrace::Backtrace::force_capture()
                    )
                    .as_str()
                )))
            );
        }
    };
}

#[cfg(test)]
mod tests {

    #[derive(Debug, PartialEq)]
    enum TestError {
        InvalidValue,
        Critical,
    }

    // Test assert! macro with ENABLE_ASSERT disabled (no-op)
    #[test_log::test]
    fn test_assert_disabled_no_op() {
        unsafe { std::env::set_var("ENABLE_ASSERT", "0") };
        // Should not exit or do anything when condition is false
        crate::assert!(false);
        crate::assert!(false, "this message should not appear");
    }

    #[test_log::test]
    fn test_assert_disabled_with_true_condition() {
        unsafe { std::env::set_var("ENABLE_ASSERT", "0") };
        crate::assert!(true);
        crate::assert!(true, "condition is true");
    }

    // Test assert_or_err! macro with ENABLE_ASSERT disabled
    #[test_log::test]
    #[allow(clippy::items_after_statements)]
    fn test_assert_or_err_returns_error_when_disabled() {
        unsafe { std::env::set_var("ENABLE_ASSERT", "0") };

        fn test_function(value: i32) -> Result<i32, TestError> {
            crate::assert_or_err!(value >= 0, TestError::InvalidValue,);
            Ok(value * 2)
        }

        let result = test_function(-5);
        assert_eq!(result, Err(TestError::InvalidValue));
    }

    #[test_log::test]
    #[allow(clippy::items_after_statements)]
    fn test_assert_or_err_succeeds_with_true_condition() {
        unsafe { std::env::set_var("ENABLE_ASSERT", "0") };

        fn test_function(value: i32) -> Result<i32, TestError> {
            crate::assert_or_err!(value >= 0, TestError::InvalidValue, "value was {}", value);
            Ok(value * 2)
        }

        let result = test_function(5);
        assert_eq!(result, Ok(10));
    }

    #[test_log::test]
    #[allow(clippy::items_after_statements)]
    fn test_assert_or_err_with_message() {
        unsafe { std::env::set_var("ENABLE_ASSERT", "0") };

        fn test_function(value: i32) -> Result<i32, TestError> {
            crate::assert_or_err!(
                value <= 100,
                TestError::InvalidValue,
                "Value {} exceeds maximum",
                value
            );
            Ok(value)
        }

        let result = test_function(150);
        assert_eq!(result, Err(TestError::InvalidValue));
    }

    // Test assert_or_error! macro with ENABLE_ASSERT disabled
    #[test_log::test]
    fn test_assert_or_error_logs_when_disabled() {
        unsafe { std::env::set_var("ENABLE_ASSERT", "0") };

        // This should log an error but not exit
        crate::assert_or_error!(false, "This is a test error message");

        // With formatting
        let value = 42;
        crate::assert_or_error!(false, "Value is {}", value);
    }

    #[test_log::test]
    fn test_assert_or_error_succeeds_with_true_condition() {
        unsafe { std::env::set_var("ENABLE_ASSERT", "0") };
        crate::assert_or_error!(true, "This should not log");
    }

    // Test assert_or_panic! macro with ENABLE_ASSERT disabled
    #[test_log::test]
    #[should_panic(expected = "Expected panic message")]
    fn test_assert_or_panic_panics_when_disabled() {
        unsafe { std::env::set_var("ENABLE_ASSERT", "0") };
        crate::assert_or_panic!(false, "Expected panic message");
    }

    #[test_log::test]
    fn test_assert_or_panic_succeeds_with_true_condition() {
        unsafe { std::env::set_var("ENABLE_ASSERT", "0") };
        crate::assert_or_panic!(true, "Should not panic");
    }

    // Test assert_or_unimplemented! macro with ENABLE_ASSERT disabled
    #[test_log::test]
    #[should_panic(expected = "not implemented")]
    fn test_assert_or_unimplemented_calls_unimplemented_when_disabled() {
        unsafe { std::env::set_var("ENABLE_ASSERT", "0") };
        crate::assert_or_unimplemented!(false, "Feature not implemented");
    }

    #[test_log::test]
    fn test_assert_or_unimplemented_succeeds_with_true_condition() {
        unsafe { std::env::set_var("ENABLE_ASSERT", "0") };
        crate::assert_or_unimplemented!(true, "Should not call unimplemented");
    }

    // Test die! macro with ENABLE_ASSERT disabled (no-op)
    #[test_log::test]
    fn test_die_disabled_no_op() {
        unsafe { std::env::set_var("ENABLE_ASSERT", "0") };
        crate::die!();
        crate::die!("This message should not exit");
    }

    // Test die_or_err! macro with ENABLE_ASSERT disabled
    #[test_log::test]
    #[allow(clippy::items_after_statements)]
    fn test_die_or_err_returns_error_when_disabled() {
        unsafe { std::env::set_var("ENABLE_ASSERT", "0") };

        fn test_function() -> Result<(), TestError> {
            crate::die_or_err!(TestError::Critical, "Critical failure");
        }

        let result = test_function();
        assert_eq!(result, Err(TestError::Critical));
    }

    #[test_log::test]
    #[allow(clippy::items_after_statements)]
    fn test_die_or_err_with_formatting() {
        unsafe { std::env::set_var("ENABLE_ASSERT", "0") };

        fn test_function(code: i32) -> Result<(), TestError> {
            crate::die_or_err!(TestError::Critical, "Error code: {}", code);
        }

        let result = test_function(500);
        assert_eq!(result, Err(TestError::Critical));
    }

    // Test die_or_error! macro with ENABLE_ASSERT disabled
    #[test_log::test]
    fn test_die_or_error_logs_when_disabled() {
        unsafe { std::env::set_var("ENABLE_ASSERT", "0") };
        crate::die_or_error!("This is a critical error");
        crate::die_or_error!("Error with value: {}", 42);
    }

    // Test die_or_warn! macro with ENABLE_ASSERT disabled
    #[test_log::test]
    fn test_die_or_warn_logs_warning_when_disabled() {
        unsafe { std::env::set_var("ENABLE_ASSERT", "0") };
        crate::die_or_warn!("This is a warning");
        crate::die_or_warn!("Warning with value: {}", 100);
    }

    // Test die_or_panic! macro with ENABLE_ASSERT disabled
    #[test_log::test]
    #[should_panic(expected = "Expected panic")]
    fn test_die_or_panic_panics_when_disabled() {
        unsafe { std::env::set_var("ENABLE_ASSERT", "0") };
        crate::die_or_panic!("Expected panic");
    }

    #[test_log::test]
    #[should_panic(expected = "Panic with code: 404")]
    fn test_die_or_panic_with_formatting() {
        unsafe { std::env::set_var("ENABLE_ASSERT", "0") };
        crate::die_or_panic!("Panic with code: {}", 404);
    }

    // Test die_or_unimplemented! macro with ENABLE_ASSERT disabled
    #[test_log::test]
    #[should_panic(expected = "not implemented")]
    fn test_die_or_unimplemented_calls_unimplemented_when_disabled() {
        unsafe { std::env::set_var("ENABLE_ASSERT", "0") };
        crate::die_or_unimplemented!("Not implemented yet");
    }

    // Note: die_or_propagate! tests omitted due to macro expansion issues with std::process::exit
    // The macro works correctly at runtime but has type-checking issues during test compilation
    // when the ENABLE_ASSERT=1 branch is analyzed. Since we can't test the exit path anyway,
    // and the macro is tested through actual usage, we skip these tests.

    // Test with complex expressions and side effects
    #[test_log::test]
    fn test_assert_with_side_effects() {
        unsafe { std::env::set_var("ENABLE_ASSERT", "0") };
        let mut counter = 0;

        // When disabled, the expression should NOT be evaluated
        crate::assert!({
            counter += 1;
            false
        });

        // Counter should remain 0 since assertion is disabled
        assert_eq!(counter, 0);
    }

    #[test_log::test]
    #[allow(clippy::items_after_statements)]
    fn test_assert_or_err_with_complex_error_types() {
        unsafe { std::env::set_var("ENABLE_ASSERT", "0") };

        #[derive(Debug, PartialEq)]
        struct ComplexError {
            code: i32,
            message: String,
        }

        fn test_function() -> Result<(), ComplexError> {
            crate::assert_or_err!(
                false,
                ComplexError {
                    code: 42,
                    message: "test error".to_string()
                },
                "Complex error test"
            );
            Ok(())
        }

        let result = test_function();
        assert!(result.is_err());
        if let Err(e) = result {
            assert_eq!(e.code, 42);
            assert_eq!(e.message, "test error");
        }
    }

    // Test macro hygiene - ensure macros work with different imports
    #[test_log::test]
    #[allow(clippy::items_after_statements)]
    fn test_macro_works_without_explicit_imports() {
        unsafe { std::env::set_var("ENABLE_ASSERT", "0") };

        fn test_function() -> Result<(), TestError> {
            crate::assert_or_err!(true, TestError::InvalidValue,);
            Ok(())
        }

        assert_eq!(test_function(), Ok(()));
    }

    // Test with trailing commas
    #[test_log::test]
    fn test_assert_with_trailing_comma() {
        unsafe { std::env::set_var("ENABLE_ASSERT", "0") };
        crate::assert!(true,);
    }

    #[test_log::test]
    #[allow(clippy::items_after_statements)]
    fn test_assert_or_err_with_trailing_comma() {
        unsafe { std::env::set_var("ENABLE_ASSERT", "0") };

        fn test_function() -> Result<(), TestError> {
            crate::assert_or_err!(true, TestError::InvalidValue,);
            Ok(())
        }

        assert_eq!(test_function(), Ok(()));
    }

    // Test multiple consecutive assertions
    #[test_log::test]
    #[allow(clippy::items_after_statements)]
    fn test_multiple_assert_or_err_in_sequence() {
        unsafe { std::env::set_var("ENABLE_ASSERT", "0") };

        fn test_function(a: i32, b: i32) -> Result<i32, TestError> {
            crate::assert_or_err!(a >= 0, TestError::InvalidValue, "a must be non-negative");
            crate::assert_or_err!(b >= 0, TestError::InvalidValue, "b must be non-negative");
            crate::assert_or_err!(a + b <= 100, TestError::InvalidValue, "sum too large");
            Ok(a + b)
        }

        // Should pass all assertions
        assert_eq!(test_function(10, 20), Ok(30));

        // Should fail first assertion
        assert_eq!(test_function(-1, 20), Err(TestError::InvalidValue));

        // Should fail second assertion
        assert_eq!(test_function(10, -1), Err(TestError::InvalidValue));

        // Should fail third assertion
        assert_eq!(test_function(60, 50), Err(TestError::InvalidValue));
    }
}