git-editor 2.0.1

A command-line tool to edit git commit timestamps, messages, and author information
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
use crate::utils::types::CommitInfo;
use crate::utils::types::Result;
use crate::{args::Args, utils::commit_history::get_commit_history};
use chrono::NaiveDateTime;
use colored::Colorize;
use crossterm::{
    cursor,
    event::{self, Event, KeyCode, KeyEvent, KeyEventKind},
    terminal::{self, Clear, ClearType},
    ExecutableCommand,
};
use git2::{Repository, Signature, Sort, Time};
use std::collections::HashMap;
use std::io::{self, Write};

#[derive(Debug, Clone)]
struct CommitEdit {
    index: usize,
    original: CommitInfo,
    author_name: String,
    author_email: String,
    timestamp: NaiveDateTime,
    message: String,
    is_modified: bool,
    modifications: ModificationFlags,
}

#[derive(Debug, Clone, Default)]
struct ModificationFlags {
    author_name_changed: bool,
    author_email_changed: bool,
    timestamp_changed: bool,
    message_changed: bool,
}

#[derive(Debug, Clone, Copy, PartialEq)]
enum TableColumn {
    Index = 0,
    Hash = 1,
    AuthorName = 2,
    AuthorEmail = 3,
    Timestamp = 4,
    Message = 5,
}

struct InteractiveTable {
    commits: Vec<CommitEdit>,
    current_row: usize,
    current_col: TableColumn,
    editing: bool,
    edit_buffer: String,
    editable_fields: (bool, bool, bool, bool), // (author_name, author_email, timestamp, message)
}

impl InteractiveTable {
    fn new(
        commits: Vec<CommitInfo>,
        start_idx: usize,
        end_idx: usize,
        editable_fields: (bool, bool, bool, bool),
    ) -> Self {
        let mut commit_edits = Vec::new();

        for (i, commit) in commits[start_idx..=end_idx].iter().enumerate() {
            commit_edits.push(CommitEdit {
                index: start_idx + i,
                original: commit.clone(),
                author_name: commit.author_name.clone(),
                author_email: commit.author_email.clone(),
                timestamp: commit.timestamp,
                message: commit.message.clone(), // Keep full message, truncate only for display
                is_modified: false,
                modifications: ModificationFlags::default(),
            });
        }

        // Find the first editable column as starting position
        let starting_col = if editable_fields.0 {
            // author_name
            TableColumn::AuthorName
        } else if editable_fields.1 {
            // author_email
            TableColumn::AuthorEmail
        } else if editable_fields.2 {
            // timestamp
            TableColumn::Timestamp
        } else if editable_fields.3 {
            // message
            TableColumn::Message
        } else {
            TableColumn::AuthorName // fallback
        };

        Self {
            commits: commit_edits,
            current_row: 0,
            current_col: starting_col,
            editing: false,
            edit_buffer: String::new(),
            editable_fields,
        }
    }

