runmat 0.0.17

High-performance MATLAB/Octave runtime with Jupyter kernel support
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
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
//! RunMat - High-performance MATLAB/Octave code runtime
//!
//! A modern, V8-inspired MATLAB code runtime with Jupyter kernel support,
//! JIT compilation, generational garbage collection, and excellent developer ergonomics.

use anyhow::{Context, Result};
use clap::{Parser, Subcommand, ValueEnum};
use env_logger::Env;
use log::{debug, error, info};

mod config;
use config::{ConfigLoader, PlotBackend, PlotMode, RunMatConfig};
use runmat_builtins::Value;
use runmat_gc::{
    gc_allocate, gc_collect_major, gc_collect_minor, gc_get_config, gc_stats, GcConfig,
};
use runmat_kernel::{ConnectionInfo, KernelConfig, KernelServer};
use runmat_repl::ReplEngine;
use runmat_snapshot::presets::SnapshotPreset;
use runmat_snapshot::{SnapshotBuilder, SnapshotConfig, SnapshotLoader};
use std::fs;
use std::path::PathBuf;
use std::time::Duration;

#[derive(Parser)]
#[command(
    name = "runmat",
    version = "0.0.2",
    about = "High-performance MATLAB/Octave code runtime",
    long_about = r#"
RunMat is a modern, high-performance runtime for MATLAB/Octave code built 
by Dystr (https://dystr.com).

It is built in Rust, and features a V8-inspired tiered execution model with a 
baseline interpreter feeding an optimizing JIT compiler built on Cranelift.

Key features:
• JIT compilation with Cranelift for optimal performance
• Generational garbage collection with configurable policies
• High-performance BLAS/LAPACK operations
• Jupyter kernel protocol support with async execution
• Fast startup with snapshotting capabilities
• World-class error messages and debugging
• Compatible with MATLAB/Octave syntax and semantics

Performance Features:
• Multi-tier execution: interpreter + JIT compiler
• Adaptive optimization based on hotspot profiling
• Generational GC with write barriers and concurrent collection
• SIMD-optimized mathematical operations
• Zero-copy memory management where possible

Examples:
  runmat                                   # Start interactive REPL with JIT
  runmat --no-jit                          # Start REPL with interpreter only
  runmat --gc-preset low-latency           # Optimize GC for low latency
  runmat script.m                          # Execute MATLAB/Octave script
  runmat --install-kernel                  # Install as Jupyter kernel
  runmat kernel                            # Start Jupyter kernel
  runmat kernel-connection connection.json # Start with connection file
  runmat --version --detailed              # Show detailed version information
"#,
    after_help = r#"
Environment Variables:
  RUSTMAT_DEBUG=1              Enable debug logging
  RUSTMAT_LOG_LEVEL=debug      Set log level (error, warn, info, debug, trace)
  RUSTMAT_KERNEL_IP=127.0.0.1  Kernel IP address  
  RUSTMAT_KERNEL_KEY=<key>     Kernel authentication key
  RUSTMAT_TIMEOUT=300          Execution timeout in seconds
  RUSTMAT_CONFIG=<path>        Path to configuration file
  RUSTMAT_SNAPSHOT_PATH=<path> Snapshot file to preload standard library
  
  Garbage Collector:
  RUSTMAT_GC_PRESET=<preset>   GC preset (low-latency, high-throughput, low-memory, debug)
  RUSTMAT_GC_YOUNG_SIZE=<mb>   Young generation size in MB
  RUSTMAT_GC_THREADS=<n>       Number of GC threads
  
  JIT Compiler:
  RUSTMAT_JIT_ENABLE=1         Enable JIT compilation (default: true)
  RUSTMAT_JIT_THRESHOLD=<n>    JIT compilation threshold (default: 10)
  RUSTMAT_JIT_OPT_LEVEL=<0-3>  JIT optimization level (default: 2)

For more information, visit: https://github.com/runmat-org/runmat
"#
)]
#[command(propagate_version = true)]
struct Cli {
    /// Enable debug logging
    #[arg(short, long, env = "RUSTMAT_DEBUG", value_parser = parse_bool_env)]
    debug: bool,

    /// Set log level
    #[arg(long, value_enum, env = "RUSTMAT_LOG_LEVEL", default_value = "info", value_parser = parse_log_level_env)]
    log_level: LogLevel,

    /// Execution timeout in seconds
    #[arg(long, env = "RUSTMAT_TIMEOUT", default_value = "300")]
    timeout: u64,

    /// Configuration file path
    #[arg(long, env = "RUSTMAT_CONFIG")]
    config: Option<PathBuf>,

    // JIT Compiler Options
    /// Disable JIT compilation (use interpreter only)
    #[arg(long, env = "RUSTMAT_JIT_DISABLE", value_parser = parse_bool_env)]
    no_jit: bool,

    /// JIT compilation threshold (number of executions before JIT)
    #[arg(long, env = "RUSTMAT_JIT_THRESHOLD", default_value = "10")]
    jit_threshold: u32,

    /// JIT optimization level (0-3)
    #[arg(
        long,
        value_enum,
        env = "RUSTMAT_JIT_OPT_LEVEL",
        default_value = "speed"
    )]
    jit_opt_level: OptLevel,

    // Garbage Collector Options
    /// GC configuration preset
    #[arg(long, value_enum, env = "RUSTMAT_GC_PRESET")]
    gc_preset: Option<GcPreset>,

    /// Young generation size in MB
    #[arg(long, env = "RUSTMAT_GC_YOUNG_SIZE")]
    gc_young_size: Option<usize>,

    /// Maximum number of GC threads
    #[arg(long, env = "RUSTMAT_GC_THREADS")]
    gc_threads: Option<usize>,

    /// Enable GC statistics collection
    #[arg(long, env = "RUSTMAT_GC_STATS", value_parser = parse_bool_env)]
    gc_stats: bool,

    /// Verbose output for REPL and execution
    #[arg(short, long)]
    verbose: bool,

    /// Snapshot file to preload standard library
    #[arg(long, env = "RUSTMAT_SNAPSHOT_PATH")]
    snapshot: Option<PathBuf>,

    // Plotting Options
    /// Plotting mode
    #[arg(long, value_enum, env = "RUSTMAT_PLOT_MODE")]
    plot_mode: Option<PlotMode>,

    /// Force headless plotting mode
    #[arg(long, env = "RUSTMAT_PLOT_HEADLESS", value_parser = parse_bool_env)]
    plot_headless: bool,

    /// Plotting backend
    #[arg(long, value_enum, env = "RUSTMAT_PLOT_BACKEND")]
    plot_backend: Option<PlotBackend>,

    // config_file is now handled by the config field above
    /// Generate sample configuration file
    #[arg(long)]
    generate_config: bool,

    /// Install RunMat as a Jupyter kernel
    #[arg(long)]
    install_kernel: bool,

    /// Command to execute
    #[command(subcommand)]
    command: Option<Commands>,

    /// MATLAB script file to execute (alternative to subcommands)
    script: Option<PathBuf>,
}

#[derive(Subcommand, Clone)]
enum Commands {
    /// Start interactive REPL
    Repl {
        /// Enable verbose output
        #[arg(short, long)]
        verbose: bool,
    },

