oxur-odm 0.3.5

An odd document manager - CLI tool for managing design documentation
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
use anyhow::Result;
use colored::Colorize;
use design::state::StateManager;

/// Info subcommands
#[derive(Debug, Clone)]
pub enum InfoCommand {
    Overview,
    States,
    Fields,
    Config,
    Stats,
    Dirs,
    Tags,
    Components,
}

impl InfoCommand {
    pub fn from_str(s: Option<&str>) -> Self {
        match s {
            Some("states") => InfoCommand::States,
            Some("fields") | Some("metadata") => InfoCommand::Fields,
            Some("config") => InfoCommand::Config,
            Some("stats") => InfoCommand::Stats,
            Some("dirs") | Some("structure") => InfoCommand::Dirs,
            Some("tags") => InfoCommand::Tags,
            Some("components") => InfoCommand::Components,
            _ => InfoCommand::Overview,
        }
    }
}

pub fn execute(subcommand: Option<String>, state_mgr: &StateManager) -> Result<()> {
    let cmd = InfoCommand::from_str(subcommand.as_deref());

    match cmd {
        InfoCommand::Overview => show_overview(state_mgr)?,
        InfoCommand::States => show_states()?,
        InfoCommand::Fields => show_fields()?,
        InfoCommand::Config => show_config(state_mgr)?,
        InfoCommand::Stats => show_stats(state_mgr)?,
        InfoCommand::Dirs => show_dirs(state_mgr)?,
        InfoCommand::Tags => show_tags(state_mgr)?,
        InfoCommand::Components => show_components(state_mgr)?,
    }

    Ok(())
}

fn show_overview(state_mgr: &StateManager) -> Result<()> {
    // Get version from Cargo.toml
    let version = env!("CARGO_PKG_VERSION");

    println!();
    println!(
        "{} {}",
        "Oxur Design Documentation Manager (odm)".cyan().bold(),
        format!("v{}", version).yellow()
    );
    println!();

    // Project info
    println!("{}", "Project:".cyan().bold());
    let docs_dir = state_mgr.docs_dir();
    println!("  {}", docs_dir.display().to_string().white());
    println!();

    // Document counts
    let all_docs = state_mgr.state().all();
    let total = all_docs.len();

    if total > 0 {
        use std::collections::HashMap;
        let mut counts: HashMap<design::DocState, usize> = HashMap::new();

        for doc in all_docs {
            *counts.entry(doc.metadata.state).or_insert(0) += 1;
        }

        println!("{} {} total", "Documents:".cyan().bold(), total.to_string().yellow());

        // Show top states
        let mut state_counts: Vec<_> = counts.iter().collect();
        state_counts.sort_by(|a, b| b.1.cmp(a.1));

        for (state, count) in state_counts.iter().take(5) {
            println!("  - {} {}", count.to_string().yellow(), state.as_str().white());
        }

        if state_counts.len() > 5 {
            println!("  - ... and {} more", state_counts.len() - 5);
        }
    } else {
        println!("{} {}", "Documents:".cyan().bold(), "0".yellow());
    }
    println!();

    // Quick help
    println!("{}", "Quick Help:".cyan().bold());
    println!("  {}  Full command reference", "odm help".yellow());
    println!("  {}  Valid document states", "odm info states".yellow());
    println!("  {}  Frontmatter fields", "odm info fields".yellow());
    println!("  {}  Configuration values", "odm info config".yellow());
    println!("  {}  Project statistics", "odm info stats".yellow());
    println!("  {}  List all tags", "odm info tags".yellow());
    println!("  {}  List all components", "odm info components".yellow());
    println!();

    println!("{}", "Documentation:".cyan().bold());
    println!("  https://github.com/oxur/oxur");
    println!();

    Ok(())
}

fn show_states() -> Result<()> {
    use design::doc::DocState;

    println!();
    println!("{}", "Valid Document States".cyan().bold());
    println!();

    let states = DocState::all_states();

    for state in states {
        // State name
        let state_name = state.as_str();
        println!("  {:<15} {}", state_name.yellow().bold(), state.description().white());

        // Directory
        let dir = state.directory();
        println!("  {:<15} Directory: {}", "", dir.dimmed());
        println!();
    }

    println!("{}", "Usage:".cyan().bold());
    println!("  Transition a document: {}", "odm transition <doc> <state>".yellow());
    println!("  List by state: {}", "odm list --state <state>".yellow());
    println!();

    Ok(())
}

