tbdflow 0.34.0

A CLI to streamline your Git workflow for Trunk-Based 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
use crate::config::{Config, ReviewLabelsConfig, ReviewStrategy};
use crate::git::{self, RunOpts};
use anyhow::{Context, Result};
use colored::Colorize;
use glob::Pattern;
use serde_json::Value;
use std::process::Command;

fn short_hash(hash: &str) -> &str {
    &hash[..7.min(hash.len())]
}

/// Returns true if any review rule patterns match the files changed in this commit.
pub fn should_auto_trigger_review(
    config: &Config,
    commit_hash: &str,
    opts: RunOpts,
) -> Result<bool> {
    if !config.review.enabled || config.review.rules.is_empty() {
        return Ok(false);
    }

    let touched_files = git::get_changed_files(commit_hash, opts)?;

    for rule in &config.review.rules {
        if let Ok(pattern) = Pattern::new(&rule.pattern) {
            if touched_files.iter().any(|f| pattern.matches(f)) {
                if opts.verbose {
                    println!(
                        "{} Auto-trigger: files match rule pattern '{}'",
                        "[REVIEW]".magenta(),
                        rule.pattern
                    );
                }
                return Ok(true);
            }
        }
    }

    Ok(false)
}

pub fn trigger_review(
    config: &Config,
    reviewers_override: Option<&[String]>,
    commit_hash: &str,
    message: &str,
    author: &str,
    opts: RunOpts,
) -> Result<()> {
    if !config.review.enabled {
        if opts.verbose {
            println!("{}", "Review system is disabled in config.".dimmed());
        }
        return Ok(());
    }

    // Identify which rules apply based on touched files
    let touched_files = git::get_changed_files(commit_hash, opts)?;
    let mut applicable_reviewers: Vec<String> = Vec::new();
    let mut is_targeted = false;

    for rule in &config.review.rules {
        if let Ok(pattern) = Pattern::new(&rule.pattern) {
            let matched = touched_files.iter().any(|f| pattern.matches(f));
            if matched {
                if opts.verbose {
                    println!(
                        "{} File match for rule: {}",
                        "[RULE]".magenta(),
                        rule.pattern.dimmed()
                    );
                }
                is_targeted = true;
                if let Some(rule_reviewers) = &rule.reviewers {
                    applicable_reviewers.extend(rule_reviewers.clone());
                }
            }
        }
    }

    let mut final_reviewers = if let Some(ovr) = reviewers_override {
        ovr.to_vec()
    } else if !applicable_reviewers.is_empty() {
        applicable_reviewers
    } else {
        config.review.default_reviewers.clone()
    };

    final_reviewers.sort();
    final_reviewers.dedup();

    println!("{}", "--- Triggering Non-blocking Review ---".blue());
    if is_targeted {
        println!("{} Review triggered by targeted file rules.", ">>".yellow());
    }

    let short = short_hash(commit_hash);
    println!(
        "{} {} ({})",
        "Review requested for:".green(),
        message.bold(),
        short.dimmed()
    );
    println!("   Author: {}", author);
    if !final_reviewers.is_empty() {
        println!("   Reviewers: {}", final_reviewers.join(", "));
    }

    if opts.dry_run {
        println!("{}", "[DRY RUN] Would create review request".yellow());
        return Ok(());
    }

    match &config.review.strategy {
        ReviewStrategy::GithubIssue => {
            create_github_issue(
                &config.review.labels,
                &final_reviewers,
                commit_hash,
                message,
                author,
                opts,
            )?;
        }
        ReviewStrategy::GithubWorkflow => {
            trigger_github_workflow(config, commit_hash, message, author, &final_reviewers, opts)?;
        }
        ReviewStrategy::LogOnly => {
            println!(
                "{}",
                "Review logged (no external system integration)".dimmed()
            );
        }
    }

    Ok(())
}

