coraline 0.8.0

Coraline: semantic code knowledge graph for faster AI-assisted development.
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
#![allow(clippy::multiple_crate_versions)]
use std::path::{Path, PathBuf};

use coraline::config;
use coraline::context;
use coraline::db;
use coraline::extraction;
use coraline::logging;
use coraline::mcp::McpServer;
use coraline::memory;
use coraline::sync::GitHooksManager;
use coraline::types::NodeKind;
use coraline::types::{BuildContextOptions, ContextFormat, EdgeKind};
use coraline::update;
#[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
use coraline::vectors;
use tracing::{debug, info};

use clap::{Args, Parser, Subcommand};

#[derive(Debug, Parser)]
#[command(name = "coraline")]
#[command(version = env!("CARGO_PKG_VERSION"))]
#[command(about = "Code intelligence and knowledge graph for any codebase")]
struct Cli {
    #[command(subcommand)]
    command: Option<Command>,
}

#[derive(Debug, Subcommand)]
enum Command {
    Install,
    Init(InitArgs),
    Index(IndexArgs),
    Sync(SyncArgs),
    Status(StatusArgs),
    Stats(StatsArgs),
    Query(QueryArgs),
    Context(ContextArgs),
    Callers(CallersArgs),
    Callees(CalleesArgs),
    Impact(ImpactArgs),
    Config(ConfigArgs),
    Hooks(HooksArgs),
    Serve(ServeArgs),
    /// Check for available updates on crates.io.
    Update,
    #[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
    Embed(EmbedArgs),
    #[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
    Model(ModelArgs),
}

#[derive(Debug, Args)]
struct InitArgs {
    path: Option<PathBuf>,
    #[arg(short = 'i', long = "index")]
    index: bool,
    #[arg(long = "no-hooks")]
    no_hooks: bool,
    #[arg(
        short = 'f',
        long = "force",
        help = "Overwrite existing .coraline directory without prompting"
    )]
    force: bool,
}

#[derive(Debug, Args)]
struct IndexArgs {
    path: Option<PathBuf>,
    #[arg(short = 'f', long = "force")]
    force: bool,
    #[arg(short = 'q', long = "quiet")]
    quiet: bool,
}

#[derive(Debug, Args)]
struct SyncArgs {
    path: Option<PathBuf>,
    #[arg(short = 'q', long = "quiet")]
    quiet: bool,
}

#[derive(Debug, Args)]
struct StatusArgs {
    path: Option<PathBuf>,
}

#[derive(Debug, Args)]
struct QueryArgs {
    search: String,
    #[arg(short = 'p', long = "path")]
    path: Option<PathBuf>,
    #[arg(short = 'l', long = "limit", default_value_t = 10)]
    limit: usize,
    #[arg(short = 'k', long = "kind")]
    kind: Option<String>,
    #[arg(short = 'j', long = "json")]
    json: bool,
}

#[derive(Debug, Args)]
struct ContextArgs {
    task: String,
    #[arg(short = 'p', long = "path")]
    path: Option<PathBuf>,
    #[arg(short = 'n', long = "max-nodes", default_value_t = 50)]
    max_nodes: usize,
    #[arg(short = 'c', long = "max-code", default_value_t = 10)]
    max_code: usize,
    #[arg(long = "no-code")]
    no_code: bool,
    #[arg(short = 'f', long = "format", default_value = "markdown")]
    format: String,
}

#[derive(Debug, Args)]
struct StatsArgs {
    path: Option<PathBuf>,
    #[arg(short = 'j', long = "json")]
    json: bool,
}

#[derive(Debug, Args)]
struct CallersArgs {
    node_id: String,
    #[arg(short = 'p', long = "path")]
    path: Option<PathBuf>,
    #[arg(short = 'l', long = "limit", default_value_t = 20)]
    limit: usize,
    #[arg(short = 'j', long = "json")]
    json: bool,
}

#[derive(Debug, Args)]
struct CalleesArgs {
    node_id: String,
    #[arg(short = 'p', long = "path")]
    path: Option<PathBuf>,
    #[arg(short = 'l', long = "limit", default_value_t = 20)]
    limit: usize,
    #[arg(short = 'j', long = "json")]
    json: bool,
}

#[derive(Debug, Args)]
struct ImpactArgs {
    node_id: String,
    #[arg(short = 'p', long = "path")]
    path: Option<PathBuf>,
    #[arg(short = 'd', long = "depth", default_value_t = 3)]
    depth: usize,
    #[arg(short = 'j', long = "json")]
    json: bool,
}

#[derive(Debug, Args)]
struct ConfigArgs {
    #[arg(short = 'p', long = "path")]
    path: Option<PathBuf>,
    /// Print config as JSON
    #[arg(short = 'j', long = "json")]
    json: bool,
    /// Section to display (indexing, context, sync, vectors)
    #[arg(short = 's', long = "section")]
    section: Option<String>,
    /// Set a value: --set section.key=value
    #[arg(long = "set")]
    set: Option<String>,
}

#[derive(Debug, Args)]
struct HooksArgs {
    #[command(subcommand)]
    action: HooksAction,
    #[arg(short = 'p', long = "path")]
    path: Option<PathBuf>,
}

#[derive(Debug, Subcommand)]
enum HooksAction {
    Install,
    Remove,
    Status,
}

#[derive(Debug, Args)]
struct ServeArgs {
    #[arg(short = 'p', long = "path")]
    path: Option<PathBuf>,
    #[arg(long = "mcp")]
    mcp: bool,
}

#[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
#[derive(Debug, Args)]
struct EmbedArgs {
    /// Project root (defaults to current directory).
    path: Option<PathBuf>,
    /// Number of nodes to embed per batch (for progress display).
    #[arg(long = "batch-size", default_value_t = 50)]
    batch_size: usize,
    /// Suppress progress output.
    #[arg(short = 'q', long = "quiet")]
    quiet: bool,
    /// Download the model from `HuggingFace` if not already present.
    #[arg(long = "download")]
    download: bool,
    /// ONNX variant to download when using `--download` (default: `model_int8.onnx`).
    #[arg(long = "variant", default_value = "model_int8.onnx")]
    variant: String,
    /// Skip the automatic sync check before embedding.
    #[arg(long = "skip-sync")]
    skip_sync: bool,
}

