tanu-core 0.20.2

The core component of tanu-rs
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
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
//! # Test Runner Module
//!
//! The core test execution engine for tanu. This module provides the `Runner` struct
//! that orchestrates test discovery, execution, filtering, reporting, and event publishing.
//! It supports concurrent test execution with retry capabilities and comprehensive
//! event-driven reporting.
//!
//! ## Key Components
//!
//! - **`Runner`**: Main test execution engine
//! - **Event System**: Real-time test execution events via channels
//! - **Filtering**: Project, module, and test name filtering
//! - **Reporting**: Pluggable reporter system for test output
//! - **Retry Logic**: Configurable retry with exponential backoff
//!
//! ## Execution Flow (block diagram)
//!
//! ```text
//! +-------------------+     +-------------------+     +---------------------+
//! | Test registry     | --> | Filter chain      | --> | Semaphore           |
//! | add_test()        |     | project/module    |     | (concurrency ctrl)  |
//! +-------------------+     | test name/ignore  |     +---------------------+
//!                           +-------------------+               |
//!                                                               v
//!                                                     +---------------------+
//!                                                     | Tokio task spawn    |
//!                                                     | + task-local ctx    |
//!                                                     +---------------------+
//!                                                               |
//!                                                               v
//!                                                     +---------------------+
//!                                                     | Test execution      |
//!                                                     | + panic recovery    |
//!                                                     | + retry/backoff     |
//!                                                     +---------------------+
//!                                                               |
//!          +----------------------------------------------------+
//!          v
//! +-------------------+     +-------------------+     +-------------------+
//! | Event channel     | --> | Broadcast to all  | --> | Reporter(s)       |
//! | Start/Check/HTTP  |     | subscribers       |     | List/Table/Null   |
//! | Retry/End/Summary |     |                   |     | (format output)   |
//! +-------------------+     +-------------------+     +-------------------+
//! ```
//!
//! ## Basic Usage
//!
//! ```rust,ignore
//! use tanu_core::Runner;
//!
//! let mut runner = Runner::new();
//! runner.add_test("my_test", "my_module", None, test_factory);
//! runner.run(&[], &[], &[]).await?;
//! ```
use backon::Retryable;
use eyre::WrapErr;
use futures::{stream::FuturesUnordered, FutureExt, StreamExt};
use itertools::Itertools;
use once_cell::sync::Lazy;
use std::{
    collections::HashMap,
    ops::Deref,
    pin::Pin,
    sync::{
        atomic::{AtomicBool, AtomicUsize, Ordering},
        Arc, Mutex,
    },
    time::{Duration, SystemTime},
};
use tokio::sync::broadcast;
use tracing::*;

use crate::{
    config::{self, get_tanu_config, CaptureHttpMode, ProjectConfig},
    http,
    reporter::Reporter,
    Config, ModuleName, ProjectName,
};

tokio::task_local! {
    pub(crate) static TEST_INFO: Arc<TestInfo>;
}

pub(crate) fn get_test_info() -> Arc<TestInfo> {
    TEST_INFO.with(Arc::clone)
}

/// Runs a future in the current tanu test context (project + test info), if any.
///
/// This is useful when spawning additional Tokio tasks (e.g. via `tokio::spawn`/`JoinSet`)
/// from inside a `#[tanu::test]`, because Tokio task-locals are not propagated
/// automatically.
pub fn scope_current<F>(fut: F) -> impl std::future::Future<Output = F::Output> + Send
where
    F: std::future::Future + Send,
    F::Output: Send,
{
    let project = crate::config::PROJECT.try_with(Arc::clone).ok();
    let test_info = TEST_INFO.try_with(Arc::clone).ok();

    async move {
        match (project, test_info) {
            (Some(project), Some(test_info)) => {
                crate::config::PROJECT
                    .scope(project, TEST_INFO.scope(test_info, fut))
                    .await
            }
            (Some(project), None) => crate::config::PROJECT.scope(project, fut).await,
            (None, Some(test_info)) => TEST_INFO.scope(test_info, fut).await,
            (None, None) => fut.await,
        }
    }
}

// NOTE: Keep the runner receiver alive here so that sender never fails to send.
#[allow(clippy::type_complexity)]
pub(crate) static CHANNEL: Lazy<
    Mutex<Option<(broadcast::Sender<Event>, broadcast::Receiver<Event>)>>,
> = Lazy::new(|| Mutex::new(Some(broadcast::channel(1000))));

/// Barrier to synchronize reporter subscription before test execution starts.
/// This prevents the race condition where tests publish events before reporters subscribe.
pub(crate) static REPORTER_BARRIER: Lazy<Mutex<Option<Arc<tokio::sync::Barrier>>>> =
    Lazy::new(|| Mutex::new(None));

/// Publishes an event to the runner's event channel.
///
/// This function is used throughout the test execution pipeline to broadcast
/// real-time events including test starts, check results, HTTP logs, retries,
/// and test completions. All events are timestamped and include test context.
///
/// # Examples
///
/// ```rust,ignore
/// use tanu_core::runner::{publish, EventBody, Check};
///
/// // Publish a successful check
/// let check = Check::success("response.status() == 200");
/// publish(EventBody::Check(Box::new(check)))?;
///
/// // Publish test start
/// publish(EventBody::Start)?;
/// ```
///
/// # Errors
///
/// Returns an error if:
/// - The channel lock cannot be acquired
/// - The channel has been closed
/// - The send operation fails
pub fn publish(e: impl Into<Event>) -> eyre::Result<()> {
    let Ok(guard) = CHANNEL.lock() else {
        eyre::bail!("failed to acquire runner channel lock");
    };
    let Some((tx, _)) = guard.deref() else {
        eyre::bail!("runner channel has been already closed");
    };

    tx.send(e.into())
        .wrap_err("failed to publish message to the runner channel")?;

    Ok(())
}

/// Subscribe to the channel to see the real-time test execution events.
pub fn subscribe() -> eyre::Result<broadcast::Receiver<Event>> {
    let Ok(guard) = CHANNEL.lock() else {
        eyre::bail!("failed to acquire runner channel lock");
    };
    let Some((tx, _)) = guard.deref() else {
        eyre::bail!("runner channel has been already closed");
    };

    Ok(tx.subscribe())
}

/// Set up barrier for N reporters (called before spawning reporters).
///
/// This ensures all reporters subscribe before tests start executing,
/// preventing the race condition where Start events are published before
/// reporters are ready to receive them.
pub(crate) fn setup_reporter_barrier(count: usize) -> eyre::Result<()> {
    let Ok(mut barrier) = REPORTER_BARRIER.lock() else {
        eyre::bail!("failed to acquire reporter barrier lock");
    };
    *barrier = Some(Arc::new(tokio::sync::Barrier::new(count + 1)));
    Ok(())
}

/// Wait on barrier (called by reporters after subscribing, and by runner before tests).
///
/// If no barrier is set (standalone reporter use), this is a no-op.
pub(crate) async fn wait_reporter_barrier() {
    let barrier = match REPORTER_BARRIER.lock() {
        Ok(guard) => guard.clone(),
        Err(e) => {
            error!("failed to acquire reporter barrier lock (poisoned): {e}");
            return;
        }
    };

    if let Some(b) = barrier {
        b.wait().await;
    }
}

