catenary-mcp 1.3.5

A high-performance multiplexing bridge between MCP (Model Context Protocol) and LSP (Language Server Protocol). Enables LLMs to access IDE-grade code intelligence across multiple languages simultaneously with smart routing and UTF-8 accuracy.
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
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 Mark Wells <contact@markwells.dev>

//! Catenary MCP server and CLI.
//!
//! This is the main entry point for the Catenary multiplexing bridge.
//! It can be run as an MCP server or as a CLI tool to list and monitor sessions.

#![allow(clippy::print_stdout, reason = "CLI tool needs to output to stdout")]
#![allow(clippy::print_stderr, reason = "CLI tool needs to output to stderr")]

use anyhow::Result;
use chrono::{Local, Utc};
use clap::{Parser, Subcommand};
use regex::Regex;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Mutex;
use tracing::{debug, info, warn};
use tracing_subscriber::EnvFilter;

use catenary_mcp::bridge::{DocumentManager, LspBridgeHandler, PathValidator};
use catenary_mcp::cli::{self, ColorConfig, ColumnWidths};
use catenary_mcp::lsp;
use catenary_mcp::mcp::McpServer;
use catenary_mcp::session::{self, EventKind, Session, SessionEvent};

/// Command-line arguments for Catenary.
#[derive(Parser, Debug)]
#[command(name = "catenary")]
#[command(about = "Multiplexing bridge between MCP and multiple LSP servers")]
struct Args {
    /// The subcommand to run.
    #[command(subcommand)]
    command: Option<Command>,

    /// LSP servers to spawn in "lang:command" format (e.g., "rust:rust-analyzer").
    /// Can be specified multiple times. These override/append to the config file.
    #[arg(short, long = "lsp", global = true)]
    lsps: Vec<String>,

    /// Path to configuration file.
    #[arg(long, global = true)]
    config: Option<PathBuf>,

    /// Workspace root directories. Can be specified multiple times.
    #[arg(short, long, global = true)]
    root: Vec<PathBuf>,

    /// Document idle timeout in seconds before auto-close (0 to disable).
    /// Overrides config file if set (default in config is 300).
    #[arg(long, global = true)]
    idle_timeout: Option<u64>,
}

/// Subcommands supported by Catenary.
#[derive(Subcommand, Debug)]
enum Command {
    /// Run the MCP server (default if no subcommand given).
    Serve,

    /// List active Catenary sessions.
    List,

    /// Monitor events from a session.
    Monitor {
        /// Session ID or row number (use 'catenary list' to see available sessions).
        id: String,

        /// Show raw JSON output.
        #[arg(long)]
        raw: bool,

        /// Disable colored output.
        #[arg(long)]
        nocolor: bool,

        /// Filter events by regex pattern.
        #[arg(long, short)]
        filter: Option<String>,
    },

    /// Show status of a session.
    Status {
        /// Session ID (use 'catenary list' to see available sessions).
        id: String,
    },

    /// Notify a running session of a file change (used by `PostToolUse` hooks).
    /// Reads hook JSON from stdin, connects to the session's notify socket,
    /// and prints any LSP diagnostics to stdout.
    Notify {
        /// Output format: "plain" (default) or "gemini".
        #[arg(long, default_value = "plain")]
        format: String,
    },

    /// Check language server health for the current workspace.
    Doctor {
        /// Disable colored output.
        #[arg(long)]
        nocolor: bool,
    },

    /// Sync /add-dir roots from Claude Code transcript to a running session.
    /// Designed for `PreToolUse` hooks — reads hook JSON from stdin.
    SyncRoots {
        /// Output format: "plain" (default) or "gemini".
        #[arg(long, default_value = "plain")]
        format: String,
    },

    /// Manage file locks for concurrent agent coordination.
    /// Used by `PreToolUse` and `PostToolUse` hooks to serialize file edits
    /// across multiple agents.
    Lock {
        /// The lock action to perform.
        #[command(subcommand)]
        action: LockAction,
    },
}

/// Lock subcommands for concurrent agent coordination.
#[derive(Subcommand, Debug)]
enum LockAction {
    /// Acquire a lock before editing a file.
    /// Blocks until the lock is available or the timeout expires.
    /// Reads hook JSON from stdin.
    Acquire {
        /// Maximum time to wait for the lock (seconds).
        #[arg(long, default_value = "180")]
        timeout: u64,

        /// Output format: "plain" (default) or "gemini".
        #[arg(long, default_value = "plain")]
        format: String,
    },

    /// Release a lock after editing a file.
    /// Sets a grace period before the lock becomes available to other agents.
    /// Reads hook JSON from stdin.
    Release {
        /// Grace period before the lock expires (seconds).
        #[arg(long, default_value = "30")]
        grace: u64,

        /// Output format: "plain" (default) or "gemini".
        #[arg(long, default_value = "plain")]
        format: String,
    },

    /// Track a file read for change detection.
    /// Records the file's modification time so future lock acquisitions
    /// can warn if the file changed.
    /// Reads hook JSON from stdin.
    TrackRead {
        /// Output format: "plain" (default) or "gemini".
        #[arg(long, default_value = "plain")]
        format: String,
    },
}

/// Entry point for the Catenary binary.
///
/// # Errors
///
/// Returns an error if the subcommand fails.
#[tokio::main]
async fn main() -> Result<()> {
    let args = Args::parse();

    match args.command {
        None | Some(Command::Serve) => run_server(args).await,
        Some(Command::List) => run_list(),
        Some(Command::Monitor {
            id,
            raw,
            nocolor,
            filter,
        }) => run_monitor(&id, raw, nocolor, filter.as_deref()),
        Some(Command::Status { id }) => run_status(&id),
        Some(Command::Notify { format }) => {
            run_notify(&format);
            Ok(())
        }
        Some(Command::Doctor { nocolor }) => run_doctor(args, nocolor).await,
        Some(Command::SyncRoots { format }) => {
            run_sync_roots(&format);
            Ok(())
        }
        Some(Command::Lock { action }) => {
            run_lock(action);
            Ok(())
        }
    }
}

