graphify-rs 0.8.1

AI-powered knowledge graph builder - transform code, docs, papers into queryable graphs
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
use anyhow::{Context, Result};
use clap::{CommandFactory, Parser, Subcommand};
use clap_complete::{Shell, generate};
use colored::Colorize;
use std::collections::{HashMap, HashSet, VecDeque};
use std::io;
use std::path::{Path, PathBuf};

mod cmd_build;
mod config;
mod install;
mod paths;
mod skill;

#[derive(Parser)]
#[command(
    name = "graphify-rs",
    version,
    about = "AI-powered knowledge graph builder"
)]
struct Cli {
    /// Suppress non-essential output
    #[arg(short, long, global = true)]
    quiet: bool,

    /// Enable verbose output (debug-level)
    #[arg(short, long, global = true)]
    verbose: bool,

    /// Number of parallel jobs (default: number of CPUs)
    #[arg(short, long, global = true)]
    jobs: Option<usize>,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Build knowledge graph from files in a directory
    Build {
        #[arg(short, long, default_value = ".")]
        path: String,
        #[arg(short, long)]
        output: Option<String>,
        #[arg(long)]
        no_llm: bool,
        #[arg(long)]
        code_only: bool,
        /// Only re-extract new/modified files since last build
        #[arg(long)]
        update: bool,
        /// Export formats (comma-separated). Available: json,html,graphml,cypher,svg,wiki,obsidian,report. Default: all
        #[arg(long, value_delimiter = ',')]
        format: Vec<String>,
        /// Maximum nodes in HTML visualization (default: 2000). Larger values may slow browser.
        #[arg(long)]
        max_viz_nodes: Option<usize>,
    },
    /// Install graphify skill for AI coding assistant
    Install {
        #[arg(long, default_value = "claude")]
        platform: String,
    },
    /// Query the knowledge graph
    Query {
        question: String,
        #[arg(long)]
        dfs: bool,
        #[arg(long, default_value_t = 2000)]
        budget: usize,
        #[arg(long)]
        graph: Option<String>,
    },
    /// Run benchmark
    Benchmark {
        #[arg()]
        graph_path: Option<String>,
    },
    /// Git hook management
    Hook {
        #[command(subcommand)]
        action: HookAction,
    },
    /// Claude Code integration
    Claude {
        #[command(subcommand)]
        action: PlatformAction,
    },
    /// CodeBuddy integration
    Codebuddy {
        #[command(subcommand)]
        action: PlatformAction,
    },
    /// Codex integration
    Codex {
        #[command(subcommand)]
        action: PlatformAction,
    },
    /// OpenCode integration
    Opencode {
        #[command(subcommand)]
        action: PlatformAction,
    },
    /// OpenClaw integration
    Claw {
        #[command(subcommand)]
        action: PlatformAction,
    },
    /// Factory Droid integration
    Droid {
        #[command(subcommand)]
        action: PlatformAction,
    },
    /// Trae integration
    Trae {
        #[command(subcommand)]
        action: PlatformAction,
    },
    /// Trae CN integration
    TraeCn {
        #[command(subcommand)]
        action: PlatformAction,
    },
    /// Save query result to memory
    SaveResult {
        #[arg(long)]
        question: String,
        #[arg(long)]
        answer: String,
        #[arg(long, default_value = "query")]
        r#type: String,
        #[arg(long)]
        nodes: Vec<String>,
        #[arg(long)]
        memory_dir: Option<String>,
    },
    /// Start MCP server
    Serve {
        #[arg(long)]
        graph: Option<String>,
    },
    /// Watch for file changes and rebuild
    Watch {
        #[arg(short, long, default_value = ".")]
        path: String,
        #[arg(short, long)]
        output: Option<String>,
    },
    /// Ingest URL content
    Ingest {
        url: String,
        #[arg(short, long)]
        output: Option<String>,
    },
    /// Compare two graph snapshots
    Diff {
        /// Path to the old graph.json
        old: String,
        /// Path to the new graph.json
        new: String,
        /// Output format: text or json
        #[arg(long, default_value = "text")]
        output: String,
    },
    /// Show graph statistics without rebuilding
    Stats {
        /// Path to graph.json
        #[arg()]
        graph: Option<String>,
    },
    /// Find test files affected by changed source files
    Affected {
        /// Changed file paths (relative to project root)
        files: Vec<String>,
        /// Read file list from stdin (pipe from git diff)
        #[arg(long)]
        stdin: bool,
        /// Maximum dependency traversal depth (default: 5)
        #[arg(short, long, default_value_t = 5)]
        depth: usize,
        /// Output format: text or json
        #[arg(long, default_value = "text")]
        output: String,
        /// Path to graph.json
        #[arg(long)]
        graph: Option<String>,
    },
    /// Generate shell completions
    Completions {
        /// Shell to generate completions for
        shell: Shell,
    },
    /// Initialize a graphify-rs.toml config file
    Init,
}