async fn execute_test(
    project: Arc<ProjectConfig>,
    info: Arc<TestInfo>,
    factory: TestCaseFactory,
    serial_mutex: Option<Arc<tokio::sync::Mutex<()>>>,
    worker_id: isize,
) -> eyre::Result<Test> {
    let project_for_scope = Arc::clone(&project);
    let info_for_scope = Arc::clone(&info);
    config::PROJECT
        .scope(project_for_scope, async {
            TEST_INFO
                .scope(info_for_scope, async {
                    let test_name = info.name.clone();
                    publish(EventBody::Start)?;

                    let retry_count = AtomicUsize::new(project.retry.count.unwrap_or(0));
                    let serial_mutex_clone = serial_mutex.clone();
                    let f = || async {
                        // Acquire serial guard just before test execution
                        let _serial_guard = if let Some(ref mutex) = serial_mutex_clone {
                            Some(mutex.lock().await)
                        } else {
                            None
                        };

                        let started_at = SystemTime::now();
                        let request_started = std::time::Instant::now();
                        let res = factory().await;
                        let ended_at = SystemTime::now();

                        if res.is_err() && retry_count.load(Ordering::SeqCst) > 0 {
                            let test_result = match &res {
                                Ok(_) => Ok(()),
                                Err(e) => Err(Error::ErrorReturned(format!("{e:?}"))),
                            };
                            let test = Test {
                                result: test_result,
                                info: Arc::clone(&info),
                                worker_id,
                                started_at,
                                ended_at,
                                request_time: request_started.elapsed(),
                            };
                            publish(EventBody::Retry(test))?;
                            retry_count.fetch_sub(1, Ordering::SeqCst);
                        };
                        res
                    };
                    let started_at = SystemTime::now();
                    let started = std::time::Instant::now();
                    let fut = f.retry(project.retry.backoff());
                    let fut = std::panic::AssertUnwindSafe(fut).catch_unwind();
                    let res = fut.await;
                    let request_time = started.elapsed();
                    let ended_at = SystemTime::now();

                    let result = match res {
                        Ok(Ok(_)) => {
                            debug!("{test_name} ok");
                            Ok(())
                        }
                        Ok(Err(e)) => {
                            debug!("{test_name} failed: {e:#}");
                            Err(Error::ErrorReturned(format!("{e:?}")))
                        }
                        Err(e) => {
                            let panic_message =
                                if let Some(panic_message) = e.downcast_ref::<&str>() {
                                    format!("{test_name} failed with message: {panic_message}")
                                } else if let Some(panic_message) = e.downcast_ref::<String>() {
                                    format!("{test_name} failed with message: {panic_message}")
                                } else {
                                    format!("{test_name} failed with unknown message")
                                };
                            let e = eyre::eyre!(panic_message);
                            Err(Error::Panicked(format!("{e:?}")))
                        }
                    };

                    let test = Test {
                        result,
                        info: Arc::clone(&info),
                        worker_id,
                        started_at,
                        ended_at,
                        request_time,
                    };

                    publish(EventBody::End(test.clone()))?;

                    eyre::Ok(test)
                })
                .await
        })
        .await
}

/// Clear barrier after use.
pub(crate) fn clear_reporter_barrier() {
    match REPORTER_BARRIER.lock() {
        Ok(mut barrier) => {
            *barrier = None;
        }
        Err(e) => {
            error!("failed to clear reporter barrier (poisoned lock): {e}");
        }
    }
}

/// Test execution errors.
///
/// Represents the different ways a test can fail during execution.
/// These errors are captured and reported by the runner system.
#[derive(Debug, Clone, thiserror::Error)]
pub enum Error {
    #[error("panic: {0}")]
    Panicked(String),
    #[error("error: {0}")]
    ErrorReturned(String),
}

/// Represents the result of a check/assertion within a test.
///
/// Checks are created by assertion macros (`check!`, `check_eq!`, etc.) and
/// track both the success/failure status and the original expression that
/// was evaluated. This information is used for detailed test reporting.
///
/// # Examples
///
/// ```rust,ignore
/// use tanu_core::runner::Check;
///
/// // Create a successful check
/// let check = Check::success("response.status() == 200");
/// assert!(check.result);
///
/// // Create a failed check
/// let check = Check::error("user_count != 0");
/// assert!(!check.result);
/// ```
#[derive(Debug, Clone)]
pub struct Check {
    pub result: bool,
    pub expr: String,
}

impl Check {
    pub fn success(expr: impl Into<String>) -> Check {
        Check {
            result: true,
            expr: expr.into(),
        }
    }

    pub fn error(expr: impl Into<String>) -> Check {
        Check {
            result: false,
            expr: expr.into(),
        }
    }
}

/// A test execution event with full context.
///
/// Events are published throughout test execution and include the project,
/// module, and test name for complete traceability. The event body contains
/// the specific event data (start, check, HTTP, retry, or end).
///
/// # Event Flow
///
/// 1. `Start` - Test begins execution
/// 2. `Check` - Assertion results (can be multiple per test)
/// 3. `Http` - HTTP request/response logs (can be multiple per test)
/// 4. `Retry` - Test retry attempts (if configured)
/// 5. `End` - Test completion with final result
#[derive(Debug, Clone)]
pub struct Event {
    pub project: ProjectName,
    pub module: ModuleName,
    pub test: ModuleName,
    pub body: EventBody,
}

/// The specific event data published during test execution.
///
/// Each event type carries different information:
/// - `Start`: Signals test execution beginning
/// - `Check`: Contains assertion results with expression details
/// - `Call`: HTTP/gRPC request/response logs for debugging
/// - `Retry`: Indicates a test retry attempt
/// - `End`: Final test result with timing and outcome
/// - `Summary`: Overall test execution summary with counts and timing
///
/// A log from a call (HTTP, gRPC, etc.)
#[derive(Debug, Clone)]
pub enum CallLog {
    Http(Box<http::Log>),
    #[cfg(feature = "grpc")]
    Grpc(Box<crate::grpc::Log>),
}

#[derive(Debug, Clone)]
pub enum EventBody {
    Start,
    Check(Box<Check>),
    Call(CallLog),
    Retry(Test),
    End(Test),
    Summary(TestSummary),
}

impl From<EventBody> for Event {
    fn from(body: EventBody) -> Self {
        let project = crate::config::get_config();
        let test_info = crate::runner::get_test_info();
        Event {
            project: project.name.clone(),
            module: test_info.module.clone(),
            test: test_info.name.clone(),
            body,
        }
    }
}

/// Final test execution result.
///
/// Contains the complete outcome of a test execution including metadata,
/// execution time, and the final result (success or specific error type).
/// This is published in the `End` event when a test completes.
#[derive(Debug, Clone)]
pub struct Test {
    pub info: Arc<TestInfo>,
    pub worker_id: isize,
    pub started_at: SystemTime,
    pub ended_at: SystemTime,
    pub request_time: Duration,
    pub result: Result<(), Error>,
}

