opencrabs 0.3.29

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Install with: cargo install opencrabs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
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
//! CLI subcommands — run, init, config, db, keyring, logs, status, doctor, and config loading.

use anyhow::{Context, Result};
use std::sync::Arc;

use crate::brain::BrainLoader;
use crate::brain::prompt_builder::RuntimeInfo;

use super::args::{
    ChannelCommands, DbCommands, LogCommands, MemoryCommands, OutputFormat, ProfileCommands,
    ServiceCommands, SessionCommands,
};

/// Show system status
pub(crate) async fn cmd_status(config: &crate::config::Config) -> Result<()> {
    use crate::db::Database;

    let version = env!("CARGO_PKG_VERSION");
    println!("🦀 OpenCrabs v{version}\n");

    // Provider
    match crate::brain::provider::create_provider(config).await {
        Ok(provider) => {
            println!(
                "  Provider:  {} ({})",
                provider.name(),
                provider.default_model()
            );
        }
        Err(_) => println!("  Provider:  not configured"),
    }

    // Brain
    let brain_path = BrainLoader::resolve_path();
    let brain_files: Vec<&str> = [
        "persona.md",
        "system.md",
        "IDENTITY.md",
        "USER.md",
        "MEMORY.md",
        "AGENTS.md",
        "TOOLS.md",
        "SOUL.md",
    ]
    .iter()
    .filter(|f| brain_path.join(f).exists())
    .copied()
    .collect();
    if brain_files.is_empty() {
        println!("  Brain:     no files found at {}", brain_path.display());
    } else {
        println!(
            "  Brain:     {} files ({})",
            brain_files.len(),
            brain_files.join(", ")
        );
    }

    // Database
    let db_path = &config.database.path;
    if db_path.exists() {
        let size = std::fs::metadata(db_path).map(|m| m.len()).unwrap_or(0);
        let size_str = if size > 1_048_576 {
            format!("{:.1} MB", size as f64 / 1_048_576.0)
        } else {
            format!("{:.0} KB", size as f64 / 1024.0)
        };

        match Database::connect(db_path).await {
            Ok(db) => {
                let counts = async {
                    let conn = db.pool().get().await.ok()?;
                    conn.interact(|c| {
                        let sessions: i64 =
                            c.query_row("SELECT COUNT(*) FROM sessions", [], |r| r.get(0))?;
                        let messages: i64 =
                            c.query_row("SELECT COUNT(*) FROM messages", [], |r| r.get(0))?;
                        Ok::<_, rusqlite::Error>((sessions, messages))
                    })
                    .await
                    .ok()?
                    .ok()
                }
                .await;
                if let Some((sessions, messages)) = counts {
                    println!(
                        "  Database:  {}{} sessions, {} messages ({})",
                        db_path.display(),
                        sessions,
                        messages,
                        size_str
                    );
                } else {
                    println!("  Database:  {} ({})", db_path.display(), size_str);
                }
            }
            Err(_) => println!("  Database:  {} ({})", db_path.display(), size_str),
        }
    } else {
        println!("  Database:  not initialized");
    }

    // Channels
    let mut channels = Vec::new();
    if config.channels.telegram.enabled {
        channels.push("Telegram");
    }
    if config.channels.discord.enabled {
        channels.push("Discord");
    }
    if config.channels.slack.enabled {
        channels.push("Slack");
    }
    if config.channels.whatsapp.enabled {
        channels.push("WhatsApp");
    }
    if config.channels.trello.enabled {
        channels.push("Trello");
    }
    if channels.is_empty() {
        println!("  Channels:  none enabled");
    } else {
        println!("  Channels:  {}", channels.join(", "));
    }

    // A2A
    if config.a2a.enabled {
        println!(
            "  A2A:       enabled ({}:{})",
            config.a2a.bind, config.a2a.port
        );
    }

    // Dynamic tools
    let tools_path = BrainLoader::resolve_path().join("tools.toml");
    if tools_path.exists()
        && let Ok(contents) = std::fs::read_to_string(&tools_path)
    {
        let count = contents.matches("[[tools]]").count();
        if count > 0 {
            println!("  Tools:     {} dynamic tool(s) in tools.toml", count);
        }
    }

    // Cron
    let cron_path = BrainLoader::resolve_path().join("cron.toml");
    if cron_path.exists()
        && let Ok(contents) = std::fs::read_to_string(&cron_path)
    {
        let count = contents.matches("[[jobs]]").count();
        if count > 0 {
            println!("  Cron:      {} job(s)", count);
        }
    }

    // Logs
    let log_dir = dirs::config_dir()
        .map(|d| d.join("opencrabs").join("logs"))
        .unwrap_or_default();
    if log_dir.exists() {
        let log_count = std::fs::read_dir(&log_dir)
            .map(|rd| {
                rd.filter_map(|e| e.ok())
                    .filter(|e| {
                        e.path()
                            .extension()
                            .map(|ext| ext == "log")
                            .unwrap_or(false)
                    })
                    .count()
            })
            .unwrap_or(0);
        if log_count > 0 {
            println!(
                "  Logs:      {} file(s) in {}",
                log_count,
                log_dir.display()
            );
        }
    }

    println!();
    Ok(())
}