    /// Start Jupyter kernel
    Kernel {
        /// Kernel IP address
        #[arg(long, env = "RUSTMAT_KERNEL_IP", default_value = "127.0.0.1")]
        ip: String,

        /// Kernel authentication key
        #[arg(long, env = "RUSTMAT_KERNEL_KEY")]
        key: Option<String>,

        /// Transport protocol
        #[arg(long, default_value = "tcp")]
        transport: String,

        /// Signature scheme
        #[arg(long, default_value = "hmac-sha256")]
        signature_scheme: String,

        /// Shell socket port (0 for auto-assign)
        #[arg(long, env = "RUSTMAT_SHELL_PORT", default_value = "0")]
        shell_port: u16,

        /// IOPub socket port (0 for auto-assign)
        #[arg(long, env = "RUSTMAT_IOPUB_PORT", default_value = "0")]
        iopub_port: u16,

        /// Stdin socket port (0 for auto-assign)
        #[arg(long, env = "RUSTMAT_STDIN_PORT", default_value = "0")]
        stdin_port: u16,

        /// Control socket port (0 for auto-assign)
        #[arg(long, env = "RUSTMAT_CONTROL_PORT", default_value = "0")]
        control_port: u16,

        /// Heartbeat socket port (0 for auto-assign)
        #[arg(long, env = "RUSTMAT_HB_PORT", default_value = "0")]
        hb_port: u16,

        /// Write connection file to path
        #[arg(long)]
        connection_file: Option<PathBuf>,
    },

    /// Start kernel with connection file
    KernelConnection {
        /// Path to Jupyter connection file
        connection_file: PathBuf,
    },

    /// Execute MATLAB script file
    Run {
        /// Script file to execute
        file: PathBuf,

        /// Arguments to pass to script
        #[arg(last = true)]
        args: Vec<String>,
    },

    /// Show version information
    Version {
        /// Show detailed version information
        #[arg(long)]
        detailed: bool,
    },

    /// Show system information
    Info,

    /// Garbage collection utilities
    Gc {
        #[command(subcommand)]
        gc_command: GcCommand,
    },

    /// Performance benchmarking
    Benchmark {
        /// Script file to benchmark
        file: PathBuf,

        /// Number of iterations
        #[arg(short, long, default_value = "10")]
        iterations: u32,

        /// Enable JIT for benchmark
        #[arg(long)]
        jit: bool,
    },

    /// Snapshot management
    Snapshot {
        #[command(subcommand)]
        snapshot_command: SnapshotCommand,
    },

    /// Interactive plotting window (requires GUI features)
    Plot {
        /// Plot mode override
        #[arg(long, value_enum)]
        mode: Option<PlotMode>,

        /// Window width
        #[arg(long)]
        width: Option<u32>,

        /// Window height
        #[arg(long)]
        height: Option<u32>,
    },

    /// Configuration management
    Config {
        #[command(subcommand)]
        config_command: ConfigCommand,
    },
    /// Package manager (coming soon)
    Pkg {
        #[command(subcommand)]
        pkg_command: PkgCommand,
    },
}

#[derive(Subcommand, Clone)]
enum GcCommand {
    /// Show GC statistics
    Stats,
    /// Force minor collection
    Minor,
    /// Force major collection
    Major,
    /// Show current configuration
    Config,
    /// Test GC under stress
    Stress {
        /// Number of allocations
        #[arg(short, long, default_value = "10000")]
        allocations: usize,
    },
}

#[derive(Subcommand, Clone)]
enum SnapshotCommand {
    /// Create a new snapshot
    Create {
        /// Output snapshot file
        #[arg(short, long)]
        output: PathBuf,
        /// Optimization level
        #[arg(short = 'O', long, value_enum, default_value = "speed")]
        optimization: OptLevel,
        /// Compression algorithm
        #[arg(short, long, value_enum)]
        compression: Option<CompressionAlg>,
    },
    /// Load and inspect a snapshot
    Info {
        /// Snapshot file to inspect
        snapshot: PathBuf,
    },
    /// List available presets
    Presets,
    /// Validate a snapshot file
    Validate {
        /// Snapshot file to validate
        snapshot: PathBuf,
    },
}

#[derive(Subcommand, Clone)]
enum ConfigCommand {
    /// Show current configuration
    Show,
    /// Generate sample configuration file
    Generate {
        /// Output file path
        #[arg(short, long, default_value = ".runmat.yaml")]
        output: PathBuf,
    },
    /// Validate configuration file
    Validate {
        /// Config file to validate
        config_file: PathBuf,
    },
    /// Show configuration file locations
    Paths,
}

#[derive(Subcommand, Clone)]
enum PkgCommand {
    /// Add a dependency (coming soon)
    Add { name: String },
    /// Remove a dependency (coming soon)
    Remove { name: String },
    /// Install dependencies (coming soon)
    Install,
    /// Update dependencies (coming soon)
    Update,
    /// Publish current package (coming soon)
    Publish,
}

#[derive(Clone, Debug, ValueEnum)]
enum CompressionAlg {
    /// No compression
    None,
    /// LZ4 compression (fast)
    Lz4,
    /// Zstd compression (balanced)
    Zstd,
}

#[derive(Clone, ValueEnum)]
enum LogLevel {
    Error,
    Warn,
    Info,
    Debug,
    Trace,
}

#[derive(Clone, Debug, ValueEnum)]
enum OptLevel {
    /// No optimization
    None,
    /// Minimal optimization
    Size,
    /// Balanced optimization (default)
    Speed,
    /// Maximum optimization
    Aggressive,
}

#[derive(Clone, Debug, ValueEnum)]
enum GcPreset {
    /// Minimize pause times
    LowLatency,
    /// Maximize throughput
    HighThroughput,
    /// Minimize memory usage
    LowMemory,
    /// Debug and analysis mode
    Debug,
}

impl From<LogLevel> for log::LevelFilter {
    fn from(level: LogLevel) -> Self {
        match level {
            LogLevel::Error => log::LevelFilter::Error,
            LogLevel::Warn => log::LevelFilter::Warn,
            LogLevel::Info => log::LevelFilter::Info,
            LogLevel::Debug => log::LevelFilter::Debug,
            LogLevel::Trace => log::LevelFilter::Trace,
        }
    }
}

impl From<GcPreset> for GcConfig {
    fn from(preset: GcPreset) -> Self {
        match preset {
            GcPreset::LowLatency => GcConfig::low_latency(),
            GcPreset::HighThroughput => GcConfig::high_throughput(),
            GcPreset::LowMemory => GcConfig::low_memory(),
            GcPreset::Debug => GcConfig::debug(),
        }
    }
}

/// Custom parser for boolean environment variables that accepts both "1"/"0" and "true"/"false"
fn parse_bool_env(s: &str) -> Result<bool, String> {
    match s.to_lowercase().as_str() {
        "1" | "true" | "yes" | "on" => Ok(true),
        "0" | "false" | "no" | "off" => Ok(false),
        "" => Ok(false), // Empty string defaults to false
        _ => Err(format!(
            "Invalid boolean value '{s}'. Expected: 1/0, true/false, yes/no, on/off"
        )),
    }
}