    fn draw_table(&self) {
        // Clear screen using crossterm
        let _ = io::stdout().execute(Clear(ClearType::All));
        let _ = io::stdout().execute(cursor::MoveTo(0, 0));

        println!(
            "{}",
            "Interactive Commit Editor - Range Mode".bold().green()
        );

        // Show which fields are editable
        let editable_info = if self.editable_fields == (true, true, true, true) {
            "All fields editable".to_string()
        } else {
            let mut editable = Vec::new();
            if self.editable_fields.0 || self.editable_fields.1 {
                editable.push("Author");
            }
            if self.editable_fields.2 {
                editable.push("Time");
            }
            if self.editable_fields.3 {
                editable.push("Message");
            }
            format!("Editable: {}", editable.join(", "))
        };
        println!("{}", editable_info.cyan());
        println!(
            "{}",
            "Use Arrow Keys to navigate, Enter to edit, Esc to save & exit, Ctrl+C to cancel"
                .yellow()
        );
        println!();

        // Print header
        println!(
            "{:<4} {:<8} {:<15} {:<20} {:<19} {}",
            "#".bold().white(),
            "HASH".bold().white(),
            "AUTHOR NAME".bold().white(),
            "AUTHOR EMAIL".bold().white(),
            "TIMESTAMP".bold().white(),
            "MESSAGE".bold().white()
        );

        // Draw rows
        for (row_idx, commit) in self.commits.iter().enumerate() {
            let is_current_row = row_idx == self.current_row;

            // Prepare content
            let index_str = format!("{}", commit.index + 1);
            let hash_str = self.truncate_text(&commit.original.short_hash, 8);
            let author_name_str = self.truncate_text(&commit.author_name, 15);
            let author_email_str = self.truncate_text(&commit.author_email, 20);
            let timestamp_str = commit.timestamp.format("%Y-%m-%d %H:%M:%S").to_string();
            let first_line_message = commit.message.lines().next().unwrap_or("");
            let message_str = self.truncate_text(first_line_message, 40);

            // Add modification indicators and current cell brackets
            let is_current_cell_index =
                is_current_row && matches!(self.current_col, TableColumn::Index);
            let is_current_cell_hash =
                is_current_row && matches!(self.current_col, TableColumn::Hash);
            let is_current_cell_author_name =
                is_current_row && matches!(self.current_col, TableColumn::AuthorName);
            let is_current_cell_author_email =
                is_current_row && matches!(self.current_col, TableColumn::AuthorEmail);
            let is_current_cell_timestamp =
                is_current_row && matches!(self.current_col, TableColumn::Timestamp);
            let is_current_cell_message =
                is_current_row && matches!(self.current_col, TableColumn::Message);

            let index_final = index_str; // Index is never editable, so no brackets
            let hash_final = hash_str; // Hash is never editable, so no brackets

            let author_name_with_mod = if commit.modifications.author_name_changed {
                format!("*{author_name_str}")
            } else {
                author_name_str
            };
            let author_name_final = author_name_with_mod;

            let author_email_with_mod = if commit.modifications.author_email_changed {
                format!("*{author_email_str}")
            } else {
                author_email_str
            };
            let author_email_final = author_email_with_mod;

            let timestamp_with_mod = if commit.modifications.timestamp_changed {
                format!("*{timestamp_str}")
            } else {
                timestamp_str
            };
            let timestamp_final = timestamp_with_mod;

            let message_with_mod = if commit.modifications.message_changed {
                format!("*{message_str}")
            } else {
                message_str
            };
            let message_final = message_with_mod;

            // Apply formatting and colors
            if is_current_row {
                if self.editing {
                    println!(
                        "{:<4} {:<8} {:<15} {:<20} {:<19} {}",
                        index_final.black().on_yellow(),
                        hash_final.black().on_yellow(),
                        author_name_final.black().on_yellow(),
                        author_email_final.black().on_yellow(),
                        timestamp_final.black().on_yellow(),
                        message_final.black().on_yellow()
                    );
                } else {
                    // Current row, not editing - highlight current cell with special background
                    let index_styled = if is_current_cell_index {
                        index_final.white().on_blue()
                    } else {
                        index_final.white().on_bright_black()
                    };
                    let hash_styled = if is_current_cell_hash {
                        hash_final.white().on_blue()
                    } else {
                        hash_final.yellow().on_bright_black()
                    };
                    let author_name_styled =
                        if is_current_cell_author_name && self.editable_fields.0 {
                            author_name_final.white().on_blue()
                        } else {
                            author_name_final.cyan().on_bright_black()
                        };
                    let author_email_styled =
                        if is_current_cell_author_email && self.editable_fields.1 {
                            author_email_final.white().on_blue()
                        } else {
                            author_email_final.blue().on_bright_black()
                        };
                    let timestamp_styled = if is_current_cell_timestamp && self.editable_fields.2 {
                        timestamp_final.white().on_blue()
                    } else {
                        timestamp_final.magenta().on_bright_black()
                    };
                    let message_styled = if is_current_cell_message && self.editable_fields.3 {
                        message_final.white().on_blue()
                    } else {
                        message_final.green().on_bright_black()
                    };

                    println!(
                        "{index_styled:<4} {hash_styled:<8} {author_name_styled:<15} {author_email_styled:<20} {timestamp_styled:<19} {message_styled}"
                    );
                }
            } else {
                println!(
                    "{:<4} {:<8} {:<15} {:<20} {:<19} {}",
                    index_final.white(),
                    hash_final.yellow(),
                    author_name_final.cyan(),
                    author_email_final.blue(),
                    timestamp_final.magenta(),
                    message_final.green()
                );
            }
        }

        println!();

        if self.editing {
            println!("{}: {}", "Editing".bold().yellow(), self.edit_buffer);
            println!("{}", "Press Enter to save, Esc to cancel edit".italic());
        } else {
            println!(
                "{}",
                "Navigation: ←→↑↓  Edit: Enter  Save & Exit: Esc  Cancel: Ctrl+C".italic()
            );
            println!(
                "{}",
                "Tip: Use '*' when selecting range to edit ALL commits at once".dimmed()
            );
        }
    }

