omni-dev 0.23.1

A powerful Git commit message analysis and amendment toolkit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
//! Create PR command — AI-powered pull request creation.

use anyhow::{Context, Result};
use clap::Parser;
use tracing::{debug, error};

use super::info::InfoCommand;

/// Create PR command options.
#[derive(Parser)]
pub struct CreatePrCommand {
    /// Base branch for the PR to be merged into (defaults to main/master).
    #[arg(long, value_name = "BRANCH")]
    pub base: Option<String>,

    /// Claude API model to use (if not specified, uses settings or default).
    #[arg(long)]
    pub model: Option<String>,

    /// Skips confirmation prompt and creates PR automatically.
    #[arg(long)]
    pub auto_apply: bool,

    /// Saves generated PR details to file without creating PR.
    #[arg(long, value_name = "FILE")]
    pub save_only: Option<String>,

    /// Creates PR as ready for review (overrides default).
    #[arg(long, conflicts_with = "draft")]
    pub ready: bool,

    /// Creates PR as draft (overrides default).
    #[arg(long, conflicts_with = "ready")]
    pub draft: bool,

    /// Path to custom context directory (defaults to .omni-dev/).
    #[arg(long)]
    pub context_dir: Option<std::path::PathBuf>,

    /// Skip pushing the branch to remote before creating the PR.
    #[arg(long)]
    pub no_push: bool,
}

/// PR action choices.
#[derive(Debug, PartialEq)]
enum PrAction {
    CreateNew,
    UpdateExisting,
    Cancel,
}

/// AI-generated PR content with structured fields.
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct PrContent {
    /// Concise PR title (ideally 50-80 characters).
    pub title: String,
    /// Full PR description in markdown format.
    pub description: String,
}

impl CreatePrCommand {
    /// Determines if the PR should be created as draft.
    ///
    /// Priority order:
    /// 1. --ready flag (not draft)
    /// 2. --draft flag (draft)
    /// 3. OMNI_DEV_DEFAULT_DRAFT_PR env/config setting
    /// 4. Hard-coded default (draft)
    fn should_create_as_draft(&self) -> bool {
        use crate::utils::settings::get_env_var;

        // Explicit flags take precedence
        if self.ready {
            return false;
        }
        if self.draft {
            return true;
        }

        // Check configuration setting
        get_env_var("OMNI_DEV_DEFAULT_DRAFT_PR")
            .ok()
            .and_then(|val| parse_bool_string(&val))
            .unwrap_or(true) // Default to draft if not configured
    }

    /// Executes the create PR command.
    pub async fn execute(self) -> Result<()> {
        // Preflight check: validate all prerequisites before any processing
        // This catches missing credentials/tools early before wasting time
        let ai_info = crate::utils::check_pr_command_prerequisites(self.model.as_deref())?;
        println!(
            "{} credentials verified (model: {})",
            ai_info.provider, ai_info.model
        );
        println!("✓ GitHub CLI verified");

        println!("🔄 Starting pull request creation process...");

        // 1. Generate repository view (reuse InfoCommand logic)
        let repo_view = self.generate_repository_view()?;

        // 2. Validate branch state (always needed)
        self.validate_branch_state(&repo_view)?;

        // 3. Show guidance files status early (before AI processing)
        use crate::claude::context::ProjectDiscovery;
        let repo_root = std::path::PathBuf::from(".");
        let context_dir = crate::claude::context::resolve_context_dir(self.context_dir.as_deref());
        let discovery = ProjectDiscovery::new(repo_root, context_dir);
        let project_context = discovery.discover().unwrap_or_default();
        self.show_guidance_files_status(&project_context)?;

        // 4. Show AI model configuration before generation
        let claude_client = crate::claude::create_default_claude_client(self.model.clone(), None)?;
        self.show_model_info_from_client(&claude_client)?;

        // 5. Show branch analysis and commit information
        self.show_commit_range_info(&repo_view)?;

        // 6. Show context analysis (quick collection for display only)
        let context = {
            use crate::claude::context::{BranchAnalyzer, FileAnalyzer, WorkPatternAnalyzer};
            use crate::data::context::CommitContext;
            let mut context = CommitContext::new();
            context.project = project_context;

            // Quick analysis for display
            if let Some(branch_info) = &repo_view.branch_info {
                context.branch = BranchAnalyzer::analyze(&branch_info.branch).unwrap_or_default();
            }

            if !repo_view.commits.is_empty() {
                context.range = WorkPatternAnalyzer::analyze_commit_range(&repo_view.commits);
                context.files = FileAnalyzer::analyze_commits(&repo_view.commits);
            }
            context
        };
        self.show_context_summary(&context)?;

        // 7. Generate AI-powered PR content (title + description)
        debug!("About to generate PR content from AI");
        let (pr_content, _claude_client) = self
            .generate_pr_content_with_client_internal(&repo_view, claude_client)
            .await?;

        // 8. Show detailed context information (like twiddle command)
        self.show_context_information(&repo_view).await?;
        debug!(
            generated_title = %pr_content.title,
            generated_description_length = pr_content.description.len(),
            generated_description_preview = %pr_content.description.lines().take(3).collect::<Vec<_>>().join("\\n"),
            "Generated PR content from AI"
        );

        // 5. Handle different output modes
        if let Some(save_path) = self.save_only {
            let pr_yaml = crate::data::to_yaml(&pr_content)
                .context("Failed to serialize PR content to YAML")?;
            std::fs::write(&save_path, &pr_yaml).context("Failed to save PR details to file")?;
            println!("💾 PR details saved to: {save_path}");
            return Ok(());
        }

        // 6. Create temporary file for PR details
        debug!("About to serialize PR content to YAML");
        let temp_dir = tempfile::tempdir()?;
        let pr_file = temp_dir.path().join("pr-details.yaml");

        debug!(
            pre_serialize_title = %pr_content.title,
            pre_serialize_description_length = pr_content.description.len(),
            pre_serialize_description_preview = %pr_content.description.lines().take(3).collect::<Vec<_>>().join("\\n"),
            "About to serialize PR content with to_yaml"
        );

        let pr_yaml =
            crate::data::to_yaml(&pr_content).context("Failed to serialize PR content to YAML")?;

        debug!(
            file_path = %pr_file.display(),
            yaml_content_length = pr_yaml.len(),
            yaml_content = %pr_yaml,
            original_title = %pr_content.title,
            original_description_length = pr_content.description.len(),
            "Writing PR details to temporary YAML file"
        );

        std::fs::write(&pr_file, &pr_yaml)?;

        // 7. Handle PR details file - show path and get user choice
        let pr_action = if self.auto_apply {
            // For auto-apply, default to update if PR exists, otherwise create new
            if repo_view
                .branch_prs
                .as_ref()
                .is_some_and(|prs| !prs.is_empty())
            {
                PrAction::UpdateExisting
            } else {
                PrAction::CreateNew
            }
        } else {
            self.handle_pr_file(&pr_file, &repo_view)?
        };

        if pr_action == PrAction::Cancel {
            println!("❌ PR operation cancelled by user");
            return Ok(());
        }

        // 8. Create or update PR (re-read from file to capture any user edits)
        let final_pr_yaml =
            std::fs::read_to_string(&pr_file).context("Failed to read PR details file")?;

        debug!(
            yaml_length = final_pr_yaml.len(),
            yaml_content = %final_pr_yaml,
            "Read PR details YAML from file"
        );

        let final_pr_content: PrContent = serde_yaml::from_str(&final_pr_yaml)
            .context("Failed to parse PR details YAML. Please check the file format.")?;

        debug!(
            title = %final_pr_content.title,
            description_length = final_pr_content.description.len(),
            description_preview = %final_pr_content.description.lines().take(3).collect::<Vec<_>>().join("\\n"),
            "Parsed PR content from YAML"
        );

        // Determine draft status
        let is_draft = self.should_create_as_draft();

        match pr_action {
            PrAction::CreateNew => {
                self.create_github_pr(
                    &repo_view,
                    &final_pr_content.title,
                    &final_pr_content.description,
                    is_draft,
                    self.base.as_deref(),
                )?;
                println!("✅ Pull request created successfully!");
            }
            PrAction::UpdateExisting => {
                self.update_github_pr(
                    &repo_view,
                    &final_pr_content.title,
                    &final_pr_content.description,
                    self.base.as_deref(),
                )?;
                println!("✅ Pull request updated successfully!");
            }
            PrAction::Cancel => unreachable!(), // Already handled above
        }

        Ok(())
    }

