rustyroad 1.0.26

Rusty Road is a framework written in Rust that is based on Ruby on Rails. It is designed to provide the familiar conventions and ease of use of Ruby on Rails, while also taking advantage of the performance and efficiency of Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
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
//! # Rusty Road
//! Rusty Road is a framework written in Rust that is based on Ruby on Rails. It is designed to provide the familiar conventions and ease of use of Ruby on Rails, while also taking advantage of the performance and efficiency of Rust.
//! Below you will find a struct that represents a project.  It is used to create a new project.
//! ## Description
//! Rusty Road is a CLI tool that is used to create and manage your rust web apps.
//! You can use this package as a part of your project and this documentation will help you understand how to use it, however, it is not intended to be used as a standalone package.
//! ## Example
//! ```no_run
//! use rustyroad::Project;
//!
//! Project::initial_prompt().expect("Failed to create project");
//! ```
//!
//! ### Code Explanation
//! The code above is the main function for the RustyRoad project.  It is the entry point for the program.
//! The project is created by calling the `initial_prompt` function on the `Project` struct.
//! The initial prompt function will ask the user a series of questions and then create a new project based on the answers.
//! From there, the user can use the project to create a new web app.
//! Notice that other functions are called on the `Project` struct.  These functions are used to create a new web app.

// Allow some clippy warnings that are prevalent in the codebase
// These can be addressed incrementally in future refactoring
#![allow(clippy::needless_borrow)]
#![allow(clippy::redundant_closure)]
#![allow(clippy::vec_init_then_push)]
#![allow(clippy::unnecessary_unwrap)]
#![allow(clippy::single_match)]
#![allow(clippy::ptr_arg)]
#![allow(clippy::useless_format)]
#![allow(clippy::to_string_in_format_args)]
#![allow(clippy::needless_return)]
#![allow(clippy::manual_unwrap_or_default)]
#![allow(clippy::let_unit_value)]
#![allow(clippy::ineffective_open_options)]
#![allow(clippy::unused_enumerate_index)]
#![allow(clippy::module_inception)]
#![allow(clippy::empty_line_after_doc_comments)]
#![allow(clippy::doc_lazy_continuation)]
#![allow(clippy::redundant_pattern_matching)]
#![allow(clippy::trivial_regex)]
#![allow(clippy::regex_creation_in_loops)]
#![allow(clippy::unnecessary_to_owned)]
#![allow(clippy::needless_doctest_main)]
//! These are the functions that ship with the cli tool and are not publicly available.

#![deny(warnings)]
#![allow(dead_code)]

use clap::{arg, Arg, Command, Parser};
use color_eyre::eyre::Result;
use dialoguer::Confirm;
use eyre::Error;
use serde::Deserialize;
use sqlx::mysql::MySqlConnectOptions;
use sqlx::postgres::PgConnectOptions;
use sqlx::sqlite::SqliteConnectOptions;
use sqlx::ConnectOptions;
use std::env;
use std::{fs::OpenOptions, io::Write};
use tokio::io;

pub mod database;
pub mod features;
pub mod generators;

use crate::features::add_feature;
use database::*;

pub mod helpers;
pub mod writers;
use crate::generators::create_directories_for_new_project;
use crate::helpers::helpers::get_project_name_from_rustyroad_toml;
use crate::writers::*;
/**
 * # Struct RustyRoad
 * ## Description
 * This struct is used to configure the project.
 * This is specfically used to read the rustyroad.toml file and
 * and decode the toml into a struct.
 */
#[derive(Debug, Deserialize)]
pub struct RustyRoad {
    name: String,
}

/**
 * # Struct Project
 * ## Description
 * This struct is used to configure the project.
 * This is specfically used to read the rustyroad.toml file and
 * and decode the toml into a struct.
 */
#[derive(Debug, Deserialize, Clone, PartialEq, Eq, Hash, Copy, Parser)]
pub enum CRUDType {
    Create,
    Read,
    Update,
    Delete,
}

/// # Name: Project
/// ## Type: Struct
/// ## Description
/// This struct is used to configure the project.
/// This is specfically used to read the rustyroad.toml file and
/// and decode the toml into a struct.
/// ## Example
/// ```
/// use rustyroad::Project;
///
/// fn main() {
///   Project::run();
/// }
///
/// ```
/// ### Code Explanation
/// The code above is the main function for the RustyRoad project.  It is the entry point for the program.
/// The project is created by calling the `initial_prompt` function on the `Project` struct.
/// The initial prompt function will ask the user a series of questions and then create a new project based on the answers.
/// From there, the user can use the project to create a new web app.
/// Notice that other functions are called on the `Project` struct.  These functions are used to create a new web app.
/// These are the functions that ship with the cli tool and are not publicly available.
#[derive(Parser, Debug, Clone)]
pub struct Project {
    pub name: String,
    pub env: String,
    pub rustyroad_toml: String,
    pub src_dir: String,
    pub main_rs: String,
    pub cargo_toml: String,
    pub package_json: String,
    pub readme: String,
    pub gitignore: String,
    pub templates: String,
    pub static_dir: String,
    pub template_components: String,
    pub template_sections: String,
    pub template_layouts: String,
    pub auth_template_layouts: String,
    pub authenticated_layout: String,
    pub layout_template: String,
    pub template_pages: String,
    pub static_css: String,
    pub static_js: String,
    pub index_js: String,
    pub static_images: String,
    pub config: String,
    pub config_env: String,
    pub config_dev_env: String,
    pub config_prod_env: String,
    pub config_test_env: String,
    pub config_default_env: String,
    pub db: String,
    pub config_dev_db: String,
    pub config_prod_db: String,
    pub config_test_db: String,
    pub controllers: String,
    pub controllers_module: String,
    pub models: String,
    pub models_module: String,
    pub migrations: String,
    pub seeders: String,
    pub tests: String,
    pub config_initializers: String,
    pub config_initializers_assets: String,
    pub config_initializers_db: String,
    pub config_initializers_default: String,
    pub config_initializers_middleware: String,
    pub config_initializers_controllers: String,
    pub index_html: String,
    pub base_html: String,
    pub tailwind_css: String,
    pub tailwind_config: String,
    pub postcss_config: String,
    pub not_found_html: String,
    pub server_error_html: String,
    pub favicon_ico: String,
    pub robots_txt: String,
    pub login_page_html: String,
    pub signup_page_html: String,
    pub reset_password_page_html: String,
    pub forgot_password_page_html: String,
    pub dashboard_page_html: String,
    pub user_controller_directory: String,
    pub user_controller: String,
    pub user_controller_module: String,
    pub user_model: String,
    pub initial_migration_directory: String,
    pub initial_migration_up: String,
    pub initial_migration_down: String,
    pub user_test: String,
    pub not_found_controller: String,
    pub index_controller: String,
    pub login_controller: String,
    pub signup_controller: String,
    pub reset_password_controller: String,
    pub forgot_password_controller: String,
    pub dashboard_controller: String,
    pub navbar_component: String,
    pub sidebar_component: String,
    pub header_section: String,
}

/// # RustyRoad Project Builder
/// Description: This is the main file for the RustyRoad project.
/// It is the entry point for the program.
///
/// ## Usage
///
/// ```rust
/// use rustyroad::Project;
///
/// let project = Project::new("MyProject".to_string());
/// ```
///
///
impl Project {
    /// # Create a new project
    /// This function creates a new project.
    /// It is called from within the CreateProject function.
    /// Takes a name and a path as arguments
    /// The {name} is the name of the project.
    /// The {path} is the path to the directory where the project will be created.
    /// If a path is not provided, the project will be created in the current directory.