fn trigger_github_workflow(
    config: &Config,
    commit_hash: &str,
    message: &str,
    author: &str,
    reviewers: &[String],
    opts: RunOpts,
) -> Result<()> {
    if !is_gh_cli_available() {
        println!(
            "{}",
            "Warning: GitHub CLI (gh) not found. Install it to trigger workflows.".yellow()
        );
        println!(
            "{}",
            "Install: https://cli.github.com/ or 'brew install gh'".dimmed()
        );
        return Ok(());
    }

    let workflow_name = config
        .review
        .workflow
        .as_deref()
        .unwrap_or("nbr-review.yml");

    let short = short_hash(commit_hash);

    if opts.verbose {
        println!(
            "{} Triggering workflow '{}' for commit {}",
            "[INFO]".cyan(),
            workflow_name,
            short
        );
    }

    // Build workflow inputs as JSON
    let reviewers_json = reviewers.join(",");

    let output = Command::new("gh")
        .args([
            "workflow",
            "run",
            workflow_name,
            "-f",
            &format!("commit_sha={}", commit_hash),
            "-f",
            &format!("commit_message={}", message),
            "-f",
            &format!("author={}", author),
            "-f",
            &format!("reviewers={}", reviewers_json),
        ])
        .output()
        .context("Failed to trigger GitHub workflow")?;

    if output.status.success() {
        println!(
            "{}",
            format!(
                "Workflow '{}' triggered for commit {}",
                workflow_name, short
            )
            .green()
        );
        println!(
            "{}",
            "   Server-side review management is now active.".dimmed()
        );
        println!(
            "{}",
            "   Check GitHub Actions for issue creation and status updates.".dimmed()
        );
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        if stderr.contains("could not find any workflows") {
            println!(
                "{}",
                format!(
                    "Warning: Workflow '{}' not found in repository.",
                    workflow_name
                )
                .yellow()
            );
            println!(
                "{}",
                "   Create the workflow file at .github/workflows/ to enable server-side reviews."
                    .dimmed()
            );
            println!(
                "{}",
                "   Falling back to client-side issue creation...".dimmed()
            );
            // Fallback to client-side issue creation
            create_github_issue(
                &config.review.labels,
                reviewers,
                commit_hash,
                message,
                author,
                opts,
            )?;
        } else {
            println!(
                "{}",
                format!("Warning: Failed to trigger workflow: {}", stderr.trim()).yellow()
            );
        }
    }

    Ok(())
}

fn create_github_issue(
    labels: &ReviewLabelsConfig,
    reviewers: &[String],
    commit_hash: &str,
    message: &str,
    author: &str,
    opts: RunOpts,
) -> Result<()> {
    let short = short_hash(commit_hash);

    // Check if gh CLI is available
    if !is_gh_cli_available() {
        println!(
            "{}",
            "Warning: GitHub CLI (gh) not found. Install it to enable GitHub issue creation."
                .yellow()
        );
        println!(
            "{}",
            "Install: https://cli.github.com/ or 'brew install gh'".dimmed()
        );
        return Ok(());
    }

    // Ensure all review labels exist (create if missing)
    ensure_review_labels_exist(labels, opts);

    // Get the repository URL for commit links
    let repo_url = git::get_remote_url(opts).unwrap_or_default();
    let commit_url = if repo_url.is_empty() {
        format!("`{}`", commit_hash)
    } else {
        format!("[`{}`]({}/commit/{})", short, repo_url, commit_hash)
    };

    let title = format!("[Review] {} ({})", message, short);
    let body = format!(
        "## Non-blocking Review Request\n\n\
        **Commit:** {}\n\
        **Author:** {}\n\
        **Message:** {}\n\n\
        ---\n\n\
        > In Trunk-Based Development, this code is already in the trunk.\n\
        > Your goal is **Course Correction** and **Knowledge Sharing**, not gatekeeping.\n\n\
        ### What to Look For\n\n\
        | Focus | Question |\n\
        |-------|----------|\n\
        | **Design & Intent** | Does the implementation align with our architectural patterns? |\n\
        | **Logic & Edge Cases** | Are there logical flaws or unhappy paths that tests might miss? |\n\
        | **Readability** | Are names descriptive? (Code as Documentation) |\n\
        | **Simplification** | Can this be done with less code or lower complexity? |\n\n\
        ### How to Comment\n\n\
        - **Questions > Commands**: _\"Could we use the existing helper here?\"_ instead of _\"Change this.\"_\n\
        - **Praise**: If you see something clever or clean, say so! NBR boosts team morale.\n\
        - **Nitpicking**: Label minor style issues as `(nit)` so the author knows they're optional.\n\n\
        ### Concerns\n\n\
        _No concerns raised yet._\n\n\
        ---\n\n\
        To approve via CLI:\n\
        ```\n\
        tbdflow review --approve {}\n\
        ```\n\n\
        To raise a concern:\n\
        ```\n\
        tbdflow review --concern {} -m \"Your concern here\"\n\
        ```",
        commit_url, author, message, short, short
    );

    let mut args = vec!["issue", "create", "--title", &title, "--body", &body];

    // Add the pending label
    if label_exists(&labels.pending) {
        args.push("--label");
        args.push(&labels.pending);
    }

    // Add assignees if configured
    let assignees: Vec<&str> = reviewers.iter().map(String::as_str).collect();
    let assignees_str = assignees.join(",");
    if !assignees.is_empty() {
        args.push("--assignee");
        args.push(&assignees_str);
    }

    if opts.verbose {
        println!("{} gh {}", "[RUNNING]".cyan(), args.join(" "));
    }

    let output = Command::new("gh")
        .args(&args)
        .output()
        .context("Failed to execute 'gh' CLI")?;

    if output.status.success() {
        let issue_url = String::from_utf8_lossy(&output.stdout).trim().to_string();
        println!("{} {}", "Review issue created:".green(), issue_url);
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        println!(
            "{}",
            format!("Warning: Failed to create GitHub issue: {}", stderr).yellow()
        );
    }

    Ok(())
}