#[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
#[derive(Debug, Args)]
struct ModelArgs {
    #[arg(short = 'p', long = "path")]
    path: Option<PathBuf>,
    /// Suppress progress output.
    #[arg(short = 'q', long = "quiet")]
    quiet: bool,
    #[command(subcommand)]
    action: ModelAction,
}

#[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
#[derive(Debug, Subcommand)]
enum ModelAction {
    /// Download model files from `HuggingFace` (tokenizer + ONNX weights).
    Download {
        /// ONNX variant filename to download.
        #[arg(long = "variant", default_value = "model_int8.onnx")]
        variant: String,
        /// Re-download even if the file already exists.
        #[arg(short = 'f', long = "force")]
        force: bool,
    },
    /// Show which model files are present in the model directory.
    Status,
}

fn main() {
    let cli = Cli::parse();
    if matches!(cli.command, None | Some(Command::Install)) {
        run_installer();
        return;
    }

    let Some(command) = cli.command else {
        return;
    };

    // Resolve project root early so logging can target the right directory
    let project_root_hint = match &command {
        Command::Init(a) => a.path.clone(),
        Command::Index(a) => a.path.clone(),
        Command::Sync(a) => a.path.clone(),
        Command::Status(a) => a.path.clone(),
        Command::Stats(a) => a.path.clone(),
        Command::Query(a) => a.path.clone(),
        Command::Context(a) => a.path.clone(),
        Command::Callers(a) => a.path.clone(),
        Command::Callees(a) => a.path.clone(),
        Command::Impact(a) => a.path.clone(),
        Command::Config(a) => a.path.clone(),
        Command::Hooks(a) => a.path.clone(),
        Command::Serve(a) => a.path.clone(),
        #[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
        Command::Embed(a) => a.path.clone(),
        #[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
        Command::Model(a) => a.path.clone(),
        Command::Install | Command::Update => None,
    };
    let project_root = resolve_project_root(project_root_hint);
    // Don't create .coraline/logs/ before the init command runs — that would
    // cause is_initialized() to return true and block a fresh init.
    let log_root =
        if matches!(command, Command::Init(_)) && !project_root.join(".coraline").is_dir() {
            None
        } else {
            Some(project_root.as_path())
        };
    let _log_guard = logging::init(log_root);
    info!("coraline starting");
    debug!(command = ?command, "dispatching command");

    match command {
        Command::Install => run_installer(),
        Command::Init(args) => run_init(args),
        Command::Index(args) => run_index(args),
        Command::Sync(args) => run_sync(args),
        Command::Status(args) => run_status(args),
        Command::Stats(args) => run_stats(args),
        Command::Query(args) => run_query(args),
        Command::Context(args) => run_context(args),
        Command::Callers(args) => run_callers(args),
        Command::Callees(args) => run_callees(args),
        Command::Impact(args) => run_impact(args),
        Command::Config(args) => run_config(args),
        Command::Hooks(args) => match args.action {
            HooksAction::Install => run_hooks_install(args.path),
            HooksAction::Remove => run_hooks_remove(args.path),
            HooksAction::Status => run_hooks_status(args.path),
        },
        Command::Serve(args) => {
            if args.mcp {
                let mut server = McpServer::new(args.path);
                if let Err(err) = server.start() {
                    eprintln!("Failed to start MCP server: {err}");
                    std::process::exit(1);
                }
            } else {
                println!("Use --mcp to start the MCP server.");
            }
        }
        Command::Update => run_update(),
        #[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
        Command::Embed(args) => run_embed(&args),
        #[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
        Command::Model(args) => run_model(args),
    }
}

#[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
fn run_model(args: ModelArgs) {
    let project_root = resolve_project_root(args.path);
    let cfg = config::load_toml_config(&project_root).unwrap_or_default();
    let model_dir = cfg
        .vectors
        .model_dir
        .map_or_else(|| vectors::default_model_dir(&project_root), PathBuf::from);

    match args.action {
        ModelAction::Download { variant, force } => {
            #[cfg(feature = "embeddings")]
            {
                if !args.quiet {
                    println!("Downloading {variant} into {} ...", model_dir.display());
                }
                if let Err(e) = vectors::download_model(&model_dir, &variant, !force, args.quiet) {
                    eprintln!("Download failed: {e}");
                    std::process::exit(1);
                }
                if !args.quiet {
                    println!("Done. Run `coraline embed` to generate embeddings.");
                }
            }
            #[cfg(not(feature = "embeddings"))]
            {
                let _ = (variant, force); // suppress unused warnings
                eprintln!("Model download is not available in this build.");
                eprintln!(
                    "This binary was built with `embeddings-dynamic`, which loads ONNX Runtime at runtime."
                );
                eprintln!();
                eprintln!("To use embeddings, manually download the model files:");
                eprintln!(
                    "  1. Download tokenizer.json from: {}",
                    vectors::tokenizer_url()
                );
                eprintln!(
                    "  2. Download model_int8.onnx from: {}",
                    vectors::model_url("model_int8.onnx")
                );
                eprintln!("  3. Place both files in: {}", model_dir.display());
                std::process::exit(1);
            }
        }
        ModelAction::Status => {
            println!("Model directory: {}", model_dir.display());
            println!();
            for name in vectors::MODEL_PREFERENCE_ORDER {
                let p = model_dir.join(name);
                if let Ok(meta) = std::fs::metadata(&p) {
                    println!("  {name:<30}  {:>6} MB  [present]", meta.len() / 1_000_000);
                } else {
                    println!("  {name:<30}  (not present)");
                }
            }
            println!();
            for name in &["tokenizer.json", "tokenizer_config.json"] {
                let p = model_dir.join(name);
                if p.exists() {
                    println!("  {name:<30}  [present]");
                } else {
                    println!("  {name:<30}  (not present)");
                }
            }
        }
    }
}