/// Custom parser for log level environment variables that handles empty strings
fn parse_log_level_env(s: &str) -> Result<LogLevel, String> {
    if s.is_empty() {
        return Ok(LogLevel::Info); // Default to info for empty string
    }

    match s.to_lowercase().as_str() {
        "error" => Ok(LogLevel::Error),
        "warn" => Ok(LogLevel::Warn),
        "info" => Ok(LogLevel::Info),
        "debug" => Ok(LogLevel::Debug),
        "trace" => Ok(LogLevel::Trace),
        _ => Err(format!(
            "Invalid log level '{s}'. Expected: error, warn, info, debug, trace"
        )),
    }
}

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();

    // Handle config generation first
    if cli.generate_config {
        let sample_config = ConfigLoader::generate_sample_config();
        println!("{sample_config}");
        return Ok(());
    }

    // Handle kernel installation
    if cli.install_kernel {
        return install_jupyter_kernel().await;
    }

    // Load configuration with CLI overrides
    let mut config = match load_configuration(&cli) {
        Ok(c) => c,
        Err(e) => {
            // Be forgiving for pkg commands: if config path is a directory `.runmat`, continue with defaults
            if matches!(cli.command, Some(Commands::Pkg { .. })) {
                eprintln!("Warning: {e}. Using default configuration for pkg command.");
                RunMatConfig::default()
            } else {
                return Err(e);
            }
        }
    };
    apply_cli_overrides(&mut config, &cli);

    // Initialize logging based on final config
    let log_level = if config.logging.debug || cli.debug {
        log::LevelFilter::Debug
    } else {
        match config.logging.level {
            config::LogLevel::Error => log::LevelFilter::Error,
            config::LogLevel::Warn => log::LevelFilter::Warn,
            config::LogLevel::Info => log::LevelFilter::Info,
            config::LogLevel::Debug => log::LevelFilter::Debug,
            config::LogLevel::Trace => log::LevelFilter::Trace,
        }
    };

    env_logger::Builder::from_env(Env::default().default_filter_or("info"))
        .filter_level(log_level)
        .init();

    // Register a minimal in-process acceleration provider so gpuArray/gather work out of the box
    runmat_accelerate::simple_provider::register_inprocess_provider();

    info!("RunMat v{} starting", env!("CARGO_PKG_VERSION"));
    debug!("Configuration loaded: {config:?}");

    // Configure Garbage Collector
    configure_gc_from_config(&config)?;

    // Initialize GUI system if needed
    let _gui_initialized = if config.plotting.mode == PlotMode::Gui
        || (config.plotting.mode == PlotMode::Auto && !config.plotting.force_headless)
    {
        info!("Initializing GUI plotting system");

        // Register this thread as the main thread for GUI operations
        runmat_plot::register_main_thread();

        // Initialize native window system (handles macOS main thread requirements)
        match runmat_plot::gui::initialize_native_window() {
            Ok(()) => {
                info!("Native window system initialized successfully");
            }
            Err(e) => {
                info!("Native window initialization failed: {e}, using thread manager");
            }
        }

        // Initialize GUI thread manager for cross-platform compatibility
        match runmat_plot::initialize_gui_manager() {
            Ok(()) => {
                info!("GUI thread manager initialized successfully");

                // Perform a health check to ensure the system is working
                match runmat_plot::health_check_global() {
                    Ok(result) => {
                        info!("GUI system health check: {result}");
                        true
                    }
                    Err(e) => {
                        error!("GUI system health check failed: {e}");
                        // Continue anyway, might work when actually needed
                        true
                    }
                }
            }
            Err(e) => {
                error!("Failed to initialize GUI thread manager: {e}");
                false
            }
        }
    } else {
        false
    };

    // Handle command or script execution
    let command = cli.command.clone();
    let script = cli.script.clone();
    match (command, script) {
        (Some(command), None) => execute_command(command, &cli, &config).await,
        (None, Some(script)) => execute_script(script, &cli, &config).await,
        (None, None) => {
            // Default to REPL
            execute_repl(&config).await
        }
        (Some(_), Some(_)) => {
            error!("Cannot specify both command and script file");
            std::process::exit(1);
        }
    }
}

/// Load configuration from files and environment
fn load_configuration(cli: &Cli) -> Result<RunMatConfig> {
    // Check if config file was explicitly provided via CLI (not just env var)
    // We can detect this by checking if RUSTMAT_CONFIG env var matches the cli.config value
    let config_from_env = std::env::var("RUSTMAT_CONFIG").ok().map(PathBuf::from);

    if let Some(config_file) = &cli.config {
        // If config matches env var, it came from environment - be graceful
        let is_from_env = config_from_env.as_ref() == Some(config_file);

        if config_file.exists() {
            if config_file.is_dir() {
                // Ignore directories per policy; fall back to standard loader
                info!(
                    "Config path is a directory, ignoring: {}",
                    config_file.display()
                );
            } else {
                info!("Loading configuration from: {}", config_file.display());
                return ConfigLoader::load_from_file(config_file);
            }
        } else if !is_from_env {
            // Only exit if explicitly specified via CLI, not env var
            error!(
                "Specified config file does not exist: {}",
                config_file.display()
            );
            std::process::exit(1);
        }
        // If from env var and doesn't exist, fall through to standard loader
    }

    // Use the standard loader (which will also check RUSTMAT_CONFIG but gracefully)
    match ConfigLoader::load() {
        Ok(c) => Ok(c),
        Err(e) => {
            // Ignore directory config paths and fall back to defaults
            if let Ok(conf_env) = std::env::var("RUSTMAT_CONFIG") {
                let p = PathBuf::from(conf_env);
                if p.is_dir() {
                    info!(
                        "Config path from env is a directory, ignoring: {}",
                        p.display()
                    );
                    return Ok(RunMatConfig::default());
                }
            }

            if let Some(home) = dirs::home_dir() {
                let dir = home.join(".runmat");
                if dir.is_dir() {
                    info!(
                        "Home config path is a directory, ignoring: {}",
                        dir.display()
                    );
                    return Ok(RunMatConfig::default());
                }
            }

            Err(e)
        }
    }
}

/// Apply CLI argument overrides to configuration
fn apply_cli_overrides(config: &mut RunMatConfig, cli: &Cli) {
    // JIT settings
    if cli.no_jit {
        config.jit.enabled = false;
    }
    config.jit.threshold = cli.jit_threshold;
    config.jit.optimization_level = match cli.jit_opt_level {
        OptLevel::None => config::JitOptLevel::None,
        OptLevel::Size => config::JitOptLevel::Size,
        OptLevel::Speed => config::JitOptLevel::Speed,
        OptLevel::Aggressive => config::JitOptLevel::Aggressive,
    };

    // Runtime settings
    config.runtime.timeout = cli.timeout;
    config.runtime.verbose = cli.verbose;
    if let Some(snapshot) = &cli.snapshot {
        config.runtime.snapshot_path = Some(snapshot.clone());
    }

    // GC settings
    if let Some(preset) = &cli.gc_preset {
        config.gc.preset = Some(match preset {
            GcPreset::LowLatency => config::GcPreset::LowLatency,
            GcPreset::HighThroughput => config::GcPreset::HighThroughput,
            GcPreset::LowMemory => config::GcPreset::LowMemory,
            GcPreset::Debug => config::GcPreset::Debug,
        });
    }
    if let Some(young_size) = cli.gc_young_size {
        config.gc.young_size_mb = Some(young_size);
    }
    if let Some(threads) = cli.gc_threads {
        config.gc.threads = Some(threads);
    }
    config.gc.collect_stats = cli.gc_stats;

    // Plotting settings
    if let Some(plot_mode) = &cli.plot_mode {
        config.plotting.mode = *plot_mode;
        // Also set environment variable so runtime can see it
        let env_value = match plot_mode {
            PlotMode::Auto => "auto",
            PlotMode::Gui => "gui",
            PlotMode::Headless => "headless",
            PlotMode::Jupyter => "jupyter",
        };
        std::env::set_var("RUSTMAT_PLOT_MODE", env_value);
    }
    if cli.plot_headless {
        config.plotting.force_headless = true;
        std::env::set_var("RUSTMAT_PLOT_MODE", "headless");
    }
    if let Some(backend) = &cli.plot_backend {
        config.plotting.backend = *backend;
    }

    // Logging settings
    config.logging.debug = cli.debug;
    config.logging.level = match cli.log_level {
        LogLevel::Error => config::LogLevel::Error,
        LogLevel::Warn => config::LogLevel::Warn,
        LogLevel::Info => config::LogLevel::Info,
        LogLevel::Debug => config::LogLevel::Debug,
        LogLevel::Trace => config::LogLevel::Trace,
    };
}