/// Run the MCP server (main functionality)
/// Runs the MCP server.
///
/// # Errors
///
/// Returns an error if the server fails to start or encounters an internal error.
#[allow(
    clippy::too_many_lines,
    reason = "Server setup requires sequential initialization steps"
)]
async fn run_server(args: Args) -> Result<()> {
    tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::from_default_env().add_directive("catenary=info".parse()?))
        .with_writer(std::io::stderr)
        .init();

    // Load configuration
    let mut config = catenary_mcp::config::Config::load(args.config.clone())?;

    // Override idle_timeout if provided on CLI
    if let Some(timeout) = args.idle_timeout {
        config.idle_timeout = timeout;
    }

    // Merge CLI LSPs into config
    for lsp_spec in args.lsps {
        let (lang, command_str) = lsp_spec.split_once(':').ok_or_else(|| {
            anyhow::anyhow!("Invalid LSP spec: {lsp_spec}. Expected 'lang:command'")
        })?;

        let lang = lang.trim().to_string();
        let command_str = command_str.trim();

        // Parse command into program and arguments
        let mut parts = command_str.split_whitespace();
        let program = parts
            .next()
            .ok_or_else(|| anyhow::anyhow!("command cannot be empty"))?
            .to_string();
        let cmd_args: Vec<String> = parts.map(std::string::ToString::to_string).collect();

        config.server.insert(
            lang,
            catenary_mcp::config::ServerConfig {
                command: program,
                args: cmd_args,
                initialization_options: None,
            },
        );
    }

    // Default to current directory if no roots specified
    let raw_roots = if args.root.is_empty() {
        vec![PathBuf::from(".")]
    } else {
        args.root
    };
    let roots: Vec<PathBuf> = raw_roots
        .into_iter()
        .map(|r| r.canonicalize())
        .collect::<std::io::Result<Vec<_>>>()?;

    let workspace_display = roots
        .iter()
        .map(|r| r.to_string_lossy().into_owned())
        .collect::<Vec<_>>()
        .join(", ");

    // Create session for observability
    let session = Arc::new(std::sync::Mutex::new(Session::create(&workspace_display)?));
    let broadcaster = session
        .lock()
        .map_err(|_| anyhow::anyhow!("mutex poisoned"))?
        .broadcaster();

    info!("Starting catenary multiplexing bridge");
    info!(
        "Session ID: {}",
        session
            .lock()
            .map_err(|_| anyhow::anyhow!("mutex poisoned"))?
            .info
            .id
    );
    info!("Workspace roots: {}", workspace_display);
    info!("Document idle timeout: {}s", config.idle_timeout);

    // Create managers
    let client_manager = Arc::new(lsp::ClientManager::new(
        config.clone(),
        roots,
        broadcaster.clone(),
    ));
    client_manager.spawn_all().await;

    let doc_manager = Arc::new(Mutex::new(DocumentManager::new()));
    let runtime = tokio::runtime::Handle::current();

    // Start document cleanup task if timeout is enabled
    let cleanup_handle = if config.idle_timeout > 0 {
        let client_manager_clone = client_manager.clone();
        let doc_manager_clone = doc_manager.clone();
        let idle_timeout = config.idle_timeout;

        Some(tokio::spawn(async move {
            document_cleanup_task(client_manager_clone, doc_manager_clone, idle_timeout).await;
        }))
    } else {
        None
    };

    let current_roots = client_manager.roots().await;

    let path_validator = Arc::new(tokio::sync::RwLock::new(PathValidator::new(
        current_roots.clone(),
    )));

    // Start the notify socket server for PostToolUse hook integration
    let notify_server = catenary_mcp::notify::NotifyServer::new(
        client_manager.clone(),
        doc_manager.clone(),
        path_validator.clone(),
        broadcaster.clone(),
    );
    let socket_path = session
        .lock()
        .map_err(|_| anyhow::anyhow!("mutex poisoned"))?
        .socket_path();
    let notify_handle = notify_server.start(&socket_path)?;
    session
        .lock()
        .map_err(|_| anyhow::anyhow!("mutex poisoned"))?
        .set_socket_active();

    let handler = LspBridgeHandler::new(
        client_manager.clone(),
        doc_manager,
        runtime,
        broadcaster.clone(),
        path_validator.clone(),
    );

    // Run MCP server (blocking - reads from stdin)
    let session_for_callback = session.clone();
    let client_manager_for_roots = client_manager.clone();
    let path_validator_for_roots = path_validator.clone();
    let runtime_for_roots = tokio::runtime::Handle::current();
    let mut mcp_server = McpServer::new(handler, broadcaster)
        .on_client_info(Box::new(move |name: &str, version: &str| {
            if let Ok(mut session) = session_for_callback.lock() {
                session.set_client_info(name, version);
            }
        }))
        .on_roots_changed(Box::new(move |roots| {
            let paths: Vec<PathBuf> = roots
                .iter()
                .filter_map(|root| {
                    root.uri.strip_prefix("file://").and_then(|p| {
                        let path = PathBuf::from(p);
                        match path.canonicalize() {
                            Ok(canonical) => Some(canonical),
                            Err(e) => {
                                warn!("Skipping root {p}: {e}");
                                None
                            }
                        }
                    })
                })
                .collect();

            // Update path validator with new roots
            runtime_for_roots
                .block_on(path_validator_for_roots.write())
                .update_roots(paths.clone());

            runtime_for_roots.block_on(client_manager_for_roots.sync_roots(paths))?;
            runtime_for_roots.block_on(client_manager_for_roots.spawn_all());
            Ok(())
        }));

    // Run in a blocking task since MCP server uses synchronous I/O
    let mcp_task = tokio::task::spawn_blocking(move || mcp_server.run());

    // Wait for either the MCP task to finish or a termination signal
    let mcp_result = tokio::select! {
        res = mcp_task => {
            res?
        }
        _ = tokio::signal::ctrl_c() => {
            info!("Received shutdown signal");
            Ok(())
        }
    };

    // Stop notify socket server
    notify_handle.abort();
    let _ = notify_handle.await;

    // Stop cleanup task
    if let Some(handle) = cleanup_handle {
        handle.abort();
        let _ = handle.await;
    }

    // Shutdown LSP clients gracefully
    info!("Shutting down LSP servers");
    client_manager.shutdown_all().await;

    // Session cleanup happens automatically via Drop

    mcp_result
}