    fn truncate_text(&self, text: &str, max_width: usize) -> String {
        if text.len() > max_width {
            format!("{}", &text[..max_width.saturating_sub(1)])
        } else {
            text.to_string()
        }
    }

    fn handle_navigation_key_input(&mut self, key: KeyCode) -> Result<bool> {
        match key {
            KeyCode::Up => {
                if self.current_row > 0 {
                    self.current_row -= 1;
                }
            }
            KeyCode::Down => {
                if self.current_row < self.commits.len() - 1 {
                    self.current_row += 1;
                }
            }
            KeyCode::Left => {
                self.move_to_prev_editable_column();
            }
            KeyCode::Right => {
                self.move_to_next_editable_column();
            }
            KeyCode::Char('h') => {
                // Left (vim-style)
                self.move_to_prev_editable_column();
            }
            KeyCode::Char('l') => {
                // Right (vim-style)
                self.move_to_next_editable_column();
            }
            KeyCode::Char('k') => {
                // Up (vim-style)
                if self.current_row > 0 {
                    self.current_row -= 1;
                }
            }
            KeyCode::Char('j') => {
                // Down (vim-style)
                if self.current_row < self.commits.len() - 1 {
                    self.current_row += 1;
                }
            }
            KeyCode::Enter => {
                self.start_editing();
                return Ok(true);
            }
            KeyCode::Esc => {
                return Ok(false); // Exit and save
            }
            _ => {}
        }
        Ok(true)
    }

    fn is_column_editable(&self, col: &TableColumn) -> bool {
        match col {
            TableColumn::Index | TableColumn::Hash => false,
            TableColumn::AuthorName => self.editable_fields.0,
            TableColumn::AuthorEmail => self.editable_fields.1,
            TableColumn::Timestamp => self.editable_fields.2,
            TableColumn::Message => self.editable_fields.3,
        }
    }

    fn move_to_next_editable_column(&mut self) {
        let columns = [
            TableColumn::Index,
            TableColumn::Hash,
            TableColumn::AuthorName,
            TableColumn::AuthorEmail,
            TableColumn::Timestamp,
            TableColumn::Message,
        ];

        let current_index = columns
            .iter()
            .position(|c| std::mem::discriminant(c) == std::mem::discriminant(&self.current_col))
            .unwrap_or(0);

        for i in 1..columns.len() {
            let next_index = (current_index + i) % columns.len();
            let next_col = &columns[next_index];
            if self.is_column_editable(next_col) {
                self.current_col = *next_col;
                return;
            }
        }
    }

    fn move_to_prev_editable_column(&mut self) {
        let columns = [
            TableColumn::Index,
            TableColumn::Hash,
            TableColumn::AuthorName,
            TableColumn::AuthorEmail,
            TableColumn::Timestamp,
            TableColumn::Message,
        ];

        let current_index = columns
            .iter()
            .position(|c| std::mem::discriminant(c) == std::mem::discriminant(&self.current_col))
            .unwrap_or(0);

        for i in 1..columns.len() {
            let prev_index = if current_index >= i {
                current_index - i
            } else {
                columns.len() - (i - current_index)
            };
            let prev_col = &columns[prev_index];
            if self.is_column_editable(prev_col) {
                self.current_col = *prev_col;
                return;
            }
        }
    }

    fn start_editing(&mut self) {
        if !self.is_column_editable(&self.current_col) {
            return; // This column is not editable
        }

        self.editing = true;

        // Initialize edit buffer with current value
        self.edit_buffer = match self.current_col {
            TableColumn::AuthorName => self.commits[self.current_row].author_name.clone(),
            TableColumn::AuthorEmail => self.commits[self.current_row].author_email.clone(),
            TableColumn::Timestamp => self.commits[self.current_row]
                .timestamp
                .format("%Y-%m-%d %H:%M:%S")
                .to_string(),
            TableColumn::Message => {
                // Use the full original message when editing, not the truncated display version
                if self.commits[self.current_row].modifications.message_changed {
                    self.commits[self.current_row].message.clone()
                } else {
                    // Get the full original message from the first line or full message
                    self.commits[self.current_row].original.message.clone()
                }
            }
            _ => String::new(),
        };
    }