    /// Generates the repository view (reuses InfoCommand logic).
    fn generate_repository_view(&self) -> Result<crate::data::RepositoryView> {
        use crate::data::{
            AiInfo, BranchInfo, FieldExplanation, FileStatusInfo, RepositoryView, VersionInfo,
            WorkingDirectoryInfo,
        };
        use crate::git::{GitRepository, RemoteInfo};
        use crate::utils::ai_scratch;

        // Open git repository
        let repo = GitRepository::open()
            .context("Failed to open git repository. Make sure you're in a git repository.")?;

        // Get current branch name
        let current_branch = repo.get_current_branch().context(
            "Failed to get current branch. Make sure you're not in detached HEAD state.",
        )?;

        // Get remote information to determine proper remote and main branch
        let remotes = RemoteInfo::get_all_remotes(repo.repository())?;

        // Find the primary remote (prefer origin, fallback to first available)
        let primary_remote = remotes
            .iter()
            .find(|r| r.name == "origin")
            .or_else(|| remotes.first())
            .ok_or_else(|| anyhow::anyhow!("No remotes found in repository"))?;

        // Determine base branch (with remote prefix)
        let base_branch = if let Some(branch) = self.base.as_ref() {
            // User specified base branch - try to resolve it
            // First, check if it's already a valid remote ref (e.g., "origin/main")
            let remote_ref = format!("refs/remotes/{branch}");
            if repo.repository().find_reference(&remote_ref).is_ok() {
                branch.clone()
            } else {
                // Try prepending the primary remote name (e.g., "main" -> "origin/main")
                let with_remote = format!("{}/{}", primary_remote.name, branch);
                let remote_ref = format!("refs/remotes/{with_remote}");
                if repo.repository().find_reference(&remote_ref).is_ok() {
                    with_remote
                } else {
                    anyhow::bail!(
                        "Remote branch '{branch}' does not exist (also tried '{with_remote}')"
                    );
                }
            }
        } else {
            // Auto-detect using the primary remote's main branch
            let main_branch = &primary_remote.main_branch;
            if main_branch == "unknown" {
                let remote_name = &primary_remote.name;
                anyhow::bail!("Could not determine main branch for remote '{remote_name}'");
            }

            let remote_main = format!("{}/{}", primary_remote.name, main_branch);

            // Validate that the remote main branch exists
            let remote_ref = format!("refs/remotes/{remote_main}");
            if repo.repository().find_reference(&remote_ref).is_err() {
                anyhow::bail!(
                    "Remote main branch '{remote_main}' does not exist. Try running 'git fetch' first."
                );
            }

            remote_main
        };

        // Calculate commit range: [remote_base]..HEAD
        let commit_range = format!("{base_branch}..HEAD");

        // Get working directory status
        let wd_status = repo.get_working_directory_status()?;
        let working_directory = WorkingDirectoryInfo {
            clean: wd_status.clean,
            untracked_changes: wd_status
                .untracked_changes
                .into_iter()
                .map(|fs| FileStatusInfo {
                    status: fs.status,
                    file: fs.file,
                })
                .collect(),
        };

        // Get remote information
        let remotes = RemoteInfo::get_all_remotes(repo.repository())?;

        // Parse commit range and get commits
        let commits = repo.get_commits_in_range(&commit_range)?;

        // Check for PR template
        let pr_template_result = InfoCommand::read_pr_template().ok();
        let (pr_template, pr_template_location) = match pr_template_result {
            Some((content, location)) => (Some(content), Some(location)),
            None => (None, None),
        };

        // Get PRs for current branch
        let branch_prs = InfoCommand::get_branch_prs(&current_branch)
            .ok()
            .filter(|prs| !prs.is_empty());

        // Create version information
        let versions = Some(VersionInfo {
            omni_dev: env!("CARGO_PKG_VERSION").to_string(),
        });

        // Get AI scratch directory
        let ai_scratch_path =
            ai_scratch::get_ai_scratch_dir().context("Failed to determine AI scratch directory")?;
        let ai_info = AiInfo {
            scratch: ai_scratch_path.to_string_lossy().to_string(),
        };

        // Build repository view with branch info
        let mut repo_view = RepositoryView {
            versions,
            explanation: FieldExplanation::default(),
            working_directory,
            remotes,
            ai: ai_info,
            branch_info: Some(BranchInfo {
                branch: current_branch,
            }),
            pr_template,
            pr_template_location,
            branch_prs,
            commits,
        };

        // Update field presence based on actual data
        repo_view.update_field_presence();

        Ok(repo_view)
    }

    /// Validates the branch state for PR creation.
    fn validate_branch_state(&self, repo_view: &crate::data::RepositoryView) -> Result<()> {
        // Check if working directory is clean
        if !repo_view.working_directory.clean {
            anyhow::bail!(
                "Working directory has uncommitted changes. Please commit or stash your changes before creating a PR."
            );
        }

        // Check if there are any untracked changes
        if !repo_view.working_directory.untracked_changes.is_empty() {
            let file_list: Vec<&str> = repo_view
                .working_directory
                .untracked_changes
                .iter()
                .map(|f| f.file.as_str())
                .collect();
            anyhow::bail!(
                "Working directory has untracked changes: {}. Please commit or stash your changes before creating a PR.",
                file_list.join(", ")
            );
        }

        // Check if commits exist
        if repo_view.commits.is_empty() {
            anyhow::bail!("No commits found to create PR from. Make sure you have commits that are not in the base branch.");
        }

        // Check if PR already exists for this branch
        if let Some(existing_prs) = &repo_view.branch_prs {
            if !existing_prs.is_empty() {
                let pr_info: Vec<String> = existing_prs
                    .iter()
                    .map(|pr| format!("#{} ({})", pr.number, pr.state))
                    .collect();

                println!(
                    "📋 Existing PR(s) found for this branch: {}",
                    pr_info.join(", ")
                );
                // Don't bail - we'll handle this in the main flow
            }
        }

        Ok(())
    }