#[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
fn run_embed(args: &EmbedArgs) {
    let project_root = resolve_project_root(args.path.clone());

    if !is_initialized(&project_root) {
        eprintln!("Coraline not initialized in {}", project_root.display());
        std::process::exit(1);
    }

    // Auto-sync: ensure the index is up to date before embedding.
    if args.skip_sync {
        if !args.quiet {
            eprintln!("Skipping sync (--skip-sync). Embeddings may be stale.");
        }
    } else {
        auto_sync_before_embed(&project_root, args.quiet);
    }

    // Auto-download model files if requested.
    #[cfg(feature = "embeddings")]
    if args.download {
        let cfg = config::load_toml_config(&project_root).unwrap_or_default();
        let model_dir = cfg
            .vectors
            .model_dir
            .map_or_else(|| vectors::default_model_dir(&project_root), PathBuf::from);
        if !args.quiet {
            println!(
                "Downloading {} into {} ...",
                args.variant,
                model_dir.display()
            );
        }
        if let Err(e) = vectors::download_model(&model_dir, &args.variant, true, args.quiet) {
            eprintln!("Download failed: {e}");
            std::process::exit(1);
        }
    }
    #[cfg(not(feature = "embeddings"))]
    if args.download {
        eprintln!("Model download is not available in this build (embeddings-dynamic).");
        eprintln!("Please download the model files manually. See: coraline model download --help");
        std::process::exit(1);
    }

    if !args.quiet {
        println!("Loading embedding model…");
    }

    let mut vm = vectors::VectorManager::from_project(&project_root).unwrap_or_else(|err| {
        eprintln!("Failed to load model: {err}");
        eprintln!(
            "Download model.onnx + tokenizer.json into {}",
            vectors::default_model_dir(&project_root).display()
        );
        std::process::exit(1);
    });

    embed_all_nodes(&project_root, args, &mut vm);
}

#[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
fn embed_all_nodes(project_root: &Path, args: &EmbedArgs, vm: &mut vectors::VectorManager) {
    let conn = db::open_database(project_root).unwrap_or_else(|err| {
        eprintln!("Failed to open database: {err}");
        std::process::exit(1);
    });

    let nodes = db::get_all_nodes(&conn).unwrap_or_else(|err| {
        eprintln!("Failed to read nodes: {err}");
        std::process::exit(1);
    });

    let total = nodes.len();
    if total == 0 {
        println!("No nodes found. Run `coraline index` first.");
        return;
    }

    if !args.quiet {
        println!("Embedding {total} nodes…");
    }

    let mut ok = 0usize;
    let mut skipped = 0usize;

    for (i, node) in nodes.iter().enumerate() {
        let text = vectors::node_embed_text(
            &node.name,
            &node.qualified_name,
            node.docstring.as_deref(),
            node.signature.as_deref(),
        );

        match vm.embed(&text) {
            Ok(embedding) => {
                if let Err(err) =
                    vectors::store_embedding(&conn, &node.id, &embedding, vm.model_name())
                {
                    if !args.quiet {
                        eprintln!(
                            "  Warning: failed to store embedding for {}: {err}",
                            node.id
                        );
                    }
                    skipped += 1;
                } else {
                    ok += 1;
                }
            }
            Err(err) => {
                if !args.quiet {
                    eprintln!("  Warning: failed to embed {}: {err}", node.name);
                }
                skipped += 1;
            }
        }

        if !args.quiet && (i + 1) % args.batch_size == 0 {
            print!("\r  {}/{total}", i + 1);
        }
    }

    if !args.quiet {
        println!("\rEmbedded {ok}/{total} nodes ({skipped} skipped)");
    }
}

/// Check whether the index is stale and run sync automatically before embedding.
#[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
fn auto_sync_before_embed(project_root: &Path, quiet: bool) {
    let mut cfg = match config::load_config(project_root) {
        Ok(cfg) => cfg,
        Err(err) => {
            eprintln!("Failed to load config: {err}");
            std::process::exit(1);
        }
    };
    if let Ok(toml_cfg) = config::load_toml_config(project_root) {
        config::apply_toml_to_code_graph(&mut cfg, &toml_cfg);
    }

    if !quiet {
        print!("Checking index freshness…");
    }

    let status = extraction::needs_sync(project_root, &cfg).unwrap_or_else(|err| {
        eprintln!("\nFailed to check sync status: {err}");
        std::process::exit(1);
    });

    if !status.is_stale() {
        if !quiet {
            println!(" up to date.");
        }
        return;
    }

    if !quiet {
        let total_changes = status.files_added + status.files_modified + status.files_removed;
        println!(" {total_changes} change(s) detected, syncing…");
    }

    let result = extraction::sync(
        project_root,
        &cfg,
        if quiet { None } else { Some(&print_progress) },
    )
    .unwrap_or_else(|err| {
        eprintln!("Auto-sync failed: {err}");
        std::process::exit(1);
    });

    if !quiet {
        clear_progress_line();
        let total_changes = result.files_added + result.files_modified + result.files_removed;
        println!("Synced {total_changes} files before embedding.");
        if result.files_added > 0 {
            println!("  Added: {}", result.files_added);
        }
        if result.files_modified > 0 {
            println!("  Modified: {}", result.files_modified);
        }
        if result.files_removed > 0 {
            println!("  Removed: {}", result.files_removed);
        }
    }
}

fn cargo_bin_dir() -> PathBuf {
    // Prefer CARGO_HOME if set, then fall back to the platform home directory.
    if let Ok(cargo_home) = std::env::var("CARGO_HOME") {
        return PathBuf::from(cargo_home).join("bin");
    }
    let home_var = if cfg!(windows) { "USERPROFILE" } else { "HOME" };
    if let Some(home) = std::env::var_os(home_var) {
        return PathBuf::from(home).join(".cargo").join("bin");
    }
    PathBuf::from(".cargo/bin")
}