    fn handle_edit_key_input(&mut self, key: KeyCode) -> Result<bool> {
        match key {
            KeyCode::Esc => {
                // Esc - cancel edit
                self.editing = false;
                self.edit_buffer.clear();
            }
            KeyCode::Enter => {
                // Enter - save edit
                if let Err(e) = self.save_current_edit() {
                    // On error, show message and stay in edit mode
                    self.edit_buffer = format!("Error: {e} (Press Esc to cancel)");
                    return Ok(true);
                }
                self.editing = false;
                self.edit_buffer.clear();
            }
            KeyCode::Backspace => {
                self.edit_buffer.pop();
            }
            KeyCode::Char(c) => {
                // Handle printable characters
                self.edit_buffer.push(c);
            }
            _ => {}
        }
        Ok(true)
    }

    fn save_current_edit(&mut self) -> Result<()> {
        let commit = &mut self.commits[self.current_row];

        match self.current_col {
            TableColumn::AuthorName => {
                if self.edit_buffer.trim().is_empty() {
                    return Err("Author name cannot be empty".into());
                }
                if commit.author_name != self.edit_buffer {
                    commit.author_name = self.edit_buffer.clone();
                    commit.modifications.author_name_changed =
                        commit.original.author_name != commit.author_name;
                    commit.is_modified = true;
                }
            }
            TableColumn::AuthorEmail => {
                if self.edit_buffer.trim().is_empty() {
                    return Err("Author email cannot be empty".into());
                }
                if !self.edit_buffer.contains('@') {
                    return Err("Invalid email format".into());
                }
                if commit.author_email != self.edit_buffer {
                    commit.author_email = self.edit_buffer.clone();
                    commit.modifications.author_email_changed =
                        commit.original.author_email != commit.author_email;
                    commit.is_modified = true;
                }
            }
            TableColumn::Timestamp => {
                let new_timestamp =
                    NaiveDateTime::parse_from_str(&self.edit_buffer, "%Y-%m-%d %H:%M:%S")
                        .map_err(|_| "Invalid timestamp format (use YYYY-MM-DD HH:MM:SS)")?;

                if commit.timestamp != new_timestamp {
                    commit.timestamp = new_timestamp;
                    commit.modifications.timestamp_changed =
                        commit.original.timestamp != commit.timestamp;
                    commit.is_modified = true;
                }
            }
            TableColumn::Message => {
                if self.edit_buffer.trim().is_empty() {
                    return Err("Commit message cannot be empty".into());
                }
                if commit.message != self.edit_buffer {
                    commit.message = self.edit_buffer.clone();
                    commit.modifications.message_changed =
                        commit.original.message != commit.message;
                    commit.is_modified = true;
                }
            }
            _ => {}
        }
        Ok(())
    }

    fn run(&mut self) -> Result<bool> {
        let result = loop {
            // Disable raw mode for drawing the table
            let _ = terminal::disable_raw_mode();
            self.draw_table();

            // Enable raw mode only for reading input
            terminal::enable_raw_mode()?;

            if let Event::Key(KeyEvent {
                code,
                kind: KeyEventKind::Press,
                ..
            }) = event::read()?
            {
                let should_continue = if self.editing {
                    match self.handle_edit_key_input(code) {
                        Ok(cont) => cont,
                        Err(_) => break Ok(false),
                    }
                } else {
                    match self.handle_navigation_key_input(code) {
                        Ok(cont) => cont,
                        Err(_) => break Ok(false),
                    }
                };

                if !should_continue {
                    break Ok(true); // User wants to save
                }
            }
        };

        self.restore_terminal();
        result
    }

    fn restore_terminal(&self) {
        let _ = terminal::disable_raw_mode();
        let _ = io::stdout().execute(Clear(ClearType::All));
        let _ = io::stdout().execute(cursor::MoveTo(0, 0));
    }

    fn get_modified_commits(&self) -> Vec<&CommitEdit> {
        self.commits.iter().filter(|c| c.is_modified).collect()
    }
}

pub fn parse_range_input(input: &str, total_commits: usize) -> Result<(usize, usize)> {
    let trimmed_input = input.trim();

    // Check if user entered '*' to select all commits
    if trimmed_input == "*" {
        if total_commits == 0 {
            return Err("No commits available to select".into());
        }
        return Ok((1, total_commits)); // Return 1-based indexing for all commits
    }

    let parts: Vec<&str> = trimmed_input.split('-').collect();

    if parts.len() != 2 {
        return Err("Invalid range format. Use format like '5-11' or '*' for all commits".into());
    }

    let start = parts[0]
        .trim()
        .parse::<usize>()
        .map_err(|_| "Invalid start number in range")?;
    let end = parts[1]
        .trim()
        .parse::<usize>()
        .map_err(|_| "Invalid end number in range")?;

    if start < 1 {
        return Err("Start position must be 1 or greater".into());
    }

    if end < start {
        return Err("End position must be greater than or equal to start position".into());
    }

    Ok((start, end))
}