fn label_exists(label_name: &str) -> bool {
    Command::new("gh")
        .args(["label", "list", "--search", label_name, "--json", "name"])
        .output()
        .map(|o| {
            o.status.success()
                && String::from_utf8_lossy(&o.stdout)
                    .contains(&format!("\"name\":\"{}\"", label_name))
        })
        .unwrap_or(false)
}

fn ensure_label_exists(label_name: &str, description: &str, color: &str, opts: RunOpts) {
    if label_exists(label_name) {
        return;
    }

    if opts.verbose {
        println!("{} Creating '{}' label...", "[INFO]".cyan(), label_name);
    }

    let result = Command::new("gh")
        .args([
            "label",
            "create",
            label_name,
            "--description",
            description,
            "--color",
            color,
        ])
        .output();

    match result {
        Ok(output) if output.status.success() => {
            if opts.verbose {
                println!("{} Created '{}' label", "[INFO]".cyan(), label_name);
            }
        }
        _ => {
            // Silently continue - label creation may fail due to permissions
            // The issue will still be created, just without the label
        }
    }
}

fn ensure_review_labels_exist(labels: &ReviewLabelsConfig, opts: RunOpts) {
    ensure_label_exists(
        &labels.pending,
        "Review pending - awaiting attention",
        "FBCA04", // Yellow
        opts,
    );
    ensure_label_exists(
        &labels.concern,
        "Review concern raised - needs attention",
        "D93F0B", // Red-orange
        opts,
    );
    ensure_label_exists(
        &labels.accepted,
        "Review accepted/approved",
        "0E8A16", // Green
        opts,
    );
    ensure_label_exists(
        &labels.dismissed,
        "Review dismissed - won't fix",
        "6A737D", // Gray
        opts,
    );
}

fn is_gh_cli_available() -> bool {
    git::is_gh_cli_available()
}

pub fn handle_review_trigger(
    config: &Config,
    reviewers_override: Option<Vec<String>>,
    commit_sha: Option<&str>,
    opts: RunOpts,
) -> Result<()> {
    if !config.review.enabled {
        println!(
            "{}",
            "Review system is not enabled. Add the following to your .tbdflow.yml:".yellow()
        );
        println!("\n  review:");
        println!("    enabled: true");
        println!("    strategy: github-issue");
        println!("    default_reviewers:");
        println!("      - teammate-username\n");
        return Ok(());
    }

    let commit_hash = match commit_sha {
        Some(sha) if !sha.is_empty() => {
            // Resolve the provided SHA to a full hash
            let full = git::resolve_commit_hash(sha, opts)?;
            if opts.verbose {
                println!(
                    "{} Triggering review for commit {}",
                    "[REVIEW]".magenta(),
                    short_hash(&full)
                );
            }
            full
        }
        _ => git::get_head_commit_hash(opts)?,
    };
    let message = git::get_commit_message(&commit_hash, opts)?;
    let author = git::get_user_name(opts)?;

    trigger_review(
        config,
        reviewers_override.as_deref(),
        &commit_hash,
        &message,
        &author,
        opts,
    )
}