/// Overall test execution summary.
///
/// Contains aggregate information about the entire test run including
/// total counts, timing, and success/failure statistics.
/// This is published in the `Summary` event when all tests complete.
#[derive(Debug, Clone)]
pub struct TestSummary {
    pub total_tests: usize,
    pub passed_tests: usize,
    pub failed_tests: usize,
    pub skipped_tests: usize,
    pub total_time: Duration,
    pub test_prep_time: Duration,
}

/// Test metadata and identification.
///
/// Contains the module and test name for a test case. This information
/// is used for test filtering, reporting, and event context throughout
/// the test execution pipeline.
#[derive(Debug, Clone, Default)]
pub struct TestInfo {
    pub module: String,
    pub name: String,
    pub serial_group: Option<String>,
    pub line: u32,
    pub ordered: bool,
}

impl TestInfo {
    /// Full test name including module
    pub fn full_name(&self) -> String {
        format!("{}::{}", self.module, self.name)
    }

    /// Unique test name including project and module names
    pub fn unique_name(&self, project: &str) -> String {
        format!("{project}::{}::{}", self.module, self.name)
    }
}

/// Pool of reusable worker IDs for timeline visualization.
///
/// Worker IDs are assigned to tests when they start executing and returned
/// to the pool when they complete. This allows timeline visualization tools
/// to display tests in lanes based on which worker executed them.
#[derive(Debug)]
pub struct WorkerIds {
    enabled: bool,
    ids: Mutex<Vec<isize>>,
}

impl WorkerIds {
    /// Creates a new worker ID pool with IDs from 0 to concurrency-1.
    ///
    /// If `concurrency` is `None`, the pool is disabled and `acquire()` always returns -1.
    pub fn new(concurrency: Option<usize>) -> Self {
        match concurrency {
            Some(c) => Self {
                enabled: true,
                ids: Mutex::new((0..c as isize).collect()),
            },
            None => Self {
                enabled: false,
                ids: Mutex::new(Vec::new()),
            },
        }
    }

    /// Acquires a worker ID from the pool.
    ///
    /// Returns -1 if the pool is disabled, empty, or the mutex is poisoned.
    pub fn acquire(&self) -> isize {
        if !self.enabled {
            return -1;
        }
        self.ids
            .lock()
            .ok()
            .and_then(|mut guard| guard.pop())
            .unwrap_or(-1)
    }

    /// Returns a worker ID to the pool.
    ///
    /// Does nothing if the pool is disabled, the mutex is poisoned, or id is negative.
    pub fn release(&self, id: isize) {
        if !self.enabled || id < 0 {
            return;
        }
        if let Ok(mut guard) = self.ids.lock() {
            guard.push(id);
        }
    }
}

type TestCaseFactory = Arc<
    dyn Fn() -> Pin<Box<dyn futures::Future<Output = eyre::Result<()>> + Send + 'static>>
        + Sync
        + Send
        + 'static,
>;

/// Configuration options for test runner behavior.
///
/// Controls various aspects of test execution including logging,
/// concurrency, and channel management. These options can be set
/// via the builder pattern on the `Runner`.
///
/// # Examples
///
/// ```rust,ignore
/// use tanu_core::Runner;
///
/// let mut runner = Runner::new();
/// runner.capture_http(); // Enable HTTP logging
/// runner.set_concurrency(4); // Limit to 4 concurrent tests
/// ```
#[derive(Debug, Clone)]
pub struct Options {
    pub debug: bool,
    pub capture_http: CaptureHttpMode,
    pub capture_rust: bool,
    pub terminate_channel: bool,
    pub concurrency: Option<usize>,
    /// Whether to mask sensitive data (API keys, tokens) in HTTP logs.
    /// Defaults to `true` (masked). Set to `false` with `--show-sensitive` flag.
    pub mask_sensitive: bool,
    /// Whether to abort test execution after the first failure.
    pub fail_fast: bool,
}

impl Default for Options {
    fn default() -> Self {
        Self {
            debug: false,
            capture_http: CaptureHttpMode::Off,
            capture_rust: false,
            terminate_channel: false,
            concurrency: None,
            mask_sensitive: true, // Masked by default for security
            fail_fast: false,
        }
    }
}

/// Trait for filtering test cases during execution.
///
/// Filters allow selective test execution based on project configuration
/// and test metadata. Multiple filters can be applied simultaneously,
/// and a test must pass all filters to be executed.
///
/// # Examples
///
/// ```rust,ignore
/// use tanu_core::runner::{Filter, TestInfo, ProjectConfig};
///
/// struct CustomFilter;
///
/// impl Filter for CustomFilter {
///     fn filter(&self, project: &ProjectConfig, info: &TestInfo) -> bool {
///         // Only run tests with "integration" in the name
///         info.name.contains("integration")
///     }
/// }
/// ```
pub trait Filter {
    fn filter(&self, project: &ProjectConfig, info: &TestInfo) -> bool;
}

/// Filters tests to only run from specified projects.
///
/// When project names are provided, only tests from those projects
/// will be executed. If the list is empty, all projects are included.
///
/// # Examples
///
/// ```rust,ignore
/// use tanu_core::runner::ProjectFilter;
///
/// let filter = ProjectFilter { project_names: &["staging".to_string()] };
/// // Only tests from "staging" project will run
/// ```
pub struct ProjectFilter<'a> {
    project_names: &'a [String],
}

impl Filter for ProjectFilter<'_> {
    fn filter(&self, project: &ProjectConfig, _info: &TestInfo) -> bool {
        if self.project_names.is_empty() {
            return true;
        }

        self.project_names
            .iter()
            .any(|project_name| &project.name == project_name)
    }
}

/// Filters tests to only run from specified modules.
///
/// When module names are provided, only tests from those modules
/// will be executed. If the list is empty, all modules are included.
/// Module names correspond to Rust module paths.
///
/// # Examples
///
/// ```rust,ignore
/// use tanu_core::runner::ModuleFilter;
///
/// let filter = ModuleFilter { module_names: &["api".to_string(), "auth".to_string()] };
/// // Only tests from "api" and "auth" modules will run
/// ```
pub struct ModuleFilter<'a> {
    module_names: &'a [String],
}

impl Filter for ModuleFilter<'_> {
    fn filter(&self, _project: &ProjectConfig, info: &TestInfo) -> bool {
        if self.module_names.is_empty() {
            return true;
        }

        self.module_names
            .iter()
            .any(|module_name| &info.module == module_name)
    }
}

/// Filters tests to only run specific named tests.
///
/// When test names are provided, only those exact tests will be executed.
/// Test names should include the module (e.g., "api::health_check").
/// If the list is empty, all tests are included.
///
/// # Examples
///
/// ```rust,ignore
/// use tanu_core::runner::TestNameFilter;
///
/// let filter = TestNameFilter {
///     test_names: &["api::health_check".to_string(), "auth::login".to_string()]
/// };
/// // Only the specified tests will run
/// ```
pub struct TestNameFilter<'a> {
    test_names: &'a [String],
}