/// List all active sessions
/// Runs the session list command.
///
/// # Errors
///
/// Returns an error if listing sessions fails.
fn run_list() -> Result<()> {
    let sessions = session::list_sessions()?;

    if sessions.is_empty() {
        println!("No active Catenary sessions");
        return Ok(());
    }

    let term_width = cli::terminal_width();
    let widths = ColumnWidths::calculate(term_width);

    // Print header
    println!(
        "{:>width_num$} {:<width_id$} {:<width_pid$} {:<width_ws$} {:<width_client$} {:<width_lang$} STARTED",
        "#",
        "ID",
        "PID",
        "WORKSPACE",
        "CLIENT",
        "LANGUAGES",
        width_num = widths.row_num,
        width_id = widths.id,
        width_pid = widths.pid,
        width_ws = widths.workspace,
        width_client = widths.client,
        width_lang = widths.languages,
    );
    println!("{}", "-".repeat(term_width.min(120)));

    for (idx, s) in sessions.iter().enumerate() {
        let client = match (&s.client_name, &s.client_version) {
            (Some(name), Some(ver)) => format!("{name} v{ver}"),
            (Some(name), None) => name.clone(),
            _ => "-".to_string(),
        };

        let ago = format_duration_ago(s.started_at);

        // Get active languages for this session
        let languages = session::active_languages(&s.id)
            .unwrap_or_default()
            .join(",");
        let languages = if languages.is_empty() {
            "-".to_string()
        } else {
            languages
        };

        // Truncate fields to fit column widths
        let id = cli::truncate(&s.id, widths.id);
        let workspace = cli::truncate(&s.workspace, widths.workspace);
        let client = cli::truncate(&client, widths.client);
        let languages = cli::truncate(&languages, widths.languages);

        println!(
            "{:>width_num$} {:<width_id$} {:<width_pid$} {:<width_ws$} {:<width_client$} {:<width_lang$} {}",
            idx + 1,
            id,
            s.pid,
            workspace,
            client,
            languages,
            ago,
            width_num = widths.row_num,
            width_id = widths.id,
            width_pid = widths.pid,
            width_ws = widths.workspace,
            width_client = widths.client,
            width_lang = widths.languages,
        );
    }

    Ok(())
}

/// Resolve a session ID from either a row number or ID prefix
fn resolve_session_id(id: &str) -> Result<session::SessionInfo> {
    // Try parsing as a row number first (1-indexed)
    if let Ok(row_num) = id.parse::<usize>()
        && row_num > 0
    {
        let sessions = session::list_sessions()?;
        if let Some(s) = sessions.get(row_num - 1) {
            return Ok(s.clone());
        }
        // Row number out of range — try as session ID prefix before giving up.
        // Session IDs are hex strings that may be all digits (e.g., "025586387"),
        // so a purely numeric input could be either a row number or a session ID.
        if let Ok(session) = find_session(id) {
            return Ok(session);
        }
        anyhow::bail!("Row number {} out of range (1-{})", row_num, sessions.len());
    }

    // Fall back to find_session (ID prefix matching)
    find_session(id)
}

/// Monitor events from a session
/// Runs the monitor command.
///
/// # Errors
///
/// Returns an error if the session cannot be found or monitoring fails.
fn run_monitor(id: &str, raw: bool, nocolor: bool, filter: Option<&str>) -> Result<()> {
    // Resolve session ID (supports row numbers and prefix matching)
    let session = resolve_session_id(id)?;
    let full_id = session.id;

    let colors = ColorConfig::new(nocolor);
    let term_width = cli::terminal_width();

    // Compile filter regex if provided
    let filter_regex = filter
        .as_ref()
        .map(|f| Regex::new(f))
        .transpose()
        .map_err(|e| anyhow::anyhow!("Invalid filter regex: {e}"))?;

    println!("Monitoring session {full_id} (Ctrl+C to stop)\n");

    let mut reader = session::tail_events(&full_id)?;

    loop {
        if let Some(event) = reader.next_event()? {
            // Apply filter if set
            if let Some(ref re) = filter_regex {
                let event_str = format!("{:?}", event.kind);
                if !re.is_match(&event_str) {
                    continue;
                }
            }

            if raw {
                print_event_raw(&event);
            } else {
                print_event_annotated(&event, &colors, term_width);
            }
        } else {
            println!("\nSession ended");
            break;
        }
    }

    Ok(())
}

/// Show status of a session
/// Runs the status command.
///
/// # Errors
///
/// Returns an error if the session cannot be found.
fn run_status(id: &str) -> Result<()> {
    let session = find_session(id)?;

    println!("Session: {}", session.id);
    println!("PID: {}", session.pid);
    println!("Workspace: {}", session.workspace);
    println!(
        "Started: {} ({})",
        session
            .started_at
            .with_timezone(&Local)
            .format("%Y-%m-%d %H:%M:%S"),
        format_duration_ago(session.started_at)
    );

    if let Some(name) = &session.client_name {
        print!("Client: {name}");
        if let Some(ver) = &session.client_version {
            print!(" v{ver}");
        }
        println!();
    }

    // Show recent events
    println!("\nRecent events:");
    let events: Vec<_> = session::monitor_events(&session.id)?.collect();
    let recent: Vec<_> = events.iter().rev().take(10).collect();

    for event in recent.iter().rev() {
        print_event(event);
    }

    Ok(())
}

/// Returns the IPC endpoint path for a session.
///
/// On Unix this is the Unix socket path in the session directory.
/// On Windows this is a named pipe in the kernel namespace.
fn notify_endpoint(session_id: &str) -> PathBuf {
    #[cfg(unix)]
    {
        session::sessions_dir().join(session_id).join("notify.sock")
    }
    #[cfg(windows)]
    {
        PathBuf::from(format!(r"\\.\pipe\catenary-{session_id}"))
    }
}

/// Connects to a notify IPC endpoint and returns a stream for I/O.
///
/// Returns `None` silently on failure (hooks must not break Claude Code's flow).
#[cfg(unix)]
fn notify_connect(endpoint: &std::path::Path) -> Option<std::os::unix::net::UnixStream> {
    if !endpoint.exists() {
        return None;
    }
    let stream = std::os::unix::net::UnixStream::connect(endpoint).ok()?;
    let _ = stream.set_read_timeout(Some(Duration::from_secs(60)));
    let _ = stream.set_write_timeout(Some(Duration::from_secs(5)));
    Some(stream)
}

/// Connects to a notify IPC endpoint and returns a stream for I/O.
///
/// Returns `None` silently on failure (hooks must not break Claude Code's flow).
#[cfg(windows)]
fn notify_connect(endpoint: &std::path::Path) -> Option<std::fs::File> {
    use std::os::windows::fs::OpenOptionsExt;
    // SECURITY_IDENTIFICATION (0x0001_0000) prevents impersonation attacks
    std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .security_qos_flags(0x0001_0000)
        .open(endpoint)
        .ok()
}

/// Sends a JSON request over an IPC stream and reads response lines.
fn ipc_exchange(
    mut stream: impl std::io::Read + std::io::Write,
    request: &serde_json::Value,
) -> Vec<String> {
    use std::io::BufRead;

    if serde_json::to_writer(&mut stream, request).is_err() {
        return Vec::new();
    }
    if stream.write_all(b"\n").is_err() || stream.flush().is_err() {
        return Vec::new();
    }

    let reader = std::io::BufReader::new(stream);
    let mut lines = Vec::new();
    for line in reader.lines() {
        match line {
            Ok(text) if !text.is_empty() => lines.push(text),
            _ => break,
        }
    }
    lines
}