#[derive(Subcommand)]
enum HookAction {
    /// Install git hooks
    Install,
    /// Uninstall git hooks
    Uninstall,
    /// Show hook status
    Status,
}

#[derive(Subcommand)]
enum PlatformAction {
    /// Install platform integration
    Install,
    /// Uninstall platform integration
    Uninstall,
}

/// Verbosity level derived from --quiet / --verbose flags.
#[derive(Clone, Copy)]
pub(crate) enum Verbosity {
    Quiet,
    Normal,
    Verbose,
}

impl Verbosity {
    pub(crate) fn from_flags(quiet: bool, verbose: bool) -> Self {
        if quiet {
            Self::Quiet
        } else if verbose {
            Self::Verbose
        } else {
            Self::Normal
        }
    }

    pub(crate) fn is_quiet(self) -> bool {
        matches!(self, Self::Quiet)
    }

    pub(crate) fn is_verbose(self) -> bool {
        matches!(self, Self::Verbose)
    }
}

/// Print helper that respects verbosity.
#[macro_export]
macro_rules! info_print {
    ($verb:expr, $($arg:tt)*) => {
        if !$verb.is_quiet() {
            println!($($arg)*);
        }
    };
}

#[macro_export]
macro_rules! verbose_print {
    ($verb:expr, $($arg:tt)*) => {
        if $verb.is_verbose() {
            println!($($arg)*);
        }
    };
}

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

    install::check_skill_versions();

    let verb = Verbosity::from_flags(cli.quiet, cli.verbose);

    let filter = if cli.verbose {
        "debug"
    } else if cli.quiet {
        "error"
    } else {
        &std::env::var("RUST_LOG").unwrap_or_else(|_| "warn".to_string())
    };
    tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::new(filter))
        .init();

    if let Some(jobs) = cli.jobs {
        rayon::ThreadPoolBuilder::new()
            .num_threads(jobs)
            .build_global()
            .ok(); // ignore if already initialized
    }

    match cli.command {
        Commands::Build {
            path,
            output,
            no_llm,
            code_only,
            update,
            format,
            max_viz_nodes,
        } => {
            let app_cfg = config::load_config(Path::new(&path));
            let effective_path = path;
            let default_output = paths::resolve_default_output(Path::new(&effective_path))
                .to_string_lossy()
                .to_string();
            let effective_output = match output {
                Some(o) => o,
                None => app_cfg.output.unwrap_or(default_output),
            };
            let effective_no_llm = no_llm || app_cfg.no_llm.unwrap_or(false);
            let effective_code_only = code_only || app_cfg.code_only.unwrap_or(false);
            let effective_formats = if format.is_empty() {
                app_cfg.formats.unwrap_or_default()
            } else {
                format
            };

            cmd_build::cmd_build(
                &effective_path,
                &effective_output,
                effective_no_llm,
                effective_code_only,
                update,
                &effective_formats,
                verb,
                cli.jobs,
                max_viz_nodes,
                app_cfg.llm,
            )
            .await?;
        }
        Commands::Install { platform } => {
            install::install_skill(&platform)?;
        }
        Commands::Query {
            question,
            dfs,
            budget,
            graph,
        } => {
            let graph_path = graph.unwrap_or_else(|| {
                paths::resolve_default_output(Path::new("."))
                    .join("graph.json")
                    .to_string_lossy()
                    .to_string()
            });
            cmd_query(&question, dfs, budget, &graph_path)?;
        }
        Commands::Benchmark { graph_path } => {
            let gp = graph_path.unwrap_or_else(|| {
                paths::resolve_default_output(Path::new("."))
                    .join("graph.json")
                    .to_string_lossy()
                    .to_string()
            });
            let result = graphify_benchmark::run_benchmark(Path::new(&gp), None)?;
            graphify_benchmark::print_benchmark(&result);
        }
        Commands::Hook { action } => {
            let root = Path::new(".");
            match action {
                HookAction::Install => println!("{}", graphify_hooks::install_hooks(root)?),
                HookAction::Uninstall => println!("{}", graphify_hooks::uninstall_hooks(root)?),
                HookAction::Status => println!("{}", graphify_hooks::hook_status(root)?),
            }
        }
        Commands::Claude { action } => {
            let root = Path::new(".");
            match action {
                PlatformAction::Install => install::claude_install(root)?,
                PlatformAction::Uninstall => install::claude_uninstall(root)?,
            }
        }
        Commands::Codebuddy { action } => {
            let root = Path::new(".");
            match action {
                PlatformAction::Install => install::codebuddy_install(root)?,
                PlatformAction::Uninstall => install::codebuddy_uninstall(root)?,
            }
        }
        Commands::Codex { action } => {
            let root = Path::new(".");
            match action {
                PlatformAction::Install => install::codex_install(root)?,
                PlatformAction::Uninstall => install::codex_uninstall(root)?,
            }
        }
        Commands::Opencode { action } => {
            let root = Path::new(".");
            match action {
                PlatformAction::Install => install::opencode_install(root)?,
                PlatformAction::Uninstall => install::opencode_uninstall(root)?,
            }
        }
        Commands::Claw { action } => {
            let root = Path::new(".");
            match action {
                PlatformAction::Install => install::generic_platform_install(root, "Claw")?,
                PlatformAction::Uninstall => install::generic_platform_uninstall(root, "Claw")?,
            }
        }
        Commands::Droid { action } => {
            let root = Path::new(".");
            match action {
                PlatformAction::Install => install::generic_platform_install(root, "Droid")?,
                PlatformAction::Uninstall => install::generic_platform_uninstall(root, "Droid")?,
            }
        }
        Commands::Trae { action } => {
            let root = Path::new(".");
            match action {
                PlatformAction::Install => install::generic_platform_install(root, "Trae")?,
                PlatformAction::Uninstall => install::generic_platform_uninstall(root, "Trae")?,
            }
        }
        Commands::TraeCn { action } => {
            let root = Path::new(".");
            match action {
                PlatformAction::Install => install::generic_platform_install(root, "Trae CN")?,
                PlatformAction::Uninstall => install::generic_platform_uninstall(root, "Trae CN")?,
            }
        }
        Commands::SaveResult {
            question,
            answer,
            r#type,
            nodes,
            memory_dir,
        } => {
            let mem_dir = memory_dir.unwrap_or_else(|| {
                paths::resolve_default_output(Path::new("."))
                    .join("memory")
                    .to_string_lossy()
                    .to_string()
            });
            let nodes_ref: Option<&[String]> = if nodes.is_empty() { None } else { Some(&nodes) };
            let out = graphify_ingest::save_query_result(
                &question,
                &answer,
                Path::new(&mem_dir),
                &r#type,
                nodes_ref,
            )?;
            println!("Saved to {}", out.display());
        }
        Commands::Serve { graph } => {
            let graph_str = graph.unwrap_or_else(|| {
                paths::resolve_default_output(Path::new("."))
                    .join("graph.json")
                    .to_string_lossy()
                    .to_string()
            });
            let graph_path = Path::new(&graph_str);
            if !graph_path.exists() {
                tracing::info!("{} not found, running auto-build...", graph_path.display());
                let output_dir = graph_path
                    .parent()
                    .unwrap_or(&paths::resolve_default_output(Path::new(".")))
                    .to_string_lossy()
                    .to_string();
                cmd_build::cmd_build(
                    ".",
                    &output_dir,
                    true,
                    true,
                    false,
                    &["json".to_string()],
                    Verbosity::Quiet,
                    None,
                    None,
                    None,
                )
                .await
                .context("Auto-build failed")?;
            }
            graphify_serve::start_server(graph_path).await?;
        }
        Commands::Watch { path, output } => {
            let out_dir = output.unwrap_or_else(|| {
                paths::resolve_default_output(Path::new(&path))
                    .to_string_lossy()
                    .to_string()
            });
            graphify_watch::watch_directory(Path::new(&path), Path::new(&out_dir)).await?;
        }
        Commands::Ingest { url, output } => {
            let out_dir = output.unwrap_or_else(|| {
                paths::resolve_default_output(Path::new("."))
                    .to_string_lossy()
                    .to_string()
            });
            let out = graphify_ingest::ingest_url(&url, Path::new(&out_dir)).await?;
            println!("Ingested to {}", out.display());
        }
        Commands::Diff { old, new, output } => {
            cmd_diff(&old, &new, &output)?;
        }
        Commands::Stats { graph } => {
            let gp = graph.unwrap_or_else(|| {
                paths::resolve_default_output(Path::new("."))
                    .join("graph.json")
                    .to_string_lossy()
                    .to_string()
            });
            cmd_stats(&gp)?;
        }
        Commands::Affected {
            files,
            stdin,
            depth,
            output,
            graph,
        } => {
            let gp = graph.unwrap_or_else(|| {
                paths::resolve_default_output(Path::new("."))
                    .join("graph.json")
                    .to_string_lossy()
                    .to_string()
            });
            cmd_affected(&files, stdin, depth, &output, &gp)?;
        }
        Commands::Completions { shell } => {
            generate(shell, &mut Cli::command(), "graphify-rs", &mut io::stdout());
        }
        Commands::Init => {
            cmd_init()?;
        }
    }

    Ok(())
}