fn run_installer() {
    let version = env!("CARGO_PKG_VERSION");
    println!("Coraline v{version} — installation check\n");

    // 1. Where is this binary right now?
    let current_exe = match std::env::current_exe() {
        Ok(p) => p,
        Err(e) => {
            eprintln!("Could not determine current executable path: {e}");
            std::process::exit(1);
        }
    };
    let current_exe = current_exe.canonicalize().unwrap_or(current_exe);
    println!("Current binary : {}", current_exe.display());

    // 2. Determine the standard cargo bin directory.
    let cargo_bin = cargo_bin_dir();
    let bin_name = if cfg!(windows) {
        "coraline.exe"
    } else {
        "coraline"
    };
    let target = cargo_bin.join(bin_name);
    println!("Install target : {}\n", target.display());

    // 3. Copy to cargo bin if not already there.
    let already_installed = current_exe == target.canonicalize().unwrap_or_else(|_| target.clone());
    if already_installed {
        println!("✔  Already installed at: {}", target.display());
    } else {
        if let Err(e) = std::fs::create_dir_all(&cargo_bin) {
            eprintln!("Error creating {}: {e}", cargo_bin.display());
            std::process::exit(1);
        }
        match std::fs::copy(&current_exe, &target) {
            Ok(_) => println!("✔  Installed to: {}", target.display()),
            Err(e) => {
                eprintln!("Failed to copy binary to {}: {e}", target.display());
                if cfg!(windows) {
                    eprintln!("Try running the installer as Administrator, or install via:");
                } else {
                    eprintln!("Try running with sudo, or install via:");
                }
                eprintln!("  cargo install coraline");
                std::process::exit(1);
            }
        }
    }

    // 4. Set executable bit on Unix.
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if let Ok(meta) = std::fs::metadata(&target) {
            let mut perms = meta.permissions();
            perms.set_mode(perms.mode() | 0o111);
            let _ = std::fs::set_permissions(&target, perms);
        }
    }

    // 5. PATH check.
    println!();
    if which("coraline") {
        println!("✔  'coraline' is on PATH — run `coraline --version` to verify.");
    } else {
        println!("âš   The install directory is not on PATH.");
        if cfg!(windows) {
            println!(
                "   Add it via: System Properties → Environment Variables → PATH → add:\n   {}",
                cargo_bin.display()
            );
        } else {
            println!("   Add this to your shell profile (~/.bashrc, ~/.zshrc, etc.):");
            println!("     export PATH=\"$HOME/.cargo/bin:$PATH\"");
        }
        println!("   Then open a new terminal and run: coraline --version");
    }
}

fn run_update() {
    let version = env!("CARGO_PKG_VERSION");
    println!("Coraline v{version} — checking for updates...\n");

    match update::check_for_update() {
        Ok(status) => update::print_update_status(&status),
        Err(e) => {
            eprintln!("Failed to check for updates: {e}");
            eprintln!();
            eprintln!("You can manually check: https://crates.io/crates/coraline");
            std::process::exit(1);
        }
    }
}

fn run_init(args: InitArgs) {
    let project_root = resolve_project_root(args.path);

    if is_initialized(&project_root) {
        // If the user just wants to (re)index an already-initialized project,
        // skip the destructive overwrite entirely.
        if args.index && !args.force {
            println!(
                "Coraline already initialized in {}.",
                project_root.display()
            );
            #[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
            maybe_prompt_model_download(&project_root);
            run_index(IndexArgs {
                path: Some(project_root),
                force: false,
                quiet: false,
            });
            return;
        }

        if !args.force {
            // Only prompt when stdin is a terminal; otherwise abort safely.
            if std::io::IsTerminal::is_terminal(&std::io::stdin()) {
                eprint!(
                    "Coraline is already initialized in {}. Overwrite? [y/N] ",
                    project_root.display()
                );
                let mut input = String::new();
                if std::io::stdin().read_line(&mut input).is_err()
                    || !input.trim().eq_ignore_ascii_case("y")
                {
                    println!("Aborted.");
                    return;
                }
            } else {
                eprintln!(
                    "Coraline already initialized in {}. Use --force to overwrite.",
                    project_root.display()
                );
                return;
            }
        }
        // Remove the existing .coraline directory before re-initializing.
        if let Err(err) = std::fs::remove_dir_all(project_root.join(".coraline")) {
            eprintln!("Failed to remove existing .coraline directory: {err}");
            std::process::exit(1);
        }
    }

    if let Err(err) = create_coraline_dir(&project_root) {
        eprintln!("Failed to create .coraline directory: {err}");
        std::process::exit(1);
    }

    let cfg = config::create_default_config(&project_root);
    if let Err(err) = config::save_config(&project_root, &cfg) {
        eprintln!("Failed to write config: {err}");
        std::process::exit(1);
    }

    if let Err(err) = config::write_toml_template(&project_root) {
        eprintln!("Warning: Failed to write config.toml template: {err}");
    }

    if let Err(err) = db::initialize_database(&project_root) {
        eprintln!("Failed to initialize database: {err}");
        std::process::exit(1);
    }

    // Create initial memory templates
    let project_name = project_root
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("project");
    if let Err(err) = memory::create_initial_memories(&project_root, project_name) {
        eprintln!("Warning: Failed to create initial memories: {err}");
    }

    println!("Initialized Coraline in {}", project_root.display());

    if !args.no_hooks {
        let hooks = GitHooksManager::new(&project_root);
        if hooks.is_git_repository() {
            let result = hooks.install_hook();
            if result.success {
                println!("Git hooks installed.");
            } else {
                eprintln!("Git hooks not installed: {}", result.message);
            }
        }
    }

    #[cfg(any(feature = "embeddings", feature = "embeddings-dynamic"))]
    maybe_prompt_model_download(&project_root);

    if args.index {
        run_index(IndexArgs {
            path: Some(project_root),
            force: false,
            quiet: false,
        });
    }
}