/// Run diagnostics
pub(crate) async fn cmd_doctor(config: &crate::config::Config) -> Result<()> {
    use crate::db::Database;

    let version = env!("CARGO_PKG_VERSION");
    println!("🦀 OpenCrabs Doctor v{version}\n");

    let mut pass = 0u32;
    let mut fail = 0u32;
    let mut warn = 0u32;

    // 1. Config file
    let config_path = crate::config::Config::system_config_path();
    if let Some(ref p) = config_path
        && p.exists()
    {
        println!("  ✅ Config file: {}", p.display());
        pass += 1;
    } else {
        println!("  ❌ Config file: not found (run `opencrabs init` or `opencrabs onboard`)");
        fail += 1;
    }

    // 2. Keys file
    let keys_path = crate::config::keys_path();
    if keys_path.exists() {
        println!("  ✅ Keys file: {}", keys_path.display());
        pass += 1;
    } else {
        println!("  ⚠️  Keys file: not found (API keys stored in config.toml or env vars)");
        warn += 1;
    }

    // 3. Provider
    match crate::brain::provider::create_provider(config).await {
        Ok(provider) => {
            println!(
                "  ✅ Provider: {} (model: {})",
                provider.name(),
                provider.default_model()
            );
            pass += 1;
        }
        Err(e) => {
            println!("  ❌ Provider: {}", e);
            fail += 1;
        }
    }

    // 4. Database
    let db_path = &config.database.path;
    if db_path.exists() {
        match Database::connect(db_path).await {
            Ok(db) => {
                db.run_migrations().await.ok();
                println!("  ✅ Database: {}", db_path.display());
                pass += 1;
            }
            Err(e) => {
                println!("  ❌ Database: failed to connect — {}", e);
                fail += 1;
            }
        }
    } else {
        println!(
            "  ❌ Database: not found at {} (run `opencrabs db init`)",
            db_path.display()
        );
        fail += 1;
    }

    // 5. Brain files
    let brain_path = BrainLoader::resolve_path();
    if brain_path.exists() {
        let brain_files: Vec<&str> = [
            "persona.md",
            "system.md",
            "IDENTITY.md",
            "USER.md",
            "MEMORY.md",
        ]
        .iter()
        .filter(|f| brain_path.join(f).exists())
        .copied()
        .collect();
        if brain_files.is_empty() {
            println!(
                "  ⚠️  Brain: directory exists but no brain files found at {}",
                brain_path.display()
            );
            warn += 1;
        } else {
            println!(
                "  ✅ Brain: {} files ({})",
                brain_files.len(),
                brain_files.join(", ")
            );
            pass += 1;
        }
    } else {
        println!(
            "  ⚠️  Brain: directory not found at {}",
            brain_path.display()
        );
        warn += 1;
    }

    // 6. Channels
    println!();
    println!("  Channels:");

    // Telegram
    if config.channels.telegram.enabled {
        if config
            .channels
            .telegram
            .token
            .as_ref()
            .is_some_and(|t| !t.is_empty())
        {
            println!("    ✅ Telegram: enabled, token set");
            pass += 1;
        } else {
            println!("    ❌ Telegram: enabled but no bot token");
            fail += 1;
        }
    } else {
        println!("    ⬚  Telegram: disabled");
    }

    // Discord
    if config.channels.discord.enabled {
        if config
            .channels
            .discord
            .token
            .as_ref()
            .is_some_and(|t| !t.is_empty())
        {
            println!("    ✅ Discord: enabled, token set");
            pass += 1;
        } else {
            println!("    ❌ Discord: enabled but no bot token");
            fail += 1;
        }
    } else {
        println!("    ⬚  Discord: disabled");
    }

    // Slack
    if config.channels.slack.enabled {
        let has_bot = config
            .channels
            .slack
            .token
            .as_ref()
            .is_some_and(|t| !t.is_empty());
        let has_app = config
            .channels
            .slack
            .app_token
            .as_ref()
            .is_some_and(|t| !t.is_empty());
        if has_bot && has_app {
            println!("    ✅ Slack: enabled, bot + app tokens set");
            pass += 1;
        } else {
            let missing: Vec<&str> = [
                (!has_bot).then_some("bot token"),
                (!has_app).then_some("app token"),
            ]
            .into_iter()
            .flatten()
            .collect();
            println!("    ❌ Slack: enabled but missing {}", missing.join(", "));
            fail += 1;
        }
    } else {
        println!("    ⬚  Slack: disabled");
    }

    // WhatsApp
    if config.channels.whatsapp.enabled {
        println!("    ✅ WhatsApp: enabled (pairs at runtime)");
        pass += 1;
    } else {
        println!("    ⬚  WhatsApp: disabled");
    }

    // Trello
    if config.channels.trello.enabled {
        let has_token = config
            .channels
            .trello
            .token
            .as_ref()
            .is_some_and(|t| !t.is_empty());
        let has_app_token = config
            .channels
            .trello
            .app_token
            .as_ref()
            .is_some_and(|t| !t.is_empty());
        if has_token && has_app_token {
            println!("    ✅ Trello: enabled, token + app token set");
            pass += 1;
        } else {
            println!("    ❌ Trello: enabled but missing credentials");
            fail += 1;
        }
    } else {
        println!("    ⬚  Trello: disabled");
    }

    // 7. CLI tools in PATH
    println!();
    println!("  CLI tools:");
    for (name, desc) in [
        ("claude", "Claude CLI provider"),
        ("opencode", "OpenCode CLI provider"),
        ("codex", "Codex CLI provider"),
        ("docker", "container runtime"),
        ("ffmpeg", "media processing"),
        ("gh", "GitHub CLI"),
    ] {
        if which::which(name).is_ok() {
            println!("{name}: found ({desc})");
            pass += 1;
        } else {
            println!("{name}: not found ({desc})");
        }
    }

    // 8. Dynamic tools
    let tools_path = brain_path.join("tools.toml");
    if tools_path.exists()
        && let Ok(contents) = std::fs::read_to_string(&tools_path)
    {
        let count = contents.matches("[[tools]]").count();
        if count > 0 {
            println!();
            println!("  ✅ Dynamic tools: {} defined in tools.toml", count);
            pass += 1;
        }
    }

    // Summary
    println!();
    if fail == 0 {
        println!("  ✅ All checks passed ({pass} ok, {warn} warnings)");
    } else {
        println!("  {fail} issue(s), {pass} ok, {warn} warning(s)");
    }
    println!();

    Ok(())
}

/// Load configuration from file or defaults
pub(crate) async fn load_config(config_path: Option<&str>) -> Result<crate::config::Config> {
    use crate::config::Config;

    let config = if let Some(path) = config_path {
        tracing::info!("Loading configuration from custom path: {}", path);
        Config::load_from_path(path)?
    } else {
        tracing::debug!("Loading default configuration");
        Config::load()?
    };

    // Validate configuration
    config.validate()?;

    Ok(config)
}

/// Initialize configuration file
pub(crate) async fn cmd_init(_config: &crate::config::Config, force: bool) -> Result<()> {
    use crate::config::Config;

    println!("🦀 OpenCrabs Configuration Initialization\n");

    let config_path = Config::system_config_path()
        .unwrap_or_else(|| crate::config::opencrabs_home().join("config.toml"));

    // Check if config already exists
    if config_path.exists() && !force {
        anyhow::bail!(
            "Configuration file already exists at: {}\nUse --force to overwrite",
            config_path.display()
        );
    }

    // Save default configuration
    let default_config = Config::default();
    default_config.save(&config_path)?;

    println!("✅ Configuration initialized at: {}", config_path.display());
    println!("\n📝 Next steps:");
    println!("   1. Edit the config file to add your API keys");
    println!("   2. Set ANTHROPIC_API_KEY environment variable");
    println!("   3. Run 'opencrabs' or 'opencrabs chat' to start");

    Ok(())
}

/// Show configuration
pub(crate) async fn cmd_config(config: &crate::config::Config, show_secrets: bool) -> Result<()> {
    println!("🦀 OpenCrabs Configuration\n");

    if show_secrets {
        println!("{:#?}", config);
    } else {
        println!("Database: {}", config.database.path.display());
        println!("Log level: {}", config.logging.level);
        println!("\nProviders:");

        if let Some(ref anthropic) = config.providers.anthropic {
            println!(
                "  - anthropic: {}",
                anthropic
                    .default_model
                    .as_ref()
                    .unwrap_or(&"claude-3-5-sonnet-20240620".to_string())
            );
            println!(
                "    API Key: {}",
                if anthropic.api_key.is_some() {
                    "[SET]"
                } else {
                    "[NOT SET]"
                }
            );
        }

        if let Some(ref openai) = config.providers.openai {
            println!(
                "  - openai: {}",
                openai
                    .default_model
                    .as_ref()
                    .unwrap_or(&"gpt-4".to_string())
            );
            println!(
                "    API Key: {}",
                if openai.api_key.is_some() {
                    "[SET]"
                } else {
                    "[NOT SET]"
                }
            );
        }

        println!("\n💡 Use --show-secrets to display API keys");
    }

    Ok(())
}