/// Configure GC from the loaded configuration
fn configure_gc_from_config(config: &RunMatConfig) -> Result<()> {
    let mut gc_config = if let Some(preset) = &config.gc.preset {
        (*preset).into()
    } else {
        runmat_gc::GcConfig::default()
    };

    // Apply custom GC settings from config
    if let Some(young_size) = config.gc.young_size_mb {
        gc_config.young_generation_size = young_size * 1024 * 1024; // Convert MB to bytes
    }

    if let Some(threads) = config.gc.threads {
        gc_config.max_gc_threads = threads;
    }

    gc_config.collect_statistics = config.gc.collect_stats;
    gc_config.verbose_logging = config.logging.debug || config.runtime.verbose;

    info!(
        "Configuring GC with preset: {:?}",
        config
            .gc
            .preset
            .map(|p| format!("{p:?}"))
            .unwrap_or_else(|| "default".to_string())
    );
    debug!(
        "GC Configuration: young_gen={}MB, threads={}, stats={}",
        gc_config.young_generation_size / 1024 / 1024,
        gc_config.max_gc_threads,
        gc_config.collect_statistics
    );

    runmat_gc::gc_configure(gc_config).context("Failed to configure garbage collector")?;

    Ok(())
}

async fn execute_command(command: Commands, cli: &Cli, config: &RunMatConfig) -> Result<()> {
    match command {
        Commands::Repl { verbose } => {
            // Create a temporary config with the verbose override
            let mut repl_config = config.clone();
            repl_config.runtime.verbose = verbose || config.runtime.verbose;
            execute_repl(&repl_config).await
        }
        Commands::Kernel {
            ip,
            key,
            transport,
            signature_scheme,
            shell_port,
            iopub_port,
            stdin_port,
            control_port,
            hb_port,
            connection_file,
        } => {
            execute_kernel(
                ip,
                key,
                transport,
                signature_scheme,
                shell_port,
                iopub_port,
                stdin_port,
                control_port,
                hb_port,
                connection_file,
                cli.timeout,
            )
            .await
        }
        Commands::KernelConnection { connection_file } => {
            execute_kernel_with_connection(connection_file, cli.timeout).await
        }
        Commands::Run { file, args } => execute_script_with_args(file, args, cli, config).await,
        Commands::Version { detailed } => {
            show_version(detailed);
            Ok(())
        }
        Commands::Info => show_system_info(cli).await,
        Commands::Gc { gc_command } => execute_gc_command(gc_command).await,
        Commands::Benchmark {
            file,
            iterations,
            jit,
        } => execute_benchmark(file, iterations, jit, cli).await,
        Commands::Snapshot { snapshot_command } => execute_snapshot_command(snapshot_command).await,
        Commands::Plot {
            mode,
            width,
            height,
        } => execute_plot_command(mode, width, height, config).await,
        Commands::Config { config_command } => execute_config_command(config_command, config).await,
        Commands::Pkg { pkg_command } => execute_pkg_command(pkg_command).await,
    }
}

async fn execute_repl(config: &RunMatConfig) -> Result<()> {
    info!("Starting RunMat REPL");
    if config.runtime.verbose {
        info!("Verbose mode enabled");
    }

    let enable_jit = config.jit.enabled;
    info!(
        "JIT compiler: {}",
        if enable_jit { "enabled" } else { "disabled" }
    );

    // Create enhanced REPL engine with optional snapshot loading
    let mut engine = ReplEngine::with_snapshot(
        enable_jit,
        config.runtime.verbose,
        config.runtime.snapshot_path.as_ref(),
    )
    .context("Failed to create REPL engine")?;

    info!("RunMat REPL ready");

    // Use rustyline for better REPL experience
    use std::io::{self, Write};

    println!(
        "RunMat v{} by Dystr (https://dystr.com)",
        env!("CARGO_PKG_VERSION")
    );
    println!("Fast, free, modern MATLAB runtime with JIT compilation and GC");
    println!();

    if enable_jit {
        println!(
            "JIT compiler: enabled (Cranelift optimization level: {:?})",
            config.jit.optimization_level
        );
    } else {
        println!("JIT compiler: disabled (interpreter mode)");
    }
    println!(
        "Garbage collector: {:?}",
        config
            .gc
            .preset
            .map(|p| format!("{p:?}"))
            .unwrap_or_else(|| "default".to_string())
    );
    if let Some(snapshot_info) = engine.snapshot_info() {
        println!("{snapshot_info}");
    } else {
        println!("No snapshot loaded - standard library will be compiled on demand");
    }
    println!("Type 'help' for help, 'exit' to quit, '.info' for system information");
    println!();

    let mut input = String::new();
    let is_interactive = atty::is(atty::Stream::Stdin);

    loop {
        if is_interactive {
            print!("runmat> ");
            io::stdout().flush().unwrap();
        }

        input.clear();
        match io::stdin().read_line(&mut input) {
            Ok(0) => {
                // EOF reached (e.g., pipe closed)
                if !is_interactive {
                    break;
                }
                continue;
            }
            Ok(_) => {
                let line = input.trim();
                if line == "exit" || line == "quit" {
                    break;
                }
                if line == "help" {
                    show_repl_help();
                    continue;
                }
                if line == ".info" {
                    engine.show_system_info();
                    continue;
                }
                if line == ".stats" {
                    let stats = engine.stats();
                    println!("Execution Statistics:");
                    println!(
                        "  Total: {}, JIT: {}, Interpreter: {}",
                        stats.total_executions, stats.jit_compiled, stats.interpreter_fallback
                    );
                    println!("  Average time: {:.2}ms", stats.average_execution_time_ms);
                    continue;
                }
                if line == ".gc" {
                    let gc_stats = engine.gc_stats();
                    println!("{}", gc_stats.summary_report());
                    continue;
                }
                if line.is_empty() {
                    continue;
                }

                // Execute the input using the enhanced engine
                match engine.execute(line) {
                    Ok(result) => {
                        if let Some(error) = result.error {
                            eprintln!("Error: {error}");
                        } else if let Some(value) = result.value {
                            println!("ans = {value}");
                            if config.runtime.verbose && result.execution_time_ms > 10 {
                                println!(
                                    "  ({}ms {})",
                                    result.execution_time_ms,
                                    if result.used_jit {
                                        "JIT"
                                    } else {
                                        "interpreter"
                                    }
                                );
                            }
                        } else if let Some(type_info) = result.type_info {
                            println!("ans = {type_info}");
                        }
                    }
                    Err(e) => {
                        eprintln!("Execution error: {e}");
                    }
                }
            }
            Err(e) => {
                eprintln!("Error reading input: {e}");
                break;
            }
        }
    }

    info!("RunMat REPL exiting");
    Ok(())
}

#[allow(clippy::too_many_arguments)]
async fn execute_kernel(
    ip: String,
    key: Option<String>,
    transport: String,
    signature_scheme: String,
    shell_port: u16,
    iopub_port: u16,
    stdin_port: u16,
    control_port: u16,
    hb_port: u16,
    connection_file: Option<PathBuf>,
    timeout: u64,
) -> Result<()> {
    info!("Starting RunMat Jupyter kernel");

    let mut connection = ConnectionInfo {
        ip,
        transport,
        signature_scheme,
        key: key.unwrap_or_else(|| uuid::Uuid::new_v4().to_string()),
        shell_port,
        iopub_port,
        stdin_port,
        control_port,
        hb_port,
    };

    // Assign ports if they're 0 (auto-assign)
    if shell_port == 0 || iopub_port == 0 || stdin_port == 0 || control_port == 0 || hb_port == 0 {
        connection
            .assign_ports()
            .context("Failed to assign kernel ports")?;
    }

    // Write connection file if requested
    if let Some(path) = connection_file {
        connection
            .write_to_file(&path)
            .with_context(|| format!("Failed to write connection file to {path:?}"))?;
        info!("Connection file written to {path:?}");
    }

    let config = KernelConfig {
        connection,
        session_id: uuid::Uuid::new_v4().to_string(),
        debug: log::log_enabled!(log::Level::Debug),
        execution_timeout: Some(timeout),
    };

    let mut server = KernelServer::new(config);

    info!("Starting kernel server...");
    server
        .start()
        .await
        .context("Failed to start kernel server")?;

    // Keep running until interrupted
    info!("Kernel is ready. Press Ctrl+C to stop.");
    tokio::signal::ctrl_c()
        .await
        .context("Failed to listen for ctrl-c")?;

    info!("Shutting down kernel...");
    server
        .stop()
        .await
        .context("Failed to stop kernel server")?;

    Ok(())
}