    // Write to rustyroad_toml
    pub fn write_to_rustyroad_toml(&self, database_data: &Database) -> Result<(), Error> {
        let mut file = OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(&self.rustyroad_toml)?;

        let config = format!(
            "[rustyroad_project]
name = \"{}\"
[database]
database_name = \"{}\"
database_user = \"{}\"
database_password = \"{}\"
database_host = \"{}\"
database_port = \"{}\"
database_type = \"{}\"",
            self.name,
            database_data.clone().name,
            database_data.username,
            database_data.password,
            database_data.host,
            database_data.port,
            database_data.database_type.to_string().to_ascii_lowercase()
        );
        file.write_all(config.as_bytes())?;
        Ok(())
    }

    // Write to package.json
    fn write_to_package_json(&self) -> Result<(), Error> {
        let mut file = OpenOptions::new()
            .append(true)
            .open(&self.package_json)
            .expect("Failed to open package.json");

        file.write_all(
            "{
                \"name\": \"rustyroad\",
                \"version\": \"1.0.0\",
                \"main\": \"index.js\",
                \"repository\": \"https://github.com/Riley-Seaburg/RustyRoad.git\",
                \"author\": \"Riley Seaburg <riley@rileyseaburg.com>\",
                \"license\": \"MIT\",
                \"scripts\": {
                  \"server\": \"cargo run\",
                  \"tailwind:dev\": \"npx tailwindcss -i ./src/tailwind.css -o ./static/css/styles.css --watch\",
                  \"tailwind:build\": \"npx tailwindcss -i ./src/tailwind.css -o ./static/css/styles.css --minify\",
                  \"dev\": \"concurrently \\\"yarn tailwind:dev\\\" \\\" yarn server\\\"\"
                },
                \"devDependencies\": {
                  \"@tailwindcss/forms\": \"^0.5.3\",
                  \"concurrently\": \"^7.6.0\",
                  \"tailwindcss\": \"^3.2.4\"
                }
              }"
            .as_bytes(),
        )
        .expect("Failed to write to package.json");
        Ok(())
    }
    // Write to README.md
    fn write_to_readme(&self) -> Result<(), Error> {
        let mut file = OpenOptions::new()
            .append(true)
            .open(&self.readme)
            .expect("Failed to open README.md");

        file.write_all(
            format!(
                "# {}
This project was created using Rusty Road. Rusty Road is Rails for Rust. It is a CLI tool that allows you to create a new Rust project with a few commands. It also comes with TailwindCSS and Actix pre-installed.

## Getting Started

### Configure TailwindCSS

```bash
npx tailwindcss init -p
```

### Set Environment Variables

```bash
cp .env.example .env
```


To get started, run `yarn dev` to start the server and watch for changes to your TailwindCSS files.

## Contributing

If you would like to contribute to this project, please fork the repository and submit a pull request.

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details."
                , self.name
            )
                .as_bytes(),
        )
            .expect("Failed to write to README.md");

        Ok(())
    }
    // Write to .gitignore
    fn write_to_gitignore(&self) -> Result<(), Error> {
        let mut file = OpenOptions::new()
            .append(true)
            .open(&self.gitignore)
            .expect("Failed to open .gitignore");

        file.write_all(
            b"target/
Cargo.lock
.DS_Store
.env
.db
node_modules/
static/styles.css
",
        )
        .expect("Failed to write to .gitignore");

        Ok(())
    }

    // Write to index.js
    fn write_to_index_js(&self) -> Result<(), Error> {
        let contents = format!(
            "// Rusty Road
        class RustyRoad {{
            constructor() {{
                this.name = \"{}\";
                this.greet = () => {{
                    console.log(\"Welcome to {} powered by Rusty Road\");
                }}
            }}
        }}

        const rustyroad = new RustyRoad();

        rustyroad.greet();
        ",
            self.name, self.name
        );

        write_to_file(&self.index_js, contents.as_bytes())?;

        Ok(())
    }
    // Write to tailwind.css
    fn write_to_tailwind_css(&self) -> Result<(), Error> {
        let contents = "@tailwind base;
@tailwind components;
@tailwind utilities;";

        write_to_file(&self.tailwind_css.to_string(), contents.as_bytes()).unwrap_or_else(|why| {
            println!("Couldn't write to {}: {}", self.tailwind_css, why);
        });
        Ok(())
    }
    // Write to tailwind.config.js
    fn write_to_tailwind_config(&self) -> Result<(), Error> {
        let contents = "module.exports = {
        darkMode: 'media',
        content: ['./views/**/*.{html.tera,js}'],
        theme: {
            extend: {
            },
        },
        plugins: [
            require('@tailwindcss/forms'),
        ],
        };";

        write_to_file(&self.tailwind_config.to_string(), contents.as_bytes()).unwrap_or_else(
            |why| {
                println!("Couldn't write to {}: {}", self.tailwind_config, why);
            },
        );
        Ok(())
    }
    // Write to postcss.config.js
    fn write_to_postcss_config(&self) -> Result<(), Error> {
        let contents = "module.exports = {{
            plugins: [
                require('tailwindcss'),
                require('autoprefixer'),
            ],
        }};";

        write_to_file(&self.postcss_config.to_string(), contents.as_bytes()).unwrap_or_else(
            |why| {
                println!("Couldn't write to {}: {}", self.postcss_config, why);
            },
        );
        Ok(())
    }

    /// Creates a new project
    /// Takes an optional name <String> and db_type <String>
    /// If no name is provided, it will default to "rustyroad"
    /// If a name is provided, it will create a new directory with that name
    /// and create a new project in that directory
    /// If a directory with the same name already exists, it will return an error
    /// and ask the user to choose a different name
    /// If a db_type is provided, it will create a new database with that type
    /// If no db_type is provided, it will default to "sqlite"
    /// If a db_type is provided that is not supported, it will return an error
    /// and ask the user to choose a different db_type
    /// Allow unused variables because the db_type is not used yet
    #[allow(unused_variables)]
    pub async fn create_new_project(
        name: String,
        database_data: Database,
    ) -> Result<Project, Error> {
        // If name is provided, create a new directory with that name
        // If no name is provided, run the rest of the code in the function
        // write the database data to the rustyroad.toml file

        // Create new project with name
        let mut project = new(name);

        // Create the project directory
        create_directories_for_new_project(&project).unwrap_or_else(|why| {
            println!("Couldn't create directory: {:?}", why.to_string());
        });

        // Create the files
        create_files(&project).unwrap_or_else(|why| {
            panic!("Couldn't create files: {:?}", why.to_string());
        });

        // write to the .env file
        let value = set_env(&project).unwrap();
        write_to_file(&project.env, value.as_bytes()).unwrap_or_else(|why| {
            println!("Couldn't write to .env: {:?}", why.to_string());
        });

        // Write to rustyroad.toml file
        Self::write_to_rustyroad_toml(&project, &database_data)
            .expect("Failed to write to rustyroad.toml");

        // Write to the cargo.toml file
        write_to_cargo_toml(&project, &database_data).expect("Failed to write to cargo.toml");

        // Write to main.rs file
        write_to_main_rs(&project).expect("Failed to write to main.rs");

        // Write to package.json file
        Self::write_to_package_json(&project).expect("Failed to write to package.json");

        // Write to README.md file
        Self::write_to_readme(&project).expect("Failed to write to README.md");

        // Write to index.js file
        Self::write_to_index_js(&project).unwrap_or_else(|why| {
            println!("Failed to write to index.js: {:?}", why.to_string());
        });
        // Write to index.html.tera file
        write_to_index_html(&project).unwrap_or_else(|why| {
            println!("Failed to write to index.html: {:?}", why.to_string());
        });
        // Write to base.html.tera file
        write_to_base_html(&project.base_html).unwrap_or_else(|why| {
            println!("Failed to write to base.html: {:?}", why.to_string());
        });

        // Write to tailwind.css file
        Self::write_to_tailwind_css(&project).unwrap_or_else(|why| {
            println!("Failed to write to tailwind.css: {:?}", why.to_string());
        });
        // need to create the function
        // Write to tailwind.config.js file
        Self::write_to_tailwind_config(&project).unwrap_or_else(|why| {
            println!(
                "Failed to write to tailwind.config.js: {:?}",
                why.to_string()
            );
        });

        // Write to postcss.config.js file
        Self::write_to_postcss_config(&project).unwrap_or_else(|why| {
            println!(
                "Failed to write to postcss.config.js: {:?}",
                why.to_string()
            );
        });

        // Write to index.html controller
        write_to_index_controller(&project).expect("Failed to write to index controller");

        // Write to gitignore file
        Self::write_to_gitignore(&project).unwrap_or_else(|why| {
            println!("Failed to write to .gitignore: {:?}", why.to_string());
        });

        write_to_controllers_mod(&project.controllers_module, "index".to_string()).unwrap_or_else(
            |why| {
                println!("Failed to write to controllers/mod: {:?}", why.to_string());
            },
        );
        // Write to Header
        write_to_header(&project.header_section).unwrap_or_else(|why| {
            println!("Failed to write to header: {:?}", why.to_string());
        });

        // write to navbar
        write_to_navbar(&project).unwrap_or_else(|why| {
            println!("Failed to write to navbar: {:?}", why.to_string());
        });

        // write to sidebar
        write_to_sidebar(&project).unwrap_or_else(|why| {
            println!("Failed to write to sidebar: {:?}", why.to_string());
        });

        // write to the login page
        write_to_login_page(project.clone()).unwrap_or_else(|why| {
            println!("Failed to write to login: {:?}", why.to_string());
        });

        write_to_404_html(&project.not_found_html).unwrap_or_else(|why| {
            println!("Failed to write to 404: {:?}", why.to_string());
        });

        write_to_not_found_controller(&project).expect("Failed to write to not_found controller");

        write_to_authenticated_layout(project.clone()).unwrap_or_else(|why| {
            println!(
                "Failed to write to authenticated_page layout: {:?}",
                why.to_string()
            );
        });

        write_to_layout(project.clone()).unwrap_or_else(|why| {
            println!("Failed to write to layout template: {:?}", why.to_string());
        });
        // We need to tell Diesel where to find our database. We do this by setting the DATABASE_URL environment variable.
        // We can do this by running the following command in the terminal:
        let temp_database = &database_data.clone();
        // Embed migrations from the "migrations" directory
        // Use the embed_migrations macro to embed migrations into the binary
        // Adjust the path to point to the location of your migration files

        match temp_database.database_type {
            DatabaseType::Sqlite => {
                // Create the database URL
                let database_url = project.config_dev_db.to_string();
                println!("database_url: {database_url}");

                // In SQLite, creating a connection to a non-existent database
                // automatically creates the database file, so we don't need to
                // explicitly create the database.

                // Generate the SQL content for the new project
                let sql_content = load_sql_for_new_project(&project, database_data.clone()).await?;

                // Establish a connection to the new database
                let connection_result = SqliteConnectOptions::new()
                    .filename(&database_url)
                    .connect()
                    .await;

                // Check if the connection was successful
                let mut connection = match connection_result {
                    Ok(conn) => conn,
                    Err(why) => {
                        panic!("Failed to establish connection: {why}");
                    }
                };

                // Iterate through the vector of SQL commands and execute them one at a time
                for sql_command in sql_content {
                    // Execute the SQL command
                    sqlx::query(&sql_command)
                        .execute(&mut connection)
                        .await
                        .unwrap_or_else(|why| panic!("Failed to execute SQL command: {why}"));
                }

                write_to_sqlite_user_models(&project).unwrap_or_else(|why| {
                    println!("Failed to write to user models: {:?}", why.to_string());
                });
            }

            DatabaseType::Postgres => {
                // Replace this line with the correct URL for the default "postgres" database
                let admin_database_url = format!(
                    "postgres://{}:{}@{}:{}/postgres",
                    database_data.username,
                    database_data.password,
                    database_data.host,
                    database_data.port,
                );

                // Call the function with the admin_database_url
                create_database_if_not_exists(&admin_database_url, database_data.clone())
                    .await
                    .unwrap_or_else(|why| {
                        panic!("Failed to create database: {why}");
                    });

                // Create the database URL
                let database_url = format!(
                    "postgres://{}:{}@{}:{}/{}",
                    database_data.username,
                    database_data.password,
                    database_data.host,
                    database_data.port,
                    database_data.name
                );

                // Update the DATABASE_URL environment variable to point to the new 'test' database
                env::set_var(
                    "DATABASE_URL",
                    database_url.replace(&database_data.name, "test"),
                );

                project.config_dev_db = database_url.clone();

                println!("database_url: {database_url}");

                // Generate the SQL content for the new project
                let sql_content = load_sql_for_new_project(&project, database_data.clone()).await?;

                // Establish a connection to the new database
                let connection_result = PgConnectOptions::new()
                    .username(&database_data.username)
                    .password(&database_data.password)
                    .host(&database_data.host)
                    .port(database_data.port.to_string().parse::<u16>().unwrap())
                    .database(&database_data.name)
                    .connect()
                    .await;

                // Check if the connection was successful
                let mut connection = match connection_result {
                    Ok(conn) => conn,
                    Err(why) => {
                        panic!("Failed to establish connection: {why}");
                    }
                };

                // Iterate through the vector of SQL commands and execute them one at a time
                for sql_command in sql_content {
                    // Execute the SQL command
                    sqlx::query(&sql_command)
                        .execute(&mut connection)
                        .await
                        .unwrap_or_else(|why| panic!("Failed to execute SQL command: {why}"));
                }

                /* Write to user models file */
                write_to_postgres_user_models(&project).unwrap_or_else(|why| {
                    println!("Failed to write to user models: {why}");
                });
            }

            DatabaseType::Mysql => {
                // Create the database URL for the default "mysql" database
                let admin_database_url = format!(
                    "mysql://{}:{}@{}:{}/mysql",
                    database_data.username,
                    database_data.password,
                    database_data.host,
                    database_data.port,
                );

                // Call the function with the admin_database_url
                create_database_if_not_exists(&admin_database_url, database_data.clone())
                    .await
                    .unwrap_or_else(|why| {
                        panic!("Failed to create database: {:?}", why);
                    });

                // Create the database URL for the new database
                let database_url = format!(
                    "mysql://{}:{}@{}:{}/{}",
                    database_data.username,
                    database_data.password,
                    database_data.host,
                    database_data.port,
                    database_data.name
                );

                // Update the DATABASE_URL environment variable to point to the new 'test' database
                env::set_var(
                    "DATABASE_URL",
                    database_url.replace(&database_data.name, "test"),
                );

                project.config_dev_db = database_url.clone();

                println!("database_url: {database_url}");

                // Generate the SQL content for the new project
                let sql_content = load_sql_for_new_project(&project, database_data.clone()).await?;

                // Establish a connection to the new database
                let connection_result = MySqlConnectOptions::new()
                    .username(&database_data.username)
                    .password(&database_data.password)
                    .host(&database_data.host)
                    .port(database_data.port)
                    .database(&database_data.name)
                    .connect()
                    .await;

                // Check if the connection was successful
                let mut connection = match connection_result {
                    Ok(conn) => conn,
                    Err(why) => {
                        panic!("Failed to establish connection: {why}");
                    }
                };

                // Iterate through the vector of SQL commands and execute them one at a time
                for sql_command in sql_content {
                    println!("Executing SQL command: {sql_command}"); // Log the SQL command being executed
                                                                      // Execute the SQL command
                    match sqlx::query(&sql_command).execute(&mut connection).await {
                        Ok(_) => {
                            println!("Successfully executed SQL command: {sql_command}");
                        }
                        Err(why) => {
                            println!("Failed to execute SQL command: {sql_command}, Error: {why}");
                            // Optionally, return an error instead of panicking
                            // return Err(why.into());
                        }
                    }
                }

                write_to_mysql_user_models(&project).unwrap_or_else(|why| {
                    println!("Failed to write to user models: {:?}", why.to_string());
                });
            }

            DatabaseType::Mongo => {
                // Create the database
                let database_url = format!(
                    "DATABASE_URL=mongodb://localhost:27017/{}",
                    &database_data.clone().name
                );
                println!("database_url: {database_url}");
                let output = std::process::Command::new("diesel")
                    .arg("setup")
                    .env("DATABASE_URL", database_url)
                    .output()
                    .expect("Failed to execute process");
                println!("output: {:?}", output);
            }
        }

        // write to the dashboard page
        write_to_dashboard(project.clone()).unwrap_or_else(|why| {
            println!("Failed to write to dashboard: {:?}", why.to_string());
        });

        println!("Project {} created!", &project.name);

        // Create the database
        Ok(project)
    } // End of create_new_project function

    pub fn exit_program() {
        println!("Exiting...");
        std::process::exit(0);
    }

    pub fn cli() -> Command {
        Command::new("RustyRoad")
            .about("CLI for Rusty Road")
            .subcommand_required(true)
            .arg_required_else_help(true)
            .allow_external_subcommands(true)
            .arg(
                arg!(--format <FORMAT> "Output format (text, json)")
                    .required(false)
                    .default_value("text")
                    .value_parser(["text", "json"])
            )
            .subcommand(
                Command::new("new")
                    .about("Creates a new project")
                    .arg(arg!(<name> "The name of the project"))
                    .arg_required_else_help(true),
            )
            .subcommand(
                Command::new("generate")
                    .about("Generates a new controller, model, or controller")
                    .subcommand(
                        Command::new("controller")
                            .about("Generates a new controller")
                            .long_about(
                                "Interactively creates a new controller for a model.\n\n\
                                PREREQUISITES:\n\
                                 - Must be run from your RustyRoad project root (where rustyroad.toml exists)\n\
                                 - The model you reference should already exist\n\n\
                                PROMPTS:\n\
                                 1. Controller type: GET (Read), POST (Create), PUT (Update), DELETE\n\
                                 2. Model name to create a controller for\n\n\
                                FILES CREATED:\n\
                                 - src/controllers/<model_name>/mod.rs\n\
                                 - src/controllers/<model_name>/<action>.rs\n\n\
                                EXAMPLE:\n\
                                 rustyroad generate controller\n\
                                 # Then follow the prompts\n"
                            )
                            .subcommand_required(false)
                            .arg_required_else_help(false)
                            .allow_external_subcommands(false),
                    )
                    .subcommand(
                        Command::new("model")
                            .about("Generates a new model")
                            .long_about(
                                "Creates a new Rust model file for database operations.\n\n\
                                CONFIG:\n\
                                  Reads database type from ./rustyroad.toml to generate database-specific code.\n\n\
                                PREREQUISITES:\n\
                                  - Must be run from your RustyRoad project root\n\n\
                                FILES CREATED:\n\
                                  - src/models/<name>.rs\n\
                                  - Updates src/models/mod.rs\n\n\
                                EXAMPLE:\n\
                                  rustyroad generate model user\n\
                                  rustyroad generate model blog_post\n"
                            )
                            .arg(arg!(<name> "The name of the model"))
                            .subcommand_required(false)
                            .arg_required_else_help(true)
                            .allow_external_subcommands(false),
                    )
                    .subcommand(Command::new("controller").about("Generates a new controller"))
                    .after_help(
                        "EXAMPLES:
                To generate a new controller:
                    rustyroad generate controller <name>
                To generate a new model:
                    rustyroad generate model <name>
                To generate a new controller:
                    rustyroad generate controller <name>
                To generate a new migration:
                    rustyroad generate migration <name>",
                    )
                    .subcommand_required(true),
            )
            .subcommand(
                Command::new("migration")
                    .about("Database schema migrations")
                    .long_about(
                        "Database migrations manage schema changes over time.\n\nWhere migrations live:\n  ./config/database/migrations/<timestamp>-<name>/{up.sql,down.sql}\n\nDo NOT create a plain ./migrations/ folder — RustyRoad will not read it.\n\nTypical flow:\n  1) Generate a migration (creates folder + up.sql + down.sql)\n  2) Edit up.sql / down.sql if needed\n  3) Run migrations\n",
                    )
                    .after_help(
                        "EXAMPLES:\n  rustyroad migration generate create_users_table id:serial:primary_key email:string:not_null,unique\n  rustyroad migration all\n  rustyroad migration run create_users_table\n  rustyroad migration rollback create_users_table\n  rustyroad migration list\n",
                    )
                    .subcommand(
                        Command::new("generate")
                            .alias("new")
                            .alias("create")
                            .alias("make")
                            .about("Generate a new migration folder with up.sql and down.sql")
                            .long_about(
"Generates UP and DOWN SQL migration files for creating a new table.
Specify the table name and the columns with their types and optional constraints.

Column Format: name:type[:constraints]
Constraints are comma-separated (e.g., primary_key, not_null, unique, default=value).

Example:
rustyroad migration generate create_users id:serial:primary_key email:string:not_null,unique created_at:timestamp:default=now"
                            )
                            .arg(arg!(<name> "The name of the migration (e.g., create_users_table)"))
                            .arg(
                                Arg::new("columns")
                                    .help("Column definitions in name:type[:constraints] format")
                                    .value_name("COLUMNS")
                                    .required(false) // Make columns optional for now, can add interactive mode later if needed
                                    .num_args(1..) // Allow one or more column definitions
                            )
                            .arg_required_else_help(true), // Require at least the name
                    )
                    .subcommand(
                        Command::new("all")
                            .about("Run all migrations (up) in timestamp order")
                            .long_about(
                                "Applies all pending migrations from ./config/database/migrations/ in timestamp order.\n\n\
                                CONFIG:\n\
                                 Database connection from ./rustyroad.toml (or ./rustyroad.<ENVIRONMENT>.toml).\n\n\
                                BEHAVIOR:\n\
                                 - Executes each up.sql file in timestamp order\n\
                                 - Records applied migrations in _rustyroad_migrations table\n\
                                 - Skips already-applied migrations\n\n\
                                EXAMPLE:\n\
                                 rustyroad migration all\n\
                                 ENVIRONMENT=prod rustyroad migration all\n"
                            )
                            .after_help(
                                "This reads migrations from ./config/database/migrations and applies each migration's up.sql.\n\nExample:\n  rustyroad migration all\n",
                            ),
                    )
                    .subcommand(
                        Command::new("run")
                            .about("Run a specific migration by name")
                            .long_about(
                                "Runs a specific migration by name.\n\n\
                                CONFIG:\n\
                                 Database connection from ./rustyroad.toml (or ./rustyroad.<ENVIRONMENT>.toml).\n\n\
                                The name is the part after the timestamp (e.g., for 20231225120000-create_users, use: create_users)\n\n\
                                EXAMPLE:\n\
                                 rustyroad migration run create_users\n\
                                 ENVIRONMENT=prod rustyroad migration run add_email_column\n"
                            )
                            .arg(arg!(<name> "The migration name (the part after the timestamp in the folder name)."))
                            .arg_required_else_help(true)
                            .after_help(
                                "If you're not sure what the name is, run: rustyroad migration list\n\nExample:\n  rustyroad migration run create_users_table\n",
                            ),
                    )
                    .subcommand(
                        Command::new("rollback")
                            .about("Rollback (down) a specific migration by name")
                            .long_about(
                                "Rollbacks (down) a specific migration by name.\n\n\
                                CONFIG:\n\
                                 Database connection from ./rustyroad.toml (or ./rustyroad.<ENVIRONMENT>.toml).\n\n\
                                WARNING: This is destructive. It will undo the changes made by the migration.\n\n\
                                EXAMPLE:\n\
                                 rustyroad migration rollback create_users\n\
                                 ENVIRONMENT=prod rustyroad migration rollback add_email_column\n"
                            )
                            .arg(arg!(<name> "The migration name (e.g., create_users_table)."))
                            .arg_required_else_help(true),
                    )
                    .subcommand(
                        Command::new("redo")
                            .about("Rollback (down) then run (up) a migration by name")
                            .long_about(
                                "Rollbacks (down) then runs (up) a migration by name.\n\n\
                                CONFIG:\n\
                                 Database connection from ./rustyroad.toml (or ./rustyroad.<ENVIRONMENT>.toml).\n\n\
                                Useful when testing or debugging migration changes.\n\n\
                                EXAMPLE:\n\
                                 rustyroad migration redo create_users\n\
                                 ENVIRONMENT=prod rustyroad migration redo add_email_column\n"
                            )
                            .arg(arg!(<name> "The migration name (e.g., create_users_table)."))
                            .arg_required_else_help(true),
                    )
                    .subcommand(
                        Command::new("reset")
                            .about("Rollback ALL migrations (down) in reverse timestamp order")
                            .long_about(
                                "Rollbacks ALL migrations (down) in reverse timestamp order.\n\n\
                                CONFIG:\n\
                                 Database connection from ./rustyroad.toml (or ./rustyroad.<ENVIRONMENT>.toml).\n\n\
                                WARNING: This is destructive. It will undo all migrations and reset the database schema.\n\n\
                                EXAMPLE:\n\
                                 rustyroad migration reset\n\
                                 ENVIRONMENT=prod rustyroad migration reset\n"
                            )
                            .after_help(
                                "This is destructive. It will execute down.sql for each migration.\n\nExample:\n  rustyroad migration reset\n",
                            ),
                    )
                    .subcommand(
                        Command::new("list")
                            .alias("status")
                            .about("List migrations and whether they're applied")
                            .long_about(
                                "Lists migrations and whether they're applied.\n\n\
                                CONFIG:\n\
                                 Database connection from ./rustyroad.toml (or ./rustyroad.<ENVIRONMENT>.toml).\n\n\
                                OUTPUT:\n\
                                 - Applied: Migration has been run (up)\n\
                                 - Rolled back: Migration has been undone (down)\n\
                                 - Pending: Migration exists but has not been run\n\n\
                                EXAMPLE:\n\
                                 rustyroad migration list\n\
                                 ENVIRONMENT=prod rustyroad migration list\n"
                            )
                            .after_help(
                                "Example:\n  rustyroad migration list\n",
                            ),
                    )
                    .subcommand(
                        Command::new("convert")
                            .alias("fix")
                            .alias("import")
                            .about("Convert rogue SQL migrations to RustyRoad format")
                            .long_about(
                                "Detects SQL migration files created in non-standard locations (like ./migrations/)\n\
                                and converts them to RustyRoad's expected format.\n\n\
                                AI agents and developers often create migrations in the wrong location.\n\
                                This command automatically:\n\
                                 1. Scans for SQL files in common incorrect locations\n\
                                 2. Parses the SQL to understand the operations\n\
                                 3. Generates proper up.sql and down.sql files\n\
                                 4. Places them in ./config/database/migrations/<timestamp>-<name>/\n\n\
                                DETECTED LOCATIONS:\n\
                                 - ./migrations/\n\
                                 - ./migration/\n\
                                 - ./db/migrations/\n\
                                 - ./sql/\n\
                                 - *.sql files in project root\n\n\
                                EXAMPLE:\n\
                                 rustyroad migration convert\n\
                                 rustyroad migration convert --remove-source\n"
                            )
                            .arg(
                                Arg::new("remove-source")
                                    .long("remove-source")
                                    .short('r')
                                    .help("Remove the source files after successful conversion")
                                    .action(clap::ArgAction::SetTrue)
                            )
                            .arg(
                                Arg::new("dry-run")
                                    .long("dry-run")
                                    .short('d')
                                    .help("Show what would be converted without making changes")
                                    .action(clap::ArgAction::SetTrue)
                            ),
                    )
                    .subcommand_help_heading("SUBCOMMANDS:")
                    // if no subcommand is provided, print help
                    .subcommand_required(true)
                    .arg_required_else_help(true)
                    .allow_external_subcommands(true),
            )
            .subcommand(
                Command::new("feature")
                    .about("Adds a feature to the project")
                    .subcommand(
                        Command::new("add")
                            .about("Adds a feature to the project")
                            .subcommand(
                                Command::new("grapesjs").about("Adds grapesjs to the project")
                            )
                            .subcommand(
                                Command::new("non_interactive_grapesjs")
                                    .about("Adds grapesjs to the project without asking questions")
                            )
                            .subcommand_required(true)
                            .arg_required_else_help(true)
                            .allow_external_subcommands(true),
                    )
                    .subcommand_required(true)
                    .arg_required_else_help(true)
                    .allow_external_subcommands(true),
            )
            .subcommand(
                Command::new("kubernetes_project")
                    .about("Creates a new rustyroad project for use in kubernetes")
                    .arg(Arg::new("name")
                        .short('n')
                        .long("name")
                        .value_name("NAME")
                        .help("The name of the project")
                        .required(true))
                    .arg(Arg::new("database")
                        .short('d')
                        .long("database")
                        .value_name("DATABASE")
                        .help("The type of database to use")
                        .required(true))
                    .arg(Arg::new("username")
                        .short('u')
                        .long("username")
                        .value_name("USERNAME")
                        .help("The username for the database")
                        .required(true))
                    .arg(Arg::new("password")
                        .short('p')
                        .long("password")
                        .value_name("PASSWORD")
                        .help("The password for the database")
                        .required(true))
                    .arg(Arg::new("host")
                        .short('h')
                        .long("host")
                        .value_name("HOST")
                        .help("The host for the database")
                        .required(true))
                    .arg(Arg::new("port")
                        .short('o')
                        .long("port")
                        .value_name("PORT")
                        .help("The port for the database")
                        .required(true))
                    .arg_required_else_help(true)
                    .allow_external_subcommands(true),
            )
            .subcommand(
                Command::new("version")
                    .about("Prints the version of Rusty Road")
                    .subcommand_required(false)
                    .arg_required_else_help(false)
                    .allow_external_subcommands(false),
            )
            .subcommand(
                Command::new("config")
                    .about("Show which config file RustyRoad will use")
                    .long_about(
                        "Prints the active ENVIRONMENT and the config filename RustyRoad will read.\n\n\
By default RustyRoad uses: ./rustyroad.toml\n\
If ENVIRONMENT is set (and not 'dev'), RustyRoad uses: ./rustyroad.<ENVIRONMENT>.toml\n\n\
Example:\n\
  ENVIRONMENT=prod rustyroad config\n",
                    )
                    .subcommand_required(false)
                    .arg_required_else_help(false)
                    .allow_external_subcommands(false),
            )
            .subcommand(
                Command::new("db")
                    .about("Database operations")
                    .subcommand(
                        Command::new("schema")
                            .about("Inspect database schema")
                            .long_about(
                                "Lists all tables and their columns from the connected database.\n\n\
                                CONFIG:\n\
                                 Reads from ./rustyroad.toml by default.\n\
                                 Set ENVIRONMENT=<env> to use ./rustyroad.<env>.toml instead.\n\n\
                                PREREQUISITES:\n\
                                 - Must be run from your RustyRoad project root\n\
                                 - Database must be reachable\n\n\
                                Supports: PostgreSQL, MySQL, SQLite\n\n\
                                EXAMPLE:\n\
                                 rustyroad db schema\n\
                                 ENVIRONMENT=prod rustyroad db schema\n"
                            )
                    )
                    .subcommand_required(true)
                    .arg_required_else_help(true)
            )
            .subcommand(
                Command::new("query")
                    .about("Execute SQL query")
                    .long_about(
                        "Executes a SQL query against the database configured in rustyroad.toml.\n\n\
                        CONFIG:\n\
                         Reads from ./rustyroad.toml (or ./rustyroad.<ENVIRONMENT>.toml if ENVIRONMENT is set).\n\n\
                        PREREQUISITES:\n\
                         - Must be run from your RustyRoad project root (where rustyroad.toml exists)\n\
                         - Database must be reachable\n\n\
                        EXAMPLES:\n\
                         rustyroad query \"SELECT * FROM users\"\n\
                         ENVIRONMENT=prod rustyroad query \"SELECT COUNT(*) FROM orders\"\n\n\
                        WARNING: Destructive queries (UPDATE, DELETE, DROP) execute immediately with no confirmation.\n"
                    )
                    .arg(arg!(<QUERY> "SQL query to execute"))
                    .arg_required_else_help(true)
            )
    }

    fn print_config_info() {
        let environment = std::env::var("ENVIRONMENT").unwrap_or("dev".to_string());
        let file_name = if environment == "dev" {
            "rustyroad.toml".to_string()
        } else {
            format!("rustyroad.{}.toml", environment)
        };
        println!("Config file: {}", file_name);
        println!("Environment: {}", environment);
    }

    pub fn push_args() -> Vec<Arg> {
        vec![arg!(-m --message <MESSAGE>)]
    }

    pub async fn run() {
        let matches = Self::cli().get_matches();
        let format = matches.get_one::<String>("format").unwrap().as_str();
        match matches.subcommand() {
            // New Project Case
            Some(("new", matches)) => {
                let name = matches.get_one::<String>("name").unwrap().to_string();
                // ask what database they would like to use "postgres, mysql, sqlite, or none"
                // print a selection menu for the database
                // if they select postgres, mysql, or sqlite, ask for the database name, username, and password
                // if they select none, continue
                // create a new project with the name and database information

                // ask what database they would like to use "postgres, mysql, sqlite, or none"
                // print a selection menu for the database
                println!("What database would you like to use?");
                println!("1. Postgres");
                println!("2. MySQL");
                println!("3. SQLite");
                println!("4. MongoDB");
                println!("5. None");
                let mut database_choice = String::new();
                std::io::stdin()
                    .read_line(&mut database_choice)
                    .expect("Failed to read line");
                let database_choice_int = database_choice.trim().parse::<u32>().unwrap();

                // match the database choice
                match database_choice_int {
                    1 => {
                        // ask for the database name, username, and password
                        println!("What is the database name?");
                        let mut database_name = String::new();
                        std::io::stdin()
                            .read_line(&mut database_name)
                            .expect("Failed to read line");
                        let database_name = database_name.trim().to_string();
                        println!("What is the database username?");
                        let mut database_username = String::new();
                        std::io::stdin()
                            .read_line(&mut database_username)
                            .expect("Failed to read line");
                        let database_username = database_username.trim().to_string();
                        println!("What is the database password?");
                        let mut database_password = String::new();
                        std::io::stdin()
                            .read_line(&mut database_password)
                            .expect("Failed to read line");
                        let database_password = database_password.trim().to_string();
                        println!("What is the database port?");
                        let mut database_port = String::new();
                        std::io::stdin()
                            .read_line(&mut database_port)
                            .expect("Failed to read line");
                        let database_port = database_port.trim().parse::<u16>().unwrap();
                        println!("What is the database host?");
                        let mut database_host = String::new();
                        std::io::stdin()
                            .read_line(&mut database_host)
                            .expect("Failed to read line");
                        let database_host = database_host.trim().to_string();
                        database_choice = "postgres".to_string();
                        // create a new project with the name and database information
                        let database: Database = Database::new(
                            database_name,
                            database_username,
                            database_password,
                            database_host,
                            database_port,
                            database_choice.as_str(),
                        );
                        Self::create_new_project(name, database).await.err();
                    }
                    2 => {
                        // ask for the database name, username, and password
                        println!("What is the database name?");
                        let mut database_name = String::new();
                        std::io::stdin()
                            .read_line(&mut database_name)
                            .expect("Failed to read line");
                        let database_name = database_name.trim().to_string();
                        println!("What is the database username?");
                        let mut database_username = String::new();
                        std::io::stdin()
                            .read_line(&mut database_username)
                            .expect("Failed to read line");
                        let database_username = database_username.trim().to_string();
                        println!("What is the database password?");
                        let mut database_password = String::new();
                        std::io::stdin()
                            .read_line(&mut database_password)
                            .expect("Failed to read line");
                        let database_password = database_password.trim().to_string();
                        println!("What is the database port?");
                        let mut database_port = String::new();
                        std::io::stdin()
                            .read_line(&mut database_port)
                            .expect("Failed to read line");
                        let database_port = database_port.trim().parse::<u16>().unwrap();
                        println!("What is the database host?");
                        let mut database_host = String::new();
                        std::io::stdin()
                            .read_line(&mut database_host)
                            .expect("Failed to read line");
                        let database_host = database_host.trim().to_string();
                        database_choice = "mysql".to_string();
                        // create a new project with the name and database information
                        let database: Database = Database::new(
                            database_name,
                            database_username,
                            database_password,
                            database_host,
                            database_port,
                            database_choice.as_str(),
                        );
                        Self::create_new_project(name, database).await.err();
                    }
                    3 => {
                        database_choice = "SQLite".to_string();
                        // Since we are using Rusqlite, we don't need to ask for a username or password port or database name
                        // create a new project with the name and database information
                        let database: Database = Database::new(
                            database_choice.to_string(),
                            "Sqlite Local DB".to_string(),
                            "Not Needed".to_string(),
                            "localhost".to_string(),
                            0,
                            "sqlite".trim_end(),
                        );
                        Self::create_new_project(name, database).await.err();
                    }
                    4 => {
                        // ask for the database name, username, and password
                        println!("What is the database name?");
                        let mut database_name = String::new();
                        std::io::stdin()
                            .read_line(&mut database_name)
                            .expect("Failed to read line");
                        let database_name = database_name.trim().to_string();
                        println!("What is the database username?");
                        let mut database_username = String::new();
                        std::io::stdin()
                            .read_line(&mut database_username)
                            .expect("Failed to read line");
                        let database_username = database_username.trim().to_string();
                        println!("What is the database password?");
                        let mut database_password = String::new();
                        std::io::stdin()
                            .read_line(&mut database_password)
                            .expect("Failed to read line");
                        let database_password = database_password.trim().to_string();
                        println!("What is the database port?");
                        let mut database_port = String::new();
                        std::io::stdin()
                            .read_line(&mut database_port)
                            .expect("Failed to read line");
                        let database_port = database_port.trim().parse::<u16>().unwrap();
                        println!("What is the database host?");
                        let mut database_host = String::new();
                        std::io::stdin()
                            .read_line(&mut database_host)
                            .expect("Failed to read line");
                        let database_host = database_host.trim().to_string();
                        database_choice = "mongodb".to_string();
                        // create a new project with the name and database information
                        let database: Database = Database::new(
                            database_choice.to_string(),
                            database_name,
                            database_username,
                            database_password,
                            database_port,
                            database_host.as_str(),
                        );
                        Self::create_new_project(name, database).await.err();
                    }
                    5 => {
                        // create a new project with the name and database information
                        let database: Database = Database::new(
                            database_choice.to_string(),
                            "".to_string(),
                            "".to_string(),
                            "".to_string(),
                            0,
                            "".to_string().as_str(),
                        );
                        Self::create_new_project(name, database).await.err();
                    }
                    _ => {
                        println!("Invalid database choice");
                    }
                };
            }
            // Generate new controllers, models, controllers and migrations
            Some(("generate", matches)) => match matches.subcommand() {
                Some(("controller", _matches)) => {
                    // because we removed the arguments from the user, we need to auto define the controller name below
                    println!("What type of controller would you like to create?");
                    println!("1. GET");
                    println!("2. POST");
                    println!("3. PUT");
                    println!("4. DELETE");
                    let mut controller_type_choice = String::new();
                    std::io::stdin()
                        .read_line(&mut controller_type_choice)
                        .expect("Failed to read line");
                    let controller_type_choice_int =
                        controller_type_choice.trim().parse::<u32>().unwrap();
                    let crud_type = match controller_type_choice_int {
                        1 => CRUDType::Read,
                        2 => CRUDType::Create,
                        3 => CRUDType::Update,
                        4 => CRUDType::Delete,
                        _ => {
                            println!("Invalid controller type choice");
                            return;
                        }
                    };

                    // ask the user the name of the controller
                    println!(
                        "What is the name of the model you want to create a controller for?: "
                    );
                    println!("In order to work out of the box, ensure the model already exists.");
                    let mut input = String::new();
                    std::io::stdin().read_line(&mut input).unwrap();
                    // this pattern needs to be repeated for each CRUD type
                    let model_name = input.trim();

                    create_new_controller(model_name.to_string(), crud_type)
                        .await
                        .expect("Error creating controller");
                }
                Some(("model", matches)) => {
                    // derive the name of the model from the arguments
                    let model_name = matches.get_one::<String>("name").unwrap().as_str();

                    create_base_model(model_name)
                        .await
                        .expect("Error creating model");
                }
                _ => {
                    println!("Invalid generate choice");
                }
            },
            // Migration Case - Can generate migrations, run migrations, and rollback migrations
            Some(("migration", matches)) => {
                // Check for rogue migrations at the start of any migration command
                // (except for 'convert' which handles this itself)
                if matches.subcommand_name() != Some("convert") {
                    warn_about_rogue_migrations();
                }
                
                match matches.subcommand() {
                Some(("generate", matches)) => {
                    let name = matches.get_one::<String>("name").unwrap().to_string();
                    // Get the column definitions provided via CLI
                    let columns: Vec<String> = matches
                        .get_many::<String>("columns")
                        .map(|vals| vals.map(|s| s.to_string()).collect())
                        .unwrap_or_else(Vec::new);

                    println!("Generating migration: {}", name);
                    // Pass the captured columns vector to the updated create_migration function
                    create_migration(&name, columns)
                        .await
                        .expect("Error creating migration");
                }
                Some(("all", _)) => {
                    Self::print_config_info();
                    get_project_name_from_rustyroad_toml()
                        .unwrap_or_else(|why| panic!("This is not a Rusty Road project: {why}"));

                    run_all_migrations(MigrationDirection::Up)
                        .await
                        .expect("Error running migrations");
                }
                Some(("run", matches)) => {
                    Self::print_config_info();
                    let name = matches.get_one::<String>("name").unwrap().to_string();

                    run_migration(name.clone(), MigrationDirection::Up)
                        .await
                        .expect("Error running migration");
                    println!("'{}' migration completed successfully!", name.clone());
                }
                Some(("rollback", matches)) => {
                    Self::print_config_info();
                    let name = matches.get_one::<String>("name").unwrap().to_string();
                    // Create a confirmation prompt
                    let confirmation = Confirm::new()
                        .with_prompt(format!(
                            "Are you sure you want to rollback the '{}' migration?",
                            name
                        ))
                        .interact()
                        .map_err(|err| io::Error::other(err))
                        .expect("Error rolling back migration: ");

                    if confirmation {
                        println!("Rolling back the '{}' migration...", name.clone());
                        run_migration(name.clone(), MigrationDirection::Down)
                            .await
                            .expect("Error rolling back migration");
                        println!(
                            "'{}' migration rollback completed successfully!",
                            name.clone()
                        );
                    } else {
                        println!("'{}' migration rollback canceled by user.", name);
                    }
                }
                Some(("redo", matches)) => {
                    Self::print_config_info();
                    let name = matches.get_one::<String>("name").unwrap().to_string();

                    let confirmation = Confirm::new()
                        .with_prompt(format!(
                            "Redo will rollback (down) then re-apply (up) the '{}' migration. Continue?",
                            name
                        ))
                        .interact()
                        .map_err(|err| io::Error::other(err))
                        .expect("Error confirming redo migration: ");

                    if confirmation {
                        println!("Rolling back '{}'...", name);
                        run_migration(name.clone(), MigrationDirection::Down)
                            .await
                            .expect("Error rolling back migration");
                        println!("Re-applying '{}'...", name);
                        run_migration(name.clone(), MigrationDirection::Up)
                            .await
                            .expect("Error running migration");
                        println!("'{}' migration redo completed successfully!", name);
                    } else {
                        println!("'{}' migration redo canceled by user.", name);
                    }
                }
                Some(("reset", _)) => {
                    Self::print_config_info();
                    let confirmation = Confirm::new()
                        .with_prompt(
                            "Reset will rollback ALL migrations (down) in reverse order. This is destructive. Continue?",
                        )
                        .interact()
                        .map_err(|err| io::Error::other(err))
                        .expect("Error confirming reset migrations: ");

                    if confirmation {
                        run_all_migrations(MigrationDirection::Down)
                            .await
                            .expect("Error rolling back migrations");
                        println!("All migrations rolled back successfully.");
                    } else {
                        println!("Migration reset canceled by user.");
                    }
                }
                Some(("list", _)) => {
                    Self::print_config_info();
                    list_migrations(format).await.expect("Error listing migrations");
                }
                Some(("convert", matches)) => {
                    let remove_source = matches.get_flag("remove-source");
                    let dry_run = matches.get_flag("dry-run");

                    if dry_run {
                        // Just detect and report, don't convert
                        let detected = detect_rogue_migrations();
                        if detected.is_empty() {
                            println!("No rogue migrations detected.");
                        } else {
                            println!("Found {} rogue migration(s) that would be converted:\n", detected.len());
                            for (i, migration) in detected.iter().enumerate() {
                                println!(
                                    "  {}. {} (from {:?})",
                                    i + 1,
                                    migration.name,
                                    migration.source_path
                                );
                                println!("     Operations:");
                                for op in &migration.operations {
                                    match op {
                                        SqlOperation::CreateTable { table_name, .. } => {
                                            println!("       - CREATE TABLE {}", table_name);
                                        }
                                        SqlOperation::DropTable { table_name } => {
                                            println!("       - DROP TABLE {}", table_name);
                                        }
                                        SqlOperation::AlterTableAddColumn { table_name, columns, .. } => {
                                            println!("       - ALTER TABLE {} ADD COLUMN {}", table_name, columns.join(", "));
                                        }
                                        SqlOperation::AlterTableDropColumn { table_name, columns, .. } => {
                                            println!("       - ALTER TABLE {} DROP COLUMN {}", table_name, columns.join(", "));
                                        }
                                        SqlOperation::CreateIndex { index_name, table_name, .. } => {
                                            println!("       - CREATE INDEX {} ON {}", index_name, table_name);
                                        }
                                        SqlOperation::DropIndex { index_name } => {
                                            println!("       - DROP INDEX {}", index_name);
                                        }
                                        SqlOperation::RawSql { .. } => {
                                            println!("       - [Raw SQL statement]");
                                        }
                                    }
                                }
                                println!();
                            }
                            println!("Run without --dry-run to convert these migrations.");
                        }
                    } else {
                        let count = detect_and_convert_rogue_migrations(true, remove_source);
                        if count == 0 {
                            println!("No rogue migrations found to convert.");
                        }
                    }
                }
                _ => {
                    println!("Invalid migration choice");
                }
            }
            },
            // Add Feature Case
            Some(("feature", matches)) => match matches.subcommand() {
                Some(("add", matches)) => match matches.subcommand() {
                    Some(("grapesjs", _matches)) => {
                        // ask the user if they are sure they want to add grapesjs to the project
                        // if they are sure, add grapesjs to the project
                        // if they are not sure, cancel the command
                        let confirmation = Confirm::new()
                            .with_prompt("Are you sure you want to add grapesjs to the project?")
                            .interact()
                            .map_err(|err| io::Error::other(err))
                            .expect("Error adding grapesjs to the project: ");

                        if confirmation {
                            add_feature("grapesjs".to_string())
                                .await
                                .expect("Error adding grapesjs to the project");
                        }
                    }
                    Some(("non_interactive_grapesjs", _matches)) => {
                        add_feature("grapesjs".to_string())
                            .await
                            .expect("Error adding grapesjs to the project");
                    }
                    _ => {}
                },
                _ => {
                    println!("Invalid add choice");
                }
            },
            // Kubernetes Project Case
            Some(("kubernetes_project", matches)) => {
                let name = matches.get_one::<String>("name").unwrap().to_string();
                let database = matches.get_one::<String>("database").unwrap().to_string();
                let username = matches.get_one::<String>("username").unwrap().to_string();
                let password = matches.get_one::<String>("password").unwrap().to_string();
                let host = matches.get_one::<String>("host").unwrap().to_string();
                let port = matches.get_one::<String>("port").unwrap().to_string();
                let database_type = match database.as_str() {
                    "postgres" => DatabaseType::Postgres,
                    "mysql" => DatabaseType::Mysql,
                    "sqlite" => DatabaseType::Sqlite,
                    "mongodb" => DatabaseType::Mongo,
                    _ => DatabaseType::Sqlite,
                };
                let database: Database = match database_type {
                    DatabaseType::Postgres => Database::new(
                        name.clone(),
                        username.clone(),
                        password.clone(),
                        host.clone(),
                        port.clone().parse::<u16>().unwrap(),
                        database_type.to_string().as_str(),
                    ),
                    DatabaseType::Mysql => Database::new(
                        name.clone(),
                        username.clone(),
                        password.clone(),
                        host.clone(),
                        port.clone().parse::<u16>().unwrap(),
                        database_type.to_string().as_str(),
                    ),
                    DatabaseType::Sqlite => Database::new(
                        database_type.to_string(),
                        "Sqlite Local DB".to_string(),
                        "Not Needed".to_string(),
                        "localhost".to_string(),
                        0,
                        "sqlite".trim_end(),
                    ),
                    DatabaseType::Mongo => {
                        todo!("Implement this");
                    }
                };

                Self::create_new_project(name, database).await.err();
            }
            Some(("version", _matches)) => {
                println!("Rusty Road Version: {}", env!("CARGO_PKG_VERSION"));
            }
            Some(("config", _matches)) => {
                let environment = env::var("ENVIRONMENT").unwrap_or_else(|_| "dev".to_string());
                let file_name = if environment == "dev" {
                    "rustyroad.toml".to_string()
                } else {
                    format!("rustyroad.{}.toml", environment)
                };

                let db = match Database::get_database_from_rustyroad_toml() {
                    Ok(db) => db,
                    Err(e) => {
                        println!("Could not load database config: {}", e);
                        return;
                    }
                };

                let password_hint = if db.password.is_empty() {
                    "".to_string()
                } else {
                    format!("(set, {} chars)", db.password.len())
                };

                // Project name is stored in rustyroad.toml under [rustyroad_project].name.
                // We intentionally try only rustyroad.toml here since other ENV-specific files may only contain [database].
                let project_name = std::fs::read_to_string("rustyroad.toml")
                    .ok()
                    .and_then(|contents| toml::from_str::<toml::Value>(&contents).ok())
                    .and_then(|v| v.get("rustyroad_project").and_then(|t| t.as_table()).cloned())
                    .and_then(|t| {
                        t.get("name")
                            .and_then(|name| name.as_str())
                            .map(|s| s.to_string())
                    });

                if format == "json" {
                    let output = serde_json::json!({
                        "environment": environment,
                        "config_file": file_name,
                        "database": {
                            "type": db.database_type.to_string().to_ascii_lowercase(),
                            "host": db.host,
                            "port": db.port,
                            "name": db.name,
                            "user": db.username,
                            "password": password_hint
                        },
                        "project_name": project_name.unwrap_or_else(|| "(unknown)".to_string())
                    });
                    println!("{}", serde_json::to_string_pretty(&output).unwrap());
                } else {
                    println!("ENVIRONMENT={}", environment);
                    println!("Database config file: {}", file_name);

                    println!("Database:");
                    println!("  type: {}", db.database_type.to_string().to_ascii_lowercase());
                    println!("  host: {}", db.host);
                    println!("  port: {}", db.port);
                    println!("  name: {}", db.name);
                    println!("  user: {}", db.username);
                    println!("  password: {}", password_hint);

                    match project_name {
                        Some(name) => println!("Project name: {}", name),
                        None => println!(
                            "Project name: (unknown) — add [rustyroad_project] name=\"...\" to rustyroad.toml"
                        ),
                    }
                }
            }
            Some(("db", matches)) => match matches.subcommand() {
                Some(("schema", _)) => {
                    inspect_schema(format)
                        .await
                        .unwrap_or_else(|e| println!("Error inspecting schema: {}", e));
                }
                _ => {
                    println!("Invalid db command");
                }
            },
            Some(("query", matches)) => {
                let query = matches.get_one::<String>("QUERY").unwrap();
                execute_query(query, format)
                    .await
                    .unwrap_or_else(|e| println!("Error executing query: {}", e));
            }
            _ => {
                println!("Invalid choice");
            }
        }
    }
}