/// After a fresh `init`, offer to download the embedding model when stdin is a
/// terminal.  If the user declines (or is non-interactive), we print a hint and
/// continue — all non-embedding tools remain fully functional.
#[cfg(feature = "embeddings")]
fn maybe_prompt_model_download(project_root: &Path) {
    use std::io::Write as _;

    let cfg = config::load_toml_config(project_root).unwrap_or_default();
    let model_dir = cfg
        .vectors
        .model_dir
        .map_or_else(|| vectors::default_model_dir(project_root), PathBuf::from);

    // Nothing to do if any model variant is already present.
    if vectors::MODEL_PREFERENCE_ORDER
        .iter()
        .any(|name| model_dir.join(name).exists())
    {
        return;
    }

    if !std::io::IsTerminal::is_terminal(&std::io::stdin()) {
        eprintln!(
            "Tip: run `coraline model download` then `coraline embed` to enable semantic search."
        );
        return;
    }

    eprint!("Download embedding model for semantic search? (~137 MB) [Y/n] ");
    let _ = std::io::stderr().flush();
    let mut input = String::new();
    if std::io::stdin().read_line(&mut input).is_err() {
        return;
    }
    let answer = input.trim();
    if answer.is_empty() || answer.eq_ignore_ascii_case("y") {
        println!("Downloading model into {} ...", model_dir.display());
        match vectors::download_model(&model_dir, "model_int8.onnx", true, false) {
            Ok(()) => println!("Done. Run `coraline embed` to generate embeddings."),
            Err(e) => {
                eprintln!("Model download failed: {e}");
                eprintln!("You can retry later with: coraline model download");
            }
        }
    } else {
        println!("Skipped. Run `coraline model download` later to enable semantic search.");
    }
}

/// For embeddings-dynamic builds, we can't auto-download but we can point users
/// to manual download instructions.
#[cfg(all(feature = "embeddings-dynamic", not(feature = "embeddings")))]
fn maybe_prompt_model_download(project_root: &Path) {
    let cfg = config::load_toml_config(project_root).unwrap_or_default();
    let model_dir = cfg
        .vectors
        .model_dir
        .map_or_else(|| vectors::default_model_dir(project_root), PathBuf::from);

    // Nothing to do if any model variant is already present.
    if vectors::MODEL_PREFERENCE_ORDER
        .iter()
        .any(|name| model_dir.join(name).exists())
    {
        return;
    }

    eprintln!("Tip: To enable semantic search, download the model files manually:");
    eprintln!(
        "  1. Download tokenizer.json from: {}",
        vectors::tokenizer_url()
    );
    eprintln!(
        "  2. Download model_int8.onnx from: {}",
        vectors::model_url("model_int8.onnx")
    );
    eprintln!("  3. Place both files in: {}", model_dir.display());
    eprintln!("  4. Run `coraline embed` to generate embeddings.");
}

fn run_index(args: IndexArgs) {
    let project_root = resolve_project_root(args.path);

    if !is_initialized(&project_root) {
        eprintln!("Coraline not initialized in {}", project_root.display());
        std::process::exit(1);
    }

    let mut cfg = match config::load_config(&project_root) {
        Ok(cfg) => cfg,
        Err(err) => {
            eprintln!("Failed to load config: {err}");
            std::process::exit(1);
        }
    };
    if let Ok(toml_cfg) = config::load_toml_config(&project_root) {
        config::apply_toml_to_code_graph(&mut cfg, &toml_cfg);
    }

    if !args.quiet {
        println!("Indexing project...\n");
    }

    let result = extraction::index_all(
        &project_root,
        &cfg,
        args.force,
        if args.quiet {
            None
        } else {
            Some(&print_progress)
        },
    )
    .unwrap_or_else(|err| {
        eprintln!("Indexing failed: {err}");
        std::process::exit(1);
    });

    if !args.quiet {
        clear_progress_line();
        println!("Indexed {} files", result.files_indexed);
        println!("Created {} nodes", result.nodes_created);
        println!("Completed in {}ms", result.duration_ms);
    }
}

fn run_sync(args: SyncArgs) {
    let project_root = resolve_project_root(args.path);

    if !is_initialized(&project_root) {
        eprintln!("Coraline not initialized in {}", project_root.display());
        std::process::exit(1);
    }

    let mut cfg = match config::load_config(&project_root) {
        Ok(cfg) => cfg,
        Err(err) => {
            eprintln!("Failed to load config: {err}");
            std::process::exit(1);
        }
    };
    if let Ok(toml_cfg) = config::load_toml_config(&project_root) {
        config::apply_toml_to_code_graph(&mut cfg, &toml_cfg);
    }

    let result = extraction::sync(
        &project_root,
        &cfg,
        if args.quiet {
            None
        } else {
            Some(&print_progress)
        },
    )
    .unwrap_or_else(|err| {
        eprintln!("Sync failed: {err}");
        std::process::exit(1);
    });

    if !args.quiet {
        clear_progress_line();
        let total_changes = result.files_added + result.files_modified + result.files_removed;
        if total_changes == 0 {
            println!("Already up to date");
        } else {
            println!("Synced {total_changes} files");
            if result.files_added > 0 {
                println!("  Added: {}", result.files_added);
            }
            if result.files_modified > 0 {
                println!("  Modified: {}", result.files_modified);
            }
            if result.files_removed > 0 {
                println!("  Removed: {}", result.files_removed);
            }
            println!("Updated {} nodes", result.nodes_updated);
        }
    }
}

fn run_status(args: StatusArgs) {
    let project_root = resolve_project_root(args.path);

    if !is_initialized(&project_root) {
        println!("Coraline Status\n");
        println!("Project: {}", project_root.display());
        println!("Not initialized. Run `coraline init`.");
        return;
    }

    let cfg_path = config::config_path(&project_root);
    let db_path = db::database_path(&project_root);
    let db_size = std::fs::metadata(&db_path).map(|m| m.len()).unwrap_or(0);

    println!("Coraline Status\n");
    println!("Project: {}", project_root.display());
    println!("Config:  {}", cfg_path.display());
    println!("Database: {} ({} bytes)", db_path.display(), db_size);

    let hooks = GitHooksManager::new(&project_root);
    if hooks.is_git_repository() {
        if hooks.is_hook_installed() {
            println!("Git hooks: installed");
        } else {
            println!("Git hooks: not installed");
        }
    } else {
        println!("Git hooks: not a git repository");
    }
}