pub fn select_commit_range(commits: &[CommitInfo]) -> Result<(usize, usize)> {
    println!("\n{}", "Commit History:".bold().green());
    println!("{}", "-".repeat(80).cyan());

    for (i, commit) in commits.iter().enumerate() {
        println!(
            "{:3}. {} {} {} {}",
            i + 1,
            commit.short_hash.yellow().bold(),
            commit
                .timestamp
                .format("%Y-%m-%d %H:%M:%S")
                .to_string()
                .blue(),
            commit.author_name.magenta(),
            commit.message.lines().next().unwrap_or("").white()
        );
    }

    println!("{}", "-".repeat(80).cyan());
    println!(
        "\n{}",
        "Enter range in format 'start-end' (e.g., '5-11') or '*' for all commits:"
            .bold()
            .green()
    );
    print!("{} ", "Range:".bold());
    io::stdout().flush()?;

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

    let (start, end) = parse_range_input(&input, commits.len())?;

    if start > commits.len() || end > commits.len() {
        return Err(format!(
            "Range out of bounds. Available commits: 1-{}",
            commits.len()
        )
        .into());
    }

    Ok((start - 1, end - 1)) // Convert to 0-based indexing
}

pub fn show_range_details(commits: &[CommitInfo], start_idx: usize, end_idx: usize) -> Result<()> {
    let total_selected = end_idx - start_idx + 1;
    let is_all_commits = total_selected == commits.len();

    if is_all_commits {
        println!("\n{}", "Selected All Commits for Editing:".bold().green());
    } else {
        println!("\n{}", "Selected Commit Range:".bold().green());
    }
    println!("{}", "=".repeat(80).cyan());

    for (idx, commit) in commits[start_idx..=end_idx].iter().enumerate() {
        println!(
            "\n{}: {} ({})",
            format!("Commit {}", start_idx + idx + 1).bold(),
            commit.short_hash.yellow(),
            &commit.oid.to_string()[..8]
        );
        println!(
            "{}: {}",
            "Author".bold(),
            format!("{} <{}>", commit.author_name, commit.author_email).magenta()
        );
        println!(
            "{}: {}",
            "Date".bold(),
            commit
                .timestamp
                .format("%Y-%m-%d %H:%M:%S")
                .to_string()
                .blue()
        );
        println!(
            "{}: {}",
            "Message".bold(),
            commit.message.lines().next().unwrap_or("").white()
        );
    }

    println!("\n{}", "=".repeat(80).cyan());
    if is_all_commits {
        println!(
            "{} {} commits selected for editing {}",
            "Total:".bold(),
            total_selected.to_string().green(),
            "(ALL COMMITS)".bold().yellow()
        );
    } else {
        println!(
            "{} {} commits selected for editing",
            "Total:".bold(),
            total_selected.to_string().green()
        );
    }

    Ok(())
}

pub fn get_range_edit_info(args: &Args) -> Result<(String, String, NaiveDateTime, NaiveDateTime)> {
    println!("\n{}", "Range Edit Configuration:".bold().green());

    // Get author name
    let author_name = if let Some(name) = &args.name {
        name.clone()
    } else {
        print!("{} ", "New author name:".bold());
        io::stdout().flush()?;
        let mut input = String::new();
        io::stdin().read_line(&mut input)?;
        input.trim().to_string()
    };

    // Get author email
    let author_email = if let Some(email) = &args.email {
        email.clone()
    } else {
        print!("{} ", "New author email:".bold());
        io::stdout().flush()?;
        let mut input = String::new();
        io::stdin().read_line(&mut input)?;
        input.trim().to_string()
    };

    // Get start timestamp
    let start_timestamp = if let Some(start) = &args.start {
        NaiveDateTime::parse_from_str(start, "%Y-%m-%d %H:%M:%S")
            .map_err(|_| "Invalid start timestamp format")?
    } else {
        print!("{} ", "Start timestamp (YYYY-MM-DD HH:MM:SS):".bold());
        io::stdout().flush()?;
        let mut input = String::new();
        io::stdin().read_line(&mut input)?;
        NaiveDateTime::parse_from_str(input.trim(), "%Y-%m-%d %H:%M:%S")
            .map_err(|_| "Invalid start timestamp format")?
    };

    // Get end timestamp
    let end_timestamp = if let Some(end) = &args.end {
        NaiveDateTime::parse_from_str(end, "%Y-%m-%d %H:%M:%S")
            .map_err(|_| "Invalid end timestamp format")?
    } else {
        print!("{} ", "End timestamp (YYYY-MM-DD HH:MM:SS):".bold());
        io::stdout().flush()?;
        let mut input = String::new();
        io::stdin().read_line(&mut input)?;
        NaiveDateTime::parse_from_str(input.trim(), "%Y-%m-%d %H:%M:%S")
            .map_err(|_| "Invalid end timestamp format")?
    };

    if end_timestamp <= start_timestamp {
        return Err("End timestamp must be after start timestamp".into());
    }

    Ok((author_name, author_email, start_timestamp, end_timestamp))
}