    /// Shows detailed context information (similar to twiddle command).
    async fn show_context_information(
        &self,
        _repo_view: &crate::data::RepositoryView,
    ) -> Result<()> {
        // Note: commit range info and context summary are now shown earlier
        // This method is kept for potential future detailed information
        // that should be shown after AI generation

        Ok(())
    }

    /// Shows commit range and count information.
    fn show_commit_range_info(&self, repo_view: &crate::data::RepositoryView) -> Result<()> {
        // Recreate the base branch determination logic from generate_repository_view
        let base_branch = match self.base.as_ref() {
            Some(branch) => {
                // User specified base branch
                // Get the primary remote name from repo_view
                let primary_remote_name = repo_view
                    .remotes
                    .iter()
                    .find(|r| r.name == "origin")
                    .or_else(|| repo_view.remotes.first())
                    .map_or("origin", |r| r.name.as_str());
                // Check if already has remote prefix
                if branch.starts_with(&format!("{primary_remote_name}/")) {
                    branch.clone()
                } else {
                    format!("{primary_remote_name}/{branch}")
                }
            }
            None => {
                // Auto-detected base branch from remotes
                repo_view
                    .remotes
                    .iter()
                    .find(|r| r.name == "origin")
                    .or_else(|| repo_view.remotes.first())
                    .map_or_else(
                        || "unknown".to_string(),
                        |r| format!("{}/{}", r.name, r.main_branch),
                    )
            }
        };

        let commit_range = format!("{base_branch}..HEAD");
        let commit_count = repo_view.commits.len();

        // Get current branch name
        let current_branch = repo_view
            .branch_info
            .as_ref()
            .map_or("unknown", |bi| bi.branch.as_str());

        println!("📊 Branch Analysis:");
        println!("   🌿 Current branch: {current_branch}");
        println!("   📏 Commit range: {commit_range}");
        println!("   📝 Commits found: {commit_count} commits");
        println!();

        Ok(())
    }

    /// Collects contextual information for enhanced PR generation (adapted from twiddle).
    async fn collect_context(
        &self,
        repo_view: &crate::data::RepositoryView,
    ) -> Result<crate::data::context::CommitContext> {
        use crate::claude::context::{
            BranchAnalyzer, FileAnalyzer, ProjectDiscovery, WorkPatternAnalyzer,
        };
        use crate::data::context::{CommitContext, ProjectContext};
        use crate::git::GitRepository;

        let mut context = CommitContext::new();

        // 1. Discover project context
        let context_dir = crate::claude::context::resolve_context_dir(self.context_dir.as_deref());

        // ProjectDiscovery takes repo root and context directory
        let repo_root = std::path::PathBuf::from(".");
        let discovery = ProjectDiscovery::new(repo_root, context_dir);
        match discovery.discover() {
            Ok(project_context) => {
                context.project = project_context;
            }
            Err(_e) => {
                context.project = ProjectContext::default();
            }
        }

        // 2. Analyze current branch
        let repo = GitRepository::open()?;
        let current_branch = repo
            .get_current_branch()
            .unwrap_or_else(|_| "HEAD".to_string());
        context.branch = BranchAnalyzer::analyze(&current_branch).unwrap_or_default();

        // 3. Analyze commit range patterns
        if !repo_view.commits.is_empty() {
            context.range = WorkPatternAnalyzer::analyze_commit_range(&repo_view.commits);
        }

        // 3.5. Analyze file-level context
        if !repo_view.commits.is_empty() {
            context.files = FileAnalyzer::analyze_commits(&repo_view.commits);
        }

        Ok(context)
    }

    /// Shows guidance files status (adapted from twiddle).
    fn show_guidance_files_status(
        &self,
        project_context: &crate::data::context::ProjectContext,
    ) -> Result<()> {
        use crate::claude::context::{
            config_source_label, resolve_context_dir_with_source, ConfigSourceLabel,
        };

        let (context_dir, dir_source) =
            resolve_context_dir_with_source(self.context_dir.as_deref());

        println!("📋 Project guidance files status:");
        println!("   📂 Config dir: {} ({dir_source})", context_dir.display());

        // Check PR guidelines (for PR commands)
        let pr_guidelines_source = if project_context.pr_guidelines.is_some() {
            match config_source_label(&context_dir, "pr-guidelines.md") {
                ConfigSourceLabel::NotFound => "✅ (source unknown)".to_string(),
                label => format!("{label}"),
            }
        } else {
            "❌ None found".to_string()
        };
        println!("   🔀 PR guidelines: {pr_guidelines_source}");

        // Check scopes
        let scopes_count = project_context.valid_scopes.len();
        let scopes_source = if scopes_count > 0 {
            match config_source_label(&context_dir, "scopes.yaml") {
                ConfigSourceLabel::NotFound => {
                    format!("✅ (source unknown + ecosystem defaults) ({scopes_count} scopes)")
                }
                label => format!("{label} ({scopes_count} scopes)"),
            }
        } else {
            "❌ None found".to_string()
        };
        println!("   🎯 Valid scopes: {scopes_source}");

        // Check PR template
        let pr_template_path = std::path::Path::new(".github/pull_request_template.md");
        let pr_template_status = if pr_template_path.exists() {
            format!("✅ Project: {}", pr_template_path.display())
        } else {
            "❌ None found".to_string()
        };
        println!("   📋 PR template: {pr_template_status}");

        println!();
        Ok(())
    }