impl Filter for TestNameFilter<'_> {
    fn filter(&self, _project: &ProjectConfig, info: &TestInfo) -> bool {
        if self.test_names.is_empty() {
            return true;
        }

        self.test_names
            .iter()
            .any(|test_name| &info.full_name() == test_name)
    }
}

/// Filters out tests that are configured to be ignored.
///
/// This filter reads the `test_ignore` configuration from each project
/// and excludes those tests from execution. Tests are matched by their
/// full name (module::test_name).
///
/// # Configuration
///
/// In `tanu.toml`:
/// ```toml
/// [[projects]]
/// name = "staging"
/// test_ignore = ["flaky_test", "slow_integration_test"]
/// ```
///
/// # Examples
///
/// ```rust,ignore
/// use tanu_core::runner::TestIgnoreFilter;
///
/// let filter = TestIgnoreFilter::default();
/// // Tests listed in test_ignore config will be skipped
/// ```
pub struct TestIgnoreFilter {
    test_ignores: HashMap<String, Vec<String>>,
}

impl Default for TestIgnoreFilter {
    fn default() -> TestIgnoreFilter {
        TestIgnoreFilter {
            test_ignores: get_tanu_config()
                .projects
                .iter()
                .map(|proj| (proj.name.clone(), proj.test_ignore.clone()))
                .collect(),
        }
    }
}

impl Filter for TestIgnoreFilter {
    fn filter(&self, project: &ProjectConfig, info: &TestInfo) -> bool {
        let Some(test_ignore) = self.test_ignores.get(&project.name) else {
            return true;
        };

        test_ignore
            .iter()
            .all(|test_name| &info.full_name() != test_name)
    }
}

/// The main test execution engine for tanu.
///
/// `Runner` is responsible for orchestrating the entire test execution pipeline:
/// test discovery, filtering, concurrent execution, retry handling, event publishing,
/// and result reporting. It supports multiple projects, configurable concurrency,
/// and pluggable reporters.
///
/// # Features
///
/// - **Concurrent Execution**: Tests run in parallel with configurable limits
/// - **Retry Logic**: Automatic retry with exponential backoff for flaky tests
/// - **Event System**: Real-time event publishing for UI integration
/// - **Filtering**: Filter tests by project, module, or test name
/// - **Reporting**: Support for multiple output formats via reporters
/// - **HTTP Logging**: Capture and log all HTTP requests/responses
///
/// # Examples
///
/// ```rust,ignore
/// use tanu_core::{Runner, reporter::TableReporter};
///
/// let mut runner = Runner::new();
/// runner.capture_http();
/// runner.set_concurrency(8);
/// runner.add_reporter(TableReporter::new());
///
/// // Add tests (typically done by procedural macros)
/// runner.add_test("health_check", "api", None, test_factory);
///
/// // Run all tests
/// runner.run(&[], &[], &[]).await?;
/// ```
///
/// # Architecture
///
/// Tests are executed in separate tokio tasks with:
/// - Project-scoped configuration
/// - Test-scoped context for event publishing  
/// - Semaphore-based concurrency control
/// - Panic recovery and error handling
/// - Automatic retry with configurable backoff
#[derive(Default)]
pub struct Runner {
    cfg: Config,
    options: Options,
    test_cases: Vec<(Arc<TestInfo>, TestCaseFactory)>,
    reporters: Vec<Box<dyn Reporter + Send>>,
}

impl Runner {
    /// Creates a new runner with the global tanu configuration.
    ///
    /// This loads the configuration from `tanu.toml` and sets up
    /// default options. Use `with_config()` for custom configuration.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use tanu_core::Runner;
    ///
    /// let runner = Runner::new();
    /// ```
    pub fn new() -> Runner {
        Runner::with_config(get_tanu_config().clone())
    }

    /// Creates a new runner with the specified configuration.
    ///
    /// This allows for custom configuration beyond what's in `tanu.toml`,
    /// useful for testing or programmatic setup.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use tanu_core::{Runner, Config};
    ///
    /// let config = Config::default();
    /// let runner = Runner::with_config(config);
    /// ```
    pub fn with_config(cfg: Config) -> Runner {
        Runner {
            cfg,
            options: Options::default(),
            test_cases: Vec::new(),
            reporters: Vec::new(),
        }
    }

    /// Enables HTTP request/response logging.
    ///
    /// When enabled, all HTTP requests made via tanu's HTTP client
    /// will be logged and included in test reports. This is useful
    /// for debugging API tests and understanding request/response flow.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let mut runner = Runner::new();
    /// runner.capture_http();
    /// ```
    pub fn capture_http(&mut self) {
        self.options.capture_http = CaptureHttpMode::All;
    }

    /// Sets the HTTP capture mode.
    pub fn set_capture_http_mode(&mut self, mode: CaptureHttpMode) {
        self.options.capture_http = mode;
    }

    /// Enables Rust logging output during test execution.
    ///
    /// This initializes the tracing subscriber to capture debug, info,
    /// warn, and error logs from tests and the framework itself.
    /// Useful for debugging test execution issues.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let mut runner = Runner::new();
    /// runner.capture_rust();
    /// ```
    pub fn capture_rust(&mut self) {
        self.options.capture_rust = true;
    }

    /// Configures the runner to close the event channel after test execution.
    ///
    /// By default, the event channel remains open for continued monitoring.
    /// This option closes the channel when all tests complete, signaling
    /// that no more events will be published.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let mut runner = Runner::new();
    /// runner.terminate_channel();
    /// ```
    pub fn terminate_channel(&mut self) {
        self.options.terminate_channel = true;
    }

    /// Adds a reporter for test output formatting.
    ///
    /// Reporters receive test events and format them for different output
    /// destinations (console, files, etc.). Multiple reporters can be added
    /// to generate multiple output formats simultaneously.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use tanu_core::{Runner, reporter::TableReporter};
    ///
    /// let mut runner = Runner::new();
    /// runner.add_reporter(TableReporter::new());
    /// ```
    pub fn add_reporter(&mut self, reporter: impl Reporter + 'static + Send) {
        self.reporters.push(Box::new(reporter));
    }

    /// Adds a boxed reporter for test output formatting.
    ///
    /// Similar to `add_reporter()` but accepts an already-boxed reporter.
    /// Useful when working with dynamic reporter selection.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use tanu_core::{Runner, reporter::ListReporter};
    ///
    /// let mut runner = Runner::new();
    /// let reporter: Box<dyn Reporter + Send> = Box::new(ListReporter::new());
    /// runner.add_boxed_reporter(reporter);
    /// ```
    pub fn add_boxed_reporter(&mut self, reporter: Box<dyn Reporter + 'static + Send>) {
        self.reporters.push(reporter);
    }

    /// Add a test case to the runner.
    pub fn add_test(
        &mut self,
        name: &str,
        module: &str,
        serial_group: Option<&str>,
        line: u32,
        ordered: bool,
        factory: TestCaseFactory,
    ) {
        self.test_cases.push((
            Arc::new(TestInfo {
                name: name.into(),
                module: module.into(),
                serial_group: serial_group.map(|s| s.to_string()),
                line,
                ordered,
            }),
            factory,
        ));
    }