fn show_fields() -> Result<()> {
    println!();
    println!("{}", "Supported Frontmatter Fields".cyan().bold());
    println!();

    // Required fields
    println!("{}", "Required Fields:".green().bold());
    println!();

    print_field("number", "Document number (4-digit integer)", Some("42"));
    print_field("title", "Document title", Some("\"Feature Design: Advanced Caching\""));
    print_field("state", "Current document state", Some("draft"));
    println!("         {} {}", "Note:".dimmed(), "Valid states: odm info states".dimmed());
    println!();
    print_field("created", "Creation date (YYYY-MM-DD)", Some("2025-01-15"));
    println!("         {} {}", "Note:".dimmed(), "Auto-extracted from git if missing".dimmed());
    println!();
    print_field("updated", "Last update date (YYYY-MM-DD)", Some("2025-01-20"));
    println!("         {} {}", "Note:".dimmed(), "Auto-updated on transitions".dimmed());
    println!();
    print_field("author", "Document author name", Some("\"Jane Developer\""));
    println!("         {} {}", "Note:".dimmed(), "Auto-extracted from git if missing".dimmed());
    println!();

    // Optional fields
    println!("{}", "Optional Fields:".cyan().bold());
    println!();

    print_field("supersedes", "Number of document this supersedes", Some("41"));
    println!("         {} {}", "Note:".dimmed(), "Used when document replaces another".dimmed());
    println!();
    print_field("superseded-by", "Number of document that supersedes this", Some("43"));
    println!("         {} {}", "Note:".dimmed(), "Auto-set when document is superseded".dimmed());
    println!();

    // Example
    println!("{}", "Example Document Header:".yellow().bold());
    println!();
    println!("{}", "  ---".dimmed());
    println!("  number: 42");
    println!("  title: \"Feature Design: Advanced Caching\"");
    println!("  state: draft");
    println!("  created: 2025-01-15");
    println!("  updated: 2025-01-20");
    println!("  author: \"Jane Developer\"");
    println!("{}", "  ---".dimmed());
    println!();

    // Commands
    println!("{}", "Related Commands:".cyan().bold());
    println!("  {}  Add missing headers to a document", "odm add-headers <doc>".yellow());
    println!("  {}  Check all documents for valid headers", "odm validate".yellow());
    println!();

    Ok(())
}

fn print_field(name: &str, description: &str, example: Option<&str>) {
    println!("  {:<15} {}", name.yellow().bold(), description.white());
    if let Some(ex) = example {
        println!("  {:<15} Example: {}", "", ex.cyan());
    }
}