fn run_query(args: QueryArgs) {
    let project_root = resolve_project_root(args.path);

    if !is_initialized(&project_root) {
        eprintln!("Coraline not initialized in {}", project_root.display());
        std::process::exit(1);
    }

    let conn = db::open_database(&project_root).unwrap_or_else(|err| {
        eprintln!("Failed to open database: {err}");
        std::process::exit(1);
    });

    let kind = args.kind.as_deref().and_then(parse_node_kind);
    let results = db::search_nodes(&conn, &args.search, kind, args.limit).unwrap_or_else(|err| {
        eprintln!("Search failed: {err}");
        std::process::exit(1);
    });

    if args.json {
        let json = serde_json::to_string_pretty(&results).unwrap_or_default();
        println!("{json}");
        return;
    }

    if results.is_empty() {
        println!("No results found for \"{}\"", args.search);
        return;
    }

    println!("Search Results for \"{}\":\n", args.search);
    for result in results {
        let node = result.node;
        println!(
            "{:?} {} ({:.0}%)",
            node.kind,
            node.name,
            result.score * 100.0
        );
        println!("  {}:{}", node.file_path, node.start_line);
        if let Some(signature) = node.signature {
            println!("  {signature}");
        }
        println!();
    }
}

fn run_context(args: ContextArgs) {
    let project_root = resolve_project_root(args.path);

    if !is_initialized(&project_root) {
        eprintln!("Coraline not initialized in {}", project_root.display());
        std::process::exit(1);
    }

    let format = match args.format.to_ascii_lowercase().as_str() {
        "json" => ContextFormat::Json,
        _ => ContextFormat::Markdown,
    };

    let options = BuildContextOptions {
        max_nodes: Some(args.max_nodes),
        max_code_blocks: Some(args.max_code),
        max_code_block_size: None,
        include_code: Some(!args.no_code),
        format: Some(format),
        search_limit: None,
        traversal_depth: None,
        min_score: None,
    };

    let output =
        context::build_context(&project_root, &args.task, &options).unwrap_or_else(|err| {
            eprintln!("Failed to build context: {err}");
            std::process::exit(1);
        });

    println!("{output}");
}

fn run_hooks_install(path: Option<PathBuf>) {
    let project_root = resolve_project_root(path);
    let hooks = GitHooksManager::new(&project_root);
    let result = hooks.install_hook();
    if result.success {
        println!("{}", result.message);
        if let Some(backup) = result.backup_path {
            println!("Previous hook backed up at {}", backup.display());
        }
    } else {
        eprintln!("{}", result.message);
        std::process::exit(1);
    }
}

fn run_hooks_remove(path: Option<PathBuf>) {
    let project_root = resolve_project_root(path);
    let hooks = GitHooksManager::new(&project_root);
    let result = hooks.remove_hook();
    if result.success {
        println!("{}", result.message);
    } else {
        eprintln!("{}", result.message);
        std::process::exit(1);
    }
}

fn run_hooks_status(path: Option<PathBuf>) {
    let project_root = resolve_project_root(path);
    let hooks = GitHooksManager::new(&project_root);
    if !hooks.is_git_repository() {
        println!("Not a git repository.");
        return;
    }
    if hooks.is_hook_installed() {
        println!("Git hook is installed.");
    } else {
        println!("Git hook is not installed.");
    }
}

fn run_stats(args: StatsArgs) {
    let project_root = resolve_project_root(args.path);

    if !is_initialized(&project_root) {
        eprintln!("Coraline not initialized in {}", project_root.display());
        std::process::exit(1);
    }

    let conn = db::open_database(&project_root).unwrap_or_else(|err| {
        eprintln!("Failed to open database: {err}");
        std::process::exit(1);
    });

    let stats = db::get_db_stats(&conn).unwrap_or_else(|err| {
        eprintln!("Failed to get stats: {err}");
        std::process::exit(1);
    });

    if args.json {
        let json = serde_json::to_string_pretty(&stats).unwrap_or_default();
        println!("{json}");
        return;
    }

    println!("Coraline Statistics\n");
    println!("Files:     {}", stats.file_count);
    println!("\nNodes:     {}", stats.node_count);
    println!("Edges:     {}", stats.edge_count);
    println!("Unresolved refs: {}", stats.unresolved_count);
}

fn run_callers(args: CallersArgs) {
    let project_root = resolve_project_root(args.path);

    if !is_initialized(&project_root) {
        eprintln!("Coraline not initialized in {}", project_root.display());
        std::process::exit(1);
    }

    let conn = db::open_database(&project_root).unwrap_or_else(|err| {
        eprintln!("Failed to open database: {err}");
        std::process::exit(1);
    });

    let node = db::get_node_by_id(&conn, &args.node_id)
        .unwrap_or_else(|err| {
            eprintln!("Database error: {err}");
            std::process::exit(1);
        })
        .unwrap_or_else(|| {
            eprintln!("Node not found: {}", args.node_id);
            std::process::exit(1);
        });

    let edges = db::get_edges_by_target(&conn, &args.node_id, Some(EdgeKind::Calls), args.limit)
        .unwrap_or_else(|err| {
            eprintln!("Failed to get callers: {err}");
            std::process::exit(1);
        });

    if args.json {
        let results: Vec<_> = edges
            .iter()
            .filter_map(|e| db::get_node_by_id(&conn, &e.source).ok().flatten())
            .map(|n| serde_json::json!({ "id": n.id, "name": n.name, "kind": n.kind, "file": n.file_path, "line": n.start_line }))
            .collect();
        println!(
            "{}",
            serde_json::to_string_pretty(&results).unwrap_or_default()
        );
        return;
    }

    println!("Callers of {} ({:?}):\n", node.name, node.kind);
    if edges.is_empty() {
        println!("  No callers found.");
        return;
    }
    for edge in &edges {
        if let Ok(Some(caller)) = db::get_node_by_id(&conn, &edge.source) {
            println!(
                "  {:?} {} ({}:{})",
                caller.kind, caller.name, caller.file_path, caller.start_line
            );
        }
    }
}