/// Query the knowledge graph
fn cmd_query(question: &str, use_dfs: bool, budget: usize, graph_path: &str) -> Result<()> {
    let gp = PathBuf::from(graph_path);
    if !gp.exists() {
        anyhow::bail!("Graph file not found: {}", gp.display());
    }

    let json_str = std::fs::read_to_string(&gp).context("Could not read graph file")?;
    let json_value: serde_json::Value =
        serde_json::from_str(&json_str).context("Could not parse graph JSON")?;
    let graph = graphify_core::graph::KnowledgeGraph::from_node_link_json(&json_value)
        .context("Could not load graph from JSON")?;

    let terms: Vec<String> = question
        .split_whitespace()
        .filter(|w| w.len() > 2)
        .map(str::to_lowercase)
        .collect();

    let scored = graphify_serve::score_nodes(&graph, &terms);
    if scored.is_empty() {
        println!("No matching nodes found.");
        return Ok(());
    }

    let start: Vec<String> = scored.iter().take(5).map(|(_, id)| id.clone()).collect();
    let (nodes, edges) = if use_dfs {
        graphify_serve::dfs(&graph, &start, 2)
    } else {
        graphify_serve::bfs(&graph, &start, 2)
    };
    let text = graphify_serve::subgraph_to_text(&graph, &nodes, &edges, budget);
    println!("{text}");

    Ok(())
}