/// Database operations
pub(crate) async fn cmd_db(config: &crate::config::Config, operation: DbCommands) -> Result<()> {
    use crate::db::Database;

    match operation {
        DbCommands::Init => {
            println!("🗄️  Initializing database...");
            let db = Database::connect(&config.database.path).await?;
            db.run_migrations().await?;
            println!(
                "✅ Database initialized at: {}",
                config.database.path.display()
            );
            Ok(())
        }
        DbCommands::Stats => {
            println!("📊 Database Statistics\n");
            let db = Database::connect(&config.database.path).await?;

            let (session_count, message_count, file_count) = db
                .pool()
                .get()
                .await
                .context("Failed to get connection")?
                .interact(|conn| {
                    let sessions: i64 =
                        conn.query_row("SELECT COUNT(*) FROM sessions", [], |r| r.get(0))?;
                    let messages: i64 =
                        conn.query_row("SELECT COUNT(*) FROM messages", [], |r| r.get(0))?;
                    let files: i64 =
                        conn.query_row("SELECT COUNT(*) FROM files", [], |r| r.get(0))?;
                    Ok::<_, rusqlite::Error>((sessions, messages, files))
                })
                .await
                .map_err(crate::db::interact_err)?
                .context("Failed to query stats")?;

            println!("Sessions: {}", session_count);
            println!("Messages: {}", message_count);
            println!("Files: {}", file_count);

            Ok(())
        }
        DbCommands::Clear { force } => {
            let db = Database::connect(&config.database.path).await?;

            let (session_count, message_count, file_count) = db
                .pool()
                .get()
                .await
                .context("Failed to get connection")?
                .interact(|conn| {
                    let sessions: i64 =
                        conn.query_row("SELECT COUNT(*) FROM sessions", [], |r| r.get(0))?;
                    let messages: i64 =
                        conn.query_row("SELECT COUNT(*) FROM messages", [], |r| r.get(0))?;
                    let files: i64 =
                        conn.query_row("SELECT COUNT(*) FROM files", [], |r| r.get(0))?;
                    Ok::<_, rusqlite::Error>((sessions, messages, files))
                })
                .await
                .map_err(crate::db::interact_err)?
                .context("Failed to query counts")?;

            if session_count == 0 && message_count == 0 && file_count == 0 {
                println!("✨ Database is already empty");
                return Ok(());
            }

            println!("⚠️  WARNING: This will permanently delete ALL data:\n");
            println!("{} sessions", session_count);
            println!("{} messages", message_count);
            println!("{} files", file_count);
            println!();

            // Confirmation prompt
            if !force {
                use std::io::{self, Write};
                print!("Type 'yes' to confirm deletion: ");
                io::stdout().flush()?;

                let mut input = String::new();
                io::stdin().read_line(&mut input)?;

                if input.trim().to_lowercase() != "yes" {
                    println!("❌ Cancelled - no data was deleted");
                    return Ok(());
                }
            }

            // Clear all tables
            println!("\n🗑️  Clearing database...");

            // Delete in correct order to respect foreign key constraints
            db.pool()
                .get()
                .await
                .context("Failed to get connection")?
                .interact(|conn| {
                    conn.execute("DELETE FROM messages", [])?;
                    conn.execute("DELETE FROM files", [])?;
                    conn.execute("DELETE FROM sessions", [])?;
                    Ok::<_, rusqlite::Error>(())
                })
                .await
                .map_err(crate::db::interact_err)?
                .context("Failed to clear database")?;

            println!(
                "✅ Successfully cleared {} sessions, {} messages, and {} files",
                session_count, message_count, file_count
            );

            Ok(())
        }
    }
}

/// Run a single command non-interactively
pub(crate) async fn cmd_run(
    config: &crate::config::Config,
    prompt: String,
    auto_approve: bool,
    format: OutputFormat,
) -> Result<()> {
    use crate::{
        brain::{
            agent::AgentService,
            tools::{
                bash::BashTool, brave_search::BraveSearchTool, code_exec::CodeExecTool,
                config_tool::ConfigTool, context::ContextTool, doc_parser::DocParserTool,
                edit::EditTool, exa_search::ExaSearchTool,
                follow_up_question::FollowUpQuestionTool, glob::GlobTool, grep::GrepTool,
                http::HttpClientTool, ls::LsTool, memory_search::MemorySearchTool,
                notebook::NotebookEditTool, plan_tool::PlanTool, read::ReadTool,
                registry::ToolRegistry, rename_session::RenameSessionTool,
                session_search::SessionSearchTool, slash_command::SlashCommandTool, task::TaskTool,
                web_search::WebSearchTool, write::WriteTool,
            },
        },
        db::Database,
        services::{ServiceContext, SessionService},
    };

    tracing::info!("Running non-interactive command: {}", prompt);

    // Initialize database
    let db = Database::connect(&config.database.path).await?;
    db.run_migrations().await?;

    // Select provider based on configuration using factory
    let provider = crate::brain::provider::create_provider(config).await?;

    // Create tool registry (Arc-wrapped early so SpawnAgentTool can reference it)
    let tool_registry = Arc::new(ToolRegistry::new());
    // Phase 1: Essential file operations
    tool_registry.register(Arc::new(ReadTool));
    tool_registry.register(Arc::new(WriteTool));
    tool_registry.register(Arc::new(EditTool));
    tool_registry.register(Arc::new(crate::brain::tools::hashline::HashlineEditTool));
    tool_registry.register(Arc::new(BashTool));
    tool_registry.register(Arc::new(LsTool));
    tool_registry.register(Arc::new(GlobTool));
    tool_registry.register(Arc::new(GrepTool));
    // Phase 2: Advanced features
    tool_registry.register(Arc::new(WebSearchTool));
    tool_registry.register(Arc::new(CodeExecTool));
    tool_registry.register(Arc::new(NotebookEditTool));
    tool_registry.register(Arc::new(DocParserTool));
    // Phase 3: Workflow & integration
    tool_registry.register(Arc::new(TaskTool));
    tool_registry.register(Arc::new(ContextTool));
    tool_registry.register(Arc::new(HttpClientTool));
    tool_registry.register(Arc::new(PlanTool));
    // Memory search (built-in FTS5, always available)
    tool_registry.register(Arc::new(MemorySearchTool));
    // Session search — hybrid QMD search across all session message history
    tool_registry.register(Arc::new(SessionSearchTool::new(db.pool().clone())));
    // Config management (read/write config.toml, commands.toml)
    tool_registry.register(Arc::new(ConfigTool));
    // Slash command invocation (agent can call any slash command)
    tool_registry.register(Arc::new(SlashCommandTool));
    // Session rename — agent can update the current session's title
    tool_registry.register(Arc::new(RenameSessionTool));
    // Follow-up question — agent asks the user a multi-choice question
    // mid-task and blocks until they click an option button.
    tool_registry.register(Arc::new(FollowUpQuestionTool));
    // EXA search: always available (free via MCP), uses direct API if key is set
    let exa_key = config
        .providers
        .web_search
        .as_ref()
        .and_then(|ws| ws.exa.as_ref())
        .and_then(|p| p.api_key.clone())
        .filter(|k| !k.is_empty());
    tool_registry.register(Arc::new(ExaSearchTool::new(exa_key)));
    // Brave search: requires enabled = true in config.toml AND API key in keys.toml
    if let Some(brave_cfg) = config
        .providers
        .web_search
        .as_ref()
        .and_then(|ws| ws.brave.as_ref())
        && brave_cfg.enabled
        && let Some(brave_key) = brave_cfg.api_key.clone()
    {
        tool_registry.register(Arc::new(BraveSearchTool::new(brave_key)));
    }

    // Phase 5: Multi-agent orchestration
    let subagent_manager = Arc::new(crate::brain::tools::subagent::SubAgentManager::new());
    tool_registry.register(Arc::new(
        crate::brain::tools::subagent::SpawnAgentTool::new(
            subagent_manager.clone(),
            tool_registry.clone(),
        ),
    ));
    tool_registry.register(Arc::new(crate::brain::tools::subagent::WaitAgentTool::new(
        subagent_manager.clone(),
    )));
    tool_registry.register(Arc::new(crate::brain::tools::subagent::SendInputTool::new(
        subagent_manager.clone(),
    )));
    tool_registry.register(Arc::new(
        crate::brain::tools::subagent::CloseAgentTool::new(subagent_manager.clone()),
    ));
    tool_registry.register(Arc::new(
        crate::brain::tools::subagent::ResumeAgentTool::new(
            subagent_manager.clone(),
            tool_registry.clone(),
        ),
    ));

    let team_manager = Arc::new(crate::brain::tools::subagent::TeamManager::new());
    tool_registry.register(Arc::new(
        crate::brain::tools::subagent::TeamCreateTool::new(
            subagent_manager.clone(),
            team_manager.clone(),
            tool_registry.clone(),
        ),
    ));
    tool_registry.register(Arc::new(
        crate::brain::tools::subagent::TeamDeleteTool::new(
            subagent_manager.clone(),
            team_manager.clone(),
        ),
    ));
    tool_registry.register(Arc::new(
        crate::brain::tools::subagent::TeamBroadcastTool::new(
            subagent_manager.clone(),
            team_manager.clone(),
        ),
    ));

    // Recursive Self-Improvement tools
    use crate::brain::tools::feedback_analyze::FeedbackAnalyzeTool;
    use crate::brain::tools::feedback_record::FeedbackRecordTool;
    use crate::brain::tools::self_improve::SelfImproveTool;
    tool_registry.register(Arc::new(FeedbackRecordTool));
    tool_registry.register(Arc::new(FeedbackAnalyzeTool));
    tool_registry.register(Arc::new(SelfImproveTool));

    // Build dynamic system brain from workspace files
    let brain_path = BrainLoader::resolve_path();
    let brain_loader = BrainLoader::new(brain_path.clone());
    let runtime_info = RuntimeInfo {
        model: Some(provider.default_model().to_string()),
        provider: Some(provider.name().to_string()),
        // Collapse $HOME → ~ for the same reason as the TUI runtime
        // info builder: don't leak username, save tokens, keep cache
        // keys stable across machines.
        working_directory: Some(crate::brain::tools::error::collapse_home(
            &std::env::current_dir().unwrap_or_default(),
        )),
    };
    let mut system_brain = brain_loader.build_system_brain(Some(&runtime_info), None);
    if let Some(digest) =
        crate::brain::prompt_builder::build_feedback_digest(db.pool().clone()).await
    {
        system_brain.push_str(&digest);
    }

    // Load dynamic tools from ~/.opencrabs/tools.toml
    let tools_toml_path = crate::brain::tools::dynamic::DynamicToolLoader::default_path()
        .unwrap_or_else(|| std::path::PathBuf::from("tools.toml"));
    let dynamic_count =
        crate::brain::tools::dynamic::DynamicToolLoader::load(&tools_toml_path, &tool_registry);
    if dynamic_count > 0 {
        tracing::info!("Loaded {dynamic_count} dynamic tool(s) from tools.toml");
    }

    // Create service context and agent service
    let service_context = ServiceContext::new(db.pool().clone());
    let agent_service = AgentService::new(provider.clone(), service_context.clone(), config)
        .await
        .with_tool_registry(tool_registry.clone())
        .with_system_brain(system_brain);

    // Create or get session
    let session_service = SessionService::new(service_context);

    let session = session_service
        .create_session(Some("CLI Run".to_string()))
        .await?;

    // Send message
    println!("🤔 Processing...\n");
    let response = agent_service.send_message(session.id, prompt, None).await?;

    // Format and display output
    match format {
        OutputFormat::Text => {
            println!("{}", response.content);
            println!();
            println!(
                "📊 Tokens: {}",
                response.usage.input_tokens + response.usage.output_tokens
            );
            println!("💰 Cost: ${:.6}", response.cost);
        }
        OutputFormat::Json => {
            let output = serde_json::json!({
                "content": response.content,
                "usage": {
                    "input_tokens": response.usage.input_tokens,
                    "output_tokens": response.usage.output_tokens,
                },
                "cost": response.cost,
                "model": response.model,
            });
            println!("{}", serde_json::to_string_pretty(&output)?);
        }
        OutputFormat::Markdown => {
            println!("# Response\n");
            println!("{}\n", response.content);
            println!("---");
            println!(
                "**Tokens:** {}",
                response.usage.input_tokens + response.usage.output_tokens
            );
            println!("**Cost:** ${:.6}", response.cost);
        }
    }

    if auto_approve {
        println!("\n⚠️  Auto-approve mode was enabled");
    }

    Ok(())
}

