ghostscope 0.1.1

Command-line entrypoint that drives GhostScope compiler, loader, and UI end-to-end.
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
//! Script execution integration tests
//!
//! Tests for ghostscope script execution and tracing functionality.
//! Assumes tests are run with sudo permissions for eBPF attachment.
//!
//! Concurrency note: these tests intentionally exercise multiple scripts
//! against a single long-lived sample_program process (per optimization
//! level). This is by design to validate real-world multi-attachment
//! scenarios and reduce test startup overhead. Do not serialize this file.

mod common;

use common::{init, OptimizationLevel, FIXTURES};
use lazy_static::lazy_static;
use std::collections::HashMap;
use std::process::Stdio;
use std::sync::{Arc, Once};
use std::time::Duration;
use tokio::process::Command;
use tokio::sync::RwLock;
use tokio::time::timeout;

// Global test program management
lazy_static! {
    // Maintain one process per optimization level to avoid cross-test interference.
    static ref GLOBAL_TEST_MANAGER: Arc<RwLock<HashMap<OptimizationLevel, GlobalTestProcess>>> =
        Arc::new(RwLock::new(HashMap::new()));
}

struct GlobalTestProcess {
    child: tokio::process::Child,
    pid: u32,
    optimization_level: OptimizationLevel,
}

impl GlobalTestProcess {
    async fn start_with_opt(opt_level: OptimizationLevel) -> anyhow::Result<Self> {
        let binary_path = FIXTURES.get_test_binary_with_opt("sample_program", opt_level)?;

        println!(
            "🚀 Starting global sample_program ({}): {}",
            opt_level.description(),
            binary_path.display()
        );

        let child = Command::new(binary_path)
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()?;

        let pid = child
            .id()
            .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;

        // Give it a moment to start
        tokio::time::sleep(Duration::from_millis(500)).await;

        println!(
            "✓ Started global sample_program ({}) with PID: {}",
            opt_level.description(),
            pid
        );

        Ok(Self {
            child,
            pid,
            optimization_level: opt_level,
        })
    }

    fn get_pid(&self) -> u32 {
        self.pid
    }

    async fn terminate(mut self) -> anyhow::Result<()> {
        println!(
            "🛑 Terminating global sample_program ({}, PID: {})",
            self.optimization_level.description(),
            self.pid
        );

        // Try graceful shutdown first
        let _ = self.child.kill().await.is_ok();

        // Wait for termination with timeout
        match timeout(Duration::from_secs(2), self.child.wait()).await {
            Ok(_) => {
                println!(
                    "✓ Global sample_program ({}) terminated gracefully",
                    self.optimization_level.description()
                );
            }
            Err(_) => {
                // Force kill if it doesn't respond
                let _ = std::process::Command::new("kill")
                    .arg("-KILL")
                    .arg(self.pid.to_string())
                    .status()
                    .is_ok();
                println!(
                    "⚠️ Force killed global sample_program ({})",
                    self.optimization_level.description()
                );
            }
        }

        Ok(())
    }
}

// Get or start the global test process with specific optimization level
async fn get_global_test_pid_with_opt(opt_level: OptimizationLevel) -> anyhow::Result<u32> {
    let manager = GLOBAL_TEST_MANAGER.clone();

    // Fast path: check if we already have a live process for this opt level
    {
        let read_guard = manager.read().await;
        if let Some(process) = read_guard.get(&opt_level) {
            let status = std::process::Command::new("kill")
                .arg("-0")
                .arg(process.pid.to_string())
                .status();
            if status.is_ok_and(|s| s.success()) {
                return Ok(process.pid);
            }
        }
    }

    // Slow path: create or replace the entry for this opt level
    let mut write_guard = manager.write().await;

    // Double-check under write lock in case another task started it
    if let Some(process) = write_guard.get(&opt_level) {
        let status = std::process::Command::new("kill")
            .arg("-0")
            .arg(process.pid.to_string())
            .status();
        if status.is_ok_and(|s| s.success()) {
            return Ok(process.pid);
        }
    }

    // If an old process exists for this opt level, remove it first (drop lock before awaiting)
    let old_proc = write_guard.remove(&opt_level);
    drop(write_guard);

    if let Some(old) = old_proc {
        let _ = old.terminate().await;
    }

    // Start new process with the requested optimization level
    let new_process = GlobalTestProcess::start_with_opt(opt_level).await?;
    let pid = new_process.get_pid();

    // Re-acquire write lock to insert the new process
    let mut write_guard = manager.write().await;
    write_guard.insert(opt_level, new_process);
    Ok(pid)
}

// Get or start the global test process (defaults to Debug optimization)
// Cleanup function to be called when tests finish
pub async fn cleanup_global_test_process() -> anyhow::Result<()> {
    let manager = GLOBAL_TEST_MANAGER.clone();
    let mut write_guard = manager.write().await;

    // Terminate all managed processes (for every optimization level)
    let processes: Vec<GlobalTestProcess> = write_guard.drain().map(|(_, p)| p).collect();
    drop(write_guard);

    for proc in processes.into_iter() {
        let _ = proc.terminate().await;
    }

    Ok(())
}

#[tokio::test]
async fn test_void_pointer_addition_prints_address() -> anyhow::Result<()> {
    // Verify: for sink_void(const void* p), p+1 prints an address (fallback path)
    init();
    ensure_global_cleanup_registered();

    let opt_level = OptimizationLevel::Debug;
    let _ = get_global_test_pid_with_opt(opt_level).await?;

    let script_content = r#"
trace sink_void {
    print p + 1;
}
"#;

    let (exit_code, stdout, stderr) =
        run_ghostscope_with_script_opt(script_content, 4, opt_level).await?;
    assert_eq!(
        exit_code, 0,
        "unexpected error: stderr={stderr}\nstdout={stdout}"
    );

    // Expect something like: (p+1) = 0x... or plain 0x... (void*)
    // This covers the AddressValue path rendered via ComplexFormat
    let mut saw_addr = false;
    for line in stdout.lines() {
        let t = line.trim();
        if (t.starts_with("(p+1) = ") && t.contains("0x"))
            || (t.starts_with("0x") && t.contains("(void*)"))
        {
            saw_addr = true;
            break;
        }
    }
    assert!(
        saw_addr,
        "expected (p+1) to print an address.\nSTDOUT: {stdout}\nSTDERR: {stderr}"
    );
    Ok(())
}