pub fn handle_review_digest(config: &Config, since: &str, opts: RunOpts) -> Result<()> {
    println!(
        "{}",
        format!("--- Trunk Evolution Digest (Since {}) ---", since).blue()
    );

    let log = git::get_log_since(since, opts)?;

    if log.is_empty() {
        println!(
            "{}",
            "No new commits found in the specified time range.".yellow()
        );
        return Ok(());
    }

    println!("\n{}", "COMMITS FOR REVIEW".cyan().bold());
    println!("{}", "─".repeat(50).cyan());

    for line in log.lines() {
        if line.is_empty() {
            continue;
        }
        let parts: Vec<&str> = line.splitn(3, '|').collect();
        if parts.len() >= 2 {
            let hash = short_hash(parts[0]);
            let author = parts.get(1).unwrap_or(&"unknown");
            let message = parts.get(2).unwrap_or(&"");
            println!(
                "  {} {} {}",
                hash.yellow(),
                format!("({})", author).dimmed(),
                message
            );
        }
    }

    println!("{}", "─".repeat(50).cyan());

    if !config.review.default_reviewers.is_empty() {
        println!(
            "\n{}",
            format!(
                "Default reviewers: {}",
                config.review.default_reviewers.join(", ")
            )
            .dimmed()
        );
    }

    println!("\n{}", "Next steps:".bold());
    println!("   • Review commits above and discuss with the team");
    println!("   • Run 'tbdflow review --approve <hash>' to mark as reviewed");
    println!("   • Run 'tbdflow review --trigger' to create review issues\n");

    Ok(())
}

pub fn handle_review_approve(config: &Config, commit_hash: &str, opts: RunOpts) -> Result<()> {
    let short = short_hash(commit_hash);

    println!("{}", format!("--- Approving Commit {} ---", short).blue());

    if opts.dry_run {
        println!("{}", "[DRY RUN] Would mark commit as approved".yellow());
        return Ok(());
    }

    match &config.review.strategy {
        ReviewStrategy::GithubIssue => {
            close_github_review_issue(&config.review.labels, short, opts)?;
        }
        ReviewStrategy::GithubWorkflow => {
            // For workflow strategy, close the issue which will trigger
            // the server-side Action to update commit status
            close_github_review_issue(&config.review.labels, short, opts)?;
            println!(
                "{}",
                "   Server-side workflow will update commit status.".dimmed()
            );
        }
        ReviewStrategy::LogOnly => {
            println!("{}", format!("Commit {} marked as approved", short).green());
        }
    }

    Ok(())
}

pub fn handle_review_concern(
    config: &Config,
    commit_hash: &str,
    message: &str,
    opts: RunOpts,
) -> Result<()> {
    let short = short_hash(commit_hash);

    println!(
        "{}",
        format!("--- Raising Concern on Commit {} ---", short).blue()
    );

    if opts.dry_run {
        println!("{}", "[DRY RUN] Would raise concern on commit".yellow());
        return Ok(());
    }

    match &config.review.strategy {
        ReviewStrategy::GithubIssue | ReviewStrategy::GithubWorkflow => {
            raise_github_concern(config, commit_hash, message, opts)?;
        }
        ReviewStrategy::LogOnly => {
            println!("{}", format!("CONCERN on {}: {}", short, message).yellow());
        }
    }

    Ok(())
}

pub fn handle_review_dismiss(
    config: &Config,
    commit_hash: &str,
    message: &str,
    opts: RunOpts,
) -> Result<()> {
    let short = short_hash(commit_hash);

    println!(
        "{}",
        format!("--- Dismissing Review for Commit {} ---", short).blue()
    );

    if opts.dry_run {
        println!("{}", "[DRY RUN] Would dismiss review".yellow());
        return Ok(());
    }

    match &config.review.strategy {
        ReviewStrategy::GithubIssue | ReviewStrategy::GithubWorkflow => {
            dismiss_github_review_issue(&config.review.labels, short, message, opts)?;
        }
        ReviewStrategy::LogOnly => {
            println!(
                "{}",
                format!("Review for {} dismissed: {}", short, message).dimmed()
            );
        }
    }

    Ok(())
}