/// Compare two graph snapshots and display differences
fn cmd_diff(old_path: &str, new_path: &str, output_format: &str) -> Result<()> {
    let old_p = PathBuf::from(old_path);
    let new_p = PathBuf::from(new_path);

    if !old_p.exists() {
        anyhow::bail!("Old graph file not found: {}", old_p.display());
    }
    if !new_p.exists() {
        anyhow::bail!("New graph file not found: {}", new_p.display());
    }

    let old_json: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(&old_p).context("Could not read old graph file")?,
    )
    .context("Could not parse old graph JSON")?;
    let new_json: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(&new_p).context("Could not read new graph file")?,
    )
    .context("Could not parse new graph JSON")?;

    let old_graph = graphify_core::graph::KnowledgeGraph::from_node_link_json(&old_json)
        .context("Could not load old graph")?;
    let new_graph = graphify_core::graph::KnowledgeGraph::from_node_link_json(&new_json)
        .context("Could not load new graph")?;

    let diff = graphify_analyze::graph_diff(&old_graph, &new_graph);

    if output_format == "json" {
        println!("{}", serde_json::to_string_pretty(&diff)?);
    } else {
        let added_nodes = diff.get("added_nodes").and_then(|v| v.as_array());
        let removed_nodes = diff.get("removed_nodes").and_then(|v| v.as_array());
        let added_edges = diff.get("added_edges").and_then(|v| v.as_array());
        let removed_edges = diff.get("removed_edges").and_then(|v| v.as_array());

        println!(
            "{} {} → {}",
            "Graph Diff:".bold(),
            old_p.display(),
            new_p.display()
        );
        println!("─────────────────────────────────────");

        if let Some(nodes) = added_nodes {
            println!("\n{} ({})", "+ Added nodes".green(), nodes.len());
            for n in nodes.iter().take(20) {
                println!("  {} {}", "+".green(), n.as_str().unwrap_or("?"));
            }
            if nodes.len() > 20 {
                println!("  ... and {} more", nodes.len() - 20);
            }
        }

        if let Some(nodes) = removed_nodes {
            println!("\n{} ({})", "- Removed nodes".red(), nodes.len());
            for n in nodes.iter().take(20) {
                println!("  {} {}", "-".red(), n.as_str().unwrap_or("?"));
            }
            if nodes.len() > 20 {
                println!("  ... and {} more", nodes.len() - 20);
            }
        }

        if let Some(edges) = added_edges {
            println!("\n{} ({})", "+ Added edges".green(), edges.len());
            for e in edges.iter().take(20) {
                if let Some(arr) = e.as_array() {
                    let parts: Vec<&str> = arr.iter().filter_map(|v| v.as_str()).collect();
                    println!(
                        "  {} {} --[{}]--> {}",
                        "+".green(),
                        parts.first().unwrap_or(&"?"),
                        parts.get(2).unwrap_or(&"?"),
                        parts.get(1).unwrap_or(&"?")
                    );
                }
            }
            if edges.len() > 20 {
                println!("  ... and {} more", edges.len() - 20);
            }
        }

        if let Some(edges) = removed_edges {
            println!("\n{} ({})", "- Removed edges".red(), edges.len());
            for e in edges.iter().take(20) {
                if let Some(arr) = e.as_array() {
                    let parts: Vec<&str> = arr.iter().filter_map(|v| v.as_str()).collect();
                    println!(
                        "  {} {} --[{}]--> {}",
                        "-".red(),
                        parts.first().unwrap_or(&"?"),
                        parts.get(2).unwrap_or(&"?"),
                        parts.get(1).unwrap_or(&"?")
                    );
                }
            }
            if edges.len() > 20 {
                println!("  ... and {} more", edges.len() - 20);
            }
        }

        let summary_added =
            added_nodes.map_or(0, std::vec::Vec::len) + added_edges.map_or(0, std::vec::Vec::len);
        let summary_removed = removed_nodes.map_or(0, std::vec::Vec::len)
            + removed_edges.map_or(0, std::vec::Vec::len);
        println!(
            "\n{}: {} additions, {} removals",
            "Summary".bold(),
            format!("+{summary_added}").green(),
            format!("-{summary_removed}").red()
        );
    }

    Ok(())
}