    /// Sets the maximum number of tests to run concurrently.
    ///
    /// By default, tests run with unlimited concurrency. This setting
    /// allows you to limit concurrent execution to reduce resource usage
    /// or avoid overwhelming external services.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let mut runner = Runner::new();
    /// runner.set_concurrency(4); // Max 4 tests at once
    /// ```
    pub fn set_concurrency(&mut self, concurrency: usize) {
        self.options.concurrency = Some(concurrency);
    }

    /// Disables sensitive data masking in HTTP logs.
    ///
    /// By default, sensitive data (Authorization headers, API keys in URLs, etc.)
    /// is masked with `*****` when HTTP logging is enabled. Call this method
    /// to show the actual values instead.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let mut runner = Runner::new();
    /// runner.capture_http(); // Enable HTTP logging
    /// runner.show_sensitive(); // Show actual values instead of *****
    /// ```
    pub fn show_sensitive(&mut self) {
        self.options.mask_sensitive = false;
    }

    /// Enables fail-fast mode: abort test execution after the first failure.
    pub fn set_fail_fast(&mut self, fail_fast: bool) {
        self.options.fail_fast = fail_fast;
    }

    /// Executes all registered tests with optional filtering.
    ///
    /// Runs tests concurrently according to the configured options and filters.
    /// Tests can be filtered by project name, module name, or specific test names.
    /// Empty filter arrays mean "include all".
    ///
    /// # Parameters
    ///
    /// - `project_names`: Only run tests from these projects (empty = all projects)
    /// - `module_names`: Only run tests from these modules (empty = all modules)  
    /// - `test_names`: Only run these specific tests (empty = all tests)
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let mut runner = Runner::new();
    ///
    /// // Run all tests
    /// runner.run(&[], &[], &[]).await?;
    ///
    /// // Run only "staging" project tests
    /// runner.run(&["staging".to_string()], &[], &[]).await?;
    ///
    /// // Run specific test
    /// runner.run(&[], &[], &["api::health_check".to_string()]).await?;
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Any test fails (unless configured to continue on failure)
    /// - A test panics and cannot be recovered
    /// - Reporter setup or execution fails
    /// - Event channel operations fail
    #[allow(clippy::too_many_lines)]
    pub async fn run(
        &mut self,
        project_names: &[String],
        module_names: &[String],
        test_names: &[String],
    ) -> eyre::Result<()> {
        // Set masking configuration for HTTP logs
        crate::masking::set_mask_sensitive(self.options.mask_sensitive);

        if self.options.capture_rust {
            tracing_subscriber::fmt::init();
        }

        let reporters = std::mem::take(&mut self.reporters);

        // Set up barrier for all reporters + runner
        // This ensures all reporters subscribe before tests start
        setup_reporter_barrier(reporters.len())?;

        let reporter_handles: Vec<_> = reporters
            .into_iter()
            .map(|mut reporter| tokio::spawn(async move { reporter.run().await }))
            .collect();

        // Wait for all reporters to subscribe before starting tests
        wait_reporter_barrier().await;

        let project_filter = ProjectFilter { project_names };
        let module_filter = ModuleFilter { module_names };
        let test_name_filter = TestNameFilter { test_names };
        let test_ignore_filter = TestIgnoreFilter::default();

        let start = std::time::Instant::now();
        let fail_fast = self.options.fail_fast;
        let cancelled = Arc::new(AtomicBool::new(false));
        let handles: FuturesUnordered<_> = {
            // Create a semaphore to limit concurrency
            let concurrency = self.options.concurrency;
            let semaphore = Arc::new(tokio::sync::Semaphore::new(
                concurrency.unwrap_or(tokio::sync::Semaphore::MAX_PERMITS),
            ));

            // Worker ID pool for timeline visualization (only when concurrency is specified)
            let worker_ids = Arc::new(WorkerIds::new(concurrency));

            // Per-group mutexes for serial execution (project-scoped)
            // Key format: "project_name::group_name"
            let serial_groups: Arc<
                tokio::sync::RwLock<std::collections::HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
            > = Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new()));

            let projects = self.cfg.projects.clone();
            let projects = if projects.is_empty() {
                vec![Arc::new(ProjectConfig {
                    name: "default".into(),
                    ..Default::default()
                })]
            } else {
                projects
            };

            // Collect all tests and apply filters
            let mut all_tests: Vec<_> = self
                .test_cases
                .iter()
                .cartesian_product(projects)
                .map(|((info, factory), project)| (project, Arc::clone(info), factory.clone()))
                .filter(move |(project, info, _)| test_name_filter.filter(project, info))
                .filter(move |(project, info, _)| module_filter.filter(project, info))
                .filter(move |(project, info, _)| project_filter.filter(project, info))
                .filter(move |(project, info, _)| test_ignore_filter.filter(project, info))
                .collect();

            // Separate ordered and non-ordered tests
            let (mut ordered_tests, non_ordered_tests): (Vec<_>, Vec<_>) =
                all_tests.drain(..).partition(|(_, info, _)| info.ordered);

            // Sort ordered tests by (serial_group, line) to ensure source order within groups
            ordered_tests
                .sort_by_key(|(_project, info, _factory)| (info.serial_group.clone(), info.line));

            // Group ordered tests by (project_name, serial_group) for sequential execution
            let mut ordered_groups: std::collections::HashMap<String, Vec<_>> =
                std::collections::HashMap::new();
            for (project, info, factory) in ordered_tests {
                let key = format!(
                    "{}::{}",
                    project.name,
                    info.serial_group.as_deref().unwrap_or("")
                );
                ordered_groups
                    .entry(key)
                    .or_default()
                    .push((project, info, factory));
            }

            // Create futures for ordered test groups (each group runs sequentially)
            let ordered_handles = ordered_groups.into_iter().map(|(group_key, tests)| {
                let semaphore = semaphore.clone();
                let worker_ids = worker_ids.clone();
                let serial_groups = serial_groups.clone();
                let cancelled = cancelled.clone();

                tokio::spawn(async move {
                    // Get serial mutex for this group once
                    let serial_mutex = {
                        let mut write_lock = serial_groups.write().await;
                        write_lock
                            .entry(group_key.clone())
                            .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
                            .clone()
                    };

                    // Run all tests in this group sequentially (await each before starting next)
                    let mut group_failed = false;
                    let mut group_error: Option<eyre::Report> = None;
                    for (project, info, factory) in tests {
                        if cancelled.load(Ordering::Relaxed) {
                            break;
                        }

                        // Acquire semaphore for this test
                        let _permit = semaphore
                            .acquire()
                            .await
                            .map_err(|e| eyre::eyre!("failed to acquire semaphore: {e}"));

                        if _permit.is_err() {
                            continue;
                        }

                        // Acquire worker ID
                        let worker_id = worker_ids.acquire();

                        let result = execute_test(
                            project,
                            info,
                            factory,
                            Some(serial_mutex.clone()),
                            worker_id,
                        )
                        .await;
                        worker_ids.release(worker_id);

                        match result {
                            Ok(test) => {
                                if test.result.is_err() {
                                    group_failed = true;
                                }
                            }
                            Err(e) => {
                                group_failed = true;
                                if group_error.is_none() {
                                    group_error = Some(e);
                                }
                            }
                        }
                    }
                    if group_failed {
                        if let Some(e) = group_error {
                            return Err(e);
                        }
                        eyre::bail!("one or more tests failed");
                    }
                    eyre::Ok(())
                })
            });