fn run_callees(args: CalleesArgs) {
    let project_root = resolve_project_root(args.path);

    if !is_initialized(&project_root) {
        eprintln!("Coraline not initialized in {}", project_root.display());
        std::process::exit(1);
    }

    let conn = db::open_database(&project_root).unwrap_or_else(|err| {
        eprintln!("Failed to open database: {err}");
        std::process::exit(1);
    });

    let node = db::get_node_by_id(&conn, &args.node_id)
        .unwrap_or_else(|err| {
            eprintln!("Database error: {err}");
            std::process::exit(1);
        })
        .unwrap_or_else(|| {
            eprintln!("Node not found: {}", args.node_id);
            std::process::exit(1);
        });

    let edges = db::get_edges_by_source(&conn, &args.node_id, Some(EdgeKind::Calls), args.limit)
        .unwrap_or_else(|err| {
            eprintln!("Failed to get callees: {err}");
            std::process::exit(1);
        });

    if args.json {
        let results: Vec<_> = edges
            .iter()
            .filter_map(|e| db::get_node_by_id(&conn, &e.target).ok().flatten())
            .map(|n| serde_json::json!({ "id": n.id, "name": n.name, "kind": n.kind, "file": n.file_path, "line": n.start_line }))
            .collect();
        println!(
            "{}",
            serde_json::to_string_pretty(&results).unwrap_or_default()
        );
        return;
    }

    println!("Callees of {} ({:?}):\n", node.name, node.kind);
    if edges.is_empty() {
        println!("  No callees found.");
        return;
    }
    for edge in &edges {
        if let Ok(Some(callee)) = db::get_node_by_id(&conn, &edge.target) {
            println!(
                "  {:?} {} ({}:{})",
                callee.kind, callee.name, callee.file_path, callee.start_line
            );
        }
    }
}

fn run_impact(args: ImpactArgs) {
    let project_root = resolve_project_root(args.path);

    if !is_initialized(&project_root) {
        eprintln!("Coraline not initialized in {}", project_root.display());
        std::process::exit(1);
    }

    let conn = db::open_database(&project_root).unwrap_or_else(|err| {
        eprintln!("Failed to open database: {err}");
        std::process::exit(1);
    });

    let node = db::get_node_by_id(&conn, &args.node_id)
        .unwrap_or_else(|err| {
            eprintln!("Database error: {err}");
            std::process::exit(1);
        })
        .unwrap_or_else(|| {
            eprintln!("Node not found: {}", args.node_id);
            std::process::exit(1);
        });

    // BFS outward from target edges (who directly or transitively uses this node)
    let mut visited = std::collections::HashSet::new();
    let mut frontier = vec![args.node_id.clone()];
    visited.insert(args.node_id.clone());

    for _ in 0..args.depth {
        let mut next = Vec::new();
        for id in &frontier {
            if let Ok(edges) = db::get_edges_by_target(&conn, id, None, 100) {
                for edge in edges {
                    if visited.insert(edge.source.clone()) {
                        next.push(edge.source);
                    }
                }
            }
        }
        if next.is_empty() {
            break;
        }
        frontier = next;
    }
    visited.remove(&args.node_id);

    if args.json {
        let results: Vec<_> = visited
            .iter()
            .filter_map(|id| db::get_node_by_id(&conn, id).ok().flatten())
            .map(|n| serde_json::json!({ "id": n.id, "name": n.name, "kind": n.kind, "file": n.file_path }))
            .collect();
        println!(
            "{}",
            serde_json::to_string_pretty(&results).unwrap_or_default()
        );
        return;
    }

    println!(
        "Impact of {} ({:?}) — depth {}:\n",
        node.name, node.kind, args.depth
    );
    if visited.is_empty() {
        println!("  No dependents found.");
        return;
    }
    let mut affected: Vec<_> = visited
        .iter()
        .filter_map(|id| db::get_node_by_id(&conn, id).ok().flatten())
        .collect();
    affected.sort_by(|a, b| {
        a.file_path
            .cmp(&b.file_path)
            .then(a.start_line.cmp(&b.start_line))
    });
    for n in &affected {
        println!(
            "  {:?} {} ({}:{})",
            n.kind, n.name, n.file_path, n.start_line
        );
    }
    println!("\n{} affected symbol(s)", affected.len());
}