/// Notify a running session of a file change (`PostToolUse` hook handler).
///
/// Reads hook JSON from stdin, finds the matching session by workspace,
/// connects to its notify endpoint, and prints diagnostics to stdout.
/// Silently succeeds on any error to avoid breaking Claude Code's flow.
fn run_notify(format: &str) {
    let Ok(stdin_data) = std::io::read_to_string(std::io::stdin()) else {
        return;
    };

    let Ok(hook_json) = serde_json::from_str::<serde_json::Value>(&stdin_data) else {
        return;
    };

    // Extract file_path from tool_input
    let file_path = hook_json
        .get("tool_input")
        .and_then(|ti| ti.get("file_path").or_else(|| ti.get("file")))
        .and_then(|fp| fp.as_str());

    let Some(file_path) = file_path else {
        return;
    };

    // Resolve to absolute path using cwd from hook JSON (matching run_sync_roots)
    let abs_path = if std::path::Path::new(file_path).is_absolute() {
        std::path::PathBuf::from(file_path)
    } else {
        let cwd = hook_json.get("cwd").and_then(|v| v.as_str()).map_or_else(
            || std::env::current_dir().unwrap_or_default(),
            PathBuf::from,
        );
        cwd.join(file_path)
    };

    // Find session whose workspace contains this file
    let sessions = session::list_sessions().unwrap_or_default();
    let session = sessions
        .iter()
        .find(|s| abs_path.to_string_lossy().starts_with(&s.workspace));

    let Some(session) = session else {
        return;
    };

    let endpoint = notify_endpoint(&session.id);
    let Some(stream) = notify_connect(&endpoint) else {
        return;
    };

    let request = serde_json::json!({ "file": abs_path.to_string_lossy() });
    let lines = ipc_exchange(stream, &request);

    if lines.is_empty() {
        return;
    }

    let output = format_diagnostics(&lines, format);
    print!("{output}");
}

/// Sync `/add-dir` roots from Claude Code transcript to a running Catenary session.
///
/// Reads hook JSON from stdin, scans the transcript for `/add-dir` confirmation
/// messages, and sends newly discovered roots to the session's notify endpoint.
/// Uses a byte-offset cache to avoid re-scanning the entire transcript each time.
///
/// Silently succeeds on any error to avoid breaking Claude Code's flow.
#[allow(
    clippy::too_many_lines,
    reason = "Sequential hook processing with early returns"
)]
fn run_sync_roots(format: &str) {
    use std::io::{BufRead, Seek, SeekFrom};

    let Ok(stdin_data) = std::io::read_to_string(std::io::stdin()) else {
        return;
    };

    let Ok(hook_json) = serde_json::from_str::<serde_json::Value>(&stdin_data) else {
        return;
    };

    // Extract transcript_path and cwd from hook input
    let Some(transcript_path) = hook_json.get("transcript_path").and_then(|v| v.as_str()) else {
        return;
    };

    let cwd = hook_json.get("cwd").and_then(|v| v.as_str()).map_or_else(
        || std::env::current_dir().unwrap_or_default(),
        PathBuf::from,
    );

    // Find the session whose workspace matches cwd
    let sessions = session::list_sessions().unwrap_or_default();
    let cwd_str = cwd.to_string_lossy();
    let session = sessions.iter().find(|s| cwd_str.starts_with(&s.workspace));

    let Some(session) = session else {
        return;
    };

    let session_dir = session::sessions_dir().join(&session.id);

    // Read the byte offset from previous invocation
    let offset_path = session_dir.join("transcript_offset");
    let start_offset: u64 = std::fs::read_to_string(&offset_path)
        .ok()
        .and_then(|s| s.trim().parse().ok())
        .unwrap_or(0);

    // Open transcript and seek to offset
    let Ok(mut file) = std::fs::File::open(transcript_path) else {
        return;
    };

    if file.seek(SeekFrom::Start(start_offset)).is_err() {
        return;
    }

    // Scan new lines for /add-dir confirmation messages
    let mut new_roots = Vec::new();
    let reader = std::io::BufReader::new(&mut file);

    // Pattern: Added \x1b[1m/path\x1b[22m as a working directory
    // In the JSONL file, ESC (\x1b) is JSON-encoded as \u001b, and we're
    // reading raw text lines (not deserializing), so match the escaped form.
    let add_dir_pattern = "Added \\u001b[1m";
    let add_dir_suffix = "\\u001b[22m as a working directory";

    for line in reader.lines() {
        let Ok(line) = line else {
            break;
        };

        // Each line is a JSON object; look inside message.content for the pattern
        if !line.contains(add_dir_pattern) {
            continue;
        }

        // Extract all occurrences of the pattern from this line
        let mut search_from = 0;
        while let Some(start) = line[search_from..].find(add_dir_pattern) {
            let abs_start = search_from + start + add_dir_pattern.len();
            if let Some(end) = line[abs_start..].find(add_dir_suffix) {
                let path_str = &line[abs_start..abs_start + end];
                // Unescape JSON string escapes (the path is inside a JSON string)
                let path_str = path_str
                    .replace("\\\\", "\\")
                    .replace("\\/", "/")
                    .replace("\\\"", "\"");
                let path = PathBuf::from(&path_str);
                let resolved = if path.is_absolute() {
                    path
                } else {
                    cwd.join(path)
                };
                if !new_roots.contains(&resolved) {
                    new_roots.push(resolved);
                }
                search_from = abs_start + end + add_dir_suffix.len();
            } else {
                break;
            }
        }
    }

    // Update the byte offset for next invocation
    if let Ok(pos) = file.stream_position() {
        let _ = std::fs::write(&offset_path, pos.to_string());
    }

    if new_roots.is_empty() {
        return;
    }

    let endpoint = notify_endpoint(&session.id);
    let Some(stream) = notify_connect(&endpoint) else {
        return;
    };

    let root_strings: Vec<String> = new_roots
        .iter()
        .map(|p| p.to_string_lossy().into_owned())
        .collect();
    let request = serde_json::json!({ "add_roots": root_strings });
    let lines = ipc_exchange(stream, &request);

    if lines.is_empty() {
        return;
    }

    let output = format_diagnostics(&lines, format);
    print!("{output}");
}