/// Log management commands
pub(crate) async fn cmd_logs(operation: LogCommands) -> Result<()> {
    use crate::logging;
    use std::io::{BufRead, BufReader};

    let log_dir = std::env::current_dir()?.join(".opencrabs").join("logs");

    match operation {
        LogCommands::Status => {
            println!("📊 OpenCrabs Logging Status\n");
            println!("Log directory: {}", log_dir.display());

            if log_dir.exists() {
                // Count log files and total size
                let mut file_count = 0;
                let mut total_size = 0u64;
                let mut newest_file: Option<std::path::PathBuf> = None;
                let mut newest_time = std::time::UNIX_EPOCH;

                for entry in std::fs::read_dir(&log_dir)? {
                    let entry = entry?;
                    let path = entry.path();
                    if path.extension().map(|e| e == "log").unwrap_or(false) {
                        file_count += 1;
                        if let Ok(metadata) = entry.metadata() {
                            total_size += metadata.len();
                            if let Ok(modified) = metadata.modified()
                                && modified > newest_time
                            {
                                newest_time = modified;
                                newest_file = Some(path);
                            }
                        }
                    }
                }

                println!("Status: ✅ Active");
                println!("Log files: {}", file_count);
                println!(
                    "Total size: {:.2} MB",
                    total_size as f64 / (1024.0 * 1024.0)
                );

                if let Some(newest) = newest_file {
                    println!("Latest log: {}", newest.display());
                }

                println!("\n💡 To enable debug logging, run with -d flag:");
                println!("   opencrabs -d");
            } else {
                println!("Status: ❌ No logs found");
                println!("\n💡 To enable debug logging, run with -d flag:");
                println!("   opencrabs -d");
                println!("\nThis will create log files in:");
                println!("   {}", log_dir.display());
            }

            Ok(())
        }

        LogCommands::View { lines } => {
            if let Some(log_path) = logging::get_log_path() {
                println!(
                    "📜 Viewing last {} lines of: {}\n",
                    lines,
                    log_path.display()
                );

                let file = std::fs::File::open(&log_path)?;
                let reader = BufReader::new(file);

                // Collect all lines then show last N
                let all_lines: Vec<String> = reader.lines().map_while(Result::ok).collect();
                let start = all_lines.len().saturating_sub(lines);

                for line in &all_lines[start..] {
                    println!("{}", line);
                }

                if all_lines.is_empty() {
                    println!("(empty log file)");
                }
            } else {
                println!("❌ No log files found.\n");
                println!("💡 Run OpenCrabs with -d flag to enable debug logging:");
                println!("   opencrabs -d");
            }

            Ok(())
        }

        LogCommands::Clean { days } => {
            println!("🧹 Cleaning up log files older than {} days...\n", days);

            match logging::cleanup_old_logs(days) {
                Ok(removed) => {
                    if removed > 0 {
                        println!("✅ Removed {} old log file(s)", removed);
                    } else {
                        println!("✅ No old log files to remove");
                    }
                }
                Err(e) => {
                    println!("❌ Error cleaning logs: {}", e);
                }
            }

            Ok(())
        }

        LogCommands::Open => {
            if !log_dir.exists() {
                println!("❌ Log directory does not exist: {}", log_dir.display());
                println!("\n💡 Run OpenCrabs with -d flag to enable debug logging:");
                println!("   opencrabs -d");
                return Ok(());
            }

            println!("📂 Opening log directory: {}", log_dir.display());

            #[cfg(target_os = "macos")]
            {
                std::process::Command::new("open")
                    .arg(&log_dir)
                    .spawn()
                    .context("Failed to open directory")?;
            }

            #[cfg(target_os = "linux")]
            {
                std::process::Command::new("xdg-open")
                    .arg(&log_dir)
                    .spawn()
                    .context("Failed to open directory")?;
            }

            #[cfg(target_os = "windows")]
            {
                std::process::Command::new("explorer")
                    .arg(&log_dir)
                    .spawn()
                    .context("Failed to open directory")?;
            }

            Ok(())
        }
    }
}