    /// Shows the context summary (adapted from twiddle).
    fn show_context_summary(&self, context: &crate::data::context::CommitContext) -> Result<()> {
        use crate::data::context::{VerbosityLevel, WorkPattern};

        println!("🔍 Context Analysis:");

        // Project context
        if !context.project.valid_scopes.is_empty() {
            let scope_names: Vec<&str> = context
                .project
                .valid_scopes
                .iter()
                .map(|s| s.name.as_str())
                .collect();
            println!("   📁 Valid scopes: {}", scope_names.join(", "));
        }

        // Branch context
        if context.branch.is_feature_branch {
            println!(
                "   🌿 Branch: {} ({})",
                context.branch.description, context.branch.work_type
            );
            if let Some(ref ticket) = context.branch.ticket_id {
                println!("   🎫 Ticket: {ticket}");
            }
        }

        // Work pattern
        match context.range.work_pattern {
            WorkPattern::Sequential => println!("   🔄 Pattern: Sequential development"),
            WorkPattern::Refactoring => println!("   🧹 Pattern: Refactoring work"),
            WorkPattern::BugHunt => println!("   🐛 Pattern: Bug investigation"),
            WorkPattern::Documentation => println!("   📖 Pattern: Documentation updates"),
            WorkPattern::Configuration => println!("   ⚙️  Pattern: Configuration changes"),
            WorkPattern::Unknown => {}
        }

        // File analysis
        if let Some(label) = super::formatting::format_file_analysis(&context.files) {
            println!("   {label}");
        }

        // Verbosity level
        match context.suggested_verbosity() {
            VerbosityLevel::Comprehensive => {
                println!("   📝 Detail level: Comprehensive (significant changes detected)");
            }
            VerbosityLevel::Detailed => println!("   📝 Detail level: Detailed"),
            VerbosityLevel::Concise => println!("   📝 Detail level: Concise"),
        }

        println!();
        Ok(())
    }

    /// Generates PR content with a pre-created client (internal method that does not show model info).
    async fn generate_pr_content_with_client_internal(
        &self,
        repo_view: &crate::data::RepositoryView,
        claude_client: crate::claude::client::ClaudeClient,
    ) -> Result<(PrContent, crate::claude::client::ClaudeClient)> {
        use tracing::debug;

        // Get PR template (either from repo or default)
        let pr_template = match &repo_view.pr_template {
            Some(template) => template.clone(),
            None => self.get_default_pr_template(),
        };

        debug!(
            pr_template_length = pr_template.len(),
            pr_template_preview = %pr_template.lines().take(5).collect::<Vec<_>>().join("\\n"),
            "Using PR template for generation"
        );

        println!("🤖 Generating AI-powered PR description...");

        // Collect project context for PR guidelines
        debug!("Collecting context for PR generation");
        let context = self.collect_context(repo_view).await?;
        debug!("Context collection completed");

        // Generate AI-powered PR content with context
        debug!("About to call Claude AI for PR content generation");
        match claude_client
            .generate_pr_content_with_context(repo_view, &pr_template, &context)
            .await
        {
            Ok(pr_content) => {
                debug!(
                    ai_generated_title = %pr_content.title,
                    ai_generated_description_length = pr_content.description.len(),
                    ai_generated_description_preview = %pr_content.description.lines().take(3).collect::<Vec<_>>().join("\\n"),
                    "AI successfully generated PR content"
                );
                Ok((pr_content, claude_client))
            }
            Err(e) => {
                debug!(error = %e, "AI PR generation failed, falling back to basic description");
                // Fallback to basic description with commit analysis (silently)
                let mut description = pr_template;
                self.enhance_description_with_commits(&mut description, repo_view)?;

                // Generate fallback title from commits
                let title = self.generate_title_from_commits(repo_view);

                debug!(
                    fallback_title = %title,
                    fallback_description_length = description.len(),
                    "Created fallback PR content"
                );

                Ok((PrContent { title, description }, claude_client))
            }
        }
    }

    /// Returns the default PR template when none exists in the repository.
    fn get_default_pr_template(&self) -> String {
        r#"# Pull Request

## Description
<!-- Provide a brief description of what this PR does -->

## Type of Change
<!-- Mark the relevant option with an "x" -->
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
- [ ] Documentation update
- [ ] Refactoring (no functional changes)
- [ ] Performance improvement
- [ ] Test coverage improvement

## Changes Made
<!-- List the specific changes made in this PR -->
- 
- 
- 

## Testing
- [ ] All existing tests pass
- [ ] New tests added for new functionality
- [ ] Manual testing performed

## Additional Notes
<!-- Add any additional notes for reviewers -->
"#.to_string()
    }

    /// Enhances the PR description with commit analysis.
    fn enhance_description_with_commits(
        &self,
        description: &mut String,
        repo_view: &crate::data::RepositoryView,
    ) -> Result<()> {
        if repo_view.commits.is_empty() {
            return Ok(());
        }

        // Add commit summary section
        description.push_str("\n---\n");
        description.push_str("## 📝 Commit Summary\n");
        description
            .push_str("*This section was automatically generated based on commit analysis*\n\n");

        // Analyze commit types and scopes
        let mut types_found = std::collections::HashSet::new();
        let mut scopes_found = std::collections::HashSet::new();
        let mut has_breaking_changes = false;

        for commit in &repo_view.commits {
            let detected_type = &commit.analysis.detected_type;
            types_found.insert(detected_type.clone());
            if is_breaking_change(detected_type, &commit.original_message) {
                has_breaking_changes = true;
            }

            let detected_scope = &commit.analysis.detected_scope;
            if !detected_scope.is_empty() {
                scopes_found.insert(detected_scope.clone());
            }
        }

        // Update type checkboxes based on detected types
        if types_found.contains("feat") {
            check_checkbox(description, "- [ ] New feature");
        }
        if types_found.contains("fix") {
            check_checkbox(description, "- [ ] Bug fix");
        }
        if types_found.contains("docs") {
            check_checkbox(description, "- [ ] Documentation update");
        }
        if types_found.contains("refactor") {
            check_checkbox(description, "- [ ] Refactoring");
        }
        if has_breaking_changes {
            check_checkbox(description, "- [ ] Breaking change");
        }

        // Add detected scopes
        let scopes_list: Vec<_> = scopes_found.into_iter().collect();
        let scopes_section = format_scopes_section(&scopes_list);
        if !scopes_section.is_empty() {
            description.push_str(&scopes_section);
        }

        // Add commit list
        let commit_entries: Vec<(&str, &str)> = repo_view
            .commits
            .iter()
            .map(|c| {
                let short = &c.hash[..crate::git::SHORT_HASH_LEN];
                let first = extract_first_line(&c.original_message);
                (short, first)
            })
            .collect();
        description.push_str(&format_commit_list(&commit_entries));

        // Add file change summary
        let total_files: usize = repo_view
            .commits
            .iter()
            .map(|c| c.analysis.file_changes.total_files)
            .sum();

        if total_files > 0 {
            description.push_str(&format!("\n**Files changed:** {total_files} files\n"));
        }

        Ok(())
    }