fn raise_github_concern(
    config: &Config,
    commit_hash: &str,
    message: &str,
    opts: RunOpts,
) -> Result<()> {
    let short = short_hash(commit_hash);
    let labels = &config.review.labels;

    if !is_gh_cli_available() {
        println!(
            "{}",
            "Warning: GitHub CLI (gh) not found. Cannot raise concern.".yellow()
        );
        return Ok(());
    }

    // Search for the review issue
    let search_query = format!("[Review] in:title {} in:title is:open", short);

    if opts.verbose {
        println!("{} Searching for review issue...", "[INFO]".cyan());
    }

    let output = Command::new("gh")
        .args([
            "issue",
            "list",
            "--search",
            &search_query,
            "--json",
            "number,body",
            "--limit",
            "1",
        ])
        .output()
        .context("Failed to search for GitHub issues")?;

    if !output.status.success() {
        println!(
            "{}",
            format!("Warning: Could not find review issue for {}", short).yellow()
        );
        return Ok(());
    }

    let json_output = String::from_utf8_lossy(&output.stdout);

    if let Some(issue_num) = extract_issue_number(&json_output) {
        let issue_num_str = issue_num.to_string();

        // Update labels: remove pending, add concern
        if opts.verbose {
            println!(
                "{} Updating labels on issue #{}",
                "[INFO]".cyan(),
                issue_num
            );
        }

        let _ = Command::new("gh")
            .args([
                "issue",
                "edit",
                &issue_num_str,
                "--remove-label",
                &labels.pending,
            ])
            .output();

        let _ = Command::new("gh")
            .args([
                "issue",
                "edit",
                &issue_num_str,
                "--add-label",
                &labels.concern,
            ])
            .output();

        // Add a comment with the concern
        let comment = format!("**Concern Raised**\n\n{}", message);

        let _ = Command::new("gh")
            .args(["issue", "comment", &issue_num_str, "--body", &comment])
            .output();

        // Append checklist item to the issue body
        append_concern_checklist_item(&issue_num_str, message, opts)?;

        // Set commit status based on config
        set_commit_status(config, commit_hash, message, opts)?;

        println!(
            "{}",
            format!(
                "Concern raised on issue #{} for commit {} (label: {})",
                issue_num, short, labels.concern
            )
            .yellow()
        );
    } else {
        println!(
            "{}",
            format!("Warning: No open review issue found for commit {}", short).yellow()
        );
        println!("   Run 'tbdflow review --trigger' first to create the review issue.");
    }

    Ok(())
}

fn append_concern_checklist_item(
    issue_num: &str,
    concern_message: &str,
    opts: RunOpts,
) -> Result<()> {
    // Get current issue body
    let output = Command::new("gh")
        .args(["issue", "view", issue_num, "--json", "body"])
        .output()
        .context("Failed to get issue body")?;

    if !output.status.success() {
        return Ok(());
    }

    let json_output = String::from_utf8_lossy(&output.stdout);

    // Extract the body content
    let current_body = extract_body_from_json(&json_output).unwrap_or_default();

    // Replace the "No concerns raised yet" placeholder or append to concerns section
    let new_body = if current_body.contains("_No concerns raised yet._") {
        current_body.replace(
            "_No concerns raised yet._",
            &format!("- [ ] {}", concern_message),
        )
    } else if current_body.contains("### Concerns") {
        // Find the concerns section and append the new item
        let concerns_marker = "### Concerns\n\n";
        if let Some(pos) = current_body.find(concerns_marker) {
            let insert_pos = pos + concerns_marker.len();
            let (before, after) = current_body.split_at(insert_pos);
            format!("{}- [ ] {}\n{}", before, concern_message, after)
        } else {
            current_body
        }
    } else {
        current_body
    };

    if opts.verbose {
        println!(
            "{} Updating issue body with concern checklist item",
            "[INFO]".cyan()
        );
    }

    let _ = Command::new("gh")
        .args(["issue", "edit", issue_num, "--body", &new_body])
        .output();

    Ok(())
}

fn extract_body_from_json(json: &str) -> Option<String> {
    let parsed: Value = serde_json::from_str(json).ok()?;
    parsed["body"].as_str().map(|s| s.to_string())
}