fn show_config(state_mgr: &StateManager) -> Result<()> {
    use design::config::Config;
    use design::doc::DocState;

    let config = Config::load(Some(state_mgr.docs_dir().to_str().unwrap()))?;

    println!();
    println!("{}", "Configuration".cyan().bold());
    println!();

    // Project paths
    println!("{}", "Project:".green().bold());
    println!("  {:<18} {}", "Root:".white(), config.project_root.display().to_string().cyan());
    println!(
        "  {:<18} {}",
        "Docs Directory:".white(),
        config.docs_directory.display().to_string().cyan()
    );
    println!();

    // Data sources
    println!("{}", "Data Sources:".green().bold());
    println!("  {:<18} {}", "State File:".white(), config.state_file.display().to_string().cyan());
    println!();

    // Dustbin
    println!("{}", "Dustbin:".green().bold());
    println!(
        "  {:<18} {}",
        "Directory:".white(),
        config.dustbin_directory.display().to_string().cyan()
    );
    println!(
        "  {:<18} {}",
        "Structure:".white(),
        if config.preserve_dustbin_structure {
            "preserve_state_dirs".green()
        } else {
            "flat".yellow()
        }
    );
    println!();

    // Git integration
    println!("{}", "Git Integration:".green().bold());
    println!(
        "  {:<18} {}",
        "Auto-stage:".white(),
        if config.auto_stage_git { "enabled".green() } else { "disabled".yellow() }
    );
    println!();

    // State directories
    println!("{}", "State Directories:".green().bold());
    let states = [
        DocState::Draft,
        DocState::UnderReview,
        DocState::Revised,
        DocState::Accepted,
        DocState::Active,
        DocState::Final,
        DocState::Deferred,
        DocState::Rejected,
        DocState::Withdrawn,
        DocState::Superseded,
    ];

    for state in states {
        println!("  {:<18} → {}", state.as_str().white(), state.directory().cyan());
    }
    println!();

    // Configuration sources (in precedence order)
    println!("{}", "Configuration Sources:".green().bold());
    println!("  1. {} (always present)", "Built-in defaults".dimmed());

    // Check for odm.toml via confyg search paths
    let mut config_num = 2;

    // Check current directory
    let cwd_config = std::path::PathBuf::from("./odm.toml");
    let cwd_config_canonical = cwd_config.canonicalize().ok();

    if cwd_config.exists() {
        println!("  {}. {} (found)", config_num, "./odm.toml".cyan());
        config_num += 1;
    }

    // Check git repo root
    if let Some(repo_root) = design::git::get_repo_root() {
        let repo_config = repo_root.join("odm.toml");

        // Only show if different from current directory config
        let is_different = match (&cwd_config_canonical, repo_config.canonicalize().ok()) {
            (Some(cwd), Some(repo)) => cwd != &repo,
            _ => true, // If canonicalization fails, assume they're different
        };

        if repo_config.exists() && is_different {
            println!("  {}. {} (found)", config_num, repo_config.display().to_string().cyan());
            config_num += 1;
        }

        // Check for legacy .odmrc
        let legacy_config = repo_root.join(".odmrc");
        if legacy_config.exists() {
            println!(
                "  {}. {} (deprecated, migrate to odm.toml)",
                config_num,
                legacy_config.display().to_string().yellow()
            );
            config_num += 1;
        }
    }

    // Check user config directory
    if let Ok(home) = std::env::var("HOME") {
        let user_config = std::path::PathBuf::from(home).join(".config/odm/odm.toml");
        if user_config.exists() {
            println!("  {}. {} (found)", config_num, user_config.display().to_string().cyan());
            config_num += 1;
        }
    }

    // Check .odm/config.toml in docs directory
    let docs_config = std::path::PathBuf::from(&config.docs_directory).join(".odm/config.toml");
    if docs_config.exists() {
        println!("  {}. {} (found)", config_num, docs_config.display().to_string().cyan());
    } else {
        println!("  {}. {} (not found)", config_num, ".odm/config.toml".dimmed());
    }

    println!();

    // Modification help
    println!("{}", "Modify Configuration:".yellow().bold());
    println!("  Project-wide:  {}", "odm.toml (in repo root)".cyan());
    println!("  User-wide:     {}", "~/.config/odm/odm.toml".cyan());
    println!("  Per-docs-dir:  {}", ".odm/config.toml (in docs directory)".cyan());
    println!("  Reload:        Configuration is read on each command");
    println!();

    Ok(())
}

fn show_stats(state_mgr: &StateManager) -> Result<()> {
    use design::doc::DocState;
    use std::collections::HashMap;

    let all_docs = state_mgr.state().all();

    println!();
    println!("{}", "Project Statistics".cyan().bold());
    println!();

    // Document counts
    println!("{}", "Document Counts:".green().bold());
    println!("  {:<20} {}", "Total Documents:".white(), all_docs.len().to_string().yellow().bold());
    println!();

    // By state
    let mut state_counts: HashMap<DocState, usize> = HashMap::new();
    for doc in &all_docs {
        *state_counts.entry(doc.metadata.state).or_insert(0) += 1;
    }

    println!("  {}:", "By State".white());

    // Sort by count (descending)
    let mut counts_vec: Vec<_> = state_counts.iter().collect();
    counts_vec.sort_by(|a, b| b.1.cmp(a.1));

    for (state, count) in counts_vec {
        println!(
            "    {:<18} {} docs",
            format!("{}:", state.as_str()).white(),
            count.to_string().yellow()
        );
    }
    println!();

    // Activity metrics (if we have documents)
    if !all_docs.is_empty() {
        println!("{}", "Timeline:".green().bold());

        let oldest = all_docs.iter().min_by_key(|d| &d.metadata.created).unwrap();

        let newest = all_docs.iter().max_by_key(|d| &d.metadata.created).unwrap();

        println!(
            "  {:<20} {:04} ({})",
            "Oldest Document:".white(),
            oldest.metadata.number,
            oldest.metadata.created.to_string().cyan()
        );
        println!(
            "  {:<20} {:04} ({})",
            "Newest Document:".white(),
            newest.metadata.number,
            newest.metadata.created.to_string().cyan()
        );
        println!();
    }

    // Health checks
    println!("{}", "Health:".green().bold());

    // Check for documents without proper metadata
    let docs_with_placeholder = all_docs
        .iter()
        .filter(|d| d.metadata.title == "Untitled Document" || d.metadata.title.is_empty())
        .count();

    if docs_with_placeholder == 0 {
        println!("  ✓ {}", "All documents have titles".green());
    } else {
        println!(
            "  âš  {} {}",
            docs_with_placeholder.to_string().yellow(),
            "documents need titles".yellow()
        );
    }

    // Check dustbin
    let in_dustbin = all_docs.iter().filter(|d| d.metadata.state.is_in_dustbin()).count();

    if in_dustbin > 0 {
        println!(
            "  âš  {} {} {}",
            in_dustbin.to_string().yellow(),
            "documents in dustbin".yellow(),
            "(consider permanent deletion)".dimmed()
        );
    } else {
        println!("  ✓ {}", "No documents in dustbin".green());
    }

    println!();

    Ok(())
}