/// Interactive CLI agent — multi-turn conversation without TUI
pub(crate) async fn cmd_agent_interactive(
    config: &crate::config::Config,
    auto_approve: bool,
) -> Result<()> {
    use crate::{
        brain::{
            agent::AgentService,
            tools::{
                bash::BashTool, brave_search::BraveSearchTool, code_exec::CodeExecTool,
                config_tool::ConfigTool, context::ContextTool, doc_parser::DocParserTool,
                edit::EditTool, exa_search::ExaSearchTool,
                follow_up_question::FollowUpQuestionTool, glob::GlobTool, grep::GrepTool,
                http::HttpClientTool, ls::LsTool, memory_search::MemorySearchTool,
                notebook::NotebookEditTool, plan_tool::PlanTool, read::ReadTool,
                registry::ToolRegistry, rename_session::RenameSessionTool,
                session_search::SessionSearchTool, slash_command::SlashCommandTool, task::TaskTool,
                web_search::WebSearchTool, write::WriteTool,
            },
        },
        db::Database,
        services::{ServiceContext, SessionService},
    };
    use std::io::{self, BufRead, Write};

    let _ = auto_approve; // TODO: wire into approval callback

    let db = Database::connect(&config.database.path).await?;
    db.run_migrations().await?;

    let provider = crate::brain::provider::create_provider(config).await?;

    let tool_registry = Arc::new(ToolRegistry::new());
    tool_registry.register(Arc::new(ReadTool));
    tool_registry.register(Arc::new(WriteTool));
    tool_registry.register(Arc::new(EditTool));
    tool_registry.register(Arc::new(BashTool));
    tool_registry.register(Arc::new(LsTool));
    tool_registry.register(Arc::new(GlobTool));
    tool_registry.register(Arc::new(GrepTool));
    tool_registry.register(Arc::new(WebSearchTool));
    tool_registry.register(Arc::new(CodeExecTool));
    tool_registry.register(Arc::new(NotebookEditTool));
    tool_registry.register(Arc::new(DocParserTool));
    tool_registry.register(Arc::new(TaskTool));
    tool_registry.register(Arc::new(ContextTool));
    tool_registry.register(Arc::new(HttpClientTool));
    tool_registry.register(Arc::new(PlanTool));
    tool_registry.register(Arc::new(MemorySearchTool));
    tool_registry.register(Arc::new(SessionSearchTool::new(db.pool().clone())));
    tool_registry.register(Arc::new(ConfigTool));
    tool_registry.register(Arc::new(SlashCommandTool));
    tool_registry.register(Arc::new(RenameSessionTool));
    // Follow-up question — agent asks the user a multi-choice question
    // mid-task and blocks until they click an option button.
    tool_registry.register(Arc::new(FollowUpQuestionTool));
    let exa_key = config
        .providers
        .web_search
        .as_ref()
        .and_then(|ws| ws.exa.as_ref())
        .and_then(|p| p.api_key.clone())
        .filter(|k| !k.is_empty());
    tool_registry.register(Arc::new(ExaSearchTool::new(exa_key)));
    if let Some(brave_cfg) = config
        .providers
        .web_search
        .as_ref()
        .and_then(|ws| ws.brave.as_ref())
        && brave_cfg.enabled
        && let Some(brave_key) = brave_cfg.api_key.clone()
    {
        tool_registry.register(Arc::new(BraveSearchTool::new(brave_key)));
    }

    let subagent_manager = Arc::new(crate::brain::tools::subagent::SubAgentManager::new());
    tool_registry.register(Arc::new(
        crate::brain::tools::subagent::SpawnAgentTool::new(
            subagent_manager.clone(),
            tool_registry.clone(),
        ),
    ));
    tool_registry.register(Arc::new(crate::brain::tools::subagent::WaitAgentTool::new(
        subagent_manager.clone(),
    )));
    tool_registry.register(Arc::new(crate::brain::tools::subagent::SendInputTool::new(
        subagent_manager.clone(),
    )));
    tool_registry.register(Arc::new(
        crate::brain::tools::subagent::CloseAgentTool::new(subagent_manager.clone()),
    ));
    tool_registry.register(Arc::new(
        crate::brain::tools::subagent::ResumeAgentTool::new(
            subagent_manager.clone(),
            tool_registry.clone(),
        ),
    ));

    let team_manager = Arc::new(crate::brain::tools::subagent::TeamManager::new());
    tool_registry.register(Arc::new(
        crate::brain::tools::subagent::TeamCreateTool::new(
            subagent_manager.clone(),
            team_manager.clone(),
            tool_registry.clone(),
        ),
    ));
    tool_registry.register(Arc::new(
        crate::brain::tools::subagent::TeamDeleteTool::new(
            subagent_manager.clone(),
            team_manager.clone(),
        ),
    ));
    tool_registry.register(Arc::new(
        crate::brain::tools::subagent::TeamBroadcastTool::new(
            subagent_manager.clone(),
            team_manager.clone(),
        ),
    ));

    // Recursive Self-Improvement tools
    tool_registry.register(Arc::new(
        crate::brain::tools::feedback_record::FeedbackRecordTool,
    ));
    tool_registry.register(Arc::new(
        crate::brain::tools::feedback_analyze::FeedbackAnalyzeTool,
    ));
    tool_registry.register(Arc::new(crate::brain::tools::self_improve::SelfImproveTool));

    let brain_path = BrainLoader::resolve_path();
    let brain_loader = BrainLoader::new(brain_path);
    let runtime_info = RuntimeInfo {
        model: Some(provider.default_model().to_string()),
        provider: Some(provider.name().to_string()),
        working_directory: Some(crate::brain::tools::error::collapse_home(
            &std::env::current_dir().unwrap_or_default(),
        )),
    };
    let mut system_brain = brain_loader.build_system_brain(Some(&runtime_info), None);
    if let Some(digest) =
        crate::brain::prompt_builder::build_feedback_digest(db.pool().clone()).await
    {
        system_brain.push_str(&digest);
    }

    // Load dynamic tools from ~/.opencrabs/tools.toml
    let tools_toml_path = crate::brain::tools::dynamic::DynamicToolLoader::default_path()
        .unwrap_or_else(|| std::path::PathBuf::from("tools.toml"));
    let dynamic_count =
        crate::brain::tools::dynamic::DynamicToolLoader::load(&tools_toml_path, &tool_registry);
    if dynamic_count > 0 {
        tracing::info!("Loaded {dynamic_count} dynamic tool(s) from tools.toml");
    }

    let service_context = ServiceContext::new(db.pool().clone());
    let agent_service = AgentService::new(provider.clone(), service_context.clone(), config)
        .await
        .with_tool_registry(tool_registry.clone())
        .with_system_brain(system_brain);

    let session_service = SessionService::new(service_context);
    let session = session_service
        .create_session(Some("CLI Agent".to_string()))
        .await?;

    println!(
        "🦀 OpenCrabs Agent — {} ({})",
        provider.name(),
        provider.default_model()
    );
    println!("Type /exit or Ctrl+D to quit\n");

    let stdin = io::stdin();
    let mut reader = stdin.lock();

    loop {
        print!("");
        io::stdout().flush()?;

        let mut input = String::new();
        if reader.read_line(&mut input)? == 0 {
            println!();
            break;
        }

        let input = input.trim();
        if input.is_empty() {
            continue;
        }
        if input == "/exit" || input == "/quit" || input == "/q" {
            break;
        }

        match agent_service
            .send_message(session.id, input.to_string(), None)
            .await
        {
            Ok(response) => {
                println!("\n{}\n", response.content);
                println!(
                    "  tokens: {} | cost: ${:.6}\n",
                    response.usage.input_tokens + response.usage.output_tokens,
                    response.cost
                );
            }
            Err(e) => {
                eprintln!("\n  error: {e}\n");
            }
        }
    }

    Ok(())
}