    /// Handles the PR description file by showing the path and getting the user choice.
    fn handle_pr_file(
        &self,
        pr_file: &std::path::Path,
        repo_view: &crate::data::RepositoryView,
    ) -> Result<PrAction> {
        use std::io::{self, Write};

        println!("\n📝 PR details generated.");
        println!("💾 Details saved to: {}", pr_file.display());

        // Show draft status
        let is_draft = self.should_create_as_draft();
        let (status_icon, status_text) = format_draft_status(is_draft);
        println!("{status_icon} PR will be created as: {status_text}");
        println!();

        // Check if there are existing PRs and show different options
        let has_existing_prs = repo_view
            .branch_prs
            .as_ref()
            .is_some_and(|prs| !prs.is_empty());

        loop {
            if has_existing_prs {
                print!("❓ [U]pdate existing PR, [N]ew PR anyway, [S]how file, [E]dit file, or [Q]uit? [U/n/s/e/q] ");
            } else {
                print!(
                    "❓ [A]ccept and create PR, [S]how file, [E]dit file, or [Q]uit? [A/s/e/q] "
                );
            }
            io::stdout().flush()?;

            let mut input = String::new();
            io::stdin().read_line(&mut input)?;

            match input.trim().to_lowercase().as_str() {
                "u" | "update" if has_existing_prs => return Ok(PrAction::UpdateExisting),
                "n" | "new" if has_existing_prs => return Ok(PrAction::CreateNew),
                "a" | "accept" | "" if !has_existing_prs => return Ok(PrAction::CreateNew),
                "s" | "show" => {
                    self.show_pr_file(pr_file)?;
                    println!();
                }
                "e" | "edit" => {
                    self.edit_pr_file(pr_file)?;
                    println!();
                }
                "q" | "quit" => return Ok(PrAction::Cancel),
                _ => {
                    if has_existing_prs {
                        println!("Invalid choice. Please enter 'u' to update existing PR, 'n' for new PR, 's' to show, 'e' to edit, or 'q' to quit.");
                    } else {
                        println!("Invalid choice. Please enter 'a' to accept, 's' to show, 'e' to edit, or 'q' to quit.");
                    }
                }
            }
        }
    }

    /// Shows the contents of the PR details file.
    fn show_pr_file(&self, pr_file: &std::path::Path) -> Result<()> {
        use std::fs;

        println!("\n📄 PR details file contents:");
        println!("─────────────────────────────");

        let contents = fs::read_to_string(pr_file).context("Failed to read PR details file")?;
        println!("{contents}");
        println!("─────────────────────────────");

        Ok(())
    }

    /// Opens the PR details file in an external editor.
    fn edit_pr_file(&self, pr_file: &std::path::Path) -> Result<()> {
        use std::env;
        use std::io::{self, Write};
        use std::process::Command;

        // Try to get editor from environment variables
        let editor = if let Ok(e) = env::var("OMNI_DEV_EDITOR").or_else(|_| env::var("EDITOR")) {
            e
        } else {
            // Prompt user for editor if neither environment variable is set
            println!("🔧 Neither OMNI_DEV_EDITOR nor EDITOR environment variables are defined.");
            print!("Please enter the command to use as your editor: ");
            io::stdout().flush().context("Failed to flush stdout")?;

            let mut input = String::new();
            io::stdin()
                .read_line(&mut input)
                .context("Failed to read user input")?;
            input.trim().to_string()
        };

        if editor.is_empty() {
            println!("❌ No editor specified. Returning to menu.");
            return Ok(());
        }

        println!("📝 Opening PR details file in editor: {editor}");

        let (editor_cmd, args) = super::formatting::parse_editor_command(&editor);

        let mut command = Command::new(editor_cmd);
        command.args(args);
        command.arg(pr_file.to_string_lossy().as_ref());

        match command.status() {
            Ok(status) => {
                if status.success() {
                    println!("✅ Editor session completed.");
                } else {
                    println!(
                        "⚠️  Editor exited with non-zero status: {:?}",
                        status.code()
                    );
                }
            }
            Err(e) => {
                println!("❌ Failed to execute editor '{editor}': {e}");
                println!("   Please check that the editor command is correct and available in your PATH.");
            }
        }

        Ok(())
    }

    /// Generates a concise title from commit analysis (fallback).
    fn generate_title_from_commits(&self, repo_view: &crate::data::RepositoryView) -> String {
        if repo_view.commits.is_empty() {
            return "Pull Request".to_string();
        }

        // For single commit, use its first line
        if repo_view.commits.len() == 1 {
            let first = extract_first_line(&repo_view.commits[0].original_message);
            let trimmed = first.trim();
            return if trimmed.is_empty() {
                "Pull Request".to_string()
            } else {
                trimmed.to_string()
            };
        }

        // For multiple commits, generate from branch name
        let branch_name = repo_view
            .branch_info
            .as_ref()
            .map_or("feature", |bi| bi.branch.as_str());

        format!("feat: {}", clean_branch_name(branch_name))
    }

    /// Creates a new GitHub PR using gh CLI.
    fn create_github_pr(
        &self,
        repo_view: &crate::data::RepositoryView,
        title: &str,
        description: &str,
        is_draft: bool,
        new_base: Option<&str>,
    ) -> Result<()> {
        use std::process::Command;

        // Get branch name
        let branch_name = repo_view
            .branch_info
            .as_ref()
            .map(|bi| &bi.branch)
            .context("Branch info not available")?;

        let pr_status = if is_draft {
            "draft"
        } else {
            "ready for review"
        };
        println!("🚀 Creating pull request ({pr_status})...");
        println!("   📋 Title: {title}");
        println!("   🌿 Branch: {branch_name}");
        if let Some(base) = new_base {
            println!("   🎯 Base: {base}");
        }

        // Push branch to remote unless --no-push was specified
        let push_action = if self.no_push {
            determine_push_action(true, false)
        } else {
            debug!("Opening git repository to check branch status");
            let git_repo =
                crate::git::GitRepository::open().context("Failed to open git repository")?;

            debug!(
                "Checking if branch '{}' exists on remote 'origin'",
                branch_name
            );
            let branch_on_remote = git_repo.branch_exists_on_remote(branch_name, "origin")?;
            let action = determine_push_action(false, branch_on_remote);

            debug!("Push action for branch '{}': {:?}", branch_name, action);
            println!("📤 Pushing branch to remote...");
            git_repo
                .push_branch(branch_name, "origin")
                .context("Failed to push branch to remote")?;

            action
        };

        if push_action == PushAction::Skip {
            debug!("Skipping push (--no-push flag set)");
        }

        // Create PR using gh CLI with explicit head branch
        debug!("Creating PR with gh CLI - title: '{}'", title);
        debug!("PR description length: {} characters", description.len());
        debug!("PR draft status: {}", is_draft);
        if let Some(base) = new_base {
            debug!("PR base branch: {}", base);
        }

        let mut args = vec![
            "pr",
            "create",
            "--head",
            branch_name,
            "--title",
            title,
            "--body",
            description,
        ];

        if let Some(base) = new_base {
            args.push("--base");
            args.push(base);
        }

        if is_draft {
            args.push("--draft");
        }

        let pr_result = Command::new("gh")
            .args(&args)
            .output()
            .context("Failed to create pull request")?;

        if pr_result.status.success() {
            let pr_url = String::from_utf8_lossy(&pr_result.stdout);
            let pr_url = pr_url.trim();
            debug!("PR created successfully with URL: {}", pr_url);
            println!("🎉 Pull request created: {pr_url}");
        } else {
            let error_msg = String::from_utf8_lossy(&pr_result.stderr);
            error!("gh CLI failed to create PR: {}", error_msg);
            anyhow::bail!("Failed to create pull request: {error_msg}");
        }

        Ok(())
    }