            // Create futures for non-ordered tests (parallel execution as before)
            let non_ordered_handles =
                non_ordered_tests
                    .into_iter()
                    .map(|(project, info, factory)| {
                        let semaphore = semaphore.clone();
                        let worker_ids = worker_ids.clone();
                        let serial_groups = serial_groups.clone();
                        let cancelled = cancelled.clone();
                        tokio::spawn(async move {
                            if cancelled.load(Ordering::Relaxed) {
                                return Ok(());
                            }

                            // Step 1: Acquire serial group mutex FIRST (if needed) - project-scoped
                            // This ensures tests in the same group don't hold semaphore permits unnecessarily
                            let serial_mutex = match &info.serial_group {
                                Some(group_name) => {
                                    // Create project-scoped key: "project_name::group_name"
                                    let key = format!("{}::{}", project.name, group_name);

                                    // Get or create mutex for this project+group
                                    let read_lock = serial_groups.read().await;
                                    if let Some(mutex) = read_lock.get(&key) {
                                        Some(Arc::clone(mutex))
                                    } else {
                                        drop(read_lock);
                                        let mut write_lock = serial_groups.write().await;
                                        Some(
                                            write_lock
                                                .entry(key)
                                                .or_insert_with(|| {
                                                    Arc::new(tokio::sync::Mutex::new(()))
                                                })
                                                .clone(),
                                        )
                                    }
                                }
                                None => None,
                            };

                            // Step 2: Acquire global semaphore AFTER serial mutex
                            // This prevents blocking other tests while waiting for serial group
                            let _permit = semaphore
                                .acquire()
                                .await
                                .map_err(|e| eyre::eyre!("failed to acquire semaphore: {e}"))?;

                            // Acquire worker ID from pool
                            let worker_id = worker_ids.acquire();

                            let result = execute_test(
                                project,
                                info,
                                factory,
                                serial_mutex.clone(),
                                worker_id,
                            )
                            .await
                            .and_then(|test| {
                                let is_err = test.result.is_err();
                                eyre::ensure!(!is_err);
                                eyre::Ok(())
                            });

                            // Return worker ID to pool
                            worker_ids.release(worker_id);

                            result
                        })
                    });