/// Dispatch lock subcommands.
///
/// Reads hook JSON from stdin, extracts owner identity and file path,
/// and performs the requested lock operation. Silently succeeds on any
/// error to avoid breaking the host CLI's flow.
fn run_lock(action: LockAction) {
    let Ok(stdin_data) = std::io::read_to_string(std::io::stdin()) else {
        return;
    };

    let Ok(hook_json) = serde_json::from_str::<serde_json::Value>(&stdin_data) else {
        return;
    };

    let owner = extract_owner(&hook_json);
    let Some(file_path) = extract_file_path(&hook_json) else {
        return;
    };

    let Ok(mgr) = catenary_mcp::lock::FileLockManager::new() else {
        return;
    };

    match action {
        LockAction::Acquire { timeout, format } => {
            run_lock_acquire(&mgr, &file_path, &owner, timeout, &format, &hook_json);
        }
        LockAction::Release { grace, format: _ } => {
            run_lock_release(&mgr, &file_path, &owner, grace, &hook_json);
        }
        LockAction::TrackRead { format: _ } => {
            run_lock_track_read(&mgr, &file_path, &owner);
        }
    }
}

/// Acquires a file lock, blocking until available or timeout.
fn run_lock_acquire(
    mgr: &catenary_mcp::lock::FileLockManager,
    file_path: &str,
    owner: &str,
    timeout: u64,
    format: &str,
    hook_json: &serde_json::Value,
) {
    use catenary_mcp::lock::AcquireResult;

    let result = mgr.acquire(file_path, owner, timeout);

    // Broadcast event to monitor (best-effort)
    match &result {
        AcquireResult::Acquired | AcquireResult::AcquiredStaleRead { .. } => {
            broadcast_lock_event(
                hook_json,
                EventKind::LockAcquired {
                    file: file_path.to_string(),
                    owner: owner.to_string(),
                },
            );
        }
        AcquireResult::Denied { .. } => {
            // Read the lock to find who's holding it
            let held_by = "unknown".to_string();
            broadcast_lock_event(
                hook_json,
                EventKind::LockDenied {
                    file: file_path.to_string(),
                    owner: owner.to_string(),
                    held_by,
                },
            );
        }
    }

    match result {
        AcquireResult::Acquired => {
            // Silent success
        }
        AcquireResult::AcquiredStaleRead { context } => {
            let output = format_lock_output(format, Some(&context), None);
            print!("{output}");
        }
        AcquireResult::Denied { reason } => {
            let output = format_lock_output(format, None, Some(&reason));
            print!("{output}");
        }
    }
}

/// Releases a file lock with an optional grace period.
fn run_lock_release(
    mgr: &catenary_mcp::lock::FileLockManager,
    file_path: &str,
    owner: &str,
    grace: u64,
    hook_json: &serde_json::Value,
) {
    if mgr.release(file_path, owner, grace).is_ok() {
        broadcast_lock_event(
            hook_json,
            EventKind::LockReleased {
                file: file_path.to_string(),
                owner: owner.to_string(),
            },
        );
    }
}

/// Records a file read for change detection.
fn run_lock_track_read(mgr: &catenary_mcp::lock::FileLockManager, file_path: &str, owner: &str) {
    let _ = mgr.track_read(file_path, owner);
}

/// Extracts the owner identity from hook JSON.
///
/// Uses `session_id` as the primary key. If `agent_id` is present,
/// appends it as `session_id:agent_id`.
fn extract_owner(hook_json: &serde_json::Value) -> String {
    let session_id = hook_json
        .get("session_id")
        .and_then(|v| v.as_str())
        .unwrap_or("unknown");

    let agent_id = hook_json.get("agent_id").and_then(|v| v.as_str());

    agent_id.map_or_else(
        || session_id.to_string(),
        |aid| format!("{session_id}:{aid}"),
    )
}

/// Extracts the file path from hook JSON's `tool_input`.
fn extract_file_path(hook_json: &serde_json::Value) -> Option<String> {
    let file_path = hook_json
        .get("tool_input")
        .and_then(|ti| ti.get("file_path").or_else(|| ti.get("file")))
        .and_then(|fp| fp.as_str())?;

    // Resolve to absolute path
    let abs_path = if std::path::Path::new(file_path).is_absolute() {
        PathBuf::from(file_path)
    } else {
        let cwd = hook_json.get("cwd").and_then(|v| v.as_str()).map_or_else(
            || std::env::current_dir().unwrap_or_default(),
            PathBuf::from,
        );
        cwd.join(file_path)
    };

    Some(abs_path.to_string_lossy().into_owned())
}

/// Formats lock output for the hook response.
///
/// - `additional_context`: injected when the lock was acquired but the file
///   was modified since the owner's last read.
/// - `deny_reason`: injected when the lock acquisition timed out.
fn format_lock_output(
    format: &str,
    additional_context: Option<&str>,
    deny_reason: Option<&str>,
) -> String {
    let is_gemini = format == "gemini";

    match (deny_reason, additional_context) {
        // Gemini BeforeTool uses top-level decision/reason
        (Some(reason), _) if is_gemini => serde_json::json!({
            "decision": "deny",
            "reason": reason
        })
        .to_string(),
        // Claude Code PreToolUse uses hookSpecificOutput
        (Some(reason), _) => serde_json::json!({
            "hookSpecificOutput": {
                "hookEventName": "PreToolUse",
                "permissionDecision": "deny",
                "permissionDecisionReason": reason
            }
        })
        .to_string(),
        // Gemini: deny stale reads too — force re-read before editing
        (None, Some(context)) if is_gemini => serde_json::json!({
            "decision": "deny",
            "reason": context
        })
        .to_string(),
        // Claude Code: allow with advisory context
        (None, Some(context)) => serde_json::json!({
            "hookSpecificOutput": {
                "hookEventName": "PreToolUse",
                "permissionDecision": "allow",
                "additionalContext": context
            }
        })
        .to_string(),
        (None, None) => String::new(),
    }
}

/// Broadcasts a lock event to the monitor (best-effort).
///
/// Finds the Catenary session matching the hook's `cwd` and sends the event
/// via the session's event broadcaster. Silently does nothing if no session
/// is found or the broadcast fails.
fn broadcast_lock_event(hook_json: &serde_json::Value, event: EventKind) {
    use std::io::Write;

    let cwd = hook_json.get("cwd").and_then(|v| v.as_str()).unwrap_or("");

    let sessions = session::list_sessions().unwrap_or_default();
    let Some(session_info) = sessions.iter().find(|s| cwd.starts_with(&s.workspace)) else {
        return;
    };

    // Write directly to the session's events file
    let events_path = session::sessions_dir()
        .join(&session_info.id)
        .join("events.jsonl");

    let event = SessionEvent {
        timestamp: chrono::Utc::now(),
        kind: event,
    };

    if let Ok(mut line) = serde_json::to_string(&event) {
        line.push('\n');
        // Append to events file (best-effort)
        if let Ok(mut file) = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&events_path)
        {
            let _ = file.write_all(line.as_bytes());
        }
    }
}