async fn execute_kernel_with_connection(connection_file: PathBuf, timeout: u64) -> Result<()> {
    info!("Starting kernel with connection file: {connection_file:?}");

    let connection = ConnectionInfo::from_file(&connection_file)
        .with_context(|| format!("Failed to load connection file: {connection_file:?}"))?;

    let config = KernelConfig {
        connection,
        session_id: uuid::Uuid::new_v4().to_string(),
        debug: log::log_enabled!(log::Level::Debug),
        execution_timeout: Some(timeout),
    };

    let mut server = KernelServer::new(config);

    server
        .start()
        .await
        .context("Failed to start kernel server")?;

    // Keep running until interrupted
    tokio::signal::ctrl_c()
        .await
        .context("Failed to listen for ctrl-c")?;

    server
        .stop()
        .await
        .context("Failed to stop kernel server")?;

    Ok(())
}

async fn execute_script(script: PathBuf, cli: &Cli, config: &RunMatConfig) -> Result<()> {
    execute_script_with_args(script, vec![], cli, config).await
}

async fn execute_script_with_args(
    script: PathBuf,
    _args: Vec<String>,
    _cli: &Cli,
    config: &RunMatConfig,
) -> Result<()> {
    info!("Executing script: {script:?}");

    let content = fs::read_to_string(&script)
        .with_context(|| format!("Failed to read script file: {script:?}"))?;

    let enable_jit = config.jit.enabled;
    let mut engine = ReplEngine::with_snapshot(
        enable_jit,
        config.runtime.verbose,
        config.runtime.snapshot_path.as_ref(),
    )
    .context("Failed to create execution engine")?;

    let start_time = std::time::Instant::now();
    let result = engine
        .execute(&content)
        .context("Failed to execute script")?;

    let execution_time = start_time.elapsed();

    if let Some(error) = result.error {
        error!("Script execution failed: {error}");
        std::process::exit(1);
    } else {
        info!(
            "Script executed successfully in {:?} ({})",
            execution_time,
            if result.used_jit {
                "JIT"
            } else {
                "interpreter"
            }
        );
        if let Some(value) = result.value {
            println!("{value:?}");
        }
    }

    Ok(())
}

async fn execute_gc_command(gc_command: GcCommand) -> Result<()> {
    match gc_command {
        GcCommand::Stats => {
            let stats = gc_stats();
            println!("{}", stats.summary_report());
        }
        GcCommand::Minor => {
            let start = std::time::Instant::now();
            match gc_collect_minor() {
                Ok(collected) => {
                    let duration = start.elapsed();
                    println!("Minor GC collected {collected} objects in {duration:?}");
                }
                Err(e) => {
                    error!("Minor GC failed: {e}");
                    std::process::exit(1);
                }
            }
        }
        GcCommand::Major => {
            let start = std::time::Instant::now();
            match gc_collect_major() {
                Ok(collected) => {
                    let duration = start.elapsed();
                    println!("Major GC collected {collected} objects in {duration:?}");
                }
                Err(e) => {
                    error!("Major GC failed: {e}");
                    std::process::exit(1);
                }
            }
        }
        GcCommand::Config => {
            println!("Current GC Configuration:");
            let config = gc_get_config();
            println!(
                "  Young Generation Size: {} MB",
                config.young_generation_size / 1024 / 1024
            );
            println!(
                "  Minor GC Threshold: {} objects",
                config.minor_gc_threshold
            );
            println!(
                "  Major GC Threshold: {} objects",
                config.major_gc_threshold
            );
            println!("  Max GC Threads: {}", config.max_gc_threads);
            println!(
                "  Collection Statistics: {}",
                if config.collect_statistics {
                    "enabled"
                } else {
                    "disabled"
                }
            );
            println!(
                "  Verbose Logging: {}",
                if config.verbose_logging {
                    "enabled"
                } else {
                    "disabled"
                }
            );
        }
        GcCommand::Stress { allocations } => {
            info!("Starting GC stress test with {allocations} allocations");

            let start_time = std::time::Instant::now();
            let initial_stats = gc_stats();

            println!("Running GC stress test with {allocations} allocations...");

            // Perform stress test
            let mut _objects = Vec::new();
            for i in 0..allocations {
                let value = Value::Num(i as f64);
                match gc_allocate(value) {
                    Ok(ptr) => {
                        _objects.push(ptr);

                        // Trigger periodic collections to stress the GC
                        if i % 1000 == 0 && i > 0 {
                            let _ = gc_collect_minor();
                        }
                        if i % 5000 == 0 && i > 0 {
                            let _ = gc_collect_major();
                        }
                    }
                    Err(e) => {
                        error!("Allocation failed at iteration {i}: {e}");
                        break;
                    }
                }

                // Progress reporting
                if i % (allocations / 10).max(1) == 0 {
                    println!("  Progress: {i}/{allocations} allocations");
                }
            }

            let duration = start_time.elapsed();
            let final_stats = gc_stats();

            // Report results
            println!("GC Stress Test Results:");
            println!("  Duration: {duration:?}");
            println!("  Allocations completed: {}", _objects.len());
            println!(
                "  Allocation rate: {:.2} allocs/sec",
                _objects.len() as f64 / duration.as_secs_f64()
            );
            println!(
                "  Total collections: {}",
                final_stats
                    .minor_collections
                    .load(std::sync::atomic::Ordering::Relaxed)
                    - initial_stats
                        .minor_collections
                        .load(std::sync::atomic::Ordering::Relaxed)
                    + final_stats
                        .major_collections
                        .load(std::sync::atomic::Ordering::Relaxed)
                    - initial_stats
                        .major_collections
                        .load(std::sync::atomic::Ordering::Relaxed)
            );
            println!(
                "  Final memory: {} bytes",
                final_stats
                    .current_memory_usage
                    .load(std::sync::atomic::Ordering::Relaxed)
            );

            // Force a final cleanup
            match gc_collect_major() {
                Ok(collected) => println!("  Final collection freed {collected} objects"),
                Err(e) => error!("Final collection failed: {e}"),
            }
        }
    }
    Ok(())
}

async fn execute_benchmark(file: PathBuf, iterations: u32, jit: bool, _cli: &Cli) -> Result<()> {
    info!("Benchmarking script: {file:?} ({iterations} iterations, JIT: {jit})");

    let content = fs::read_to_string(&file)
        .with_context(|| format!("Failed to read script file: {file:?}"))?;

    let mut engine = ReplEngine::with_snapshot(jit, false, _cli.snapshot.as_ref())
        .context("Failed to create execution engine")?;

    let mut total_time = Duration::ZERO;
    let mut jit_executions = 0;
    let mut interpreter_executions = 0;

    println!("Warming up...");
    // Warmup runs
    for _ in 0..3 {
        let _ = engine.execute(&content)?;
    }

    println!("Running benchmark...");
    for i in 1..=iterations {
        let result = engine.execute(&content)?;

        if let Some(error) = result.error {
            error!("Benchmark iteration {i} failed: {error}");
            std::process::exit(1);
        }

        total_time += Duration::from_millis(result.execution_time_ms);
        if result.used_jit {
            jit_executions += 1;
        } else {
            interpreter_executions += 1;
        }

        if i % 10 == 0 {
            println!("  Completed {i} iterations");
        }
    }

    let avg_time = total_time / iterations;
    println!("\nBenchmark Results:");
    println!("  Total iterations: {iterations}");
    println!("  JIT executions: {jit_executions}");
    println!("  Interpreter executions: {interpreter_executions}");
    println!("  Total time: {total_time:?}");
    println!("  Average time: {avg_time:?}");
    println!(
        "  Throughput: {:.2} executions/second",
        iterations as f64 / total_time.as_secs_f64()
    );

    Ok(())
}