/// Show graph statistics without rebuilding
fn cmd_stats(graph_path: &str) -> Result<()> {
    let gp = PathBuf::from(graph_path);
    if !gp.exists() {
        anyhow::bail!("Graph file not found: {}", gp.display());
    }

    let json_str = std::fs::read_to_string(&gp).context("Could not read graph file")?;
    let json_value: serde_json::Value =
        serde_json::from_str(&json_str).context("Could not parse graph JSON")?;
    let graph = graphify_core::graph::KnowledgeGraph::from_node_link_json(&json_value)
        .context("Could not load graph from JSON")?;

    let node_count = graph.node_count();
    let edge_count = graph.edge_count();

    let mut type_counts: HashMap<String, usize> = HashMap::new();
    for id in graph.node_ids() {
        if let Some(node) = graph.get_node(&id) {
            let type_name = format!("{:?}", node.node_type);
            *type_counts.entry(type_name).or_insert(0) += 1;
        }
    }

    let mut rel_counts: HashMap<String, usize> = HashMap::new();
    for edge in graph.edges() {
        *rel_counts.entry(edge.relation.clone()).or_insert(0) += 1;
    }

    let communities = graphify_cluster::cluster(&graph);

    let god_list = graphify_analyze::god_nodes(&graph, 5);

    let degrees: Vec<usize> = graph.node_ids().iter().map(|id| graph.degree(id)).collect();
    let avg_degree = if degrees.is_empty() {
        0.0
    } else {
        degrees.iter().sum::<usize>() as f64 / degrees.len() as f64
    };
    let max_degree = degrees.iter().copied().max().unwrap_or(0);

    println!("{}", "Graph Statistics".bold().underline());
    println!("  Nodes:       {}", node_count.to_string().bold());
    println!("  Edges:       {}", edge_count.to_string().bold());
    println!("  Communities: {}", communities.len().to_string().bold());
    println!("  Avg degree:  {avg_degree:.1}");
    println!("  Max degree:  {max_degree}");

    println!("\n{}", "Node Types".bold());
    let mut types: Vec<_> = type_counts.iter().collect();
    types.sort_by(|a, b| b.1.cmp(a.1));
    for (t, count) in &types {
        println!("  {:20} {}", t, count.to_string().cyan());
    }

    println!("\n{}", "Edge Relations".bold());
    let mut rels: Vec<_> = rel_counts.iter().collect();
    rels.sort_by(|a, b| b.1.cmp(a.1));
    for (r, count) in rels.iter().take(15) {
        println!("  {:20} {}", r, count.to_string().cyan());
    }
    if rels.len() > 15 {
        println!("  ... and {} more relation types", rels.len() - 15);
    }

    if !god_list.is_empty() {
        println!("\n{}", "Top Connected Nodes".bold());
        for g in &god_list {
            println!(
                "  {} ({} edges, community {:?})",
                g.label.green(),
                g.degree,
                g.community
            );
        }
    }

    println!("\n  Source: {}", graph_path.dimmed());

    Ok(())
}