    /// Updates an existing GitHub PR using gh CLI.
    fn update_github_pr(
        &self,
        repo_view: &crate::data::RepositoryView,
        title: &str,
        description: &str,
        new_base: Option<&str>,
    ) -> Result<()> {
        use std::io::{self, Write};
        use std::process::Command;

        // Get the first existing PR (assuming we're updating the most recent one)
        let existing_pr = repo_view
            .branch_prs
            .as_ref()
            .and_then(|prs| prs.first())
            .context("No existing PR found to update")?;

        let pr_number = existing_pr.number;
        let current_base = &existing_pr.base;

        println!("🚀 Updating pull request #{pr_number}...");
        println!("   📋 Title: {title}");

        // Check if base branch should be changed
        let change_base = if let Some(base) = new_base {
            if !current_base.is_empty() && current_base != base {
                print!("   🎯 Current base: {current_base} → New base: {base}. Change? [y/N]: ");
                io::stdout().flush()?;

                let mut input = String::new();
                io::stdin().read_line(&mut input)?;
                let response = input.trim().to_lowercase();
                response == "y" || response == "yes"
            } else {
                false
            }
        } else {
            false
        };

        debug!(
            pr_number = pr_number,
            title = %title,
            description_length = description.len(),
            description_preview = %description.lines().take(3).collect::<Vec<_>>().join("\\n"),
            change_base = change_base,
            "Updating GitHub PR with title and description"
        );

        // Update PR using gh CLI
        let pr_number_str = pr_number.to_string();
        let mut gh_args = vec![
            "pr",
            "edit",
            &pr_number_str,
            "--title",
            title,
            "--body",
            description,
        ];

        if change_base {
            if let Some(base) = new_base {
                gh_args.push("--base");
                gh_args.push(base);
            }
        }

        debug!(
            args = ?gh_args,
            "Executing gh command to update PR"
        );

        let pr_result = Command::new("gh")
            .args(&gh_args)
            .output()
            .context("Failed to update pull request")?;

        if pr_result.status.success() {
            // Get the PR URL using the existing PR data
            println!("🎉 Pull request updated: {}", existing_pr.url);
            if change_base {
                if let Some(base) = new_base {
                    println!("   🎯 Base branch changed to: {base}");
                }
            }
        } else {
            let error_msg = String::from_utf8_lossy(&pr_result.stderr);
            anyhow::bail!("Failed to update pull request: {error_msg}");
        }

        Ok(())
    }

    /// Shows model information from the actual AI client.
    fn show_model_info_from_client(
        &self,
        client: &crate::claude::client::ClaudeClient,
    ) -> Result<()> {
        use crate::claude::model_config::get_model_registry;

        println!("🤖 AI Model Configuration:");

        // Get actual metadata from the client
        let metadata = client.get_ai_client_metadata();
        let registry = get_model_registry();

        if let Some(spec) = registry.get_model_spec(&metadata.model) {
            // Highlight the API identifier portion in yellow
            if metadata.model != spec.api_identifier {
                println!(
                    "   📡 Model: {}\x1b[33m{}\x1b[0m",
                    metadata.model, spec.api_identifier
                );
            } else {
                println!("   📡 Model: \x1b[33m{}\x1b[0m", metadata.model);
            }

            println!("   🏷️  Provider: {}", spec.provider);
            println!("   📊 Generation: {}", spec.generation);
            println!("   ⭐ Tier: {} ({})", spec.tier, {
                if let Some(tier_info) = registry.get_tier_info(&spec.provider, &spec.tier) {
                    &tier_info.description
                } else {
                    "No description available"
                }
            });
            println!("   📤 Max output tokens: {}", metadata.max_response_length);
            println!("   📥 Input context: {}", metadata.max_context_length);

            if let Some((ref key, ref value)) = metadata.active_beta {
                println!("   🔬 Beta header: {key}: {value}");
            }

            if spec.legacy {
                println!("   ⚠️  Legacy model (consider upgrading to newer version)");
            }
        } else {
            // Fallback to client metadata if not in registry
            println!("   📡 Model: \x1b[33m{}\x1b[0m", metadata.model);
            println!("   🏷️  Provider: {}", metadata.provider);
            println!("   ⚠️  Model not found in registry, using client metadata:");
            println!("   📤 Max output tokens: {}", metadata.max_response_length);
            println!("   📥 Input context: {}", metadata.max_context_length);
        }

        println!();
        Ok(())
    }
}

// --- Extracted pure functions ---

/// Describes what push action should be taken before PR creation.
#[derive(Debug, PartialEq)]
enum PushAction {
    /// Skip pushing entirely (user passed `--no-push`).
    Skip,
    /// Push to sync with an existing remote branch.
    SyncExisting,
    /// Push a new branch to remote.
    PushNew,
}

/// Determines what push action to take based on the `--no-push` flag and remote branch state.
fn determine_push_action(no_push: bool, branch_on_remote: bool) -> PushAction {
    if no_push {
        PushAction::Skip
    } else if branch_on_remote {
        PushAction::SyncExisting
    } else {
        PushAction::PushNew
    }
}

/// Parses a boolean-like string value.
///
/// Accepts "true"/"1"/"yes" as `true` and "false"/"0"/"no" as `false`.
/// Returns `None` for unrecognized values.
fn parse_bool_string(val: &str) -> Option<bool> {
    match val.to_lowercase().as_str() {
        "true" | "1" | "yes" => Some(true),
        "false" | "0" | "no" => Some(false),
        _ => None,
    }
}

/// Returns whether a commit represents a breaking change.
fn is_breaking_change(detected_type: &str, original_message: &str) -> bool {
    detected_type.contains("BREAKING") || original_message.contains("BREAKING CHANGE")
}

/// Checks a markdown checkbox in the description by replacing `- [ ]` with `- [x]`.
fn check_checkbox(description: &mut String, search_text: &str) {
    if let Some(pos) = description.find(search_text) {
        description.replace_range(pos..pos + 5, "- [x]");
    }
}

/// Formats a list of scopes as a markdown "Affected areas" section.
///
/// Returns an empty string if the list is empty.
fn format_scopes_section(scopes: &[String]) -> String {
    if scopes.is_empty() {
        return String::new();
    }
    format!("**Affected areas:** {}\n\n", scopes.join(", "))
}

/// Formats commit entries as a markdown list with short hashes.
fn format_commit_list(entries: &[(&str, &str)]) -> String {
    let mut output = String::from("### Commits in this PR:\n");
    for (hash, message) in entries {
        output.push_str(&format!("- `{hash}` {message}\n"));
    }
    output
}

/// Replaces path separators (`/`, `-`, `_`) in a branch name with spaces.
fn clean_branch_name(branch: &str) -> String {
    branch.replace(['/', '-', '_'], " ")
}

/// Returns the first line of a text block, trimmed.
fn extract_first_line(text: &str) -> &str {
    text.lines().next().unwrap_or("").trim()
}