/// Execute the plot command (interactive plotting window)
async fn execute_plot_command(
    mode: Option<PlotMode>,
    width: Option<u32>,
    height: Option<u32>,
    config: &RunMatConfig,
) -> Result<()> {
    info!("Starting interactive plotting window");

    // Determine the plotting mode
    let plot_mode = mode.unwrap_or(config.plotting.mode);

    match plot_mode {
        PlotMode::Auto => {
            // Auto-detect environment for plotting
            if config.plotting.force_headless || !is_gui_available() {
                info!("Auto-detected headless environment");
                execute_headless_plot().await
            } else {
                info!("Auto-detected GUI environment");
                execute_gui_plot(width, height, config).await
            }
        }
        PlotMode::Gui => execute_gui_plot(width, height, config).await,
        PlotMode::Headless => execute_headless_plot().await,
        PlotMode::Jupyter => {
            info!("Jupyter plotting mode not yet implemented");
            println!("Jupyter plotting mode will be available in future releases.");
            Ok(())
        }
    }
}

/// Execute GUI plotting
async fn execute_gui_plot(
    _width: Option<u32>,
    _height: Option<u32>,
    _config: &RunMatConfig,
) -> Result<()> {
    info!("Initializing GUI plotting window");

    // For now, return success since we have the unified plotting system in the runtime
    // This function may not be needed anymore with the new architecture
    match Ok::<(), anyhow::Error>(()) {
        Ok(()) => {
            info!("GUI plotting window closed successfully");
            Ok(())
        }
        Err(e) => {
            error!("GUI plotting failed: {e}");
            Err(anyhow::anyhow!("GUI plotting failed: {}", e))
        }
    }
}

/// Execute headless plotting (generates static images)
async fn execute_headless_plot() -> Result<()> {
    info!("Generating sample static plots");

    // Generate some sample plots to demonstrate headless functionality
    let sample_data_x = vec![1.0, 2.0, 3.0, 4.0, 5.0];
    let sample_data_y = vec![1.0, 4.0, 2.0, 8.0, 3.0];

    let options = runmat_plot::PlotOptions::default();

    match runmat_plot::plot_line(&sample_data_x, &sample_data_y, "sample_plot.png", options) {
        Ok(()) => {
            println!("Sample plot generated: sample_plot.png");
            Ok(())
        }
        Err(e) => {
            error!("Failed to generate plot: {e}");
            Err(anyhow::anyhow!("Plot generation failed: {}", e))
        }
    }
}

/// Check if GUI is available
fn is_gui_available() -> bool {
    // Simple heuristic: check if we're in a TTY and not in a known headless environment
    use std::env;

    // Check for headless environment indicators
    if env::var("CI").is_ok()
        || env::var("GITHUB_ACTIONS").is_ok()
        || env::var("HEADLESS").is_ok()
        || env::var("NO_GUI").is_ok()
    {
        return false;
    }

    // Check if running in SSH without X11 forwarding
    if env::var("SSH_CLIENT").is_ok() && env::var("DISPLAY").is_err() {
        return false;
    }

    // Use atty to check if stdout is a TTY
    atty::is(atty::Stream::Stdout)
}

/// Execute config command
async fn execute_config_command(
    config_command: ConfigCommand,
    config: &RunMatConfig,
) -> Result<()> {
    match config_command {
        ConfigCommand::Show => {
            println!("Current RunMat Configuration:");
            println!("==============================");

            let yaml =
                serde_yaml::to_string(config).context("Failed to serialize configuration")?;
            println!("{yaml}");
        }
        ConfigCommand::Generate { output } => {
            let sample_config = RunMatConfig::default();
            ConfigLoader::save_to_file(&sample_config, &output)
                .with_context(|| format!("Failed to write config to {}", output.display()))?;

            println!("Sample configuration generated: {}", output.display());
            println!("Edit this file to customize your RunMat settings.");
        }
        ConfigCommand::Validate { config_file } => {
            match ConfigLoader::load_from_file(&config_file) {
                Ok(_) => {
                    println!("Configuration file is valid: {}", config_file.display());
                }
                Err(e) => {
                    error!("Configuration validation failed: {e}");
                    std::process::exit(1);
                }
            }
        }
        ConfigCommand::Paths => {
            println!("RunMat Configuration File Locations:");
            println!("====================================");
            println!();

            if let Ok(config_path) = std::env::var("RUSTMAT_CONFIG") {
                println!("Environment override: {config_path}");
            }

            println!("Current directory:");
            if let Ok(current_dir) = std::env::current_dir() {
                for name in &[
                    ".runmat.yaml",
                    ".runmat.yml",
                    ".runmat.json",
                    ".runmat.toml",
                ] {
                    let path = current_dir.join(name);
                    let exists = if path.exists() { " (exists)" } else { "" };
                    println!("  {}{}", path.display(), exists);
                }
            }

            println!();
            println!("Home directory:");
            if let Some(home_dir) = dirs::home_dir() {
                for name in &[".runmat.yaml", ".runmat.yml", ".runmat.json"] {
                    let path = home_dir.join(name);
                    let exists = if path.exists() { " (exists)" } else { "" };
                    println!("  {}{}", path.display(), exists);
                }

                let config_dir = home_dir.join(".config/runmat");
                for name in &["config.yaml", "config.yml", "config.json"] {
                    let path = config_dir.join(name);
                    let exists = if path.exists() { " (exists)" } else { "" };
                    println!("  {}{}", path.display(), exists);
                }
            }

            #[cfg(unix)]
            {
                println!();
                println!("System-wide:");
                for name in &[
                    "/etc/runmat/config.yaml",
                    "/etc/runmat/config.yml",
                    "/etc/runmat/config.json",
                ] {
                    let path = std::path::Path::new(name);
                    let exists = if path.exists() { " (exists)" } else { "" };
                    println!("  {}{}", path.display(), exists);
                }
            }
        }
    }
    Ok(())
}

async fn execute_pkg_command(pkg_command: PkgCommand) -> Result<()> {
    let msg = "RunMat package manager is coming soon. Track progress in the repo.";
    match pkg_command {
        PkgCommand::Add { name } => println!("pkg add {name}: {msg}"),
        PkgCommand::Remove { name } => println!("pkg remove {name}: {msg}"),
        PkgCommand::Install => println!("pkg install: {msg}"),
        PkgCommand::Update => println!("pkg update: {msg}"),
        PkgCommand::Publish => println!("pkg publish: {msg}"),
    }
    Ok(())
}

// Conversion implementations
impl From<config::GcPreset> for runmat_gc::GcConfig {
    fn from(preset: config::GcPreset) -> Self {
        match preset {
            config::GcPreset::LowLatency => runmat_gc::GcConfig::low_latency(),
            config::GcPreset::HighThroughput => runmat_gc::GcConfig::high_throughput(),
            config::GcPreset::LowMemory => runmat_gc::GcConfig::low_memory(),
            config::GcPreset::Debug => runmat_gc::GcConfig::debug(),
        }
    }
}