fn run_config(args: ConfigArgs) {
    let project_root = resolve_project_root(args.path);

    if !is_initialized(&project_root) {
        eprintln!("Coraline not initialized in {}", project_root.display());
        std::process::exit(1);
    }

    // Handle --set section.key=value
    if let Some(set_expr) = &args.set {
        let parts: Vec<&str> = set_expr.splitn(2, '=').collect();
        let &[path_part, value_str] = parts.as_slice() else {
            eprintln!("Invalid --set format. Expected: section.key=value");
            std::process::exit(1);
        };
        let path_parts: Vec<&str> = path_part.splitn(2, '.').collect();
        let &[section, key] = path_parts.as_slice() else {
            eprintln!(
                "Invalid --set path. Expected: section.key=value (e.g. indexing.batch_size=50)"
            );
            std::process::exit(1);
        };

        let mut cfg = config::load_toml_config(&project_root).unwrap_or_else(|err| {
            eprintln!("Failed to load config: {err}");
            std::process::exit(1);
        });

        // Parse value as JSON for type flexibility
        let json_value: serde_json::Value = serde_json::from_str(value_str)
            .unwrap_or_else(|_| serde_json::Value::String(value_str.to_string()));

        let mut cfg_json = serde_json::to_value(&cfg).unwrap_or_default();
        if let Some(section_obj) = cfg_json.get_mut(section).and_then(|v| v.as_object_mut()) {
            section_obj.insert(key.to_string(), json_value.clone());
        } else {
            eprintln!("Unknown config section: {section}");
            std::process::exit(1);
        }

        cfg = serde_json::from_value(cfg_json).unwrap_or_else(|err| {
            eprintln!("Invalid value for {section}.{key}: {err}");
            std::process::exit(1);
        });

        config::save_toml_config(&project_root, &cfg).unwrap_or_else(|err| {
            eprintln!("Failed to save config: {err}");
            std::process::exit(1);
        });

        println!("Updated {section}.{key} = {json_value}");
        return;
    }

    let cfg = config::load_toml_config(&project_root).unwrap_or_else(|err| {
        eprintln!("Failed to load config: {err}");
        std::process::exit(1);
    });

    if args.json {
        let mut v = serde_json::to_value(&cfg).unwrap_or_default();
        if let Some(section) = &args.section {
            v = v
                .get(section.as_str())
                .cloned()
                .unwrap_or(serde_json::Value::Null);
        }
        println!("{}", serde_json::to_string_pretty(&v).unwrap_or_default());
        return;
    }

    // Pretty-print TOML
    let toml_str = toml::to_string_pretty(&cfg).unwrap_or_else(|_| format!("{cfg:#?}"));
    if let Some(section) = &args.section {
        // Print only the requested section
        let section_header = format!("[{section}]");
        let mut in_section = false;
        for line in toml_str.lines() {
            if line.starts_with('[') {
                in_section = line == section_header;
            }
            if in_section {
                println!("{line}");
            }
        }
    } else {
        println!("{toml_str}");
    }
}

fn resolve_project_root(path: Option<PathBuf>) -> PathBuf {
    path.unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")))
}

fn is_initialized(project_root: &Path) -> bool {
    let dir = project_root.join(".coraline");
    dir.is_dir()
}

fn create_coraline_dir(project_root: &Path) -> std::io::Result<()> {
    let dir = project_root.join(".coraline");
    std::fs::create_dir_all(&dir)?;
    let gitignore_path = dir.join(".gitignore");
    if !gitignore_path.exists() {
        let content = "# Coraline data files\n# These are local to each machine and should not be committed\n\n# Database\n*.db\n*.db-wal\n*.db-shm\n\n# Cache\ncache/\n\n# Logs\n*.log\n";
        std::fs::write(gitignore_path, content)?;
    }
    Ok(())
}

#[allow(clippy::needless_pass_by_value)]
fn print_progress(progress: extraction::IndexProgress) {
    use std::io::Write;
    let phase = match progress.phase {
        extraction::IndexPhase::Scanning => "Scanning",
        extraction::IndexPhase::Parsing => "Parsing",
        extraction::IndexPhase::Storing => "Storing",
        extraction::IndexPhase::Resolving => "Resolving",
    };
    let file = progress
        .current_file
        .as_ref()
        .map(|f| format!(" {f}"))
        .unwrap_or_default();
    print!(
        "\r\x1B[K{phase}: {}/{}{}",
        progress.current, progress.total, file
    );
    let _ = std::io::stdout().flush();
}

fn clear_progress_line() {
    use std::io::Write;
    println!();
    let _ = std::io::stdout().flush();
}

fn parse_node_kind(value: &str) -> Option<NodeKind> {
    match value.to_ascii_lowercase().as_str() {
        "file" => Some(NodeKind::File),
        "module" => Some(NodeKind::Module),
        "class" => Some(NodeKind::Class),
        "struct" => Some(NodeKind::Struct),
        "interface" => Some(NodeKind::Interface),
        "trait" => Some(NodeKind::Trait),
        "protocol" => Some(NodeKind::Protocol),
        "function" => Some(NodeKind::Function),
        "method" => Some(NodeKind::Method),
        "property" => Some(NodeKind::Property),
        "field" => Some(NodeKind::Field),
        "variable" => Some(NodeKind::Variable),
        "constant" => Some(NodeKind::Constant),
        "enum" => Some(NodeKind::Enum),
        "enum_member" => Some(NodeKind::EnumMember),
        "type_alias" => Some(NodeKind::TypeAlias),
        "namespace" => Some(NodeKind::Namespace),
        "parameter" => Some(NodeKind::Parameter),
        "import" => Some(NodeKind::Import),
        "export" => Some(NodeKind::Export),
        "route" => Some(NodeKind::Route),
        "component" => Some(NodeKind::Component),
        _ => None,
    }
}

fn which(name: &str) -> bool {
    let Some(path) = std::env::var_os("PATH") else {
        return false;
    };

    let mut extensions: Vec<std::ffi::OsString> = Vec::new();
    if cfg!(windows) {
        if let Some(pathext) = std::env::var_os("PATHEXT") {
            extensions = std::env::split_paths(&pathext)
                .map(std::path::PathBuf::into_os_string)
                .collect();
        }
        if extensions.is_empty() {
            extensions.push(std::ffi::OsString::from(".exe"));
        }
    }

    for dir in std::env::split_paths(&path) {
        let base = dir.join(name);
        if cfg!(windows) {
            if base.exists() && base.is_file() {
                return true;
            }
            for ext in &extensions {
                let candidate =
                    PathBuf::from(format!("{}{}", base.display(), ext.to_string_lossy()));
                if candidate.exists() && candidate.is_file() {
                    return true;
                }
            }
        } else if base.exists() && base.is_file() && is_executable(&base) {
            return true;
        }
    }

    false
}

fn is_executable(path: &PathBuf) -> bool {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if let Ok(metadata) = std::fs::metadata(path) {
            return metadata.permissions().mode() & 0o111 != 0;
        }
        false
    }

    #[cfg(not(unix))]
    {
        path.exists() && path.is_file()
    }
}