fn show_dirs(state_mgr: &StateManager) -> Result<()> {
    use design::doc::DocState;
    use std::collections::HashMap;

    let all_docs = state_mgr.state().all();

    println!();
    println!("{}", "Directory Structure".cyan().bold());
    println!();

    // Count documents per state
    let mut state_counts: HashMap<DocState, usize> = HashMap::new();
    for doc in &all_docs {
        *state_counts.entry(doc.metadata.state).or_insert(0) += 1;
    }

    // Display tree
    let docs_dir = state_mgr.docs_dir();
    println!("{}/", docs_dir.file_name().unwrap().to_string_lossy());
    println!("├── {}  {}", ".odm/".cyan(), "(state tracking)".dimmed());
    println!("│   └── {}  {}", "state.json".cyan(), "(document state)".dimmed());

    // Dustbin
    let dustbin_count = all_docs.iter().filter(|d| d.metadata.state.is_in_dustbin()).count();

    if dustbin_count > 0 {
        println!(
            "├── {}  {}",
            ".dustbin/".cyan(),
            format!("({} removed docs)", dustbin_count).dimmed()
        );
    }

    // State directories
    let states = [
        (DocState::Draft, "01-draft"),
        (DocState::UnderReview, "02-under-review"),
        (DocState::Revised, "03-revised"),
        (DocState::Accepted, "04-accepted"),
        (DocState::Active, "05-active"),
        (DocState::Final, "06-final"),
        (DocState::Deferred, "07-deferred"),
        (DocState::Rejected, "08-rejected"),
        (DocState::Withdrawn, "09-withdrawn"),
        (DocState::Superseded, "10-superseded"),
    ];

    for (i, (state, dir_name)) in states.iter().enumerate() {
        let count = state_counts.get(state).unwrap_or(&0);
        let is_last = i == states.len() - 1 && dustbin_count == 0;
        let prefix = if is_last { "└── " } else { "├── " };

        println!(
            "{}{}  {}",
            prefix,
            format!("{}/", dir_name).cyan(),
            format!("({} docs)", count).dimmed()
        );
    }

    if dustbin_count == 0 {
        // No final entry needed
    }

    println!();

    // Distribution chart
    if !all_docs.is_empty() {
        println!("{}", "Document Distribution:".cyan().bold());

        let total = all_docs.len().max(1);
        let max_width = 40;

        let mut active_state_counts: Vec<_> = all_docs
            .iter()
            .filter(|d| !d.metadata.state.is_in_dustbin())
            .fold(HashMap::new(), |mut acc, doc| {
                *acc.entry(doc.metadata.state).or_insert(0) += 1;
                acc
            })
            .into_iter()
            .collect();

        active_state_counts.sort_by(|a, b| b.1.cmp(&a.1));

        for (state, count) in active_state_counts {
            let bar_width = (count * max_width / total).max(1);
            let bar = "â–ˆ".repeat(bar_width);

            println!(
                "  {:<35} {} {}",
                bar.green(),
                count.to_string().yellow(),
                state.as_str().white()
            );
        }

        println!();
    }

    Ok(())
}