/// Initialize a graphify-rs.toml configuration file
fn cmd_init() -> Result<()> {
    let path = Path::new("graphify-rs.toml");
    if path.exists() {
        anyhow::bail!("graphify-rs.toml already exists");
    }
    std::fs::write(
        path,
        r#"# graphify-rs configuration
# These values serve as defaults and can be overridden by CLI flags.

# Output directory for graph files
# output = "graphify-rs-out"

# Disable LLM-based semantic extraction
# no_llm = false

# Only process code files (skip docs/papers)
# code_only = false

# Export formats (comma-separated). Available: json,html,graphml,cypher,svg,wiki,obsidian,report
# Leave empty or omit for all formats.
# formats = ["json", "html", "report"]

# LLM provider for semantic extraction
# [llm]
# provider = "anthropic"          # anthropic | openai | ollama | openai_compatible
# model = "claude-sonnet-4.6"  # required, no default
# anthropic_api_key = "sk-..."    # optional, falls back to ANTHROPIC_API_KEY env or Claude Code OAuth
# anthropic_base_url = "https://api.anthropic.com"  # optional override
# openai_api_key = "sk-..."       # optional, falls back to OPENAI_API_KEY env
# openai_base_url = "https://api.openai.com/v1"     # optional override
# ollama_base_url = "http://localhost:11434"          # optional override
# openai_compatible_api_key = "..."                   # optional
# openai_compatible_base_url = "http://localhost:8000/v1"  # required for openai_compatible
"#,
    )?;
    println!("{} Created graphify-rs.toml", "✓".green());
    Ok(())
}