/// Returns an (icon, label) pair for a PR's draft status.
fn format_draft_status(is_draft: bool) -> (&'static str, &'static str) {
    if is_draft {
        ("\u{1f4cb}", "draft")
    } else {
        ("\u{2705}", "ready for review")
    }
}

/// Structured output from [`run_create_pr`] for programmatic consumers (MCP).
#[derive(Debug, Clone)]
pub struct CreatePrOutcome {
    /// Title as produced by the AI (or the fallback heuristic).
    pub title: String,
    /// Description body as produced by the AI (or the fallback heuristic).
    pub description: String,
    /// YAML serialisation of the [`PrContent`].
    pub pr_yaml: String,
}

/// Non-interactive core for `omni-dev git branch create pr`.
///
/// Generates PR title + description via the AI but does NOT push the branch
/// or call `gh pr create`. The MCP boundary should expose the proposed PR
/// content so the assistant can decide what to do with it; actually pushing
/// a branch or creating a PR is out of scope for a single tool call. This
/// function must produce no stdout output — the MCP server uses stdout for
/// the JSON-RPC protocol.
pub async fn run_create_pr(
    model: Option<String>,
    base_branch: Option<&str>,
    repo_path: Option<&std::path::Path>,
) -> Result<CreatePrOutcome> {
    let _cwd_guard = match repo_path {
        Some(p) => Some(super::CwdGuard::enter(p).await?),
        None => None,
    };

    crate::utils::check_pr_command_prerequisites(model.as_deref())?;

    let cmd = CreatePrCommand {
        base: base_branch.map(str::to_string),
        model: model.clone(),
        auto_apply: true,
        save_only: None,
        ready: false,
        draft: false,
        context_dir: None,
        no_push: true,
    };

    let repo_view = cmd.generate_repository_view()?;
    let context = cmd.collect_context(&repo_view).await?;
    let claude_client = crate::claude::create_default_claude_client(model, None)?;
    run_create_pr_with_client(&cmd, &repo_view, &context, &claude_client).await
}