/// Channel operations
pub(crate) async fn cmd_channel(
    config: &crate::config::Config,
    operation: ChannelCommands,
) -> Result<()> {
    match operation {
        ChannelCommands::List => {
            println!("🦀 Configured Channels\n");

            let channels: Vec<(&str, bool, &str)> = vec![
                (
                    "Telegram",
                    config.channels.telegram.enabled,
                    if config
                        .channels
                        .telegram
                        .token
                        .as_ref()
                        .is_some_and(|t| !t.is_empty())
                    {
                        "token set"
                    } else {
                        "no token"
                    },
                ),
                (
                    "Discord",
                    config.channels.discord.enabled,
                    if config
                        .channels
                        .discord
                        .token
                        .as_ref()
                        .is_some_and(|t| !t.is_empty())
                    {
                        "token set"
                    } else {
                        "no token"
                    },
                ),
                (
                    "Slack",
                    config.channels.slack.enabled,
                    if config
                        .channels
                        .slack
                        .token
                        .as_ref()
                        .is_some_and(|t| !t.is_empty())
                        && config
                            .channels
                            .slack
                            .app_token
                            .as_ref()
                            .is_some_and(|t| !t.is_empty())
                    {
                        "bot + app tokens set"
                    } else {
                        "missing tokens"
                    },
                ),
                (
                    "WhatsApp",
                    config.channels.whatsapp.enabled,
                    "pairs at runtime",
                ),
                (
                    "Trello",
                    config.channels.trello.enabled,
                    if config
                        .channels
                        .trello
                        .token
                        .as_ref()
                        .is_some_and(|t| !t.is_empty())
                    {
                        "token set"
                    } else {
                        "no token"
                    },
                ),
            ];

            for (name, enabled, detail) in channels {
                let status = if enabled { "" } else { "" };
                let state = if enabled { "enabled" } else { "disabled" };
                println!("  {status} {name:<12} {state:<10} ({detail})");
            }
            println!();
            Ok(())
        }
        ChannelCommands::Doctor => {
            println!("🦀 Channel Health Check\n");
            cmd_doctor_channels(config);
            println!();
            Ok(())
        }
    }
}

/// Shared channel diagnostics
fn cmd_doctor_channels(config: &crate::config::Config) {
    if config.channels.telegram.enabled {
        if config
            .channels
            .telegram
            .token
            .as_ref()
            .is_some_and(|t| !t.is_empty())
        {
            println!("  ✅ Telegram: enabled, token set");
        } else {
            println!("  ❌ Telegram: enabled but no bot token");
        }
    } else {
        println!("  ⬚  Telegram: disabled");
    }

    if config.channels.discord.enabled {
        if config
            .channels
            .discord
            .token
            .as_ref()
            .is_some_and(|t| !t.is_empty())
        {
            println!("  ✅ Discord: enabled, token set");
        } else {
            println!("  ❌ Discord: enabled but no bot token");
        }
    } else {
        println!("  ⬚  Discord: disabled");
    }

    if config.channels.slack.enabled {
        let has_bot = config
            .channels
            .slack
            .token
            .as_ref()
            .is_some_and(|t| !t.is_empty());
        let has_app = config
            .channels
            .slack
            .app_token
            .as_ref()
            .is_some_and(|t| !t.is_empty());
        if has_bot && has_app {
            println!("  ✅ Slack: enabled, bot + app tokens set");
        } else {
            let missing: Vec<&str> = [
                (!has_bot).then_some("bot token"),
                (!has_app).then_some("app token"),
            ]
            .into_iter()
            .flatten()
            .collect();
            println!("  ❌ Slack: enabled but missing {}", missing.join(", "));
        }
    } else {
        println!("  ⬚  Slack: disabled");
    }

    if config.channels.whatsapp.enabled {
        println!("  ✅ WhatsApp: enabled (pairs at runtime)");
    } else {
        println!("  ⬚  WhatsApp: disabled");
    }

    if config.channels.trello.enabled {
        let has_token = config
            .channels
            .trello
            .token
            .as_ref()
            .is_some_and(|t| !t.is_empty());
        let has_app_token = config
            .channels
            .trello
            .app_token
            .as_ref()
            .is_some_and(|t| !t.is_empty());
        if has_token && has_app_token {
            println!("  ✅ Trello: enabled, token + app token set");
        } else {
            println!("  ❌ Trello: enabled but missing credentials");
        }
    } else {
        println!("  ⬚  Trello: disabled");
    }
}

/// Memory operations
pub(crate) async fn cmd_memory(operation: MemoryCommands) -> Result<()> {
    let brain_path = BrainLoader::resolve_path();

    match operation {
        MemoryCommands::List => {
            println!("🦀 Memory Files\n");

            let brain_files = [
                "MEMORY.md",
                "IDENTITY.md",
                "USER.md",
                "AGENTS.md",
                "TOOLS.md",
                "SOUL.md",
                "persona.md",
                "system.md",
            ];

            println!("  Brain files:");
            for name in &brain_files {
                let path = brain_path.join(name);
                if path.exists() {
                    let size = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
                    println!("    ✅ {name:<16} ({size} bytes)");
                }
            }

            let memory_dir = brain_path.join("memory");
            if memory_dir.exists() {
                let mut count = 0;
                let mut total_size = 0u64;
                if let Ok(entries) = std::fs::read_dir(&memory_dir) {
                    for entry in entries.flatten() {
                        if entry
                            .path()
                            .extension()
                            .is_some_and(|e| e == "md" || e == "txt")
                        {
                            count += 1;
                            total_size += entry.metadata().map(|m| m.len()).unwrap_or(0);
                        }
                    }
                }
                if count > 0 {
                    println!(
                        "\n  Memory directory: {count} file(s), {:.1} KB",
                        total_size as f64 / 1024.0
                    );
                    println!("    {}", memory_dir.display());
                }
            }

            println!();
            Ok(())
        }
        MemoryCommands::Get { name } => {
            let name = if name.ends_with(".md") {
                name
            } else {
                format!("{name}.md")
            };

            let path = brain_path.join(&name);
            let path = if path.exists() {
                path
            } else {
                let alt = brain_path.join("memory").join(&name);
                if alt.exists() {
                    alt
                } else {
                    anyhow::bail!("Memory file not found: {name}");
                }
            };

            let content = std::fs::read_to_string(&path)
                .with_context(|| format!("Failed to read {}", path.display()))?;
            println!("{content}");
            Ok(())
        }
        MemoryCommands::Stats => {
            println!("🦀 Memory Statistics\n");

            let brain_files: Vec<_> = [
                "MEMORY.md",
                "IDENTITY.md",
                "USER.md",
                "AGENTS.md",
                "TOOLS.md",
                "SOUL.md",
            ]
            .iter()
            .filter(|f| brain_path.join(f).exists())
            .collect();

            let brain_size: u64 = brain_files
                .iter()
                .map(|f| {
                    std::fs::metadata(brain_path.join(f))
                        .map(|m| m.len())
                        .unwrap_or(0)
                })
                .sum();
            println!(
                "  Brain files:    {} ({:.1} KB)",
                brain_files.len(),
                brain_size as f64 / 1024.0
            );

            let memory_dir = brain_path.join("memory");
            if memory_dir.exists() {
                let (count, size) = std::fs::read_dir(&memory_dir)
                    .map(|rd| {
                        rd.flatten().fold((0u32, 0u64), |(c, s), e| {
                            (c + 1, s + e.metadata().map(|m| m.len()).unwrap_or(0))
                        })
                    })
                    .unwrap_or((0, 0));
                println!("  Memory entries: {count} ({:.1} KB)", size as f64 / 1024.0);
            }

            println!("  Brain path:     {}", brain_path.display());
            println!();
            Ok(())
        }
    }
}