fn cmd_affected(
    files: &[String],
    read_stdin: bool,
    max_depth: usize,
    output_format: &str,
    graph_path: &str,
) -> Result<()> {
    let gp = PathBuf::from(graph_path);
    if !gp.exists() {
        anyhow::bail!("Graph file not found: {}", gp.display());
    }

    let json_str = std::fs::read_to_string(&gp).context("Could not read graph file")?;
    let json_value: serde_json::Value =
        serde_json::from_str(&json_str).context("Could not parse graph JSON")?;
    let graph = graphify_core::graph::KnowledgeGraph::from_node_link_json(&json_value)
        .context("Could not load graph from JSON")?;

    let mut changed_files: Vec<String> = files.to_vec();
    if read_stdin {
        use std::io::BufRead;
        let stdin = std::io::stdin();
        for line in stdin.lock().lines().map_while(Result::ok) {
            let trimmed = line.trim().to_string();
            if !trimmed.is_empty() {
                changed_files.push(trimmed);
            }
        }
    }

    if changed_files.is_empty() {
        println!("No changed files provided. Use positional args or --stdin.");
        return Ok(());
    }

    let changed: HashSet<String> = changed_files.iter().cloned().collect();

    let file_nodes: HashMap<String, String> = graph
        .nodes()
        .into_iter()
        .filter(|n| n.node_type == graphify_core::model::NodeType::File)
        .map(|n| (n.source_file.clone(), n.id.clone()))
        .collect();

    // Build a reverse dependency index: target_id -> Vec<source_id>
    // Only consider dependency-like edges (imports, uses, calls)
    let mut reverse_deps: HashMap<String, Vec<String>> = HashMap::new();
    for edge in graph.edges() {
        if matches!(edge.relation.as_str(), "imports" | "uses" | "calls") {
            reverse_deps
                .entry(edge.target.clone())
                .or_default()
                .push(edge.source.clone());
        }
    }

    let mut affected: HashSet<String> = HashSet::new();
    let mut queue: VecDeque<String> = VecDeque::new();

    for path in &changed {
        let normalized = path.trim_start_matches("./").replace('\\', "/");
        let file_id = file_nodes
            .get(normalized.as_str())
            .or_else(|| file_nodes.get(path.as_str()));
        if let Some(file_id) = file_id {
            queue.push_back(file_id.clone());
        }
    }

    let mut visited: HashSet<String> = HashSet::new();
    let mut depth_map: HashMap<String, usize> = HashMap::new();
    for id in queue.iter() {
        visited.insert(id.clone());
        depth_map.insert(id.clone(), 0);
    }

    while let Some(current) = queue.pop_front() {
        let current_depth = *depth_map.get(&current).unwrap_or(&max_depth);
        if current_depth >= max_depth {
            continue;
        }

        // Traverse only reverse dependency edges (who depends on current node)
        if let Some(dependents) = reverse_deps.get(&current) {
            for dep_id in dependents {
                if !visited.contains(dep_id) {
                    visited.insert(dep_id.clone());
                    depth_map.insert(dep_id.clone(), current_depth + 1);
                    queue.push_back(dep_id.clone());

                    if let Some(node) = graph.get_node(dep_id) {
                        if is_test_file(&node.source_file) && !changed.contains(&node.source_file) {
                            affected.insert(node.source_file.clone());
                        }
                    }
                }
            }
        }
    }

    let mut sorted: Vec<String> = affected.into_iter().collect();
    sorted.sort();

    match output_format {
        "json" => {
            let result = serde_json::json!({
                "changed_files": changed_files,
                "affected_tests": sorted,
                "depth": max_depth,
            });
            println!("{}", serde_json::to_string_pretty(&result)?);
        }
        _ => {
            if sorted.is_empty() {
                println!("No affected test files found.");
            } else {
                for file in &sorted {
                    println!("{file}");
                }
            }
        }
    }

    Ok(())
}