/// Format diagnostic lines for output.
///
/// - `"gemini"`: wraps in a JSON envelope for Gemini CLI hooks.
/// - Any other value (including `"plain"`): joins lines with newlines and a trailing newline.
fn format_diagnostics(lines: &[String], format: &str) -> String {
    if format == "gemini" {
        let diagnostics = lines.join("\n");
        let envelope = serde_json::json!({
            "hookSpecificOutput": {
                "additionalContext": format!("LSP Diagnostics:\n{diagnostics}")
            }
        });
        // serde_json::to_string cannot fail on Value
        envelope.to_string()
    } else {
        let mut out = lines.join("\n");
        out.push('\n');
        out
    }
}

/// Run the doctor command: check language server health for the current workspace.
///
/// # Errors
///
/// Returns an error if the configuration cannot be loaded or roots cannot be resolved.
#[allow(
    clippy::too_many_lines,
    reason = "Doctor command has sequential output logic"
)]
async fn run_doctor(args: Args, nocolor: bool) -> Result<()> {
    let colors = ColorConfig::new(nocolor);

    // Load configuration (same as run_server)
    let mut config = catenary_mcp::config::Config::load(args.config.clone())?;
    for lsp_spec in &args.lsps {
        let (lang, command_str) = lsp_spec.split_once(':').ok_or_else(|| {
            anyhow::anyhow!("Invalid LSP spec: {lsp_spec}. Expected 'lang:command'")
        })?;
        let lang = lang.trim().to_string();
        let command_str = command_str.trim();
        let mut parts = command_str.split_whitespace();
        let program = parts
            .next()
            .ok_or_else(|| anyhow::anyhow!("command cannot be empty"))?
            .to_string();
        let cmd_args: Vec<String> = parts.map(std::string::ToString::to_string).collect();
        config.server.insert(
            lang,
            catenary_mcp::config::ServerConfig {
                command: program,
                args: cmd_args,
                initialization_options: None,
            },
        );
    }

    // Resolve workspace roots
    let raw_roots = if args.root.is_empty() {
        vec![PathBuf::from(".")]
    } else {
        args.root
    };
    let roots: Vec<PathBuf> = raw_roots
        .into_iter()
        .map(|r| r.canonicalize())
        .collect::<std::io::Result<Vec<_>>>()?;

    // Print config and roots
    let config_source = args
        .config
        .as_ref()
        .map_or_else(|| "default paths".to_string(), |p| p.display().to_string());
    println!("{} {}", colors.bold("Config:"), config_source);
    println!(
        "{} {}",
        colors.bold("Roots: "),
        roots
            .iter()
            .map(|r| r.to_string_lossy().into_owned())
            .collect::<Vec<_>>()
            .join(", ")
    );
    println!();

    if config.server.is_empty() {
        println!("No language servers configured.");
        return Ok(());
    }

    // Detect which languages have files in the workspace
    let configured_keys: std::collections::HashSet<&str> =
        config.server.keys().map(String::as_str).collect();
    let detected = lsp::detect_workspace_languages(&roots, &configured_keys);

    // Sort servers alphabetically
    let mut servers: Vec<(&String, &catenary_mcp::config::ServerConfig)> =
        config.server.iter().collect();
    servers.sort_by_key(|(lang, _)| *lang);

    // Determine column width for language name
    let max_lang_width = servers.iter().map(|(l, _)| l.len()).max().unwrap_or(10);
    let max_cmd_width = servers
        .iter()
        .map(|(_, s)| s.command.len())
        .max()
        .unwrap_or(10);

    // Create a broadcaster for client spawning (no-op since we don't need events)
    let broadcaster = catenary_mcp::session::EventBroadcaster::noop()?;

    for (lang, server_config) in &servers {
        let lang_display = format!("{lang:<max_lang_width$}");
        let cmd_display = format!("{cmd:<max_cmd_width$}", cmd = server_config.command);

        // Check if any files for this language exist
        if !detected.contains(lang.as_str()) {
            println!(
                "{}  {}  {}",
                colors.dim(&lang_display),
                colors.dim(&cmd_display),
                colors.dim("- skipped (no matching files)"),
            );
            continue;
        }

        // Check if binary exists on PATH
        if !binary_exists(&server_config.command) {
            println!(
                "{}  {}  {}",
                lang_display,
                cmd_display,
                colors.red("✗ command not found"),
            );
            continue;
        }

        // Spawn and initialize the server
        let args_refs: Vec<&str> = server_config.args.iter().map(String::as_str).collect();
        let spawn_result = lsp::LspClient::spawn_quiet(
            &server_config.command,
            &args_refs,
            lang,
            broadcaster.clone(),
        );

        let mut client = match spawn_result {
            Ok(client) => client,
            Err(e) => {
                println!(
                    "{}  {}  {}",
                    lang_display,
                    cmd_display,
                    colors.red(&format!("✗ spawn failed: {e}")),
                );
                continue;
            }
        };

        match client
            .initialize(&roots, server_config.initialization_options.clone())
            .await
        {
            Ok(result) => {
                let tools = extract_capabilities(&result.capabilities);
                println!(
                    "{}  {}  {}",
                    lang_display,
                    cmd_display,
                    colors.green("✓ ready"),
                );
                if !tools.is_empty() {
                    println!(
                        "{}  {}",
                        " ".repeat(max_lang_width + max_cmd_width + 4),
                        colors.dim(&tools.join(" ")),
                    );
                }
            }
            Err(e) => {
                println!(
                    "{}  {}  {}",
                    lang_display,
                    cmd_display,
                    colors.red(&format!("✗ initialize failed: {e}")),
                );
            }
        }

        // Shutdown cleanly
        let _ = client.shutdown().await;
    }

    Ok(())
}

/// Checks whether a binary can be found on `$PATH`.
fn binary_exists(command: &str) -> bool {
    // If the command contains a path separator, check it directly
    if command.contains('/') {
        return std::path::Path::new(command).exists();
    }

    // Search PATH
    let path_var = std::env::var("PATH").unwrap_or_default();
    std::env::split_paths(&path_var).any(|dir| dir.join(command).is_file())
}