/// Session management
pub(crate) async fn cmd_session(
    config: &crate::config::Config,
    operation: SessionCommands,
) -> Result<()> {
    use crate::{
        db::Database,
        services::{ServiceContext, SessionService},
    };

    let db = Database::connect(&config.database.path).await?;
    db.run_migrations().await?;
    let service_context = ServiceContext::new(db.pool().clone());
    let session_svc = SessionService::new(service_context);

    match operation {
        SessionCommands::List { all } => {
            use crate::db::repository::SessionListOptions;

            println!("🦀 Sessions\n");
            let options = SessionListOptions {
                include_archived: all,
                ..Default::default()
            };
            let sessions = session_svc.list_sessions(options).await?;

            if sessions.is_empty() {
                println!("  No sessions found");
            } else {
                for s in &sessions {
                    let title = s.title.as_deref().unwrap_or("untitled");
                    let provider = s.provider_name.as_deref().unwrap_or("-");
                    let model = s.model.as_deref().unwrap_or("-");
                    let tokens = s.token_count;
                    let archived = if s.archived_at.is_some() {
                        " [archived]"
                    } else {
                        ""
                    };
                    println!(
                        "  {} {:<30} {}/{} ({}tok){archived}",
                        &s.id.to_string()[..8],
                        title,
                        provider,
                        model,
                        tokens,
                    );
                }
                println!("\n  {} session(s)", sessions.len());
            }
            println!();
            Ok(())
        }
        SessionCommands::Get { id } => {
            let uuid = uuid::Uuid::parse_str(&id).context("Invalid session ID")?;
            match session_svc.get_session(uuid).await? {
                Some(s) => {
                    println!("🦀 Session {}\n", s.id);
                    println!("  Title:    {}", s.title.as_deref().unwrap_or("untitled"));
                    println!("  Provider: {}", s.provider_name.as_deref().unwrap_or("-"));
                    println!("  Model:    {}", s.model.as_deref().unwrap_or("-"));
                    println!("  Tokens:   {}", s.token_count);
                    println!("  Cost:     ${:.6}", s.total_cost);
                    println!("  Archived: {}", s.archived_at.is_some());
                    println!("  Created:  {}", s.created_at);
                    println!("  Updated:  {}", s.updated_at);
                    println!();
                }
                None => println!("Session not found: {id}"),
            }
            Ok(())
        }
    }
}

/// Resolve profile-specific service identifiers.
/// Default profile → `com.opencrabs.daemon` / `opencrabs`
/// Named profile → `com.opencrabs.daemon.hermes` / `opencrabs-hermes`
fn service_identifiers() -> (String, String, String) {
    let profile = crate::config::profile::active_profile();
    let suffix = match profile {
        Some(name) if name != "default" => format!(".{name}"),
        _ => String::new(),
    };
    let systemd_suffix = match profile {
        Some(name) if name != "default" => format!("-{name}"),
        _ => String::new(),
    };
    let plist_name = format!("com.opencrabs.daemon{suffix}");
    let systemd_name = format!("opencrabs{systemd_suffix}");
    let log_suffix = if suffix.is_empty() {
        String::new()
    } else {
        suffix.clone()
    };
    (plist_name, systemd_name, log_suffix)
}

/// Build the daemon arguments, including `-p <profile>` when a named profile is active.
fn daemon_args() -> Vec<String> {
    let mut args = Vec::new();
    if let Some(name) = crate::config::profile::active_profile()
        && name != "default"
    {
        args.push("-p".to_string());
        args.push(name.to_string());
    }
    args.push("daemon".to_string());
    args
}