fn is_test_file(path: &str) -> bool {
    let lp = path.to_lowercase();
    let name = lp.rsplit('/').next().unwrap_or(&lp);
    lp.contains("/tests/")
        || lp.contains("/__tests__/")
        || lp.contains("/test/")
        || lp.contains("/spec/")
        || name.starts_with("test_")
        || name.starts_with("tests_")
        || name.ends_with("_test.go")
        || name.ends_with("_test.py")
        || name.ends_with("_test.rs")
        || name.ends_with("_test.rb")
        || name.ends_with("_spec.rb")
        || name.ends_with("_test.dart")
        || name.ends_with("_test.swift")
        || name.ends_with("_test.kt")
        || name.ends_with("_test.scala")
        || name.contains(".test.")
        || name.contains(".spec.")
}

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

    #[test]
    fn test_file_dirs() {
        assert!(is_test_file("src/tests/utils.rs"));
        assert!(is_test_file("app/__tests__/App.test.tsx"));
        assert!(is_test_file("pkg/test/helper.go"));
        assert!(is_test_file("spec/models/user_spec.rb"));
    }

    #[test]
    fn test_file_prefixes() {
        assert!(is_test_file("test_helper.py"));
        assert!(is_test_file("tests_main.go"));
        assert!(is_test_file("src/test_auth.rs"));
    }

    #[test]
    fn test_file_suffixes() {
        assert!(is_test_file("server_test.go"));
        assert!(is_test_file("parser_test.py"));
        assert!(is_test_file("handler_test.rs"));
        assert!(is_test_file("user_test.rb"));
        assert!(is_test_file("model_spec.rb"));
        assert!(is_test_file("widget_test.dart"));
        assert!(is_test_file("NetworkManager_test.swift"));
        assert!(is_test_file("RepoTest_test.kt"));
        assert!(is_test_file("Service_test.scala"));
    }

    #[test]
    fn test_dot_patterns() {
        assert!(is_test_file("App.test.tsx"));
        assert!(is_test_file("utils.spec.ts"));
        assert!(is_test_file("Component.test.js"));
    }

    #[test]
    fn non_test_files() {
        assert!(!is_test_file("src/main.rs"));
        assert!(!is_test_file("lib.rs"));
        assert!(!is_test_file("src/auth/controller.go"));
        assert!(!is_test_file("testing_utils.rs"));
        assert!(!is_test_file("testimony.rs"));
        assert!(!is_test_file("contest_handler.py"));
        assert!(!is_test_file("latest_data.go"));
    }

    #[test]
    fn case_insensitive() {
        assert!(is_test_file("src/Tests/Utils.rs"));
        assert!(is_test_file("SRC/TEST/main.go"));
        assert!(is_test_file("App.Test.tsx"));
    }
}