fn set_commit_status(
    config: &Config,
    commit_hash: &str,
    message: &str,
    opts: RunOpts,
) -> Result<()> {
    if !is_gh_cli_available() {
        return Ok(());
    }

    let (state, description) = if config.review.concern_blocks_status {
        ("failure", format!("Audit Concern: {}", message))
    } else {
        (
            "pending",
            format!("Awaiting fix-forward for concern: {}", message),
        )
    };

    // Get repo owner/name
    let repo_info = Command::new("gh")
        .args(["repo", "view", "--json", "owner,name"])
        .output();

    let repo = match repo_info {
        Ok(output) if output.status.success() => {
            let json = String::from_utf8_lossy(&output.stdout);
            extract_repo_from_json(&json)
        }
        _ => return Ok(()),
    };

    let Some((owner, name)) = repo else {
        return Ok(());
    };

    if opts.verbose {
        println!(
            "{} Setting commit status to '{}' for {}",
            "[INFO]".cyan(),
            state,
            short_hash(commit_hash)
        );
    }

    let api_path = format!("repos/{}/{}/statuses/{}", owner, name, commit_hash);

    let _ = Command::new("gh")
        .args([
            "api",
            &api_path,
            "-f",
            &format!("state={}", state),
            "-f",
            "context=peer-review",
            "-f",
            &format!("description={}", description),
        ])
        .output();

    Ok(())
}

fn extract_repo_from_json(json: &str) -> Option<(String, String)> {
    let parsed: Value = serde_json::from_str(json).ok()?;
    let owner = parsed["owner"]["login"].as_str()?.to_string();
    let name = parsed["name"].as_str()?.to_string();
    Some((owner, name))
}

fn dismiss_github_review_issue(
    labels: &ReviewLabelsConfig,
    short_hash: &str,
    message: &str,
    opts: RunOpts,
) -> Result<()> {
    if !is_gh_cli_available() {
        println!(
            "{}",
            "Warning: GitHub CLI (gh) not found. Cannot dismiss review.".yellow()
        );
        return Ok(());
    }

    // Search for the review issue
    let search_query = format!("[Review] in:title {} in:title is:open", short_hash);

    if opts.verbose {
        println!("{} Searching for review issue...", "[INFO]".cyan());
    }

    let output = Command::new("gh")
        .args([
            "issue",
            "list",
            "--search",
            &search_query,
            "--json",
            "number",
            "--limit",
            "1",
        ])
        .output()
        .context("Failed to search for GitHub issues")?;

    if output.status.success() {
        let json_output = String::from_utf8_lossy(&output.stdout);

        if let Some(issue_num) = extract_issue_number(&json_output) {
            let issue_num_str = issue_num.to_string();

            // Update labels: remove pending/concern, add dismissed
            if opts.verbose {
                println!(
                    "{} Updating labels on issue #{}",
                    "[INFO]".cyan(),
                    issue_num
                );
            }

            let _ = Command::new("gh")
                .args([
                    "issue",
                    "edit",
                    &issue_num_str,
                    "--remove-label",
                    &labels.pending,
                ])
                .output();

            let _ = Command::new("gh")
                .args([
                    "issue",
                    "edit",
                    &issue_num_str,
                    "--remove-label",
                    &labels.concern,
                ])
                .output();

            let _ = Command::new("gh")
                .args([
                    "issue",
                    "edit",
                    &issue_num_str,
                    "--add-label",
                    &labels.dismissed,
                ])
                .output();

            // Close with a comment
            let comment = format!(
                "**Dismissed** via `tbdflow review --dismiss`\n\nReason: {}",
                message
            );

            let close_output = Command::new("gh")
                .args(["issue", "close", &issue_num_str, "--comment", &comment])
                .output()
                .context("Failed to close GitHub issue")?;

            if close_output.status.success() {
                println!(
                    "{}",
                    format!(
                        "Review for commit {} dismissed and issue #{} closed (label: {})",
                        short_hash, issue_num, labels.dismissed
                    )
                    .dimmed()
                );
            } else {
                println!(
                    "{}",
                    "Review dismissed (issue close failed)".to_string().yellow()
                );
            }
        } else {
            println!(
                "{}",
                format!(
                    "Review for {} dismissed (no open review issue found)",
                    short_hash
                )
                .dimmed()
            );
        }
    } else {
        println!(
            "{}",
            format!("Review for {} dismissed", short_hash).dimmed()
        );
    }

    Ok(())
}