/// OS service management
#[allow(unused_variables)]
pub(crate) async fn cmd_service(operation: ServiceCommands) -> Result<()> {
    let binary = std::env::current_exe().context("Could not determine binary path")?;
    let binary_str = binary.display().to_string();
    let (plist_name, systemd_name, log_suffix) = service_identifiers();
    let args = daemon_args();
    let profile_label = crate::config::profile::active_profile().unwrap_or("default");

    match operation {
        ServiceCommands::Install => {
            #[cfg(target_os = "macos")]
            {
                let plist_path = dirs::home_dir()
                    .context("No home dir")?
                    .join("Library/LaunchAgents")
                    .join(format!("{plist_name}.plist"));

                let args_xml: String =
                    std::iter::once(format!("        <string>{binary_str}</string>"))
                        .chain(args.iter().map(|a| format!("        <string>{a}</string>")))
                        .collect::<Vec<_>>()
                        .join("\n");

                let plist = format!(
                    r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>{plist_name}</string>
    <key>ProgramArguments</key>
    <array>
{args_xml}
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/tmp/opencrabs-daemon{log_suffix}.out.log</string>
    <key>StandardErrorPath</key>
    <string>/tmp/opencrabs-daemon{log_suffix}.err.log</string>
</dict>
</plist>"#
                );

                if let Some(parent) = plist_path.parent() {
                    std::fs::create_dir_all(parent)?;
                }
                std::fs::write(&plist_path, plist)?;
                println!(
                    "✅ Installed LaunchAgent [{profile_label}]: {}",
                    plist_path.display()
                );
                println!("   Run: opencrabs service start");
            }

            #[cfg(target_os = "linux")]
            {
                let unit_path = dirs::home_dir()
                    .context("No home dir")?
                    .join(format!(".config/systemd/user/{systemd_name}.service"));

                let exec_args = std::iter::once(binary_str.clone())
                    .chain(args.iter().cloned())
                    .collect::<Vec<_>>()
                    .join(" ");

                let unit = format!(
                    r#"[Unit]
Description=OpenCrabs Daemon [{profile_label}]
After=network.target

[Service]
Type=simple
ExecStart={exec_args}
Restart=on-failure
RestartSec=5

[Install]
WantedBy=default.target
"#
                );

                if let Some(parent) = unit_path.parent() {
                    std::fs::create_dir_all(parent)?;
                }
                std::fs::write(&unit_path, unit)?;
                std::process::Command::new("systemctl")
                    .args(["--user", "daemon-reload"])
                    .status()?;
                println!(
                    "✅ Installed systemd user unit [{profile_label}]: {}",
                    unit_path.display()
                );
                println!("   Run: opencrabs service start");
            }

            #[cfg(not(any(target_os = "macos", target_os = "linux")))]
            return Err(anyhow::anyhow!(
                "Service install not supported on this platform"
            ));

            #[cfg(any(target_os = "macos", target_os = "linux"))]
            Ok(())
        }
        ServiceCommands::Start => {
            #[cfg(target_os = "macos")]
            {
                std::process::Command::new("launchctl")
                    .args(["load", "-w"])
                    .arg(
                        dirs::home_dir()
                            .context("No home dir")?
                            .join(format!("Library/LaunchAgents/{plist_name}.plist")),
                    )
                    .status()?;
                println!("✅ Started OpenCrabs daemon [{profile_label}]");
            }

            #[cfg(target_os = "linux")]
            {
                std::process::Command::new("systemctl")
                    .args(["--user", "start", &systemd_name])
                    .status()?;
                println!("✅ Started OpenCrabs daemon [{profile_label}]");
            }

            Ok(())
        }
        ServiceCommands::Stop => {
            #[cfg(target_os = "macos")]
            {
                std::process::Command::new("launchctl")
                    .args(["unload"])
                    .arg(
                        dirs::home_dir()
                            .context("No home dir")?
                            .join(format!("Library/LaunchAgents/{plist_name}.plist")),
                    )
                    .status()?;
                println!("✅ Stopped OpenCrabs daemon [{profile_label}]");
            }

            #[cfg(target_os = "linux")]
            {
                std::process::Command::new("systemctl")
                    .args(["--user", "stop", &systemd_name])
                    .status()?;
                println!("✅ Stopped OpenCrabs daemon [{profile_label}]");
            }

            Ok(())
        }
        ServiceCommands::Restart => {
            #[cfg(target_os = "macos")]
            {
                let plist = dirs::home_dir()
                    .context("No home dir")?
                    .join(format!("Library/LaunchAgents/{plist_name}.plist"));
                let _ = std::process::Command::new("launchctl")
                    .args(["unload"])
                    .arg(&plist)
                    .status();
                std::process::Command::new("launchctl")
                    .args(["load", "-w"])
                    .arg(&plist)
                    .status()?;
                println!("✅ Restarted OpenCrabs daemon [{profile_label}]");
            }
            #[cfg(target_os = "linux")]
            {
                std::process::Command::new("systemctl")
                    .args(["--user", "restart", &systemd_name])
                    .status()?;
                println!("✅ Restarted OpenCrabs daemon [{profile_label}]");
            }
            Ok(())
        }
        ServiceCommands::Status => {
            #[cfg(target_os = "macos")]
            {
                let output = std::process::Command::new("launchctl")
                    .args(["list", &plist_name])
                    .output()?;
                if output.status.success() {
                    println!("✅ OpenCrabs daemon [{profile_label}] is running");
                    println!("{}", String::from_utf8_lossy(&output.stdout));
                } else {
                    println!("⬚  OpenCrabs daemon [{profile_label}] is not running");
                }
            }

            #[cfg(target_os = "linux")]
            {
                let output = std::process::Command::new("systemctl")
                    .args(["--user", "status", &systemd_name])
                    .output()?;
                println!("{}", String::from_utf8_lossy(&output.stdout));
            }

            Ok(())
        }
        ServiceCommands::Uninstall => {
            #[cfg(target_os = "macos")]
            {
                let plist = dirs::home_dir()
                    .context("No home dir")?
                    .join(format!("Library/LaunchAgents/{plist_name}.plist"));
                let _ = std::process::Command::new("launchctl")
                    .args(["unload"])
                    .arg(&plist)
                    .status();
                if plist.exists() {
                    std::fs::remove_file(&plist)?;
                    println!(
                        "✅ Removed LaunchAgent [{profile_label}]: {}",
                        plist.display()
                    );
                } else {
                    println!("⬚  LaunchAgent [{profile_label}] not found");
                }
            }
            #[cfg(target_os = "linux")]
            {
                let _ = std::process::Command::new("systemctl")
                    .args(["--user", "stop", &systemd_name])
                    .status();
                std::process::Command::new("systemctl")
                    .args(["--user", "disable", &systemd_name])
                    .status()?;
                let unit_path = dirs::home_dir()
                    .context("No home dir")?
                    .join(format!(".config/systemd/user/{systemd_name}.service"));
                if unit_path.exists() {
                    std::fs::remove_file(&unit_path)?;
                    std::process::Command::new("systemctl")
                        .args(["--user", "daemon-reload"])
                        .status()?;
                    println!(
                        "✅ Removed systemd unit [{profile_label}]: {}",
                        unit_path.display()
                    );
                } else {
                    println!("⬚  Systemd unit [{profile_label}] not found");
                }
            }

            Ok(())
        }
    }
}

/// Profile management
pub(crate) async fn cmd_profile(operation: ProfileCommands) -> Result<()> {
    use crate::config::profile;

    match operation {
        ProfileCommands::Create { name, description } => {
            let path = profile::create_profile(&name, description.as_deref())?;
            println!("✅ Created profile '{name}'");
            println!("   Path: {}", path.display());
            println!("\n   Usage: opencrabs -p {name}");
            Ok(())
        }
        ProfileCommands::List => {
            let profiles = profile::list_profiles()?;
            let active = profile::active_profile().unwrap_or("default");

            println!("Profiles:\n");
            for p in &profiles {
                let marker = if p.name == active { "" } else { "" };
                let desc = p
                    .description
                    .as_deref()
                    .map(|d| format!("{d}"))
                    .unwrap_or_default();
                println!("  {}{}{}", p.name, desc, marker);
            }
            println!("\n  {} profile(s) total", profiles.len());
            Ok(())
        }
        ProfileCommands::Delete { name, force } => {
            if !force {
                println!("⚠️  This will permanently delete profile '{name}' and ALL its data.");
                println!("   Re-run with --force to confirm.");
                return Ok(());
            }
            profile::delete_profile(&name)?;
            println!("✅ Deleted profile '{name}'");
            Ok(())
        }
        ProfileCommands::Export { name, output } => {
            let output_path = output
                .map(std::path::PathBuf::from)
                .unwrap_or_else(|| std::path::PathBuf::from(format!("{name}.tar.gz")));
            profile::export_profile(&name, &output_path)?;
            println!("✅ Exported profile '{name}' to {}", output_path.display());
            Ok(())
        }
        ProfileCommands::Import { path } => {
            let name = profile::import_profile(std::path::Path::new(&path))?;
            println!("✅ Imported profile '{name}'");
            println!("\n   Usage: opencrabs -p {name}");
            Ok(())
        }
        ProfileCommands::Migrate { from, to, force } => {
            let migrated = profile::migrate_profile(&from, &to, force)?;
            if migrated.is_empty() {
                println!("⚠️  No files migrated from '{from}' to '{to}'.");
                println!("   All files already exist in '{to}'. Use --force to overwrite.");
            } else {
                println!(
                    "✅ Migrated {} files from '{from}' to '{to}':\n",
                    migrated.len()
                );
                for file in &migrated {
                    println!("   {file}");
                }
                println!("\n   Switch to the new profile: opencrabs -p {to}");
                println!("   Then customize identity, brain files, keys, etc.");
            }
            Ok(())
        }
    }
}