pub fn generate_range_timestamps(
    start_time: NaiveDateTime,
    end_time: NaiveDateTime,
    count: usize,
) -> Vec<NaiveDateTime> {
    if count == 0 {
        return vec![];
    }

    if count == 1 {
        return vec![start_time];
    }

    let total_duration = end_time.signed_duration_since(start_time);
    let step_duration = total_duration / (count - 1) as i32;

    (0..count)
        .map(|i| start_time + step_duration * i as i32)
        .collect()
}

pub fn rewrite_range_commits(args: &Args) -> Result<()> {
    let commits = get_commit_history(args, false)?;

    if commits.is_empty() {
        println!("{}", "No commits found!".red());
        return Ok(());
    }

    let (start_idx, end_idx) = select_commit_range(&commits)?;

    // Show range details for user feedback
    show_range_details(&commits, start_idx, end_idx)?;

    // Get editable fields based on command line flags
    let editable_fields = args.get_editable_fields();

    // Launch interactive table editor
    let mut table = InteractiveTable::new(commits.clone(), start_idx, end_idx, editable_fields);
    let should_save = table.run()?;

    if !should_save {
        println!("{}", "Operation cancelled.".yellow());
        return Ok(());
    }

    let modified_commits = table.get_modified_commits();

    if modified_commits.is_empty() {
        println!("{}", "No changes made.".yellow());
        return Ok(());
    }

    // Show summary of changes
    println!("\n{}", "Summary of Changes:".bold().green());
    println!("{}", "=".repeat(80).cyan());

    for commit_edit in &modified_commits {
        println!(
            "\n{}: {} ({})",
            format!("Commit {}", commit_edit.index + 1).bold(),
            commit_edit.original.short_hash.yellow(),
            &commit_edit.original.oid.to_string()[..8]
        );

        if commit_edit.modifications.author_name_changed {
            println!(
                "  {}: {} -> {}",
                "Author Name".bold(),
                commit_edit.original.author_name.red(),
                commit_edit.author_name.green()
            );
        }

        if commit_edit.modifications.author_email_changed {
            println!(
                "  {}: {} -> {}",
                "Author Email".bold(),
                commit_edit.original.author_email.red(),
                commit_edit.author_email.green()
            );
        }

        if commit_edit.modifications.timestamp_changed {
            println!(
                "  {}: {} -> {}",
                "Timestamp".bold(),
                commit_edit
                    .original
                    .timestamp
                    .format("%Y-%m-%d %H:%M:%S")
                    .to_string()
                    .red(),
                commit_edit
                    .timestamp
                    .format("%Y-%m-%d %H:%M:%S")
                    .to_string()
                    .green()
            );
        }

        if commit_edit.modifications.message_changed {
            let original_first_line = commit_edit.original.message.lines().next().unwrap_or("");
            let new_first_line = commit_edit.message.lines().next().unwrap_or("");
            println!(
                "  {}: {} -> {}",
                "Message".bold(),
                original_first_line.red(),
                new_first_line.green()
            );
        }
    }

    print!("\n{} (y/n): ", "Apply these changes?".bold());
    io::stdout().flush()?;

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

    if confirm.trim().to_lowercase() != "y" {
        println!("{}", "Operation cancelled.".yellow());
        return Ok(());
    }

    // Apply changes
    apply_interactive_range_changes(args, &commits, &table.commits)?;

    println!("\n{}", "✓ Commit range successfully edited!".green().bold());

    if args.show_history {
        get_commit_history(args, true)?;
    }

    Ok(())
}