fn close_github_review_issue(
    labels: &ReviewLabelsConfig,
    short_hash: &str,
    opts: RunOpts,
) -> Result<()> {
    if !is_gh_cli_available() {
        println!(
            "{}",
            "Warning: GitHub CLI (gh) not found. Marking as approved locally only.".yellow()
        );
        println!("{}", format!("Commit {} approved", short_hash).green());
        return Ok(());
    }

    // Search for the review issue
    let search_query = format!("[Review] in:title {} in:title is:open", short_hash);

    if opts.verbose {
        println!("{} Searching for review issue...", "[INFO]".cyan());
    }

    let output = Command::new("gh")
        .args([
            "issue",
            "list",
            "--search",
            &search_query,
            "--json",
            "number",
            "--limit",
            "1",
        ])
        .output()
        .context("Failed to search for GitHub issues")?;

    if output.status.success() {
        let json_output = String::from_utf8_lossy(&output.stdout);

        // Simple JSON parsing for issue number
        if let Some(issue_num) = extract_issue_number(&json_output) {
            let issue_num_str = issue_num.to_string();

            // Remove pending/concern labels and add accepted label
            if opts.verbose {
                println!(
                    "{} Updating labels on issue #{}",
                    "[INFO]".cyan(),
                    issue_num
                );
            }

            let _ = Command::new("gh")
                .args([
                    "issue",
                    "edit",
                    &issue_num_str,
                    "--remove-label",
                    &labels.pending,
                ])
                .output();

            let _ = Command::new("gh")
                .args([
                    "issue",
                    "edit",
                    &issue_num_str,
                    "--remove-label",
                    &labels.concern,
                ])
                .output();

            let _ = Command::new("gh")
                .args([
                    "issue",
                    "edit",
                    &issue_num_str,
                    "--add-label",
                    &labels.accepted,
                ])
                .output();

            if opts.verbose {
                println!("{} Closing issue #{}", "[INFO]".cyan(), issue_num);
            }

            let close_output = Command::new("gh")
                .args([
                    "issue",
                    "close",
                    &issue_num_str,
                    "--comment",
                    "Approved via `tbdflow review --approve`",
                ])
                .output()
                .context("Failed to close GitHub issue")?;

            if close_output.status.success() {
                println!(
                    "{}",
                    format!(
                        "Commit {} approved and review issue #{} closed (label: {})",
                        short_hash, issue_num, labels.accepted
                    )
                    .green()
                );
            } else {
                println!(
                    "{}",
                    format!("Commit {} approved (issue close failed)", short_hash).yellow()
                );
            }
        } else {
            println!(
                "{}",
                format!(
                    "Commit {} approved (no open review issue found)",
                    short_hash
                )
                .green()
            );
        }
    } else {
        println!("{}", format!("Commit {} approved", short_hash).green());
    }

    Ok(())
}

fn extract_issue_number(json: &str) -> Option<i64> {
    let parsed: Value = serde_json::from_str(json).ok()?;
    parsed.as_array()?.first()?["number"].as_i64()
}

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

    #[test]
    fn short_hash_returns_first_seven_chars() {
        assert_eq!(short_hash("abc1234567890"), "abc1234");
    }

    #[test]
    fn short_hash_handles_exact_seven_chars() {
        assert_eq!(short_hash("abc1234"), "abc1234");
    }

    #[test]
    fn short_hash_handles_short_input() {
        assert_eq!(short_hash("abc"), "abc");
    }

    #[test]
    fn short_hash_handles_empty_input() {
        assert_eq!(short_hash(""), "");
    }

    #[test]
    fn extract_issue_number_parses_valid_json() {
        let json = r#"[{"number":123}]"#;
        assert_eq!(extract_issue_number(json), Some(123));
    }

    #[test]
    fn extract_issue_number_parses_larger_number() {
        let json = r#"[{"number":98765}]"#;
        assert_eq!(extract_issue_number(json), Some(98765));
    }

    #[test]
    fn extract_issue_number_returns_none_for_empty_array() {
        let json = r#"[]"#;
        assert_eq!(extract_issue_number(json), None);
    }

    #[test]
    fn extract_issue_number_returns_none_for_invalid_json() {
        let json = r#"not json"#;
        assert_eq!(extract_issue_number(json), None);
    }

    #[test]
    fn extract_issue_number_handles_whitespace() {
        let json = r#"[{"number": 42}]"#;
        assert_eq!(extract_issue_number(json), Some(42));
    }
}