impl From<CompressionAlg> for runmat_snapshot::CompressionAlgorithm {
    fn from(alg: CompressionAlg) -> Self {
        use runmat_snapshot::CompressionAlgorithm;
        match alg {
            CompressionAlg::None => CompressionAlgorithm::None,
            CompressionAlg::Lz4 => CompressionAlgorithm::Lz4,
            CompressionAlg::Zstd => CompressionAlgorithm::Zstd,
        }
    }
}

async fn execute_snapshot_command(snapshot_command: SnapshotCommand) -> Result<()> {
    match snapshot_command {
        SnapshotCommand::Create {
            output,
            optimization,
            compression,
        } => {
            info!("Creating snapshot: {output:?}");

            let mut config = SnapshotConfig::default();

            // Set compression if specified
            if let Some(comp) = compression {
                config.compression_enabled = !matches!(comp, CompressionAlg::None);
                config.compression_algorithm = comp.into();
            }

            // Note: optimization level affects JIT hints in the data, not the builder directly
            let _optimization_level = match optimization {
                OptLevel::None => runmat_snapshot::OptimizationLevel::None,
                OptLevel::Size => runmat_snapshot::OptimizationLevel::Basic,
                OptLevel::Speed => runmat_snapshot::OptimizationLevel::Aggressive,
                OptLevel::Aggressive => runmat_snapshot::OptimizationLevel::MaxPerformance,
            };

            let builder = SnapshotBuilder::new(config);

            builder
                .build_and_save(&output)
                .with_context(|| format!("Failed to build and save snapshot to {output:?}"))?;

            println!("Snapshot created successfully: {output:?}");
        }
        SnapshotCommand::Info { snapshot } => {
            info!("Loading snapshot info: {snapshot:?}");

            let mut loader = SnapshotLoader::new(SnapshotConfig::default());
            let (loaded, stats) = loader
                .load(&snapshot)
                .with_context(|| format!("Failed to load snapshot from {snapshot:?}"))?;

            println!("Snapshot Information:");
            println!("  File: {snapshot:?}");
            println!("  Version: {}", loaded.metadata.runmat_version);
            println!("  Created: {:?}", loaded.metadata.created_at);
            println!("  Tool Version: {}", loaded.metadata.tool_version);
            println!("  Build Config: {:?}", loaded.metadata.build_config);
            println!("  Builtin Functions: {}", loaded.builtins.functions.len());
            println!(
                "  HIR Cache Functions: {}",
                loaded.hir_cache.functions.len()
            );
            println!("  HIR Cache Patterns: {}", loaded.hir_cache.patterns.len());
            println!(
                "  Bytecode Cache (stdlib): {}",
                loaded.bytecode_cache.stdlib_bytecode.len()
            );
            println!(
                "  Bytecode Cache (sequences): {}",
                loaded.bytecode_cache.operation_sequences.len()
            );
            println!(
                "  Bytecode Cache (hotspots): {}",
                loaded.bytecode_cache.hotspots.len()
            );
            println!("  GC Presets: {}", loaded.gc_presets.presets.len());
            println!("  Load Time: {:?}", stats.load_time);
            println!("  Total Size: {} bytes", stats.total_size);
            println!("  Compressed Size: {} bytes", stats.compressed_size);
            println!("  Compression Ratio: {:.2}x", stats.compression_ratio);
        }
        SnapshotCommand::Presets => {
            println!("Available Snapshot Presets:");
            println!();

            let presets = vec![
                (
                    "development",
                    SnapshotPreset::Development,
                    "Fast development iteration",
                ),
                (
                    "production",
                    SnapshotPreset::Production,
                    "Production deployment",
                ),
                (
                    "high-performance",
                    SnapshotPreset::HighPerformance,
                    "High-performance computing",
                ),
                (
                    "low-memory",
                    SnapshotPreset::LowMemory,
                    "Memory-constrained environments",
                ),
                (
                    "network-optimized",
                    SnapshotPreset::NetworkOptimized,
                    "Network-optimized (minimal size)",
                ),
                (
                    "debug",
                    SnapshotPreset::Debug,
                    "Debug-friendly (maximum validation)",
                ),
            ];

            for (name, preset, description) in presets {
                let config = preset.config();
                println!("  {name}");
                println!("    Description: {description}");
                println!("    Compression: {:?}", config.compression_algorithm);
                println!(
                    "    Validation: {}",
                    if config.validation_enabled {
                        "enabled"
                    } else {
                        "disabled"
                    }
                );
                println!(
                    "    Memory Mapping: {}",
                    if config.memory_mapping_enabled {
                        "enabled"
                    } else {
                        "disabled"
                    }
                );
                println!(
                    "    Parallel Loading: {}",
                    if config.parallel_loading {
                        "enabled"
                    } else {
                        "disabled"
                    }
                );
                println!();
            }
        }
        SnapshotCommand::Validate { snapshot } => {
            info!("Validating snapshot: {snapshot:?}");

            let mut loader = SnapshotLoader::new(SnapshotConfig::default());
            match loader.load(&snapshot) {
                Ok((_, stats)) => {
                    println!("Snapshot validation passed: {snapshot:?}");
                    println!("  Load time: {:?}", stats.load_time);
                    println!("  File size: {} bytes", stats.total_size);
                    if stats.compressed_size > 0 {
                        println!("  Compressed size: {} bytes", stats.compressed_size);
                        println!("  Compression ratio: {:.2}x", stats.compression_ratio);
                    }
                }
                Err(e) => {
                    error!("Snapshot validation failed: {e}");
                    std::process::exit(1);
                }
            }
        }
    }
    Ok(())
}

fn show_version(detailed: bool) {
    println!("RunMat v{}", env!("CARGO_PKG_VERSION"));

    if detailed {
        println!(
            "Built with Rust {}",
            std::env::var("RUSTC_VERSION").unwrap_or_else(|_| "unknown".to_string())
        );
        println!(
            "Target: {}",
            std::env::var("TARGET").unwrap_or_else(|_| "unknown".to_string())
        );
        println!(
            "Profile: {}",
            if cfg!(debug_assertions) {
                "debug"
            } else {
                "release"
            }
        );
        println!("Features: jupyter-kernel, plotting, repl, jit, gc");
        println!();
        println!("Components:");
        println!("  • runmat-lexer: MATLAB/Octave tokenizer");
        println!("  • runmat-parser: Syntax parser with error recovery");
        println!("  • runmat-hir: High-level intermediate representation");
        println!("  • runmat-ignition: Baseline interpreter");
        println!("  • runmat-turbine: JIT compiler with Cranelift");
        println!("  • runmat-gc: Generational garbage collector");
        println!("  • runmat-runtime: BLAS/LAPACK runtime with builtins");
        println!("  • runmat-kernel: Jupyter kernel protocol");
        println!("  • runmat-plot: Headless plotting backend");
    }
}