            // Combine both ordered and non-ordered handles
            let all_handles = FuturesUnordered::new();
            for handle in ordered_handles {
                all_handles.push(handle);
            }
            for handle in non_ordered_handles {
                all_handles.push(handle);
            }
            all_handles
        };
        let test_prep_time = start.elapsed();
        debug!(
            "created handles for {} test cases",
            test_prep_time.as_secs_f32()
        );

        let mut has_any_error = false;
        let total_tests = handles.len();
        let options = self.options.clone();
        let runner = async move {
            let mut handles = handles;
            let mut failed_tests = 0;
            let mut processed_tests = 0;

            while let Some(result) = handles.next().await {
                processed_tests += 1;
                match result {
                    Ok(res) => {
                        if let Err(e) = res {
                            debug!("test case failed: {e:#}");
                            has_any_error = true;
                            failed_tests += 1;
                            if fail_fast {
                                cancelled.store(true, Ordering::Relaxed);
                                break;
                            }
                        }
                    }
                    Err(e) => {
                        if e.is_panic() {
                            // Resume the panic on the main task
                            error!("{e}");
                            has_any_error = true;
                            failed_tests += 1;
                            if fail_fast {
                                cancelled.store(true, Ordering::Relaxed);
                                break;
                            }
                        }
                    }
                }
            }

            if total_tests == 0 {
                console::Term::stdout().write_line("no test cases found")?;
            }

            // Count remaining skipped tasks (when fail-fast triggered early exit)
            let skipped_tests = total_tests - processed_tests;
            let passed_tests = total_tests - failed_tests - skipped_tests;
            let total_time = start.elapsed();

            // Publish summary event
            let summary = TestSummary {
                total_tests,
                passed_tests,
                failed_tests,
                skipped_tests,
                total_time,
                test_prep_time,
            };

            // Create a dummy event for summary (since it doesn't belong to a specific test)
            let summary_event = Event {
                project: "".to_string(),
                module: "".to_string(),
                test: "".to_string(),
                body: EventBody::Summary(summary),
            };

            if let Ok(guard) = CHANNEL.lock() {
                if let Some((tx, _)) = guard.as_ref() {
                    let _ = tx.send(summary_event);
                }
            }
            debug!("all test finished. sending stop signal to the background tasks.");

            if options.terminate_channel {
                let Ok(mut guard) = CHANNEL.lock() else {
                    eyre::bail!("failed to acquire runner channel lock");
                };
                guard.take(); // closing the runner channel.
            }

            if has_any_error {
                eyre::bail!("one or more tests failed");
            }

            eyre::Ok(())
        };

        let runner_result = runner.await;

        for handle in reporter_handles {
            match handle.await {
                Ok(Ok(())) => {}
                Ok(Err(e)) => error!("reporter failed: {e:#}"),
                Err(e) => error!("reporter task panicked: {e:#}"),
            }
        }

        // Clean up barrier
        clear_reporter_barrier();

        debug!("runner stopped");

        runner_result
    }

    /// Returns a list of all registered test metadata.
    ///
    /// This provides access to test information without executing the tests.
    /// Useful for building test UIs, generating reports, or implementing
    /// custom filtering logic.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let runner = Runner::new();
    /// let tests = runner.list();
    ///
    /// for test in tests {
    ///     println!("Test: {}", test.full_name());
    /// }
    /// ```
    pub fn list(&self) -> Vec<&TestInfo> {
        self.test_cases
            .iter()
            .map(|(meta, _test)| meta.as_ref())
            .collect::<Vec<_>>()
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::config::RetryConfig;
    use crate::ProjectConfig;
    use std::sync::Arc;

    fn create_config() -> Config {
        Config {
            projects: vec![Arc::new(ProjectConfig {
                name: "default".into(),
                ..Default::default()
            })],
            ..Default::default()
        }
    }

    fn create_config_with_retry() -> Config {
        Config {
            projects: vec![Arc::new(ProjectConfig {
                name: "default".into(),
                retry: RetryConfig {
                    count: Some(1),
                    ..Default::default()
                },
                ..Default::default()
            })],
            ..Default::default()
        }
    }

    #[tokio::test]
    async fn runner_fail_because_no_retry_configured() -> eyre::Result<()> {
        let mut server = mockito::Server::new_async().await;
        let m1 = server
            .mock("GET", "/")
            .with_status(500)
            .expect(1)
            .create_async()
            .await;
        let m2 = server
            .mock("GET", "/")
            .with_status(200)
            .expect(0)
            .create_async()
            .await;

        let factory: TestCaseFactory = Arc::new(move || {
            let url = server.url();
            Box::pin(async move {
                let client = crate::http::Client::new();
                let res = client.get(&url).send().await?;
                if res.status().is_success() {
                    Ok(())
                } else {
                    eyre::bail!("request failed")
                }
            })
        });

        let _runner_rx = subscribe()?;
        let mut runner = Runner::with_config(create_config());
        runner.add_test("retry_test", "module", None, 0, false, factory);

        let result = runner.run(&[], &[], &[]).await;
        m1.assert_async().await;
        m2.assert_async().await;

        assert!(result.is_err());
        Ok(())
    }

    #[tokio::test]
    async fn runner_retry_successful_after_failure() -> eyre::Result<()> {
        let mut server = mockito::Server::new_async().await;
        let m1 = server
            .mock("GET", "/")
            .with_status(500)
            .expect(1)
            .create_async()
            .await;
        let m2 = server
            .mock("GET", "/")
            .with_status(200)
            .expect(1)
            .create_async()
            .await;

        let factory: TestCaseFactory = Arc::new(move || {
            let url = server.url();
            Box::pin(async move {
                let client = crate::http::Client::new();
                let res = client.get(&url).send().await?;
                if res.status().is_success() {
                    Ok(())
                } else {
                    eyre::bail!("request failed")
                }
            })
        });

        let _runner_rx = subscribe()?;
        let mut runner = Runner::with_config(create_config_with_retry());
        runner.add_test("retry_test", "module", None, 0, false, factory);

        let result = runner.run(&[], &[], &[]).await;
        m1.assert_async().await;
        m2.assert_async().await;

        assert!(result.is_ok());

        Ok(())
    }

    #[tokio::test]
    async fn spawned_task_panics_without_task_local_context() {
        let project = Arc::new(ProjectConfig {
            name: "default".to_string(),
            ..Default::default()
        });
        let test_info = Arc::new(TestInfo {
            module: "mod".to_string(),
            name: "test".to_string(),
            serial_group: None,
            line: 0,
            ordered: false,
        });

        crate::config::PROJECT
            .scope(
                project,
                TEST_INFO.scope(test_info, async move {
                    let handle = tokio::spawn(async move {
                        let _ = crate::config::get_config();
                    });

                    let join_err = handle.await.expect_err("spawned task should panic");
                    assert!(join_err.is_panic());
                }),
            )
            .await;
    }

    #[tokio::test]
    async fn scope_current_propagates_task_local_context_into_spawned_task() {
        let project = Arc::new(ProjectConfig {
            name: "default".to_string(),
            ..Default::default()
        });
        let test_info = Arc::new(TestInfo {
            module: "mod".to_string(),
            name: "test".to_string(),
            serial_group: None,
            line: 0,
            ordered: false,
        });

        crate::config::PROJECT
            .scope(
                project,
                TEST_INFO.scope(test_info, async move {
                    let handle = tokio::spawn(super::scope_current(async move {
                        let _ = crate::config::get_config();
                        let _ = super::get_test_info();
                    }));

                    handle.await.expect("spawned task should not panic");
                }),
            )
            .await;
    }

    #[tokio::test]
    #[serial_test::serial]
    async fn masking_masks_sensitive_query_params_in_http_logs() -> eyre::Result<()> {
        use crate::masking;

        // Ensure masking is enabled
        masking::set_mask_sensitive(true);

        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", mockito::Matcher::Any)
            .with_status(200)
            .create_async()
            .await;

        let factory: TestCaseFactory = Arc::new(move || {
            let url = server.url();
            Box::pin(async move {
                let client = crate::http::Client::new();
                // Make request with sensitive query param embedded in URL
                let _res = client
                    .get(format!("{url}?access_token=secret_token_123&user=john"))
                    .send()
                    .await?;
                Ok(())
            })
        });

        let mut rx = subscribe()?;
        let mut runner = Runner::with_config(create_config());
        runner.add_test(
            "masking_query_test",
            "masking_module",
            None,
            0,
            false,
            factory,
        );

        runner.run(&[], &[], &[]).await?;

        // Collect HTTP events for this specific test
        let mut found_http_event = false;
        while let Ok(event) = rx.try_recv() {
            // Filter to only our test's events
            if event.test != "masking_query_test" {
                continue;
            }
            if let EventBody::Call(CallLog::Http(log)) = event.body {
                found_http_event = true;
                let url_str = log.request.url.to_string();

                // Verify sensitive param is masked
                assert!(
                    url_str.contains("access_token=*****"),
                    "access_token should be masked, got: {url_str}"
                );
                // Non-sensitive params should not be masked
                assert!(
                    url_str.contains("user=john"),
                    "user should not be masked, got: {url_str}"
                );
            }
        }

        assert!(found_http_event, "Should have received HTTP event");
        Ok(())
    }

    #[tokio::test]
    #[serial_test::serial]
    async fn masking_masks_sensitive_headers_in_http_logs() -> eyre::Result<()> {
        use crate::masking;

        // Ensure masking is enabled
        masking::set_mask_sensitive(true);

        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", "/")
            .with_status(200)
            .create_async()
            .await;

        let factory: TestCaseFactory = Arc::new(move || {
            let url = server.url();
            Box::pin(async move {
                let client = crate::http::Client::new();
                // Make request with sensitive headers
                let _res = client
                    .get(&url)
                    .header("authorization", "Bearer secret_bearer_token")
                    .header("x-api-key", "my_secret_api_key")
                    .header("content-type", "application/json")
                    .send()
                    .await?;
                Ok(())
            })
        });

        let mut rx = subscribe()?;
        let mut runner = Runner::with_config(create_config());
        runner.add_test(
            "masking_headers_test",
            "masking_module",
            None,
            0,
            false,
            factory,
        );

        runner.run(&[], &[], &[]).await?;

        // Collect HTTP events for this specific test
        let mut found_http_event = false;
        while let Ok(event) = rx.try_recv() {
            // Filter to only our test's events
            if event.test != "masking_headers_test" {
                continue;
            }
            if let EventBody::Call(CallLog::Http(log)) = event.body {
                found_http_event = true;

                // Verify sensitive headers are masked
                if let Some(auth) = log.request.headers.get("authorization") {
                    assert_eq!(
                        auth.to_str().unwrap(),
                        "*****",
                        "authorization header should be masked"
                    );
                }
                if let Some(api_key) = log.request.headers.get("x-api-key") {
                    assert_eq!(
                        api_key.to_str().unwrap(),
                        "*****",
                        "x-api-key header should be masked"
                    );
                }
                // Non-sensitive headers should not be masked
                if let Some(content_type) = log.request.headers.get("content-type") {
                    assert_eq!(
                        content_type.to_str().unwrap(),
                        "application/json",
                        "content-type header should not be masked"
                    );
                }
            }
        }

        assert!(found_http_event, "Should have received HTTP event");
        Ok(())
    }

    #[tokio::test]
    #[serial_test::serial]
    async fn masking_show_sensitive_disables_masking_in_http_logs() -> eyre::Result<()> {
        use crate::masking;

        masking::set_mask_sensitive(true);

        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", "/")
            .with_status(200)
            .create_async()
            .await;

        let factory: TestCaseFactory = Arc::new(move || {
            let url = server.url();
            Box::pin(async move {
                let client = crate::http::Client::new();
                let _res = client
                    .get(format!("{url}?access_token=secret_token_123"))
                    .header("authorization", "Bearer secret_bearer_token")
                    .send()
                    .await?;
                Ok(())
            })
        });

        let mut rx = subscribe()?;
        let mut runner = Runner::with_config(create_config());
        runner.capture_http();
        runner.show_sensitive();
        runner.add_test(
            "show_sensitive_test",
            "masking_module",
            None,
            0,
            false,
            factory,
        );

        runner.run(&[], &[], &[]).await?;

        let mut found_http_event = false;
        while let Ok(event) = rx.try_recv() {
            if event.test != "show_sensitive_test" {
                continue;
            }
            if let EventBody::Call(CallLog::Http(log)) = event.body {
                found_http_event = true;
                let url_str = log.request.url.to_string();
                assert!(
                    url_str.contains("access_token=secret_token_123"),
                    "access_token should not be masked when show_sensitive is enabled"
                );
                if let Some(auth) = log.request.headers.get("authorization") {
                    assert_eq!(
                        auth.to_str().unwrap(),
                        "Bearer secret_bearer_token",
                        "authorization header should not be masked when show_sensitive is enabled"
                    );
                }
            }
        }

        assert!(found_http_event, "Should have received HTTP event");
        Ok(())
    }

    fn passing_factory() -> TestCaseFactory {
        Arc::new(|| Box::pin(async { Ok(()) }))
    }

    fn failing_factory() -> TestCaseFactory {
        Arc::new(|| Box::pin(async { eyre::bail!("intentional failure") }))
    }

    #[tokio::test]
    #[serial_test::serial]
    async fn runner_fail_fast_skips_remaining_tests() -> eyre::Result<()> {
        let mut rx = subscribe()?;
        let mut runner = Runner::with_config(create_config());
        runner.set_concurrency(1);
        runner.set_fail_fast(true);

        // Failing test added first so it is spawned first and runs first
        // under the single-threaded #[tokio::test] runtime.
        runner.add_test("ff_fail", "module", None, 0, false, failing_factory());
        runner.add_test("ff_pass1", "module", None, 1, false, passing_factory());
        runner.add_test("ff_pass2", "module", None, 2, false, passing_factory());

        let result = runner.run(&[], &[], &[]).await;
        assert!(result.is_err());

        let mut summary = None;
        while let Ok(event) = rx.try_recv() {
            if let EventBody::Summary(s) = event.body {
                summary = Some(s);
            }
        }

        let summary = summary.expect("should have received Summary event");
        assert!(
            summary.failed_tests >= 1,
            "should have at least one failure"
        );
        assert!(
            summary.skipped_tests >= 1,
            "fail-fast should have skipped remaining tests"
        );

        Ok(())
    }

    #[tokio::test]
    #[serial_test::serial]
    async fn runner_without_fail_fast_runs_all_tests() -> eyre::Result<()> {
        let mut rx = subscribe()?;
        let mut runner = Runner::with_config(create_config());
        runner.set_concurrency(1);
        // fail_fast is false by default

        runner.add_test("noff_fail", "module", None, 0, false, failing_factory());
        runner.add_test("noff_pass1", "module", None, 1, false, passing_factory());
        runner.add_test("noff_pass2", "module", None, 2, false, passing_factory());

        let result = runner.run(&[], &[], &[]).await;
        assert!(result.is_err());

        let mut summary = None;
        while let Ok(event) = rx.try_recv() {
            if let EventBody::Summary(s) = event.body {
                summary = Some(s);
            }
        }

        let summary = summary.expect("should have received Summary event");
        assert_eq!(summary.failed_tests, 1, "should have exactly one failure");
        assert_eq!(summary.passed_tests, 2, "should have two passed tests");
        assert_eq!(summary.skipped_tests, 0, "should have no skipped tests");

        Ok(())
    }

    // Verify that HTTP Call events are published to the channel regardless of
    // the capture_http mode (the HTTP client always publishes; the reporter
    // decides what to display).
    #[tokio::test]
    #[serial_test::serial]
    async fn capture_http_events_published_for_all_tests_regardless_of_mode() -> eyre::Result<()> {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", mockito::Matcher::Any)
            .with_status(200)
            .create_async()
            .await;

        let make_http_factory = |url: String| -> TestCaseFactory {
            Arc::new(move || {
                let url = url.clone();
                Box::pin(async move {
                    let client = crate::http::Client::new();
                    client.get(&url).send().await?;
                    Ok(())
                })
            })
        };

        let failing_http_factory = |url: String| -> TestCaseFactory {
            Arc::new(move || {
                let url = url.clone();
                Box::pin(async move {
                    let client = crate::http::Client::new();
                    client.get(&url).send().await?;
                    eyre::bail!("intentional failure after http call");
                })
            })
        };

        let url = server.url();

        // Run with OnFailure mode
        let mut rx = subscribe()?;
        let mut runner = Runner::with_config(create_config());
        runner.set_capture_http_mode(CaptureHttpMode::OnFailure);
        runner.add_test(
            "ch_pass",
            "ch_module",
            None,
            0,
            false,
            make_http_factory(url.clone()),
        );
        runner.add_test(
            "ch_fail",
            "ch_module",
            None,
            1,
            false,
            failing_http_factory(url.clone()),
        );

        let _ = runner.run(&[], &[], &[]).await;

        // Both tests should have published Call events — capture mode only
        // affects reporter display, not event publishing.
        let mut pass_has_call = false;
        let mut fail_has_call = false;
        while let Ok(event) = rx.try_recv() {
            if let EventBody::Call(CallLog::Http(_)) = &event.body {
                match event.test.as_str() {
                    "ch_pass" => pass_has_call = true,
                    "ch_fail" => fail_has_call = true,
                    _ => {}
                }
            }
        }

        assert!(
            pass_has_call,
            "passing test should still publish HTTP Call event"
        );
        assert!(
            fail_has_call,
            "failing test should still publish HTTP Call event"
        );

        Ok(())
    }

    #[test]
    fn set_capture_http_mode_stores_mode() {
        let mut runner = Runner::new();
        assert_eq!(runner.options.capture_http, CaptureHttpMode::Off);

        runner.capture_http();
        assert_eq!(runner.options.capture_http, CaptureHttpMode::All);

        runner.set_capture_http_mode(CaptureHttpMode::OnFailure);
        assert_eq!(runner.options.capture_http, CaptureHttpMode::OnFailure);

        runner.set_capture_http_mode(CaptureHttpMode::Off);
        assert_eq!(runner.options.capture_http, CaptureHttpMode::Off);
    }
}