/// Non-credential-gated inner core of [`run_create_pr`] for unit tests.
///
/// Takes an already-built [`CreatePrCommand`], [`crate::data::RepositoryView`],
/// and [`crate::data::context::CommitContext`] so tests can construct those
/// in-memory (avoiding the git-remote setup `generate_repository_view`
/// requires). Callers are responsible for preflight, CWD, and context
/// assembly.
pub(crate) async fn run_create_pr_with_client(
    cmd: &CreatePrCommand,
    repo_view: &crate::data::RepositoryView,
    context: &crate::data::context::CommitContext,
    claude_client: &crate::claude::client::ClaudeClient,
) -> Result<CreatePrOutcome> {
    let pr_template = match &repo_view.pr_template {
        Some(template) => template.clone(),
        None => cmd.get_default_pr_template(),
    };

    let pr_content = match claude_client
        .generate_pr_content_with_context(repo_view, &pr_template, context)
        .await
    {
        Ok(content) => content,
        Err(_e) => {
            let mut description = pr_template;
            cmd.enhance_description_with_commits(&mut description, repo_view)?;
            let title = cmd.generate_title_from_commits(repo_view);
            PrContent { title, description }
        }
    };

    let pr_yaml = crate::data::to_yaml(&pr_content).context("Failed to serialise PrContent")?;

    Ok(CreatePrOutcome {
        title: pr_content.title,
        description: pr_content.description,
        pr_yaml,
    })
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod run_create_pr_tests {
    use super::*;
    use crate::claude::client::ClaudeClient;
    use crate::claude::test_utils::ConfigurableMockAiClient;
    use crate::data::context::CommitContext;
    use crate::data::{
        AiInfo, BranchInfo, FieldExplanation, RepositoryView, VersionInfo, WorkingDirectoryInfo,
    };
    use crate::git::commit::FileChanges;
    use crate::git::{CommitAnalysis, CommitInfo};

    #[tokio::test]
    async fn run_create_pr_invalid_repo_path_errors_before_ai() {
        let err = run_create_pr(
            None,
            None,
            Some(std::path::Path::new("/no/such/path/exists")),
        )
        .await
        .unwrap_err();
        let msg = format!("{err:#}");
        assert!(
            msg.to_lowercase().contains("set_current_dir")
                || msg.to_lowercase().contains("no such")
                || msg.to_lowercase().contains("directory"),
            "expected cwd-related error, got: {msg}"
        );
    }

    fn fresh_cmd() -> CreatePrCommand {
        CreatePrCommand {
            base: None,
            model: None,
            auto_apply: true,
            save_only: None,
            ready: false,
            draft: false,
            context_dir: None,
            no_push: true,
        }
    }

    fn sample_commit(hash: &str, message: &str) -> (CommitInfo, tempfile::NamedTempFile) {
        let tmp = tempfile::NamedTempFile::new().unwrap();
        let commit = CommitInfo {
            hash: hash.to_string(),
            author: "Test <test@test.com>".to_string(),
            date: chrono::Utc::now().fixed_offset(),
            original_message: message.to_string(),
            in_main_branches: vec![],
            analysis: CommitAnalysis {
                detected_type: "feat".to_string(),
                detected_scope: String::new(),
                proposed_message: message.to_string(),
                file_changes: FileChanges {
                    total_files: 0,
                    files_added: 0,
                    files_deleted: 0,
                    file_list: vec![],
                },
                diff_summary: String::new(),
                diff_file: tmp.path().to_string_lossy().to_string(),
                file_diffs: Vec::new(),
            },
        };
        (commit, tmp)
    }

    fn sample_repo_view(commits: Vec<CommitInfo>, pr_template: Option<String>) -> RepositoryView {
        RepositoryView {
            versions: Some(VersionInfo {
                omni_dev: "0.0.0".to_string(),
            }),
            explanation: FieldExplanation::default(),
            working_directory: WorkingDirectoryInfo {
                clean: true,
                untracked_changes: vec![],
            },
            remotes: vec![],
            ai: AiInfo {
                scratch: String::new(),
            },
            branch_info: Some(BranchInfo {
                branch: "feature/test".to_string(),
            }),
            pr_template,
            pr_template_location: None,
            branch_prs: None,
            commits,
        }
    }

    #[tokio::test]
    async fn run_create_pr_with_client_ai_success_returns_content() {
        let (c1, _tmp) = sample_commit("abcdef00", "feat: work");
        let repo_view = sample_repo_view(vec![c1], None);
        let context = CommitContext::new();
        let cmd = fresh_cmd();

        let yaml = "title: My PR\ndescription: |\n  Body text\n".to_string();
        let mock = ConfigurableMockAiClient::new(vec![Ok(yaml)]);
        let client = ClaudeClient::new(Box::new(mock));

        let outcome = run_create_pr_with_client(&cmd, &repo_view, &context, &client)
            .await
            .unwrap();
        assert_eq!(outcome.title, "My PR");
        assert!(outcome.description.contains("Body text"));
        assert!(outcome.pr_yaml.contains("title:"));
    }

    #[tokio::test]
    async fn run_create_pr_with_client_ai_failure_falls_back_to_commit_summary() {
        let (c1, _tmp) = sample_commit("abcdef00", "feat: single commit subject");
        let repo_view = sample_repo_view(vec![c1], None);
        let context = CommitContext::new();
        let cmd = fresh_cmd();

        // Empty mock → AI call exhausts retries → fallback path triggered.
        let mock = ConfigurableMockAiClient::new(vec![]);
        let client = ClaudeClient::new(Box::new(mock));

        let outcome = run_create_pr_with_client(&cmd, &repo_view, &context, &client)
            .await
            .unwrap();
        assert!(
            outcome.title.contains("feat: single commit subject")
                || outcome.title.contains("Pull Request")
                || outcome.title.contains("feature/test"),
            "fallback title unexpected: {}",
            outcome.title
        );
    }

    #[tokio::test]
    async fn run_create_pr_with_client_uses_repo_template_when_present() {
        let (c1, _tmp) = sample_commit("abcdef00", "feat: x");
        let repo_view = sample_repo_view(vec![c1], Some("# Custom template\n".to_string()));
        let context = CommitContext::new();
        let cmd = fresh_cmd();

        // AI fails → fallback uses the repo template as the description base.
        let mock = ConfigurableMockAiClient::new(vec![]);
        let client = ClaudeClient::new(Box::new(mock));

        let outcome = run_create_pr_with_client(&cmd, &repo_view, &context, &client)
            .await
            .unwrap();
        assert!(
            outcome.description.contains("# Custom template"),
            "fallback description should include repo template: {}",
            outcome.description
        );
    }

    #[test]
    fn create_pr_outcome_clone_and_debug() {
        let outcome = CreatePrOutcome {
            title: "t".to_string(),
            description: "d".to_string(),
            pr_yaml: "y".to_string(),
        };
        let cloned = outcome.clone();
        assert_eq!(format!("{outcome:?}"), format!("{cloned:?}"));
    }
}

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

    // --- parse_bool_string ---

    #[test]
    fn parse_bool_true_variants() {
        assert_eq!(parse_bool_string("true"), Some(true));
        assert_eq!(parse_bool_string("1"), Some(true));
        assert_eq!(parse_bool_string("yes"), Some(true));
    }

    #[test]
    fn parse_bool_false_variants() {
        assert_eq!(parse_bool_string("false"), Some(false));
        assert_eq!(parse_bool_string("0"), Some(false));
        assert_eq!(parse_bool_string("no"), Some(false));
    }

    #[test]
    fn parse_bool_invalid() {
        assert_eq!(parse_bool_string("maybe"), None);
        assert_eq!(parse_bool_string(""), None);
    }

    #[test]
    fn parse_bool_case_insensitive() {
        assert_eq!(parse_bool_string("TRUE"), Some(true));
        assert_eq!(parse_bool_string("Yes"), Some(true));
        assert_eq!(parse_bool_string("FALSE"), Some(false));
        assert_eq!(parse_bool_string("No"), Some(false));
    }

    // --- is_breaking_change ---

    #[test]
    fn breaking_change_type_contains() {
        assert!(is_breaking_change("BREAKING", "normal message"));
    }

    #[test]
    fn breaking_change_message_contains() {
        assert!(is_breaking_change("feat", "BREAKING CHANGE: removed API"));
    }

    #[test]
    fn breaking_change_none() {
        assert!(!is_breaking_change("feat", "add new feature"));
    }

    // --- check_checkbox ---

    #[test]
    fn check_checkbox_found() {
        let mut desc = "- [ ] New feature\n- [ ] Bug fix".to_string();
        check_checkbox(&mut desc, "- [ ] New feature");
        assert!(desc.contains("- [x] New feature"));
        assert!(desc.contains("- [ ] Bug fix"));
    }

    #[test]
    fn check_checkbox_not_found() {
        let mut desc = "- [ ] Bug fix".to_string();
        let original = desc.clone();
        check_checkbox(&mut desc, "- [ ] New feature");
        assert_eq!(desc, original);
    }

    // --- format_scopes_section ---

    #[test]
    fn scopes_section_single() {
        let scopes = vec!["cli".to_string()];
        assert_eq!(
            format_scopes_section(&scopes),
            "**Affected areas:** cli\n\n"
        );
    }

    #[test]
    fn scopes_section_multiple() {
        let scopes = vec!["cli".to_string(), "git".to_string()];
        let result = format_scopes_section(&scopes);
        assert!(result.contains("cli"));
        assert!(result.contains("git"));
        assert!(result.starts_with("**Affected areas:**"));
    }

    #[test]
    fn scopes_section_empty() {
        assert_eq!(format_scopes_section(&[]), "");
    }

    // --- format_commit_list ---

    #[test]
    fn commit_list_formatting() {
        let entries = vec![
            ("abc12345", "feat: add feature"),
            ("def67890", "fix: resolve bug"),
        ];
        let result = format_commit_list(&entries);
        assert!(result.contains("### Commits in this PR:"));
        assert!(result.contains("- `abc12345` feat: add feature"));
        assert!(result.contains("- `def67890` fix: resolve bug"));
    }

    // --- clean_branch_name ---

    #[test]
    fn clean_branch_simple() {
        assert_eq!(clean_branch_name("feat/add-login"), "feat add login");
    }

    #[test]
    fn clean_branch_underscores() {
        assert_eq!(clean_branch_name("user_name/fix_bug"), "user name fix bug");
    }

    // --- extract_first_line ---

    #[test]
    fn first_line_multiline() {
        assert_eq!(extract_first_line("first\nsecond\nthird"), "first");
    }

    #[test]
    fn first_line_single() {
        assert_eq!(extract_first_line("only line"), "only line");
    }

    #[test]
    fn first_line_empty() {
        assert_eq!(extract_first_line(""), "");
    }

    // --- format_draft_status ---

    #[test]
    fn draft_status_true() {
        let (icon, text) = format_draft_status(true);
        assert_eq!(text, "draft");
        assert!(!icon.is_empty());
    }

    #[test]
    fn draft_status_false() {
        let (icon, text) = format_draft_status(false);
        assert_eq!(text, "ready for review");
        assert!(!icon.is_empty());
    }

    // --- determine_push_action ---

    #[test]
    fn push_action_skip_when_no_push() {
        assert_eq!(determine_push_action(true, false), PushAction::Skip);
        assert_eq!(determine_push_action(true, true), PushAction::Skip);
    }

    #[test]
    fn push_action_sync_existing_branch() {
        assert_eq!(determine_push_action(false, true), PushAction::SyncExisting);
    }

    #[test]
    fn push_action_push_new_branch() {
        assert_eq!(determine_push_action(false, false), PushAction::PushNew);
    }
}