async fn show_system_info(cli: &Cli) -> Result<()> {
    println!("RunMat System Information");
    println!("==========================");
    println!();

    println!("Version: {}", env!("CARGO_PKG_VERSION"));
    println!(
        "Rust Version: {}",
        std::env::var("RUSTC_VERSION").unwrap_or_else(|_| "unknown".to_string())
    );
    println!(
        "Target: {}",
        std::env::var("TARGET").unwrap_or_else(|_| "unknown".to_string())
    );
    println!();

    println!("Runtime Configuration:");
    println!(
        "  JIT Compiler: {}",
        if !cli.no_jit { "enabled" } else { "disabled" }
    );
    println!("  JIT Threshold: {}", cli.jit_threshold);
    println!("  JIT Optimization: {:?}", cli.jit_opt_level);
    println!(
        "  GC Preset: {:?}",
        cli.gc_preset
            .as_ref()
            .map(|p| format!("{p:?}"))
            .unwrap_or_else(|| "default".to_string())
    );
    if let Some(young_size) = cli.gc_young_size {
        println!("  GC Young Generation: {young_size}MB");
    }
    if let Some(threads) = cli.gc_threads {
        println!("  GC Threads: {threads}");
    }
    println!("  GC Statistics: {}", cli.gc_stats);
    println!();

    println!("Environment:");
    println!("  RUSTMAT_DEBUG: {:?}", std::env::var("RUSTMAT_DEBUG").ok());
    println!(
        "  RUSTMAT_LOG_LEVEL: {:?}",
        std::env::var("RUSTMAT_LOG_LEVEL").ok()
    );
    println!(
        "  RUSTMAT_TIMEOUT: {:?}",
        std::env::var("RUSTMAT_TIMEOUT").ok()
    );
    println!(
        "  RUSTMAT_JIT_ENABLE: {:?}",
        std::env::var("RUSTMAT_JIT_ENABLE").ok()
    );
    println!(
        "  RUSTMAT_GC_PRESET: {:?}",
        std::env::var("RUSTMAT_GC_PRESET").ok()
    );
    println!();

    // Show GC stats
    let gc_stats = gc_stats();
    println!("Garbage Collector Status:");
    println!("{}", gc_stats.summary_report());
    println!();

    println!("Available Commands:");
    println!("  repl                 Start interactive REPL with JIT");
    println!("  --install-kernel     Install RunMat as Jupyter kernel");
    println!("  kernel               Start Jupyter kernel");
    println!("  kernel-connection    Start kernel with connection file");
    println!("  run <file>           Execute MATLAB script");
    println!("  gc stats             Show GC statistics");
    println!("  gc major             Force major GC collection");
    println!("  benchmark <file>     Benchmark script execution");
    println!("  snapshot create      Create standard library snapshot");
    println!("  snapshot info        Inspect snapshot file");
    println!("  snapshot presets     List available presets");
    println!("  snapshot validate    Validate snapshot file");
    println!("  version              Show version information");
    println!("  info                 Show this system information");

    Ok(())
}

fn show_repl_help() {
    println!("RunMat REPL Help");
    println!("=================");
    println!();
    println!("Commands:");
    println!("  exit, quit        Exit the REPL");
    println!("  help              Show this help message");
    println!("  .info             Show detailed system information");
    println!("  .stats            Show execution statistics");
    println!("  .gc               Show garbage collector statistics");
    println!();
    println!("MATLAB/Octave syntax is supported:");
    println!("  x = 1 + 2                         # Assignment");
    println!("  y = [1, 2, 3]                    # Vectors");
    println!("  z = [1, 2; 3, 4]                 # Matrices");
    println!("  if x > 0; disp('positive'); end  # Control flow");
    println!("  for i = 1:5; disp(i); end        # Loops");
    println!();
    println!("Features:");
    println!("  • JIT compilation with Cranelift for optimal performance");
    println!("  • Generational garbage collection with configurable policies");
    println!("  • High-performance BLAS/LAPACK operations on matrices");
    println!("  • Interpreter fallback for unsupported JIT patterns");
    println!("  • Real-time performance monitoring and statistics");
    println!();
    println!("Performance Tips:");
    println!("  • Repeated code automatically gets JIT compiled");
    println!("  • Matrix operations use optimized BLAS routines");
    println!("  • Use '.stats' to monitor JIT compilation effectiveness");
    println!("  • Use '.gc' to monitor memory usage and collection");
    println!();
    println!("Press Enter after each statement to execute.");
}

/// Install RunMat as a Jupyter kernel
async fn install_jupyter_kernel() -> Result<()> {
    use std::fs;

    info!("Installing RunMat as a Jupyter kernel");

    // Get the path to the current executable
    let current_exe = std::env::current_exe().context("Failed to get current executable path")?;

    // Find Jupyter kernel directory
    let kernel_dir =
        find_jupyter_kernel_dir().context("Failed to find Jupyter kernel directory")?;

    let runmat_kernel_dir = kernel_dir.join("runmat");

    // Create kernel directory
    fs::create_dir_all(&runmat_kernel_dir).with_context(|| {
        format!(
            "Failed to create kernel directory: {}",
            runmat_kernel_dir.display()
        )
    })?;

    // Create kernel.json
    let kernel_json = format!(
        r#"{{
  "argv": [
    "{}",
    "kernel-connection",
    "{{connection_file}}"
  ],
  "display_name": "RunMat",
  "language": "matlab",
  "metadata": {{
    "debugger": false
  }}
}}"#,
        current_exe.display()
    );

    let kernel_json_path = runmat_kernel_dir.join("kernel.json");
    fs::write(&kernel_json_path, kernel_json).with_context(|| {
        format!(
            "Failed to write kernel.json to {}",
            kernel_json_path.display()
        )
    })?;

    // Create logo files (optional - we'll create simple text-based ones for now)
    create_kernel_logos(&runmat_kernel_dir)?;

    println!("RunMat Jupyter kernel installed successfully!");
    println!("Kernel directory: {}", runmat_kernel_dir.display());
    println!();
    println!("You can now start Jupyter and select 'RunMat' as a kernel:");
    println!("  jupyter notebook");
    println!("  # or");
    println!("  jupyter lab");
    println!();
    println!("To verify the installation:");
    println!("  jupyter kernelspec list");

    Ok(())
}

/// Find the Jupyter kernel directory
fn find_jupyter_kernel_dir() -> Result<PathBuf> {
    // Try to get Jupyter data directory using standard methods
    if let Ok(output) = std::process::Command::new("jupyter")
        .args(["--data-dir"])
        .output()
    {
        if output.status.success() {
            let data_dir_str = String::from_utf8_lossy(&output.stdout);
            let data_dir = data_dir_str.trim();
            let kernels_dir = PathBuf::from(data_dir).join("kernels");
            if kernels_dir.exists() || kernels_dir.parent().is_some_and(|p| p.exists()) {
                return Ok(kernels_dir);
            }
        }
    }

    // Fallback to standard locations
    if let Some(home_dir) = dirs::home_dir() {
        // Try user-level installation first
        let user_kernels = home_dir.join(".local/share/jupyter/kernels");
        if user_kernels.exists() || user_kernels.parent().is_some_and(|p| p.exists()) {
            return Ok(user_kernels);
        }

        // macOS specific location
        #[cfg(target_os = "macos")]
        {
            let macos_kernels = home_dir.join("Library/Jupyter/kernels");
            if macos_kernels.exists() || macos_kernels.parent().is_some_and(|p| p.exists()) {
                return Ok(macos_kernels);
            }
        }

        // Windows specific location
        #[cfg(target_os = "windows")]
        {
            if let Ok(appdata) = std::env::var("APPDATA") {
                let windows_kernels = PathBuf::from(appdata).join("jupyter/kernels");
                if windows_kernels.exists() || windows_kernels.parent().is_some_and(|p| p.exists())
                {
                    return Ok(windows_kernels);
                }
            }
        }

        // Default fallback
        let default_kernels = home_dir.join(".local/share/jupyter/kernels");
        return Ok(default_kernels);
    }

    Err(anyhow::anyhow!(
        "Could not determine Jupyter kernel directory. Please install Jupyter first."
    ))
}

/// Create simple kernel logos
fn create_kernel_logos(kernel_dir: &std::path::Path) -> Result<()> {
    // For now, we'll skip logo creation since it requires image processing
    // In a full implementation, you'd want to include actual PNG logos

    // Create a simple text file that indicates logos could be added
    let logo_info = kernel_dir.join("logo-readme.txt");
    fs::write(
        logo_info,
        "RunMat kernel logos can be added here:\n- logo-32x32.png\n- logo-64x64.png",
    )
    .context("Failed to create logo info file")?;

    Ok(())
}