fn apply_interactive_range_changes(
    args: &Args,
    _original_commits: &[CommitInfo],
    edited_commits: &[CommitEdit],
) -> Result<()> {
    let repo = Repository::open(args.repo_path.as_ref().unwrap())?;
    let head_ref = repo.head()?;
    let branch_name = head_ref
        .shorthand()
        .ok_or("Detached HEAD or invalid branch")?;
    let full_ref = format!("refs/heads/{branch_name}");

    let mut revwalk = repo.revwalk()?;
    revwalk.push_head()?;
    revwalk.set_sorting(Sort::TOPOLOGICAL | Sort::TIME)?;
    let mut orig_oids: Vec<_> = revwalk.filter_map(|id| id.ok()).collect();
    orig_oids.reverse();

    // Create a map for quick lookup of edited commits
    let mut edit_map: HashMap<usize, &CommitEdit> = HashMap::new();
    for commit_edit in edited_commits {
        if commit_edit.is_modified {
            edit_map.insert(commit_edit.index, commit_edit);
        }
    }

    let mut new_map: HashMap<git2::Oid, git2::Oid> = HashMap::new();
    let mut last_new_oid = None;

    for (commit_idx, &oid) in orig_oids.iter().enumerate() {
        let orig = repo.find_commit(oid)?;
        let tree = orig.tree()?;

        let new_parents: Result<Vec<_>> = orig
            .parent_ids()
            .map(|pid| {
                let new_pid = *new_map.get(&pid).unwrap_or(&pid);
                repo.find_commit(new_pid).map_err(|e| e.into())
            })
            .collect();

        let new_oid = if let Some(commit_edit) = edit_map.get(&commit_idx) {
            // This commit has been edited - apply changes
            let author_sig = Signature::new(
                &commit_edit.author_name,
                &commit_edit.author_email,
                &Time::new(commit_edit.timestamp.and_utc().timestamp(), 0),
            )?;

            let committer_sig = Signature::new(
                &commit_edit.author_name,
                &commit_edit.author_email,
                &Time::new(commit_edit.timestamp.and_utc().timestamp(), 0),
            )?;

            // Use the edited message or keep the original if not changed
            let message = if commit_edit.modifications.message_changed {
                &commit_edit.message
            } else {
                orig.message().unwrap_or_default()
            };

            repo.commit(
                None,
                &author_sig,
                &committer_sig,
                message,
                &tree,
                &new_parents?.iter().collect::<Vec<_>>(),
            )?
        } else {
            // Keep other commits as-is but update parent references
            let author = orig.author();
            let committer = orig.committer();

            repo.commit(
                None,
                &author,
                &committer,
                orig.message().unwrap_or_default(),
                &tree,
                &new_parents?.iter().collect::<Vec<_>>(),
            )?
        };

        new_map.insert(oid, new_oid);
        last_new_oid = Some(new_oid);
    }

    if let Some(new_head) = last_new_oid {
        repo.reference(
            &full_ref,
            new_head,
            true,
            "edited commit range interactively",
        )?;
        println!(
            "{} '{}' -> {}",
            "Updated branch".green(),
            branch_name.cyan(),
            new_head.to_string()[..8].to_string().cyan()
        );
    }

    Ok(())
}

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

    fn create_test_repo_with_commits() -> (TempDir, String) {
        let temp_dir = TempDir::new().unwrap();
        let repo_path = temp_dir.path().to_str().unwrap().to_string();

        // Initialize git repo
        let repo = git2::Repository::init(&repo_path).unwrap();

        // Create multiple commits
        for i in 1..=5 {
            let file_path = temp_dir.path().join(format!("test{i}.txt"));
            fs::write(&file_path, format!("test content {i}")).unwrap();

            let mut index = repo.index().unwrap();
            index
                .add_path(std::path::Path::new(&format!("test{i}.txt")))
                .unwrap();
            index.write().unwrap();

            let tree_id = index.write_tree().unwrap();
            let tree = repo.find_tree(tree_id).unwrap();

            let sig = git2::Signature::new(
                "Test User",
                "test@example.com",
                &git2::Time::new(1234567890 + i as i64 * 3600, 0),
            )
            .unwrap();

            let parents = if i == 1 {
                vec![]
            } else {
                let head = repo.head().unwrap();
                let parent_commit = head.peel_to_commit().unwrap();
                vec![parent_commit]
            };

            repo.commit(
                Some("HEAD"),
                &sig,
                &sig,
                &format!("Commit {i}"),
                &tree,
                &parents.iter().collect::<Vec<_>>(),
            )
            .unwrap();
        }

        (temp_dir, repo_path)
    }

    #[test]
    fn test_parse_range_input_valid() {
        let result = parse_range_input("5-11", 20);
        assert!(result.is_ok());
        let (start, end) = result.unwrap();
        assert_eq!(start, 5);
        assert_eq!(end, 11);
    }

    #[test]
    fn test_parse_range_input_with_spaces() {
        let result = parse_range_input(" 3 - 8 ", 20);
        assert!(result.is_ok());
        let (start, end) = result.unwrap();
        assert_eq!(start, 3);
        assert_eq!(end, 8);
    }

    #[test]
    fn test_parse_range_input_asterisk() {
        let result = parse_range_input("*", 10);
        assert!(result.is_ok());
        let (start, end) = result.unwrap();
        assert_eq!(start, 1);
        assert_eq!(end, 10);

        // Test with empty repository
        let result = parse_range_input("*", 0);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_range_input_invalid_format() {
        let result = parse_range_input("5", 20);
        assert!(result.is_err());

        let result = parse_range_input("5-11-15", 20);
        assert!(result.is_err());

        let result = parse_range_input("abc-def", 20);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_range_input_invalid_range() {
        let result = parse_range_input("11-5", 20);
        assert!(result.is_err());

        let result = parse_range_input("0-5", 20);
        assert!(result.is_err());
    }

    #[test]
    fn test_generate_range_timestamps() {
        let start =
            NaiveDateTime::parse_from_str("2023-01-01 00:00:00", "%Y-%m-%d %H:%M:%S").unwrap();
        let end =
            NaiveDateTime::parse_from_str("2023-01-01 10:00:00", "%Y-%m-%d %H:%M:%S").unwrap();

        let timestamps = generate_range_timestamps(start, end, 5);

        assert_eq!(timestamps.len(), 5);
        assert_eq!(timestamps[0], start);
        assert_eq!(timestamps[4], end);

        // Check that timestamps are evenly distributed
        for i in 1..timestamps.len() {
            assert!(timestamps[i] >= timestamps[i - 1]);
        }
    }

    #[test]
    fn test_generate_range_timestamps_edge_cases() {
        let start =
            NaiveDateTime::parse_from_str("2023-01-01 00:00:00", "%Y-%m-%d %H:%M:%S").unwrap();
        let end =
            NaiveDateTime::parse_from_str("2023-01-01 10:00:00", "%Y-%m-%d %H:%M:%S").unwrap();

        // Zero count
        let timestamps = generate_range_timestamps(start, end, 0);
        assert_eq!(timestamps.len(), 0);

        // Single timestamp
        let timestamps = generate_range_timestamps(start, end, 1);
        assert_eq!(timestamps.len(), 1);
        assert_eq!(timestamps[0], start);
    }

    #[test]
    fn test_rewrite_range_commits_with_repo() {
        let (_temp_dir, repo_path) = create_test_repo_with_commits();
        let args = Args {
            repo_path: Some(repo_path),
            email: Some("new@example.com".to_string()),
            name: Some("New User".to_string()),
            start: Some("2023-01-01 00:00:00".to_string()),
            end: Some("2023-01-01 10:00:00".to_string()),
            show_history: false,
            pick_specific_commits: false,
            range: false,
            simulate: false,
            show_diff: false,
            edit_message: false,
            edit_author: false,
            edit_time: false,
        };

        // Test that get_commit_history returns commits for this repo
        let commits = get_commit_history(&args, false).unwrap();
        assert_eq!(commits.len(), 5);

        // Test range validation
        let (start, end) = (0, 2); // 0-based indexing
        assert!(start <= end);
        assert!(end < commits.len());

        // Test timestamp generation
        let start_time =
            NaiveDateTime::parse_from_str("2023-01-01 00:00:00", "%Y-%m-%d %H:%M:%S").unwrap();
        let end_time =
            NaiveDateTime::parse_from_str("2023-01-01 10:00:00", "%Y-%m-%d %H:%M:%S").unwrap();
        let timestamps = generate_range_timestamps(start_time, end_time, 3);
        assert_eq!(timestamps.len(), 3);
    }
}