#[tokio::test]
async fn test_struct_pointer_addition_scales_by_type_size() -> anyhow::Result<()> {
    // Verify: on print_record(const DataRecord* record), (record+1) and (record+2)
    // have addresses separated by sizeof(DataRecord) (expected 48 bytes on x86_64 with current layout).
    // We avoid relying on successful reads; we only compare addresses when read fails (errno=-14).
    init();
    ensure_global_cleanup_registered();

    let opt_level = OptimizationLevel::Debug;
    let _ = get_global_test_pid_with_opt(opt_level).await?;

    let script_content = r#"
trace print_record {
    print record + 1;
    print record + 2;
}
"#;

    let (exit_code, stdout, stderr) =
        run_ghostscope_with_script_opt(script_content, 5, opt_level).await?;

    // If attach fails due to sandbox (BPF_PROG_LOAD), skip to avoid false negatives in CI
    if exit_code != 0 && stderr.contains("BPF_PROG_LOAD") {
        return Ok(());
    }
    assert_eq!(
        exit_code, 0,
        "unexpected error: stderr={stderr}\nstdout={stdout}"
    );

    // Gather addresses from failure lines for (record+1) and (record+2)
    let mut addr1: Option<u64> = None;
    let mut addr2: Option<u64> = None;
    for line in stdout.lines() {
        let t = line.trim();
        if t.starts_with("(record+1) = ") || t.starts_with("(record + 1) = ") {
            if let Some(ix) = t.rfind("0x") {
                let mut j = ix + 2;
                let bytes = t.as_bytes();
                while j < t.len() && bytes[j].is_ascii_hexdigit() {
                    j += 1;
                }
                if j > ix + 2 {
                    if let Ok(v) = u64::from_str_radix(&t[ix + 2..j], 16) {
                        addr1 = Some(v);
                    }
                }
            }
        }
        if t.starts_with("(record+2) = ") || t.starts_with("(record + 2) = ") {
            if let Some(ix) = t.rfind("0x") {
                let mut j = ix + 2;
                let bytes = t.as_bytes();
                while j < t.len() && bytes[j].is_ascii_hexdigit() {
                    j += 1;
                }
                if j > ix + 2 {
                    if let Ok(v) = u64::from_str_radix(&t[ix + 2..j], 16) {
                        addr2 = Some(v);
                    }
                }
            }
        }
    }

    if let (Some(a1), Some(a2)) = (addr1, addr2) {
        // Expected sizeof(DataRecord) = 48 bytes with current layout (int(4)+name[32]+padding(4)+double(8))
        let delta = a2.wrapping_sub(a1);
        assert_eq!(
            delta, 48,
            "expected address delta sizeof(DataRecord)=48 bytes (got {delta}).\nSTDOUT: {stdout}\nSTDERR: {stderr}"
        );
    } else {
        // If we didn't observe failure lines with addresses, we cannot assert safely here.
        // Consider success in this scenario to avoid flaky behavior.
    }

    Ok(())
}

#[tokio::test]
async fn test_special_pid_in_if_condition() -> anyhow::Result<()> {
    init();
    ensure_global_cleanup_registered();

    let opt_level = OptimizationLevel::Debug;
    let test_pid = get_global_test_pid_with_opt(opt_level).await?;

    // Use $pid in an expression: it should equal the traced process PID
    let script_content = format!(
        "trace sample_program.c:16 {{\n    if $pid == {test_pid} {{ print \"PID_OK\"; }} else {{ print \"PID_BAD\"; }}\n}}\n"
    );

    let (exit_code, stdout, stderr) =
        run_ghostscope_with_script_opt(&script_content, 3, opt_level).await?;

    assert_eq!(exit_code, 0, "stderr={stderr}");
    assert!(
        stdout.contains("PID_OK"),
        "Expected PID_OK in output. STDOUT: {stdout}"
    );

    Ok(())
}

#[tokio::test]
async fn test_special_tid_and_timestamp_print() -> anyhow::Result<()> {
    init();
    ensure_global_cleanup_registered();

    let opt_level = OptimizationLevel::Debug;
    let _ = get_global_test_pid_with_opt(opt_level).await?;

    // Just print them to ensure they compile, evaluate and render
    let script_content = r#"
trace sample_program.c:16 {
    print "TST:{} {}", $tid, $timestamp;
}
"#;

    let (exit_code, stdout, stderr) =
        run_ghostscope_with_script_opt(script_content, 3, opt_level).await?;

    assert_eq!(exit_code, 0, "stderr={stderr}");
    assert!(
        stdout.contains("TST:"),
        "Expected TST: with tid/timestamp in output. STDOUT: {stdout}"
    );
    Ok(())
}

// Global cleanup registration - only runs once when the first test calls it
static GLOBAL_CLEANUP_REGISTERED: Once = Once::new();

fn ensure_global_cleanup_registered() {
    GLOBAL_CLEANUP_REGISTERED.call_once(|| {
        // Use atexit to ensure cleanup runs when the test binary exits
        extern "C" fn cleanup_on_exit() {
            println!("🧹 Global test cleanup: All tests finished, cleaning up...");

            // Kill any remaining sample_program processes
            let _pkill_result = std::process::Command::new("pkill")
                .args(["-f", "sample_program"]) // pass array by value to avoid needless borrow
                .status()
                .is_ok();

            // Clean up sample_program build files
            let fixtures_path =
                std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
            let sample_program_dir = fixtures_path.join("sample_program");

            println!("🧹 Running make clean in sample_program directory...");
            let clean_result = std::process::Command::new("make")
                .arg("clean")
                .current_dir(sample_program_dir)
                .output();

            match clean_result {
                Ok(output) => {
                    if output.status.success() {
                        println!("✓ Successfully cleaned sample_program build files");
                    } else {
                        let stderr = String::from_utf8_lossy(&output.stderr);
                        println!("⚠️ Make clean failed: {stderr}");
                    }
                }
                Err(e) => {
                    println!("⚠️ Failed to run make clean: {e}");
                }
            }

            println!("🧹 Global cleanup completed");
        }

        unsafe {
            libc::atexit(cleanup_on_exit);
        }

        println!("✓ Global cleanup handler registered");
    });
}

/// Helper to run ghostscope with script and capture results with specific optimization level
/// For failing cases (syntax errors, etc.), this will return quickly with exit code != 0
/// For successful cases, this will run for timeout_secs, collect output, then terminate the process
async fn run_ghostscope_with_script_opt(
    script_content: &str,
    timeout_secs: u64,
    opt_level: OptimizationLevel,
) -> anyhow::Result<(i32, String, String)> {
    // Get PID of running sample_program with specific optimization level
    let test_pid = get_global_test_pid_with_opt(opt_level).await?;

    println!(
        "🔍 Running ghostscope with {} binary (PID: {})",
        opt_level.description(),
        test_pid
    );

    common::runner::GhostscopeRunner::new()
        .with_script(script_content)
        .with_pid(test_pid)
        .timeout_secs(timeout_secs)
        .enable_sysmon_shared_lib(false)
        .run()
        .await
}

/// Helper to run ghostscope with script and capture results (defaults to Debug optimization)
/// For failing cases (syntax errors, etc.), this will return quickly with exit code != 0
/// For successful cases, this will run for timeout_secs, collect output, then terminate the process
async fn run_ghostscope_with_script(
    script_content: &str,
    timeout_secs: u64,
) -> anyhow::Result<(i32, String, String)> {
    run_ghostscope_with_script_opt(script_content, timeout_secs, OptimizationLevel::Debug).await
}