fn show_tags(state_mgr: &StateManager) -> Result<()> {
    use std::collections::HashMap;
    use tabled::builder::Builder;
    use tabled::Tabled;

    // Marker struct for table type parameter
    #[derive(Tabled)]
    struct TagRow {
        tag: String,
        occurrences: String,
    }

    // Collect all tags with occurrence counts
    let all_docs = state_mgr.state().all();
    let mut tag_counts: HashMap<String, usize> = HashMap::new();

    for doc in &all_docs {
        for tag in &doc.metadata.tags {
            *tag_counts.entry(tag.clone()).or_insert(0) += 1;
        }
    }

    // Convert to sorted vector (by occurrence count, descending)
    let mut tag_vec: Vec<_> = tag_counts.into_iter().collect();
    tag_vec.sort_by(|a, b| b.1.cmp(&a.1));

    // Build table
    let mut builder = Builder::default();

    // Row 0: Title
    builder.push_record(["TAGS", ""]);

    // Row 1: Header
    builder.push_record(["Tag", "Occurrences"]);

    // Rows 2+: Data rows
    for (tag, count) in &tag_vec {
        builder.push_record([&format!(" {}", tag), &format!(" {}", count)]);
    }

    // Last row: Footer
    let total_text = format!("Total Tags: {}", tag_vec.len());
    builder.push_record([&total_text, ""]);

    // Build and style
    let mut table = builder.build();
    let config = oxur_cli::table::TableStyleConfig::default();
    config.apply_to_table::<TagRow>(&mut table);

    println!();
    println!("{}", table);
    println!();

    Ok(())
}