/// Extracts Catenary tool names from LSP `ServerCapabilities`.
fn extract_capabilities(caps: &lsp_types::ServerCapabilities) -> Vec<&'static str> {
    let mut tools = Vec::new();

    if caps.hover_provider.is_some() {
        tools.push("hover");
    }
    if caps.definition_provider.is_some() {
        tools.push("definition");
    }
    if caps.type_definition_provider.is_some() {
        tools.push("type_definition");
    }
    if caps.implementation_provider.is_some() {
        tools.push("implementation");
    }
    if caps.references_provider.is_some() {
        tools.push("references");
    }
    if caps.document_symbol_provider.is_some() {
        tools.push("document_symbols");
    }
    if caps.workspace_symbol_provider.is_some() {
        tools.push("search");
    }
    if caps.code_action_provider.is_some() {
        tools.push("code_actions");
    }
    if caps.rename_provider.is_some() {
        tools.push("rename");
    }
    if caps.call_hierarchy_provider.is_some() {
        tools.push("call_hierarchy");
    }
    // type_hierarchy_provider is not exposed as a direct field in lsp_types 0.97;
    // type hierarchy support is probed at call time, so we omit it here.

    tools
}

/// Find session by ID or prefix
fn find_session(id: &str) -> Result<session::SessionInfo> {
    // Try exact match first
    if let Some(s) = session::get_session(id)? {
        return Ok(s);
    }

    // Try prefix match
    let sessions = session::list_sessions()?;
    let matches: Vec<_> = sessions.iter().filter(|s| s.id.starts_with(id)).collect();

    match matches.len() {
        0 => anyhow::bail!("No session found matching '{id}'"),
        1 => Ok(matches[0].clone()),
        _ => {
            eprintln!("Multiple sessions match '{id}':");
            for s in matches {
                eprintln!("  {}", s.id);
            }
            anyhow::bail!("Please specify a more complete session ID")
        }
    }
}

/// Format a timestamp as "Xm ago" or similar
fn format_duration_ago(timestamp: chrono::DateTime<Utc>) -> String {
    let now = Utc::now();
    let duration = now.signed_duration_since(timestamp);

    if duration.num_hours() > 0 {
        format!(
            "{}h {}m ago",
            duration.num_hours(),
            duration.num_minutes() % 60
        )
    } else if duration.num_minutes() > 0 {
        format!("{}m ago", duration.num_minutes())
    } else {
        format!("{}s ago", duration.num_seconds())
    }
}

/// Print an event in raw JSON format
fn print_event_raw(event: &SessionEvent) {
    let time = event.timestamp.with_timezone(&Local).format("%H:%M:%S");

    if let EventKind::McpMessage { direction, message } = &event.kind {
        let arrow = if direction == "in" { "" } else { "" };
        println!("[{time}] {arrow}");
        let pretty = serde_json::to_string_pretty(message).unwrap_or_default();
        println!("{pretty}");
    } else {
        // For non-MCP events, print as JSON
        let json = serde_json::to_string_pretty(&event.kind).unwrap_or_default();
        println!("[{time}] {json}");
    }
}

/// Print an event with annotations and colors
#[allow(clippy::too_many_lines, reason = "Match arms for each event kind")]
fn print_event_annotated(event: &SessionEvent, colors: &ColorConfig, term_width: usize) {
    let time = event.timestamp.with_timezone(&Local).format("%H:%M:%S");
    let time_str = colors.dim(&format!("[{time}]"));

    match &event.kind {
        EventKind::Started => {
            println!("{time_str} Session started");
        }
        EventKind::Shutdown => {
            println!("{time_str} Session shutting down");
        }
        EventKind::ServerState { language, state } => {
            let lang = colors.cyan(language);
            println!("{time_str} {lang}: {state}");
        }
        EventKind::Progress {
            language,
            title,
            message,
            percentage,
        } => {
            let lang = colors.cyan(language);
            let pct = percentage.map(|p| format!(" {p}%")).unwrap_or_default();
            let msg = message
                .as_ref()
                .map(|m| format!(" ({m})"))
                .unwrap_or_default();
            println!("{time_str} {lang}: {title}{pct}{msg}");
        }
        EventKind::ProgressEnd { language } => {
            let lang = colors.cyan(language);
            println!("{time_str} {lang}: Ready");
        }
        EventKind::ToolCall { tool, file } => {
            let arrow = colors.green("");
            let file_str = file
                .as_ref()
                .map(|f| format!(" on {f}"))
                .unwrap_or_default();
            println!("{time_str} {arrow} {tool}{file_str}");
        }
        EventKind::ToolResult {
            tool,
            success,
            duration_ms,
        } => {
            let arrow = colors.blue("");
            let status = if *success {
                "ok".to_string()
            } else {
                colors.red("error")
            };
            println!("{time_str} {arrow} {tool} -> {status} ({duration_ms}ms)");
        }
        EventKind::Diagnostics {
            file,
            count,
            preview,
        } => {
            let basename = std::path::Path::new(file)
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or(file);
            if *count == 0 {
                let check = colors.green("ok");
                println!("{time_str} {basename}: {check}");
            } else {
                let label = colors.yellow(&format!(
                    "{count} diagnostic{}",
                    if *count == 1 { "" } else { "s" }
                ));
                let detail = if preview.is_empty() {
                    String::new()
                } else {
                    let max_len = term_width.saturating_sub(14 + basename.len() + 20);
                    format!(" -- {}", cli::truncate(preview, max_len))
                };
                println!("{time_str} {basename}: {label}{detail}");
            }
        }
        EventKind::LockAcquired { file, owner } => {
            let basename = std::path::Path::new(file.as_str())
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or(file);
            let lock_icon = colors.green("locked");
            let short_owner = cli::truncate(owner, 20);
            println!("{time_str} {basename}: {lock_icon} by {short_owner}");
        }
        EventKind::LockReleased { file, owner } => {
            let basename = std::path::Path::new(file.as_str())
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or(file);
            let unlock_icon = colors.dim("unlocked");
            let short_owner = cli::truncate(owner, 20);
            println!("{time_str} {basename}: {unlock_icon} by {short_owner}");
        }
        EventKind::LockDenied {
            file,
            owner,
            held_by,
        } => {
            let basename = std::path::Path::new(file.as_str())
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or(file);
            let denied = colors.red("lock denied");
            let short_owner = cli::truncate(owner, 20);
            let short_held = cli::truncate(held_by, 20);
            println!("{time_str} {basename}: {denied} for {short_owner} (held by {short_held})");
        }
        EventKind::McpMessage { direction, message } => {
            let arrow_colored = if direction == "in" {
                colors.green("")
            } else {
                colors.blue("")
            };

            // Extract meaningful info from MCP message
            let summary = extract_mcp_summary(message, colors);

            // Calculate available width for message
            // Format: [HH:MM:SS] → summary
            let prefix_len = 10 + 2 + 2; // [time] + arrow + spaces
            let max_summary_len = term_width.saturating_sub(prefix_len);

            let summary = cli::truncate(&summary, max_summary_len);
            println!("{time_str} {arrow_colored} {summary}");

            // Check for errors in response
            if direction == "out"
                && let Some(obj) = message.as_object()
                && obj.contains_key("error")
                && let Some(error) = obj.get("error")
            {
                let err_msg = error
                    .get("message")
                    .and_then(|m| m.as_str())
                    .unwrap_or("Unknown error");
                println!("    {}", colors.red(&format!("Error: {err_msg}")));
            }
        }
    }
}