#[tokio::test]
async fn test_logical_or_short_circuit_chain() -> anyhow::Result<()> {
    init();
    ensure_global_cleanup_registered();

    // Attach to a hot function so we get a few events quickly
    let script_content = r#"
trace calculate_something {
    // Exercise chained OR; final should be true
    print (0 || 0 || 1);
    // Exercise chained OR; final should be false
    print (0 || 0 || 0);
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script(script_content, 5).await?;
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    // Expect to observe both true and false lines at least once
    let saw_true = stdout.contains("true");
    let saw_false = stdout.contains("false");
    assert!(
        saw_true,
        "Expected at least one true result. STDOUT: {stdout}"
    );
    assert!(
        saw_false,
        "Expected at least one false result. STDOUT: {stdout}"
    );
    Ok(())
}

#[tokio::test]
async fn test_memcmp_rejects_script_pointer_variable_e2e() -> anyhow::Result<()> {
    init();
    ensure_global_cleanup_registered();

    // Using a script pointer variable as memcmp arg must fail at compile time now.
    let script_content = r#"
trace calculate_something {
    let p = "A";
    if memcmp(p, hex("41"), 1) { print "OK"; } else { print "NO"; }
}
"#;

    let (exit_code, _stdout, stderr) = run_ghostscope_with_script(script_content, 2).await?;
    assert!(
        exit_code != 0,
        "expected non-zero exit due to compile error; stderr={stderr}"
    );
    // Expect the consolidated failed-targets banner with the pointer/address type error and tip
    let has_banner = stderr.contains("No uprobe configurations created")
        || stderr.contains("Script compilation failed");
    let has_failed_targets = stderr.contains("Failed targets:");
    let has_reason = stderr.contains("expression is not a pointer/address");
    let has_tip = stderr.contains("Tip: fix the reported compile-time errors above");
    assert!(
        has_banner && has_failed_targets && has_reason && has_tip,
        "Expected failed-targets details with pointer/address reason and tip. stderr={stderr}"
    );
    Ok(())
}

#[tokio::test]
async fn test_pointer_ordered_comparison_is_rejected_e2e() -> anyhow::Result<()> {
    init();
    ensure_global_cleanup_registered();

    // Ordered comparisons on pointers/addresses (<, <=, >, >=) are forbidden at compile time.
    // process_data(const char* message) provides a pointer parameter for this check.
    let script_content = r#"
trace process_data {
    if message > 0 { print "BAD"; }
}
"#;

    let (exit_code, _stdout, stderr) = run_ghostscope_with_script(script_content, 2).await?;
    assert!(
        exit_code != 0,
        "expected non-zero exit due to compile error; stderr={stderr}"
    );

    // Expect banner + friendly pointer-ordered-comparison message
    let has_banner = stderr.contains("No uprobe configurations created")
        || stderr.contains("Script compilation failed");
    let has_reason =
        stderr.contains("Pointer ordered comparison ('<', '<=', '>', '>=') is not supported");
    assert!(
        has_banner && has_reason,
        "Expected pointer ordered comparison rejection with banner. stderr={stderr}"
    );
    Ok(())
}

#[tokio::test]
async fn test_pointer_addition_print_reads_element_at_offset() -> anyhow::Result<()> {
    // Verify: print activity + 1; where activity: const char* in log_activity
    // Should move by sizeof(char) and print the byte at new address (expected 'a' from "main_loop").
    init();
    ensure_global_cleanup_registered();

    let opt_level = OptimizationLevel::Debug;
    let _ = get_global_test_pid_with_opt(opt_level).await?;

    let script_content = r#"
trace log_activity {
    print activity + 1;
}
"#;

    let (exit_code, stdout, stderr) =
        run_ghostscope_with_script_opt(script_content, 4, opt_level).await?;

    assert_eq!(
        exit_code, 0,
        "unexpected error: stderr={stderr}\nstdout={stdout}"
    );

    // Expect at least one line like: "(activity+1) = <value>" or "activity + 1 = <value>"
    // Accept either numeric '97' or "'a'" depending on encoding handling.
    let mut matched = false;
    for line in stdout.lines() {
        let t = line.trim();
        let is_name = t.starts_with("(activity+1) = ") || t.starts_with("activity + 1 = ");
        if is_name && (t.ends_with("97") || t.ends_with("'a'")) {
            matched = true;
            break;
        }
    }
    assert!(
        matched,
        "expected activity + 1 to print 'a' (97).\nSTDOUT: {stdout}\nSTDERR: {stderr}"
    );
    Ok(())
}

#[tokio::test]
async fn test_pointer_addition_scales_on_int_array() -> anyhow::Result<()> {
    // Verify: on calculate_average(int* numbers, int count), numbers+1 reads the 2nd int (20), numbers+2 reads 3rd (30)
    init();
    ensure_global_cleanup_registered();

    let opt_level = OptimizationLevel::Debug;
    let _ = get_global_test_pid_with_opt(opt_level).await?;

    let script_content = r#"
trace sample_program.c:42 {
    print numbers + 1;
    print numbers + 2;
}
"#;

    let (exit_code, stdout, stderr) =
        run_ghostscope_with_script_opt(script_content, 5, opt_level).await?;

    assert_eq!(
        exit_code, 0,
        "unexpected error: stderr={stderr}\nstdout={stdout}"
    );

    let mut saw_20 = false;
    let mut saw_30 = false;
    let mut addr1: Option<u64> = None;
    let mut addr2: Option<u64> = None;
    for line in stdout.lines() {
        let t = line.trim();
        if t.starts_with("(numbers+1) = ") {
            if t.ends_with("20") {
                saw_20 = true;
            }
            if let Some(ix) = t.rfind("0x") {
                let mut j = ix + 2;
                let bytes = t.as_bytes();
                while j < t.len() && bytes[j].is_ascii_hexdigit() {
                    j += 1;
                }
                if j > ix + 2 {
                    if let Ok(v) = u64::from_str_radix(&t[ix + 2..j], 16) {
                        addr1 = Some(v);
                    }
                }
            }
        }
        if t.starts_with("(numbers+2) = ") {
            if t.ends_with("30") {
                saw_30 = true;
            }
            if let Some(ix) = t.rfind("0x") {
                let mut j = ix + 2;
                let bytes = t.as_bytes();
                while j < t.len() && bytes[j].is_ascii_hexdigit() {
                    j += 1;
                }
                if j > ix + 2 {
                    if let Ok(v) = u64::from_str_radix(&t[ix + 2..j], 16) {
                        addr2 = Some(v);
                    }
                }
            }
        }
    }
    if !(saw_20 && saw_30) {
        if let (Some(a1), Some(a2)) = (addr1, addr2) {
            assert_eq!(
                a2.wrapping_sub(a1),
                4,
                "expected address delta 4 bytes.\nSTDOUT: {stdout}\nSTDERR: {stderr}"
            );
        } else {
            panic!("expected (numbers+1)=20 and (numbers+2)=30, or address delta=4.\nSTDOUT: {stdout}\nSTDERR: {stderr}");
        }
    }
    Ok(())
}

#[tokio::test]
async fn test_string_variable_copy_allowed_e2e() -> anyhow::Result<()> {
    init();
    ensure_global_cleanup_registered();

    let script_content = r#"
trace calculate_something {
    let s = "A";
    let p = s;
    print p;
}
"#;

    let (exit_code, _stdout, stderr) = run_ghostscope_with_script(script_content, 5).await?;
    assert_eq!(exit_code, 0, "unexpected error: stderr={stderr}");
    Ok(())
}

#[tokio::test]
async fn test_assignment_is_rejected_with_friendly_message_e2e() -> anyhow::Result<()> {
    init();
    ensure_global_cleanup_registered();

    // Immutable variables: reject assignment 'a = ...' with friendly error
    let script_content = r#"
trace calculate_something {
    let a = G_STATE.lib;
    a = G_STATE;
    if memcmp(a, hex("00"), 1) { print "A"; }
    else if memcmp(gm, hex("48"), 1) { print "B"; }
    else { print "C"; }
}
"#;

    let (exit_code, _stdout, stderr) = run_ghostscope_with_script(script_content, 2).await?;
    assert!(
        exit_code != 0,
        "expected compile-time error; stderr={stderr}"
    );
    assert!(
        stderr.contains("Assignment is not supported: variables are immutable"),
        "stderr should contain friendly assignment error. stderr={stderr}"
    );
    Ok(())
}

#[tokio::test]
async fn test_logical_mixed_precedence() -> anyhow::Result<()> {
    init();
    ensure_global_cleanup_registered();

    // Validate precedence: && has higher precedence than ||
    // (1 || 0 && 0) => 1 || (0 && 0) => true
    // (0 || 1 && 0) => 0 || (1 && 0) => false
    let script_content = r#"
trace calculate_something {
    print "MIX:{}|{}", (1 || 0 && 0), (0 || 1 && 0);
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script(script_content, 5).await?;
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    // Look for a line like: MIX:true|false
    let expected = "MIX:true|false";
    assert!(
        stdout.contains(expected),
        "Expected \"{expected}\". STDOUT: {stdout}"
    );
    Ok(())
}

#[tokio::test]
async fn test_logical_and_short_circuit_chain() -> anyhow::Result<()> {
    init();
    ensure_global_cleanup_registered();

    let script_content = r#"
trace calculate_something {
    // true && true && false => false
    print (1 && 1 && 0);
    // true && true && true => true
    print (1 && 1 && 1);
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script(script_content, 5).await?;
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    let saw_true = stdout.contains("true");
    let saw_false = stdout.contains("false");
    assert!(
        saw_true,
        "Expected at least one true result. STDOUT: {stdout}"
    );
    assert!(
        saw_false,
        "Expected at least one false result. STDOUT: {stdout}"
    );
    Ok(())
}

#[tokio::test]
async fn test_syntax_error() -> anyhow::Result<()> {
    init();
    ensure_global_cleanup_registered();

    let script_content = r#"
trace calculate_something {
    print "missing semicolon"  // Missing semicolon - should cause parse error
    invalid_token_here
}
"#;

    println!("=== Syntax Error Test ===");

    let (exit_code, stdout, stderr) = run_ghostscope_with_script(script_content, 5).await?;

    println!("Exit code: {exit_code}");
    println!("STDOUT: {stdout}");
    println!("STDERR: {stderr}");
    println!("=========================");

    // Should fail fast with syntax error
    assert_ne!(exit_code, 0, "Invalid syntax should cause non-zero exit");
    assert!(
        stderr.contains("Parse error") || stderr.contains("not running"),
        "Should contain parse error: {stderr}"
    );

    if stderr.contains("Parse error") {
        println!("✓ Syntax error correctly detected and rejected");
    } else {
        println!(
            "○ Ghostscope exited because target process ended before parsing (stderr: {})",
            stderr.trim()
        );
    }
    Ok(())
}

#[tokio::test]
async fn test_format_mismatch() -> anyhow::Result<()> {
    init();
    ensure_global_cleanup_registered();

    let script_content = r#"
trace calculate_something {
    print "format {} {} but only one arg", a;  // Format/argument count mismatch
}
"#;

    println!("=== Format Mismatch Test ===");

    let (exit_code, stdout, stderr) = run_ghostscope_with_script(script_content, 5).await?;

    println!("Exit code: {exit_code}");
    println!("STDOUT: {stdout}");
    println!("STDERR: {stderr}");
    println!("============================");

    // Should fail fast with format error
    assert_ne!(exit_code, 0, "Format mismatch should cause non-zero exit");

    // Check for format validation error
    if stderr.contains("Parse error")
        || stderr.contains("Type error")
        || stderr.contains("format")
        || stderr.contains("placeholders")
    {
        println!("✓ Format mismatch correctly detected");
    } else {
        println!("⚠️  Expected format validation error, got: {stderr}");
    }

    Ok(())
}

#[tokio::test]
async fn test_nonexistent_function() -> anyhow::Result<()> {
    init();
    ensure_global_cleanup_registered();

    let script_content = r#"
trace nonexistent_function_12345 {
    print "This function does not exist in sample_program";
}
"#;

    println!("=== Nonexistent Function Test ===");

    let (exit_code, stdout, stderr) = run_ghostscope_with_script(script_content, 5).await?;

    println!("Exit code: {exit_code}");
    println!("STDOUT: {stdout}");
    println!("STDERR: {stderr}");
    println!("=================================");

    // Should fail fast when function doesn't exist
    assert_ne!(
        exit_code, 0,
        "Nonexistent function should cause non-zero exit"
    );
    assert!(
        !stderr.contains("Parse error"),
        "Script syntax should be valid: {stderr}"
    );

    if stderr.contains("No uprobe configurations created") {
        println!("✓ Correctly detected that target function doesn't exist");
    } else {
        println!("⚠️  Expected 'No uprobe configurations' error, got: {stderr}");
    }

    Ok(())
}

#[tokio::test]
async fn test_function_level_tracing() -> anyhow::Result<()> {
    init();
    ensure_global_cleanup_registered();

    let script_content = r#"
trace calculate_something {
    print "CALC: a={} b={}", a, b;
}
"#;

    // Test with both optimization levels.
    // TODO: Re-enable optimized runs once we can reconstruct inlined symbols without full debug info.
    let optimization_levels = [OptimizationLevel::Debug, OptimizationLevel::O2];

    for opt_level in &optimization_levels {
        println!(
            "=== Function Level Tracing Test ({}) ===",
            opt_level.description()
        );

        if *opt_level != OptimizationLevel::Debug {
            println!(
                "⏭️  Skipping {} run (TODO: handle inlined symbols without full debug info)",
                opt_level.description()
            );
            continue;
        }

        let (exit_code, stdout, stderr) =
            run_ghostscope_with_script_opt(script_content, 3, *opt_level).await?;

        println!("Exit code: {exit_code}");
        println!("STDOUT: {stdout}");
        println!("STDERR: {stderr}");
        println!("===============================================");

        // If we have permissions, should run successfully and produce output
        assert_eq!(
            exit_code,
            0,
            "Ghostscope should succeed for {} (stderr: {})",
            opt_level.description(),
            stderr
        );

        println!("✓ Ghostscope attached and ran successfully");

        // Parse output to validate math: a == b - 5
        let mut math_validations = 0;
        let mut function_calls_found = 0;
        let mut validation_errors = Vec::new();

        for line in stdout.lines() {
            if line.contains("CALC: ") {
                function_calls_found += 1;
                if let Some((a, b)) = parse_calc_line_simple(line) {
                    if a == b - 5 {
                        println!("✓ Math validation passed: a={} == b-5={}", a, b - 5);
                        math_validations += 1;
                    } else {
                        let error_msg =
                            format!("Math validation failed: a={a} != b-5={} (b={b})", b - 5);
                        println!("{error_msg}");
                        validation_errors.push(error_msg);
                    }
                } else {
                    println!("⚠️  Failed to parse line: {line}");
                }
            }
        }

        if function_calls_found == 0 {
            panic!("❌ No function calls captured - test failed. Expected at least one calculate_something call. This indicates either:\n  1. sample_program is not running\n  2. Function is not being called\n  3. Ghostscope failed to attach properly");
        } else if !validation_errors.is_empty() {
            panic!("❌ Function calls captured but math validation failed:\n  Found {} function calls, {} validation errors:\n  {}",
            function_calls_found, validation_errors.len(), validation_errors.join("\n  "));
        } else if math_validations > 0 {
            println!("✓ Validated {math_validations} calculate_something calls");
        }

        println!("===============================================");
    }

    Ok(())
}

#[tokio::test]
async fn test_multiple_trace_targets() -> anyhow::Result<()> {
    init();
    ensure_global_cleanup_registered();

    // Test both function-level and line-level tracing in one script
    let script_content = r#"
trace calculate_something {
    print "FUNC: a={} b={}", a, b;
}

trace sample_program.c:16 {
    print "LINE16: a={} b={} result={}", a, b, result;
}
"#;

    let optimization_levels = [OptimizationLevel::Debug, OptimizationLevel::O2];

    for opt_level in &optimization_levels {
        println!(
            "=== Multiple Trace Targets Test ({}) ===",
            opt_level.description()
        );

        let (exit_code, stdout, stderr) =
            run_ghostscope_with_script_opt(script_content, 3, *opt_level).await?;

        println!("Exit code: {exit_code}");
        println!("STDOUT: {stdout}");
        println!("STDERR: {stderr}");
        println!("=====================================");

        // Check that script syntax is valid
        assert!(
            !stderr.contains("Parse error"),
            "Multi-target script should have valid syntax: {stderr}"
        );

        assert_eq!(
            exit_code,
            0,
            "Ghostscope should succeed for {} (stderr: {})",
            opt_level.description(),
            stderr
        );

        println!("✓ Multiple trace targets attached and ran successfully");

        // Check for both function-level and line-level outputs
        let has_func = stdout.contains("FUNC:");
        let has_line16 = stdout.contains("LINE16:");

        assert!(
            has_func,
            "Expected function-level trace output for {} but none was captured. STDOUT: {}",
            opt_level.description(),
            stdout
        );
        assert!(
            has_line16,
            "Expected line-level trace output for {} but none was captured. STDOUT: {}",
            opt_level.description(),
            stdout
        );

        println!("Trace capture status: FUNC={has_func}, LINE16={has_line16}");

        let mut func_validations = 0;
        let mut line_validations = 0;
        let mut validation_errors = Vec::new();

        // Detect optimized-out markers and bad placeholders
        let func_has_placeholder_zero = stdout.lines().any(|line| line.contains("FUNC: a=0 b=0"));
        let func_has_optimized_marker = stdout
            .lines()
            .any(|line| line.contains("FUNC:") && line.to_lowercase().contains("optimiz"));
        let line_has_optimized_marker = stdout
            .lines()
            .any(|line| line.contains("LINE16:") && line.to_lowercase().contains("optimiz"));

        // Validate function-level traces (a == b - 5). Skip non-numeric or optimized-out lines.
        for line in stdout.lines() {
            if line.contains("FUNC: ") {
                if let Some((a, b)) = parse_calc_line_simple(line) {
                    // Treat O2 placeholder zeros as non-valid (will be asserted below)
                    if *opt_level == OptimizationLevel::Debug || (a != 0 || b != 0) {
                        if a == b - 5 {
                            println!(
                                "✓ Function-level math validation passed: a={} == b-5={}",
                                a,
                                b - 5
                            );
                            func_validations += 1;
                        } else {
                            let error_msg = format!(
                                "Function-level validation failed: a={} != b-5={}",
                                a,
                                b - 5
                            );
                            println!("{error_msg}");
                            validation_errors.push(error_msg);
                        }
                    }
                }
            }
        }

        // Validate line-level traces (a * b + 42 == result)
        for line in stdout.lines() {
            if line.contains("LINE16: ") {
                if let Some((a, b, result)) = parse_line16_trace(line) {
                    let expected = a * b + 42;
                    if result == expected {
                        println!("✓ Line-level math validation passed: {a} * {b} + 42 = {result}");
                        line_validations += 1;
                    } else {
                        let error_msg = format!(
                            "Line-level validation failed: {a} * {b} + 42 = {expected} but got {result}"
                        );
                        println!("{error_msg}");
                        validation_errors.push(error_msg);
                    }
                }
            }
        }

        // Adjust validation policy for optimized builds
        if *opt_level == OptimizationLevel::Debug {
            if func_validations == 0 {
                panic!(
                    "❌ Expected function-level traces for {} but none validated successfully. STDOUT: {}",
                    opt_level.description(),
                    stdout
                );
            }
            if line_validations == 0 {
                panic!(
                    "❌ Expected line-level traces for {} but none validated successfully. STDOUT: {}",
                    opt_level.description(),
                    stdout
                );
            }
        } else {
            // In optimized builds, allow optimized-out markers in place of numeric validations,
            // but ensure we never emit placeholder zeros.
            assert!(
                    !func_has_placeholder_zero,
                    "Should not emit placeholder optimized-out values in optimized builds. STDOUT: {stdout}"
                );
            if func_validations == 0 && !func_has_optimized_marker {
                panic!(
                    "❌ Expected function-level traces to be either numerically valid or marked as optimized-out. STDOUT: {stdout}"
                );
            }
            if line_validations == 0 && !line_has_optimized_marker {
                panic!(
                    "❌ Expected line-level traces to be either numerically valid or marked as optimized-out. STDOUT: {stdout}"
                );
            }
        }

        if !validation_errors.is_empty() {
            panic!(
                "❌ Traces captured but validation failed:\n  Function validations: {}, Line validations: {}\n  Errors: {}",
                func_validations,
                line_validations,
                validation_errors.join("\n  ")
            );
        }

        println!(
            "✓ Multiple trace targets validated successfully: {func_validations} function traces, {line_validations} line traces"
        );

        println!("=====================================");
    }

    Ok(())
}
/// Parse a calc line and return only (a, b) for simple validation
fn parse_calc_line_simple(line: &str) -> Option<(i32, i32)> {
    // Expected format: "CALC: a=5 b=3 ..." or "FUNC: a=5 b=3" - we only care about a and b
    let line = line
        .trim_start_matches("CALC: ")
        .trim_start_matches("FUNC: ");

    let mut a = None;
    let mut b = None;

    for part in line.split_whitespace() {
        if let Some(value_str) = part.strip_prefix("a=") {
            a = value_str.parse().ok();
        } else if let Some(value_str) = part.strip_prefix("b=") {
            b = value_str.parse().ok();
        }
    }

    match (a, b) {
        (Some(a_val), Some(b_val)) => Some((a_val, b_val)),
        _ => {
            println!("⚠️  Failed to parse a and b from line: {line}");
            None
        }
    }
}

#[tokio::test]
async fn test_line_level_tracing() -> anyhow::Result<()> {
    init();
    ensure_global_cleanup_registered();

    // Test line-level tracing at sample_program.c:16 (return result;)
    let script_content = r#"
trace sample_program.c:16 {
    print "LINE16: a={} b={} result={}", a, b, result;
}
"#;

    println!("=== Line Level Tracing Test ===");

    let (exit_code, stdout, stderr) = run_ghostscope_with_script(script_content, 3).await?;

    println!("Exit code: {exit_code}");
    println!("STDOUT: {stdout}");
    println!("STDERR: {stderr}");
    println!("===============================================");

    // Must run successfully
    assert_eq!(exit_code, 0, "Ghostscope should succeed (stderr: {stderr})");

    // If we have permissions, should run successfully and produce output
    if exit_code == 0 {
        println!("✓ Ghostscope attached and ran successfully");

        // Parse output to validate math: a * b + 42 == result
        let mut math_validations = 0;
        let mut function_calls_found = 0;
        let mut validation_errors = Vec::new();

        for line in stdout.lines() {
            if line.contains("LINE16: ") {
                function_calls_found += 1;
                if let Some((a, b, result)) = parse_line16_trace(line) {
                    let expected = a * b + 42;
                    if result == expected {
                        println!("✓ Math validation passed: {a} * {b} + 42 = {result}");
                        math_validations += 1;
                    } else {
                        let error_msg = format!(
                            "Math validation failed: {a} * {b} + 42 = {expected} but got {result}"
                        );
                        println!("{error_msg}");
                        validation_errors.push(error_msg);
                    }
                } else {
                    println!("⚠️  Failed to parse line: {line}");
                }
            }
        }

        if function_calls_found == 0 {
            panic!("❌ No line traces captured - test failed. Expected at least one line:16 execution trace. This indicates either:\n  1. sample_program is not running\n  2. Line 16 is not being executed\n  3. Line-level tracing failed to attach");
        } else if !validation_errors.is_empty() {
            panic!("❌ Line traces captured but math validation failed:\n  Found {} line executions, {} validation errors:\n  {}",
                function_calls_found, validation_errors.len(), validation_errors.join("\n  "));
        } else if math_validations > 0 {
            println!("✓ Validated {math_validations} line:16 executions with correct math");
        }
    }

    Ok(())
}

/// Parse a line16 trace like "LINE16: a=5 b=3 result=57" and return (a, b, result)
fn parse_line16_trace(line: &str) -> Option<(i32, i32, i32)> {
    // Expected format: "LINE16: a=5 b=3 result=57"
    let line = line.trim_start_matches("LINE16: ");

    let mut a = None;
    let mut b = None;
    let mut result = None;

    for part in line.split_whitespace() {
        if let Some(value_str) = part.strip_prefix("a=") {
            a = value_str.parse().ok();
        } else if let Some(value_str) = part.strip_prefix("b=") {
            b = value_str.parse().ok();
        } else if let Some(value_str) = part.strip_prefix("result=") {
            result = value_str.parse().ok();
        }
    }

    match (a, b, result) {
        (Some(a_val), Some(b_val), Some(result_val)) => Some((a_val, b_val, result_val)),
        _ => {
            println!("⚠️  Failed to parse line16 trace: {line}");
            None
        }
    }
}

#[tokio::test]
async fn test_print_variables_directly() -> anyhow::Result<()> {
    init();
    ensure_global_cleanup_registered();

    // Test printing variables directly without format strings
    let script_content = r#"
trace calculate_something {
    print a;
    print b;
}
"#;

    println!("=== Print Variables Directly Test ===");

    let (exit_code, stdout, stderr) = run_ghostscope_with_script(script_content, 3).await?;

    println!("Exit code: {exit_code}");
    println!("STDOUT: {stdout}");
    println!("STDERR: {stderr}");
    println!("======================================");

    // Check that script syntax is valid
    assert!(
        !stderr.contains("Parse error"),
        "Print variables script should have valid syntax: {stderr}"
    );

    assert_eq!(exit_code, 0, "Ghostscope should succeed (stderr: {stderr})");

    if exit_code == 0 {
        println!("✓ Print variables script attached successfully");

        // Look for direct variable prints (should just be numbers)
        let mut variable_prints = 0;
        for line in stdout.lines() {
            // Direct variable prints should produce simple numeric output
            if line.trim().parse::<i32>().is_ok() {
                variable_prints += 1;
                println!("✓ Found variable print: {}", line.trim());
            }
        }

        if variable_prints > 0 {
            println!("✓ Successfully captured {variable_prints} variable prints");
        } else {
            println!("⚠️ No direct variable prints captured");
        }
    }

    Ok(())
}

#[tokio::test]
async fn test_custom_variables() -> anyhow::Result<()> {
    init();
    ensure_global_cleanup_registered();

    // Test custom variable definition and usage
    let script_content = r#"
trace calculate_something {
    let sum = a + b;
    let diff = a - b;
    let product = a * b;
    print "CUSTOM: sum={} diff={} product={}", sum, diff, product;
}
"#;

    println!("=== Custom Variables Test ===");

    let (exit_code, stdout, stderr) = run_ghostscope_with_script(script_content, 3).await?;

    println!("Exit code: {exit_code}");
    println!("STDOUT: {stdout}");
    println!("STDERR: {stderr}");
    println!("==============================");

    // Check that script syntax is valid
    assert!(
        !stderr.contains("Parse error"),
        "Custom variables script should have valid syntax: {stderr}"
    );

    assert_eq!(exit_code, 0, "Ghostscope should succeed (stderr: {stderr})");

    if exit_code == 0 {
        println!("✓ Custom variables script attached successfully");

        let mut custom_var_outputs = 0;
        let mut math_validations = 0;

        for line in stdout.lines() {
            if line.contains("CUSTOM: ") {
                custom_var_outputs += 1;
                if let Some((a, b, sum, diff, product)) = parse_custom_variables_line(line) {
                    let expected_sum = a + b;
                    let expected_diff = a - b;
                    let expected_product = a * b;

                    if sum == expected_sum && diff == expected_diff && product == expected_product {
                        math_validations += 1;
                        println!("✓ Custom variables validated: sum={a}+{b}={sum}, diff={a}-{b}={diff}, product={a}*{b}={product}");
                    } else {
                        println!("❌ Custom variables validation failed:");
                        println!(
                            "   Expected: sum={expected_sum}, diff={expected_diff}, product={expected_product}"
                        );
                        println!("   Got: sum={sum}, diff={diff}, product={product}");
                    }
                }
            }
        }

        if custom_var_outputs > 0 && math_validations > 0 {
            println!("✓ Successfully validated {math_validations} custom variable calculations");
        } else if custom_var_outputs > 0 {
            println!("⚠️ Custom variable outputs captured but validation failed");
        } else {
            println!("⚠️ No custom variable outputs captured");
        }
    }

    Ok(())
}

/// Parse a custom variables line like "CUSTOM: sum=8 diff=2 product=15" and return (a, b, sum, diff, product)
fn parse_custom_variables_line(line: &str) -> Option<(i32, i32, i32, i32, i32)> {
    // Expected format: "CUSTOM: sum=8 diff=2 product=15"
    // We need to reverse-engineer a and b from the calculations
    let line = line.trim_start_matches("CUSTOM: ");

    let mut sum = None;
    let mut diff = None;
    let mut product = None;

    for part in line.split_whitespace() {
        if let Some(value_str) = part.strip_prefix("sum=") {
            sum = value_str.parse().ok();
        } else if let Some(value_str) = part.strip_prefix("diff=") {
            diff = value_str.parse().ok();
        } else if let Some(value_str) = part.strip_prefix("product=") {
            product = value_str.parse().ok();
        }
    }

    match (sum, diff, product) {
        (Some(sum_val), Some(diff_val), Some(product_val)) => {
            // Reverse-engineer a and b from sum and diff
            // sum = a + b, diff = a - b
            // Therefore: a = (sum + diff) / 2, b = (sum - diff) / 2
            let a = (sum_val + diff_val) / 2;
            let b = (sum_val - diff_val) / 2;
            Some((a, b, sum_val, diff_val, product_val))
        }
        _ => {
            println!("⚠️  Failed to parse custom variables line: {line}");
            None
        }
    }
}

/// Independent test program instance (separate from global shared one)
struct TestProgramInstance {
    child: tokio::process::Child,
    pid: u32,
}

impl TestProgramInstance {
    async fn terminate(mut self) -> anyhow::Result<()> {
        println!("🛑 Terminating sample_program (PID: {})", self.pid);
        let _ = self.child.kill().await.is_ok();

        // Wait for termination with timeout
        match timeout(Duration::from_secs(2), self.child.wait()).await {
            Ok(_) => println!("✓ Test_program terminated gracefully"),
            Err(_) => {
                let _ = std::process::Command::new("kill")
                    .arg("-KILL")
                    .arg(self.pid.to_string())
                    .output();
                println!("⚠️ Force killed sample_program");
            }
        }
        Ok(())
    }
}

/// Start an independent sample_program instance (not shared with other tests)
async fn start_independent_sample_program() -> anyhow::Result<TestProgramInstance> {
    let binary_path = FIXTURES.get_test_binary("sample_program")?;

    let child = Command::new(binary_path)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;

    let pid = child
        .id()
        .ok_or_else(|| anyhow::anyhow!("Failed to get PID"))?;

    // Give it a moment to start
    tokio::time::sleep(Duration::from_millis(500)).await;

    Ok(TestProgramInstance { child, pid })
}

/// Run ghostscope with a specific PID (bypass global test program)
async fn run_ghostscope_with_specific_pid(
    script_content: &str,
    target_pid: u32,
    timeout_secs: u64,
) -> anyhow::Result<(i32, String, String)> {
    common::runner::GhostscopeRunner::new()
        .with_script(script_content)
        .with_pid(target_pid)
        .timeout_secs(timeout_secs)
        .enable_sysmon_shared_lib(false)
        .run()
        .await
}

#[tokio::test]
async fn test_invalid_pid_handling() -> anyhow::Result<()> {
    init();
    ensure_global_cleanup_registered();

    let script_content = r#"
trace calculate_something {
    print "Should never see this: a={} b={}", a, b;
}
"#;

    println!("=== Invalid PID Handling Test ===");

    // Use a non-existent PID
    let fake_pid = 999999;
    let (exit_code, stdout, stderr) =
        run_ghostscope_with_specific_pid(script_content, fake_pid, 3).await?;

    println!("Exit code: {exit_code}");
    println!("STDOUT: {stdout}");
    println!("STDERR: {stderr}");
    println!("=====================================");

    // Should fail quickly
    assert_ne!(exit_code, 0, "Invalid PID should cause non-zero exit");
    assert!(
        stderr.contains("No such process")
            || stderr.contains("Failed to attach")
            || stderr.contains("Invalid PID")
            || stderr.contains("Permission denied")
            || stderr.contains("Operation not permitted")
            || stderr.contains("is not running"),
        "Should contain appropriate error message: {stderr}"
    );

    println!("✓ Invalid PID correctly rejected");
    Ok(())
}

#[tokio::test]
async fn test_string_comparison_char_ptr() -> anyhow::Result<()> {
    init();
    ensure_global_cleanup_registered();

    // Compare const char* parameter against a script literal
    let script_content = r#"
trace log_activity {
    if (activity == "main_loop") {
        print "CSTR_EQ";
    }
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script(script_content, 5).await?;

    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");
    assert!(
        stdout.contains("CSTR_EQ"),
        "Expected to see CSTR_EQ when activity == 'main_loop'. STDOUT: {stdout}"
    );
    Ok(())
}

#[tokio::test]
async fn test_string_comparison_char_array() -> anyhow::Result<()> {
    init();
    ensure_global_cleanup_registered();

    // Compare char[32] field inside DataRecord against a script literal
    // Use process_record (called every loop) to shorten wait time
    let script_content = r#"
trace process_record {
    if (record.name == "test_record") {
        print "ARR_EQ";
    }
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script(script_content, 6).await?;
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");
    assert!(
        stdout.contains("ARR_EQ"),
        "Expected to see ARR_EQ when record.name == \"test_record\". STDOUT: {stdout}"
    );
    Ok(())
}

#[tokio::test]
async fn test_builtins_strncmp_starts_with_activity() -> anyhow::Result<()> {
    init();
    ensure_global_cleanup_registered();

    // Validate builtins on DWARF char* parameter in a hot function
    let script_content = r#"
trace log_activity {
    print "SN:{}", strncmp(activity, "main", 4);
    print "SW:{}", starts_with(activity, "main");
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script(script_content, 6).await?;
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    // Expect at least one true for both builtins
    assert!(
        stdout.lines().any(|l| l.contains("SN:true")),
        "Expected SN:true for strncmp(activity, \"main\", 4). STDOUT: {stdout}"
    );
    assert!(
        stdout.lines().any(|l| l.contains("SW:true")),
        "Expected SW:true for starts_with(activity, \"main\"). STDOUT: {stdout}"
    );
    Ok(())
}

#[tokio::test]
async fn test_builtin_strncmp_on_struct_pointer_mismatch() -> anyhow::Result<()> {
    init();
    ensure_global_cleanup_registered();

    // Negative case: pass a non-string pointer (DataRecord*) to strncmp; should be false
    // Use a hot function for quick events
    let script_content = r#"
trace process_record {
    print "REC_SN:{}", strncmp(record, "HTTP", 4);
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script(script_content, 6).await?;
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    assert!(
        stdout.lines().any(|l| l.contains("REC_SN:false")),
        "Expected REC_SN:false for non-string pointer compare. STDOUT: {stdout}"
    );
    Ok(())
}

#[tokio::test]
async fn test_bool_literals_in_expressions() -> anyhow::Result<()> {
    init();
    ensure_global_cleanup_registered();

    // Validate boolean literals in expressions (both orders) and negative cases
    let script_content = r#"
trace log_activity {
    // positive cases
    print "B1:{}", starts_with(activity, "main") == true;
    print "B4:{}", true == starts_with(activity, "main");
    // unary not
    print "BN1:{}", !starts_with(activity, "main");
    // negative (non-match literal)
    print "B6:{}", starts_with(activity, "zzz") == false;
}

trace process_record {
    // positive cases
    print "B2:{}", strncmp(record, "HTTP", 4) == false;
    print "B3:{}", false == strncmp(record, "HTTP", 4);
    // unary not
    print "BN2:{}", !strncmp(record, "HTTP", 4);
    // negative case (should be false)
    print "B5:{}", strncmp(record, "HTTP", 4) == true;
}
"#;

    let (exit_code, stdout, stderr) = run_ghostscope_with_script(script_content, 6).await?;
    assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");

    // positives
    assert!(
        stdout.lines().any(|l| l.contains("B1:true")),
        "Expected B1:true. STDOUT: {stdout}"
    );
    assert!(
        stdout.lines().any(|l| l.contains("B2:true")),
        "Expected B2:true. STDOUT: {stdout}"
    );
    assert!(
        stdout.lines().any(|l| l.contains("B3:true")),
        "Expected B3:true. STDOUT: {stdout}"
    );
    assert!(
        stdout.lines().any(|l| l.contains("B4:true")),
        "Expected B4:true. STDOUT: {stdout}"
    );
    assert!(
        stdout.lines().any(|l| l.contains("B6:true")),
        "Expected B6:true. STDOUT: {stdout}"
    );
    // negative and unary not checks
    assert!(
        stdout.lines().any(|l| l.contains("B5:false")),
        "Expected B5:false. STDOUT: {stdout}"
    );
    assert!(
        stdout.lines().any(|l| l.contains("BN1:false")),
        "Expected BN1:false. STDOUT: {stdout}"
    );
    assert!(
        stdout.lines().any(|l| l.contains("BN2:true")),
        "Expected BN2:true. STDOUT: {stdout}"
    );
    Ok(())
}

#[tokio::test]
async fn test_correct_pid_filtering() -> anyhow::Result<()> {
    init();
    ensure_global_cleanup_registered();

    let script_content = r#"
trace calculate_something {
    print "FILTERED: a={} b={}", a, b;
}
"#;

    println!("=== Correct PID Filtering Test ===");

    // Start two independent sample_program processes
    let sample_program_1 = start_independent_sample_program().await?;
    let sample_program_2 = start_independent_sample_program().await?;

    println!(
        "Started sample_program_1 with PID: {}",
        sample_program_1.pid
    );
    println!(
        "Started sample_program_2 with PID: {}",
        sample_program_2.pid
    );

    // Only trace the first process
    let (exit_code, stdout, stderr) =
        run_ghostscope_with_specific_pid(script_content, sample_program_1.pid, 3).await?;

    println!("Exit code: {exit_code}");
    println!("STDOUT: {stdout}");
    println!("STDERR: {stderr}");
    println!("=====================================");

    // Clean up processes
    sample_program_1.terminate().await?;
    sample_program_2.terminate().await?;

    if exit_code == 0 {
        let filtered_outputs = stdout
            .lines()
            .filter(|line| line.contains("FILTERED:"))
            .count();

        if filtered_outputs > 0 {
            println!("✓ Successfully captured {filtered_outputs} function calls from target PID");
            println!("✓ PID filtering working correctly");
        } else {
            println!("⚠️ No function calls captured, but PID filtering test completed");
        }
    } else {
        println!("⚠️ Unexpected exit code: {exit_code}. STDERR: {stderr}");
    }

    Ok(())
}

#[tokio::test]
async fn test_pid_specificity_with_multiple_processes() -> anyhow::Result<()> {
    init();
    ensure_global_cleanup_registered();

    let script_content = r#"
trace calculate_something {
    print "TARGET_ONLY: traced a={} b={}", a, b;
}
"#;

    println!("=== PID Specificity with Multiple Processes Test ===");

    // Start 3 independent sample_program processes
    let programs = vec![
        start_independent_sample_program().await?,
        start_independent_sample_program().await?,
        start_independent_sample_program().await?,
    ];

    for (i, program) in programs.iter().enumerate() {
        println!("Started sample_program_{} with PID: {}", i + 1, program.pid);
    }

    // Only trace the middle process (programs[1])
    let target_pid = programs[1].pid;
    let (exit_code, stdout, stderr) =
        run_ghostscope_with_specific_pid(script_content, target_pid, 4).await?;

    println!("Target PID: {target_pid}");
    println!("Exit code: {exit_code}");
    println!("STDOUT: {stdout}");
    println!("STDERR: {stderr}");
    println!("==================================================");

    // Clean up all processes
    for program in programs {
        program.terminate().await?;
    }

    if exit_code == 0 {
        let traced_outputs = stdout
            .lines()
            .filter(|line| line.contains("TARGET_ONLY:"))
            .count();

        if traced_outputs > 0 {
            println!("✓ Successfully captured {traced_outputs} function calls");
            println!("✓ PID specificity verified - only target process traced");
        } else {
            println!("⚠️ No function calls captured during test window");
        }
    } else {
        println!("⚠️ Unexpected exit code: {exit_code}. STDERR: {stderr}");
    }

    Ok(())
}

#[tokio::test]
#[serial_test::serial]
async fn test_stripped_binary_with_debuglink() -> anyhow::Result<()> {
    init();
    ensure_global_cleanup_registered();

    // Compile stripped binary with separate debug file
    common::ensure_test_program_compiled_with_opt(OptimizationLevel::Stripped)?;

    let script_content = r#"
trace add_numbers {
    print "STRIPPED_BINARY: add_numbers called with a={} b={}", a, b;
}
"#;

    println!("=== Stripped Binary with .gnu_debuglink Test ===");

    // Start stripped binary
    let binary_path =
        FIXTURES.get_test_binary_with_opt("sample_program", OptimizationLevel::Stripped)?;

    println!("Binary path: {}", binary_path.display());

    // Verify debug file exists
    let debug_file = binary_path.with_file_name("sample_program_stripped.debug");
    assert!(
        debug_file.exists(),
        "Debug file should exist: {}",
        debug_file.display()
    );
    println!("Debug file found: {}", debug_file.display());

    // Verify binary is actually stripped
    let output = std::process::Command::new("readelf")
        .args(["-S", binary_path.to_str().unwrap()])
        .output()?;
    let sections_output = String::from_utf8_lossy(&output.stdout);

    if sections_output.contains(".debug_info") {
        println!("⚠️ Warning: Binary still contains .debug_info section");
    } else {
        println!("✓ Binary is stripped (no .debug_info section)");
    }

    if sections_output.contains(".gnu_debuglink") {
        println!("✓ Binary has .gnu_debuglink section");
    } else {
        println!("⚠️ Warning: Binary missing .gnu_debuglink section");
    }

    // Start the stripped binary
    let mut child = Command::new(&binary_path)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;

    let pid = child.id().expect("Failed to get PID");
    println!("Started stripped binary with PID: {pid}");

    // Give it time to start
    tokio::time::sleep(Duration::from_millis(100)).await;

    // Run ghostscope with the stripped binary
    let (exit_code, stdout, stderr) =
        run_ghostscope_with_specific_pid(script_content, pid, 3).await?;

    println!("Exit code: {exit_code}");
    println!("STDOUT: {stdout}");
    println!("STDERR: {stderr}");
    println!("===============================================");

    // Clean up
    let _ = child.kill().await.is_ok();

    // Verify results
    if exit_code == 0 {
        let traced_outputs = stdout
            .lines()
            .filter(|line| line.contains("STRIPPED_BINARY:"))
            .count();

        if traced_outputs > 0 {
            println!("✓ Successfully traced {traced_outputs} function calls from stripped binary");
            println!("✓ .gnu_debuglink mechanism working correctly");
            println!("✓ Uprobe offset calculation correct for stripped binary");
        } else {
            println!("⚠️ No function calls captured, but debuglink loading succeeded");
        }

        // Verify that debug info was actually loaded from debuglink
        if stderr.contains("Looking for debug file")
            || stderr.contains("Loading DWARF from separate debug file")
        {
            println!("✓ Confirmed: Debug info loaded from .gnu_debuglink");
        }
    } else {
        // Check for specific error messages
        if stderr.contains("No debug information found") {
            println!("✗ Failed: Could not load debug information from .gnu_debuglink");
            anyhow::bail!("Debug information not found - .gnu_debuglink not working");
        } else {
            println!("⚠️ Unexpected exit code: {exit_code}. STDERR: {stderr}");
        }
    }

    Ok(())
}