fn show_components(state_mgr: &StateManager) -> Result<()> {
    use std::collections::HashMap;
    use tabled::builder::Builder;
    use tabled::Tabled;

    // Marker struct for table type parameter
    #[derive(Tabled)]
    struct ComponentRow {
        component: String,
        occurrences: String,
    }

    // Collect all components with occurrence counts
    let all_docs = state_mgr.state().all();
    let mut component_counts: HashMap<String, usize> = HashMap::new();

    for doc in &all_docs {
        if let Some(component) = &doc.metadata.component {
            *component_counts.entry(component.clone()).or_insert(0) += 1;
        }
    }

    // Convert to sorted vector (by occurrence count, descending)
    let mut component_vec: Vec<_> = component_counts.into_iter().collect();
    component_vec.sort_by(|a, b| b.1.cmp(&a.1));

    // Build table
    let mut builder = Builder::default();

    // Row 0: Title
    builder.push_record(["COMPONENTS", ""]);

    // Row 1: Header
    builder.push_record(["Component", "Occurrences"]);

    // Rows 2+: Data rows
    for (component, count) in &component_vec {
        builder.push_record([&format!(" {}", component), &format!(" {}", count)]);
    }

    // Last row: Footer
    let total_text = format!("Total Components: {}", component_vec.len());
    builder.push_record([&total_text, ""]);

    // Build and style
    let mut table = builder.build();
    let config = oxur_cli::table::TableStyleConfig::default();
    config.apply_to_table::<ComponentRow>(&mut table);

    println!();
    println!("{}", table);
    println!();

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    /// Helper to create a test StateManager with a temporary directory
    fn setup_test_state_manager() -> (TempDir, StateManager) {
        let temp = TempDir::new().unwrap();
        let docs_dir = temp.path();

        // Create necessary directory structure
        fs::create_dir_all(docs_dir.join(".odm")).unwrap();
        fs::create_dir_all(docs_dir.join("01-draft")).unwrap();

        // Initialize git repo (required for StateManager)
        std::process::Command::new("git").args(["init"]).current_dir(docs_dir).output().unwrap();

        std::process::Command::new("git")
            .args(["config", "user.name", "Test User"])
            .current_dir(docs_dir)
            .output()
            .unwrap();

        std::process::Command::new("git")
            .args(["config", "user.email", "test@example.com"])
            .current_dir(docs_dir)
            .output()
            .unwrap();

        let state_mgr = StateManager::new(docs_dir).unwrap();

        (temp, state_mgr)
    }

    #[test]
    fn test_info_command_from_str_states() {
        let cmd = InfoCommand::from_str(Some("states"));
        assert!(matches!(cmd, InfoCommand::States));
    }

    #[test]
    fn test_info_command_from_str_fields() {
        let cmd = InfoCommand::from_str(Some("fields"));
        assert!(matches!(cmd, InfoCommand::Fields));
    }

    #[test]
    fn test_info_command_from_str_metadata_alias() {
        let cmd = InfoCommand::from_str(Some("metadata"));
        assert!(matches!(cmd, InfoCommand::Fields));
    }

    #[test]
    fn test_info_command_from_str_config() {
        let cmd = InfoCommand::from_str(Some("config"));
        assert!(matches!(cmd, InfoCommand::Config));
    }

    #[test]
    fn test_info_command_from_str_stats() {
        let cmd = InfoCommand::from_str(Some("stats"));
        assert!(matches!(cmd, InfoCommand::Stats));
    }

    #[test]
    fn test_info_command_from_str_dirs() {
        let cmd = InfoCommand::from_str(Some("dirs"));
        assert!(matches!(cmd, InfoCommand::Dirs));
    }

    #[test]
    fn test_info_command_from_str_structure_alias() {
        let cmd = InfoCommand::from_str(Some("structure"));
        assert!(matches!(cmd, InfoCommand::Dirs));
    }

    #[test]
    fn test_info_command_from_str_none_defaults_to_overview() {
        let cmd = InfoCommand::from_str(None);
        assert!(matches!(cmd, InfoCommand::Overview));
    }

    #[test]
    fn test_info_command_from_str_unknown_defaults_to_overview() {
        let cmd = InfoCommand::from_str(Some("unknown"));
        assert!(matches!(cmd, InfoCommand::Overview));
    }

    #[test]
    fn test_execute_overview() {
        let (_temp, state_mgr) = setup_test_state_manager();
        let result = execute(None, &state_mgr);
        assert!(result.is_ok());
    }

    #[test]
    fn test_execute_states() {
        let (_temp, state_mgr) = setup_test_state_manager();
        let result = execute(Some("states".to_string()), &state_mgr);
        assert!(result.is_ok());
    }

    #[test]
    fn test_execute_fields() {
        let (_temp, state_mgr) = setup_test_state_manager();
        let result = execute(Some("fields".to_string()), &state_mgr);
        assert!(result.is_ok());
    }

    #[test]
    fn test_execute_config() {
        let (_temp, state_mgr) = setup_test_state_manager();
        let result = execute(Some("config".to_string()), &state_mgr);
        assert!(result.is_ok());
    }

    #[test]
    fn test_execute_stats() {
        let (_temp, state_mgr) = setup_test_state_manager();
        let result = execute(Some("stats".to_string()), &state_mgr);
        assert!(result.is_ok());
    }

    #[test]
    fn test_execute_dirs() {
        let (_temp, state_mgr) = setup_test_state_manager();
        let result = execute(Some("dirs".to_string()), &state_mgr);
        assert!(result.is_ok());
    }

    #[test]
    fn test_show_overview_executes() {
        let (_temp, state_mgr) = setup_test_state_manager();
        let result = show_overview(&state_mgr);
        assert!(result.is_ok());
    }

    #[test]
    fn test_show_states_executes() {
        let result = show_states();
        assert!(result.is_ok());
    }

    #[test]
    fn test_show_fields_executes() {
        let result = show_fields();
        assert!(result.is_ok());
    }

    #[test]
    fn test_show_config_executes() {
        let (_temp, state_mgr) = setup_test_state_manager();
        let result = show_config(&state_mgr);
        assert!(result.is_ok());
    }

    #[test]
    fn test_show_stats_executes() {
        let (_temp, state_mgr) = setup_test_state_manager();
        let result = show_stats(&state_mgr);
        assert!(result.is_ok());
    }

    #[test]
    fn test_show_dirs_executes() {
        let (_temp, state_mgr) = setup_test_state_manager();
        let result = show_dirs(&state_mgr);
        assert!(result.is_ok());
    }

    #[test]
    fn test_show_stats_with_documents() {
        let (temp, mut state_mgr) = setup_test_state_manager();

        // Create a test document
        let doc_path = temp.path().join("01-draft/0001-test.md");
        fs::write(
            &doc_path,
            r#"---
number: 1
title: Test Document
state: Draft
created: 2024-01-01
updated: 2024-01-01
author: Test Author
---

# Test Document
"#,
        )
        .unwrap();

        // Scan to pick up the document
        state_mgr.quick_scan().unwrap();

        // Should execute without error and show stats
        let result = show_stats(&state_mgr);
        assert!(result.is_ok());
    }

    #[test]
    fn test_show_dirs_with_documents() {
        let (temp, mut state_mgr) = setup_test_state_manager();

        // Create a test document
        let doc_path = temp.path().join("01-draft/0001-test.md");
        fs::write(
            &doc_path,
            r#"---
number: 1
title: Test Document
state: Draft
created: 2024-01-01
updated: 2024-01-01
author: Test Author
---

# Test Document
"#,
        )
        .unwrap();

        // Scan to pick up the document
        state_mgr.quick_scan().unwrap();

        // Should execute without error and show directory structure
        let result = show_dirs(&state_mgr);
        assert!(result.is_ok());
    }

    #[test]
    fn test_show_overview_with_documents() {
        let (temp, mut state_mgr) = setup_test_state_manager();

        // Create multiple test documents in different states
        fs::create_dir_all(temp.path().join("02-under-review")).unwrap();

        let doc1 = temp.path().join("01-draft/0001-first.md");
        fs::write(
            &doc1,
            r#"---
number: 1
title: First Document
state: Draft
created: 2024-01-01
updated: 2024-01-01
author: Test Author
---

# First Document
"#,
        )
        .unwrap();

        let doc2 = temp.path().join("02-under-review/0002-second.md");
        fs::write(
            &doc2,
            r#"---
number: 2
title: Second Document
state: Under Review
created: 2024-01-02
updated: 2024-01-02
author: Test Author
---

# Second Document
"#,
        )
        .unwrap();

        // Scan to pick up the documents
        state_mgr.quick_scan().unwrap();

        // Should execute without error and show overview with counts
        let result = show_overview(&state_mgr);
        assert!(result.is_ok());
    }

    #[test]
    fn test_info_command_clone() {
        let cmd = InfoCommand::Overview;
        let cloned = cmd.clone();
        assert!(matches!(cloned, InfoCommand::Overview));
    }

    #[test]
    fn test_info_command_debug() {
        let cmd = InfoCommand::States;
        let debug_str = format!("{:?}", cmd);
        assert!(debug_str.contains("States"));
    }

    #[test]
    fn test_info_command_from_str_tags() {
        let cmd = InfoCommand::from_str(Some("tags"));
        assert!(matches!(cmd, InfoCommand::Tags));
    }

    #[test]
    fn test_info_command_from_str_components() {
        let cmd = InfoCommand::from_str(Some("components"));
        assert!(matches!(cmd, InfoCommand::Components));
    }

    #[test]
    fn test_execute_tags() {
        let (_temp, state_mgr) = setup_test_state_manager();
        let result = execute(Some("tags".to_string()), &state_mgr);
        assert!(result.is_ok());
    }

    #[test]
    fn test_execute_components() {
        let (_temp, state_mgr) = setup_test_state_manager();
        let result = execute(Some("components".to_string()), &state_mgr);
        assert!(result.is_ok());
    }

    #[test]
    fn test_show_tags_executes() {
        let (_temp, state_mgr) = setup_test_state_manager();
        let result = show_tags(&state_mgr);
        assert!(result.is_ok());
    }

    #[test]
    fn test_show_components_executes() {
        let (_temp, state_mgr) = setup_test_state_manager();
        let result = show_components(&state_mgr);
        assert!(result.is_ok());
    }

    #[test]
    fn test_show_tags_with_documents() {
        let (temp, mut state_mgr) = setup_test_state_manager();

        // Create documents with tags
        let doc_path = temp.path().join("01-draft/0001-test.md");
        fs::write(
            &doc_path,
            r#"---
number: 1
title: Test Document
state: Draft
created: 2024-01-01
updated: 2024-01-01
author: Test Author
tags: [Phase-0, Research]
---

# Test Document
"#,
        )
        .unwrap();

        state_mgr.quick_scan().unwrap();

        let result = show_tags(&state_mgr);
        assert!(result.is_ok());
    }

    #[test]
    fn test_show_components_with_documents() {
        let (temp, mut state_mgr) = setup_test_state_manager();

        // Create documents with components
        let doc_path = temp.path().join("01-draft/0001-test.md");
        fs::write(
            &doc_path,
            r#"---
number: 1
title: Test Document
state: Draft
created: 2024-01-01
updated: 2024-01-01
author: Test Author
component: REPL
---

# Test Document
"#,
        )
        .unwrap();

        state_mgr.quick_scan().unwrap();

        let result = show_components(&state_mgr);
        assert!(result.is_ok());
    }
}