/// Extract a human-readable summary from an MCP message
fn extract_mcp_summary(message: &serde_json::Value, colors: &ColorConfig) -> String {
    let Some(obj) = message.as_object() else {
        return message.to_string();
    };

    // Check if this is a request (has method)
    obj.get("method").and_then(|m| m.as_str()).map_or_else(
        || {
            // Check if this is a response (has result or error)
            if obj.contains_key("result") || obj.contains_key("error") {
                let id = obj.get("id").map(|i| format!("#{i}")).unwrap_or_default();

                if obj.contains_key("error") {
                    format!("{} {}", colors.red("error"), id)
                } else {
                    format!("result {id}")
                }
            } else {
                // Fallback: show compact JSON
                serde_json::to_string(message).unwrap_or_default()
            }
        },
        |method| {
            let id = obj.get("id").map(|i| format!("#{i}")).unwrap_or_default();

            // Extract params summary based on method
            let params_summary = match method {
                "tools/call" => {
                    if let Some(params) = obj.get("params")
                        && let Some(name) = params.get("name").and_then(|n| n.as_str())
                    {
                        // Try to get file argument if present
                        let file_info = params
                            .get("arguments")
                            .and_then(|a| a.get("file_path").or_else(|| a.get("path")))
                            .and_then(|f| f.as_str())
                            .map(|f| {
                                // Just show filename, not full path
                                std::path::Path::new(f)
                                    .file_name()
                                    .and_then(|n| n.to_str())
                                    .unwrap_or(f)
                            })
                            .map(|f| format!(" ({f})"))
                            .unwrap_or_default();
                        format!("{}{}", colors.cyan(name), file_info)
                    } else {
                        String::new()
                    }
                }
                "initialize" => {
                    if let Some(params) = obj.get("params")
                        && let Some(info) = params.get("clientInfo")
                        && let Some(name) = info.get("name").and_then(|n| n.as_str())
                    {
                        format!("from {name}")
                    } else {
                        String::new()
                    }
                }
                _ => String::new(),
            };

            if params_summary.is_empty() {
                format!("{method} {id}")
            } else {
                format!("{method} {params_summary} {id}")
            }
        },
    )
}

/// Print an event in human-readable format (used by `run_status`)
fn print_event(event: &SessionEvent) {
    let colors = ColorConfig::new(false);
    let term_width = cli::terminal_width();
    print_event_annotated(event, &colors, term_width);
}

/// Background task that periodically closes idle documents.
async fn document_cleanup_task(
    client_manager: Arc<lsp::ClientManager>,
    doc_manager: Arc<Mutex<DocumentManager>>,
    idle_timeout_secs: u64,
) {
    // Check every 60 seconds or half the timeout, whichever is smaller
    let check_interval = Duration::from_secs(idle_timeout_secs.min(60));

    loop {
        tokio::time::sleep(check_interval).await;

        // Find and close stale documents
        let stale_paths = {
            let doc_manager = doc_manager.lock().await;
            doc_manager.stale_documents(idle_timeout_secs)
        };

        if !stale_paths.is_empty() {
            debug!("Closing {} stale documents", stale_paths.len());

            for path in stale_paths {
                let (lang, close_params) = {
                    let mut doc_manager = doc_manager.lock().await;
                    let lang = doc_manager.language_id_for_path(&path).to_string();
                    (lang, doc_manager.close(&path))
                };

                if let Ok(Some(params)) = close_params {
                    // Only try to close if the client is active
                    let active_clients = client_manager.active_clients().await;
                    if let Some(client_mutex) = active_clients.get(&lang) {
                        let client = client_mutex.lock().await;
                        if let Err(e) = client.did_close(params).await {
                            warn!("Failed to close document {}: {}", path.display(), e);
                        } else {
                            debug!("Closed stale document: {}", path.display());
                        }
                    }
                }
            }
        }

        // Check for idle servers (no open documents) and shut them down
        let active_langs: Vec<String> = client_manager
            .active_clients()
            .await
            .keys()
            .cloned()
            .collect();
        for lang in active_langs {
            let has_docs = {
                let doc_manager = doc_manager.lock().await;
                doc_manager.has_open_documents(&lang)
            };

            if !has_docs {
                // No open documents for this language? Shut it down.
                // Note: This might be aggressive if the user just closed the last file
                // and intends to open another one soon.
                // But since we check on `idle_timeout` interval (e.g. 60s), it's probably fine.
                // Ideally we'd track "server idle time" separately, but this is a good start.
                client_manager.shutdown_client(&lang).await;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use anyhow::Context;

    #[test]
    fn test_format_diagnostics_plain() {
        let lines = vec![
            "error[E0308]: mismatched types".into(),
            "  --> src/main.rs:5:10".into(),
        ];
        let output = format_diagnostics(&lines, "plain");
        assert_eq!(
            output,
            "error[E0308]: mismatched types\n  --> src/main.rs:5:10\n"
        );
    }

    #[test]
    fn test_format_diagnostics_gemini() -> Result<()> {
        let lines = vec!["error[E0308]: mismatched types".into()];
        let output = format_diagnostics(&lines, "gemini");
        let parsed: serde_json::Value =
            serde_json::from_str(&output).context("gemini format should produce valid JSON")?;

        let context = parsed["hookSpecificOutput"]["additionalContext"]
            .as_str()
            .context("additionalContext should be a string")?;
        assert!(context.starts_with("LSP Diagnostics:\n"));
        assert!(context.contains("error[E0308]: mismatched types"));
        Ok(())
    }

    #[test]
    fn test_format_diagnostics_gemini_multiline() -> Result<()> {
        let lines = vec!["warning: unused variable".into(), "  --> lib.rs:3:9".into()];
        let output = format_diagnostics(&lines, "gemini");
        let parsed: serde_json::Value =
            serde_json::from_str(&output).context("should produce valid JSON")?;
        let context = parsed["hookSpecificOutput"]["additionalContext"]
            .as_str()
            .context("additionalContext should be a string")?;
        assert!(context.contains("warning: unused variable\n  --> lib.rs:3:9"));
        Ok(())
    }
}