synh8 0.1.1

A synaptic-inspired TUI for managing APT packages on Debian/Ubuntu. Linux only.
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
//! Core business logic - Typestate Package Manager
//!
//! This module implements a typestate-based package manager where:
//! - `user_intent: HashMap<PackageId, UserIntent>` is the single source of truth
//! - APT marks are derived from intent via `plan()`
//! - State transitions are enforced at compile time

use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::os::unix::io::AsRawFd;

use color_eyre::Result;
use rust_apt::cache::PackageSort;

use crate::apt::{AptCache, format_apt_errors};
use crate::search::SearchIndex;
use crate::types::*;

// ============================================================================
// Search State (shared across all manager states)
// ============================================================================

/// Search state management
#[derive(Default)]
pub struct SearchState {
    pub index: Option<SearchIndex>,
    pub query: String,
    pub results: Option<HashSet<String>>,
}

/// Sort configuration
#[derive(Clone)]
pub struct SortSettings {
    pub sort_by: SortBy,
    pub ascending: bool,
}

impl Default for SortSettings {
    fn default() -> Self {
        Self {
            sort_by: SortBy::CandidateVersion,
            ascending: true,
        }
    }
}

// ============================================================================
// Shared State (across all typestate variants)
// ============================================================================

/// State shared across all PackageManager states.
/// Fields are private to prevent bypassing the typestate API.
struct SharedState {
    cache: AptCache,
    user_intent: HashMap<PackageId, UserIntent>,
    search: SearchState,
    list: Vec<PackageInfo>,
    /// Per-filter memoization of rebuild_list() results.
    /// Keyed by FilterCategory only; search/sort are applied in-memory.
    /// Invalidation: compute_plan() clears MarkedChanges only;
    /// refresh()/commit() clear all entries.
    filter_cache: HashMap<FilterCategory, (Vec<PackageInfo>, ColumnWidths)>,
    upgradable_count: usize,
    installed_count: usize,
    total_count: usize,
    selected_filter: FilterCategory,
    sort_settings: SortSettings,
}

impl SharedState {
    fn new(cache: AptCache) -> Self {
        Self {
            cache,
            user_intent: HashMap::new(),
            search: SearchState::default(),
            list: Vec::new(),
            filter_cache: HashMap::new(),
            upgradable_count: 0,
            installed_count: 0,
            total_count: 0,
            selected_filter: FilterCategory::Upgradable,
            sort_settings: SortSettings::default(),
        }
    }

    /// Compute and cache package counts from the APT cache
    fn compute_cache_counts(&mut self) {
        self.upgradable_count = 0;
        self.installed_count = 0;
        self.total_count = 0;

        for pkg in self.cache.packages(&PackageSort::default()) {
            self.total_count += 1;
            if pkg.is_installed() {
                self.installed_count += 1;
                if pkg.is_upgradable() {
                    self.upgradable_count += 1;
                }
            }
        }
    }
}

// ============================================================================
// Typestate Package Manager
// ============================================================================

/// Package manager with compile-time state tracking
pub struct PackageManager<S> {
    shared: SharedState,
    state: S,
}

// Clean state - no user marks
impl PackageManager<Clean> {
    /// Create a new PackageManager in Clean state
    pub fn new() -> Result<Self> {
        let cache = AptCache::new()?;
        let mut shared = SharedState::new(cache);
        shared.compute_cache_counts();

        let mut mgr = Self {
            shared,
            state: Clean,
        };
        mgr.rebuild_list();
        Ok(mgr)
    }

    /// Mark a package for install/upgrade, transitioning to Dirty
    pub fn mark_install(mut self, id: PackageId) -> PackageManager<Dirty> {
        self.shared.user_intent.insert(id, UserIntent::Install);
        PackageManager {
            shared: self.shared,
            state: Dirty,
        }
    }

}

// Dirty state - has user marks, no computed plan
impl PackageManager<Dirty> {
    /// Mark a package for install/upgrade
    pub fn mark_install(mut self, id: PackageId) -> Self {
        self.shared.user_intent.insert(id, UserIntent::Install);
        self
    }

    /// Unmark a package (remove user intent)
    pub fn unmark(mut self, id: PackageId) -> Self {
        self.shared.user_intent.remove(&id);
        self
    }

    /// Reset all marks, returning to Clean state
    pub fn reset(mut self) -> PackageManager<Clean> {
        self.shared.user_intent.clear();
        self.shared
            .cache
            .clear_all_marks()
            .expect("APT state corruption: failed to clear marks during reset");
        PackageManager {
            shared: self.shared,
            state: Clean,
        }
    }

    /// Compute plan from user intent, transitioning to Planned
    #[hotpath::measure]
    pub fn plan(mut self) -> PackageManager<Planned> {
        // 1. Clear all APT marks
        self.shared
            .cache
            .clear_all_marks()
            .expect("APT state corruption: failed to clear marks during plan");

        // 2. Apply user intent to APT cache
        for (&id, &intent) in &self.shared.user_intent {
            match intent {
                UserIntent::Install => self.shared.cache.mark_install_id(id),
                UserIntent::Remove => self.shared.cache.mark_delete_id(id),
                UserIntent::Hold => self.shared.cache.mark_keep_id(id),
                UserIntent::Default => {}
            }
        }

        // 3. Resolve dependencies
        let errors = match self.shared.cache.resolve() {
            Ok(()) => Vec::new(),
            Err(e) => vec![format_apt_errors(&e)],
        };

        // 4. Collect raw change data from APT state
        // (separate pass to avoid borrow conflict)
        let change_data: Vec<_> = self.shared.cache.get_changes()
            .map(|pkg| {
                let fullname = pkg.fullname(false);
                let is_installed = pkg.is_installed();
                let marked_install = pkg.marked_install();
                let marked_upgrade = pkg.marked_upgrade();
                let marked_delete = pkg.marked_delete();
                let candidate_info = pkg.candidate().map(|c| (c.size(), c.installed_size()));
                (fullname, is_installed, marked_install, marked_upgrade, marked_delete, candidate_info)
            })
            .collect();

        // 5. Build PlannedChanges from raw data
        let mut changes = Vec::new();
        let mut download_size = 0u64;
        let mut install_size_change = 0i64;

        for (fullname, is_installed, marked_install, marked_upgrade, marked_delete, candidate_info) in change_data {
            let id = self.shared.cache.id_for(&fullname);

            let is_user_requested = self.shared.user_intent.contains_key(&id);

            let (action, reason) = if marked_install || marked_upgrade {
                let action = if is_installed {
                    ChangeAction::Upgrade
                } else {
                    ChangeAction::Install
                };
                let reason = if is_user_requested {
                    ChangeReason::UserRequested
                } else {
                    ChangeReason::Dependency
                };
                (action, reason)
            } else if marked_delete {
                let reason = if is_user_requested {
                    ChangeReason::UserRequested
                } else {
                    ChangeReason::AutoRemove
                };
                (ChangeAction::Remove, reason)
            } else {
                continue;
            };

            let (pkg_download, pkg_size_change) = if let Some((dl_size, inst_size)) = candidate_info {
                let sz = if action == ChangeAction::Remove {
                    -(inst_size as i64)
                } else {
                    inst_size as i64
                };
                (dl_size, sz)
            } else {
                (0, 0)
            };

            download_size += pkg_download;
            install_size_change += pkg_size_change;

            changes.push(PlannedChange {
                package: id,
                action,
                reason,
                download_size: pkg_download,
                size_change: pkg_size_change,
            });
        }

        let planned = Planned {
            changes,
            download_size,
            install_size_change,
            errors,
        };

        PackageManager {
            shared: self.shared,
            state: planned,
        }
    }

}

// Planned state - dependencies resolved, changeset computed
impl PackageManager<Planned> {
    /// Get the computed changes
    pub fn changes(&self) -> &[PlannedChange] {
        &self.state.changes
    }

    /// Apply planned changes to update package statuses in the list.
    /// No distinction between user-marked and dependency - all marked packages look the same.
    pub fn apply_planned_statuses(&mut self) {
        // Build a map of PackageId -> action from planned changes
        let change_map: HashMap<PackageId, ChangeAction> = self.state.changes
            .iter()
            .map(|c| (c.package, c.action))
            .collect();

        // Update statuses in the list - no user vs dependency distinction
        for pkg in &mut self.shared.list {
            if let Some(&action) = change_map.get(&pkg.id) {
                pkg.status = match action {
                    ChangeAction::Install => PackageStatus::MarkedForInstall,
                    ChangeAction::Upgrade => PackageStatus::MarkedForUpgrade,
                    ChangeAction::Remove => PackageStatus::MarkedForRemove,
                    ChangeAction::Downgrade => PackageStatus::MarkedForUpgrade,
                };
            }
        }
    }

    /// Go back to modify marks (keeps marks, discards plan)
    pub fn modify(self) -> PackageManager<Dirty> {
        PackageManager {
            shared: self.shared,
            state: Dirty,
        }
    }

    /// Commit the changes using caller-provided progress implementations
    pub fn commit_with_progress(
        mut self,
        acquire_progress: &mut rust_apt::progress::AcquireProgress,
        install_progress: &mut rust_apt::progress::InstallProgress,
    ) -> Result<PackageManager<Clean>> {
        self.shared.cache.commit_with_progress(acquire_progress, install_progress)?;
        self.shared.user_intent.clear();
        self.shared.search.index = None;

        Ok(PackageManager {
            shared: self.shared,
            state: Clean,
        })
    }
}

// ============================================================================
// Shared functionality (all states)
// ============================================================================

impl<S: ReadableState> PackageManager<S> {
    /// Get a package by index in current list
    pub fn get_package(&self, index: usize) -> Option<&PackageInfo> {
        self.shared.list.get(index)
    }

    /// Get number of packages in current list
    pub fn package_count(&self) -> usize {
        self.shared.list.len()
    }

    /// Check if a package is user-marked
    pub fn is_user_marked(&self, id: PackageId) -> bool {
        self.shared.user_intent.contains_key(&id)
    }

    /// Get current filter
    pub fn selected_filter(&self) -> FilterCategory {
        self.shared.selected_filter
    }

    /// Get upgradable count
    pub fn upgradable_count(&self) -> usize {
        self.shared.upgradable_count
    }

    /// Get search query
    pub fn search_query(&self) -> &str {
        &self.shared.search.query
    }

    /// Get search result count
    pub fn search_result_count(&self) -> Option<usize> {
        self.shared.search.results.as_ref().map(std::collections::HashSet::len)
    }

    // === Filtering & Listing ===

    /// Apply a filter category and rebuild the package list
    pub fn apply_filter(&mut self, filter: FilterCategory) {
        self.shared.selected_filter = filter;
        self.rebuild_list();
    }

    /// Rebuild the package list based on current filter and search.
    /// Uses per-filter memoization when no search is active to avoid
    /// expensive FFI re-extraction on repeated filter switches.
    /// The cache stores lists with BASE statuses only (no user_intent overlay);
    /// the overlay is applied fresh on every restore so mark changes don't
    /// require cache invalidation for non-MarkedChanges filters.
    #[hotpath::measure]
    pub fn rebuild_list(&mut self) -> ColumnWidths {
        let filter = self.shared.selected_filter;
        let has_search = self.shared.search.results.is_some();

        // Cache hit: clone the cached base list (cache entry stays for reuse).
        if !has_search {
            if let Some((cached_list, col_widths)) = self.shared.filter_cache.get(&filter) {
                self.shared.list = cached_list.clone();
                let col_widths = col_widths.clone();
                Self::apply_user_intent_overlay(&mut self.shared.list, &self.shared.user_intent);
                self.sort_list();
                return col_widths;
            }
        }

        self.shared.list.clear();

        let sort = if self.shared.selected_filter == FilterCategory::Upgradable {
            PackageSort::default().upgradable()
        } else {
            PackageSort::default()
        };

        // First pass: collect package IDs that match filters
        // (avoids borrow conflict between cache iteration and extract_package_info)
        let matching_ids: Vec<PackageId> = {
            let search_results = &self.shared.search.results;
            let user_intent = &self.shared.user_intent;
            let fullname_to_id = &self.shared.cache.fullname_to_id;

            self.shared.cache.packages(&sort)
                .filter(|pkg| {
                    let matches_category = match self.shared.selected_filter {
                        FilterCategory::Upgradable => pkg.is_upgradable(),
                        FilterCategory::MarkedChanges => {
                            // Check both user_intent (works in Dirty state) and
                            // APT marks (works in Planned state for dependencies)
                            let has_user_intent = fullname_to_id.get(&pkg.fullname(false))
                                .map(|id| user_intent.contains_key(id))
                                .unwrap_or(false);
                            has_user_intent || pkg.marked_install() || pkg.marked_upgrade() || pkg.marked_delete()
                        }
                        FilterCategory::Installed => pkg.is_installed(),
                        FilterCategory::NotInstalled => !pkg.is_installed(),
                        FilterCategory::All => true,
                    };

                    let matches_search = match search_results {
                        Some(results) => results.contains(pkg.name()),
                        None => true,
                    };

                    matches_category && matches_search
                })
                .filter_map(|pkg| fullname_to_id.get(&pkg.fullname(false)).copied())
                .collect()
        };

        // Second pass: extract full package info (base statuses only)
        for id in matching_ids {
            if let Some(info) = self.shared.cache.get_by_id(id).and_then(|pkg| self.shared.cache.extract_package_info(&pkg)) {
                self.shared.list.push(info);
            }
        }

        // Calculate column widths from base data
        let mut col_widths = ColumnWidths::new();
        for pkg in &self.shared.list {
            let display_len = self.shared.cache.display_name(&pkg.name).len() as u16;
            col_widths.name = col_widths.name.max(display_len);
            col_widths.section = col_widths.section.max(pkg.section.len() as u16);
            col_widths.installed = col_widths.installed.max(pkg.installed_version.len() as u16);
            col_widths.candidate = col_widths.candidate.max(pkg.candidate_version.len() as u16);
        }

        // Cache the base list (before user_intent overlay) for future switches
        if !has_search {
            self.shared.filter_cache.insert(filter, (self.shared.list.clone(), col_widths.clone()));
        }

        // Apply user_intent overlay after caching base data
        Self::apply_user_intent_overlay(&mut self.shared.list, &self.shared.user_intent);

        self.sort_list();
        col_widths
    }

    /// Apply user_intent status overlay to a package list.
    /// Converts base statuses (Installed/Upgradable/NotInstalled) to marked
    /// statuses (MarkedForUpgrade/MarkedForInstall/etc) for packages in user_intent.
    fn apply_user_intent_overlay(list: &mut [PackageInfo], user_intent: &HashMap<PackageId, UserIntent>) {
        for info in list.iter_mut() {
            if let Some(&intent) = user_intent.get(&info.id) {
                info.status = match intent {
                    UserIntent::Install => {
                        if info.status == PackageStatus::Upgradable {
                            PackageStatus::MarkedForUpgrade
                        } else {
                            PackageStatus::MarkedForInstall
                        }
                    }
                    UserIntent::Remove => PackageStatus::MarkedForRemove,
                    UserIntent::Hold => PackageStatus::Keep,
                    UserIntent::Default => info.status,
                };
            }
        }
    }

    /// Sort the package list
    fn sort_list(&mut self) {
        let sort_by = self.shared.sort_settings.sort_by;
        let ascending = self.shared.sort_settings.ascending;

        self.shared.list.sort_by(|a, b| {
            let ord = match sort_by {
                SortBy::Name => a.name.cmp(&b.name),
                SortBy::Section => a.section.cmp(&b.section),
                SortBy::InstalledVersion => a.installed_version.cmp(&b.installed_version),
                SortBy::CandidateVersion => a.candidate_version.cmp(&b.candidate_version),
            };
            if ascending { ord } else { ord.reverse() }
        });
    }

    /// Update sort settings and re-sort
    pub fn set_sort(&mut self, sort_by: SortBy, ascending: bool) {
        self.shared.sort_settings.sort_by = sort_by;
        self.shared.sort_settings.ascending = ascending;
        self.sort_list();
    }

    // === Search ===

    /// Ensure search index is built
    pub fn ensure_search_index(&mut self) -> Result<std::time::Duration> {
        if self.shared.search.index.is_none() {
            let mut index = SearchIndex::new()?;
            let (_count, duration) = index.build(&self.shared.cache)?;
            self.shared.search.index = Some(index);
            return Ok(duration);
        }
        Ok(std::time::Duration::ZERO)
    }

    /// Set search query and execute search
    pub fn set_search_query(&mut self, query: &str) -> Result<()> {
        self.shared.search.query = query.to_string();

        if query.is_empty() {
            self.shared.search.results = None;
        } else if let Some(ref index) = self.shared.search.index {
            self.shared.search.results = Some(index.search(query)?);
        }
        Ok(())
    }

    /// Clear search query and results
    pub fn clear_search(&mut self) {
        self.shared.search.query.clear();
        self.shared.search.results = None;
    }

    // === Dependency Queries ===

    /// Get forward dependencies for a package
    pub fn get_dependencies(&self, name: &str) -> Vec<(String, String)> {
        self.shared.cache.get_dependencies(name)
    }

    /// Get reverse dependencies for a package
    pub fn get_reverse_dependencies(&self, name: &str) -> Vec<(String, String)> {
        self.shared.cache.get_reverse_dependencies(name)
    }

}

// ============================================================================
// Manager Wrapper (for TUI that can't hold consuming-self types)
// ============================================================================

/// Wrapper enum that allows mutable access without consuming self
/// This is necessary for TUI where we can't easily handle typestate transitions
#[derive(Default)]
pub enum ManagerState {
    Clean(PackageManager<Clean>),
    Dirty(PackageManager<Dirty>),
    Planned(PackageManager<Planned>),
    /// Temporary placeholder used by `std::mem::take` during state transitions.
    /// Must never be observed outside a `&mut self` method body.
    /// SAFETY: Any method that `take`s self must assign `*self` back before
    /// returning — including on error paths — or accessors will panic.
    #[default]
    Transitioning,
}


impl ManagerState {
    /// Private helper: borrow the SharedState from any non-Transitioning variant.
    fn shared(&self) -> &SharedState {
        match self {
            ManagerState::Clean(m) => &m.shared,
            ManagerState::Dirty(m) => &m.shared,
            ManagerState::Planned(m) => &m.shared,
            ManagerState::Transitioning => panic!("Transitioning state observed"),
        }
    }

    /// Private helper: mutably borrow the SharedState from any non-Transitioning variant.
    fn shared_mut(&mut self) -> &mut SharedState {
        match self {
            ManagerState::Clean(m) => &mut m.shared,
            ManagerState::Dirty(m) => &mut m.shared,
            ManagerState::Planned(m) => &mut m.shared,
            ManagerState::Transitioning => panic!("Transitioning state observed"),
        }
    }

    /// Create a new manager in Clean state
    pub fn new() -> Result<Self> {
        Ok(ManagerState::Clean(PackageManager::new()?))
    }

    /// Get the planned changes (only valid in Planned state)
    pub fn planned_changes(&self) -> Option<&[PlannedChange]> {
        match self {
            ManagerState::Planned(m) => Some(m.changes()),
            _ => None,
        }
    }

    /// Check if we have any user intent (marks)
    pub fn has_marks(&self) -> bool {
        !self.shared().user_intent.is_empty()
    }

    // Accessor methods that work in any state

    pub fn user_mark_count(&self) -> usize {
        self.shared().user_intent.len()
    }

    pub fn download_size(&self) -> u64 {
        match self {
            ManagerState::Planned(m) => m.state.download_size,
            _ => 0,
        }
    }

    pub fn install_size_change(&self) -> i64 {
        match self {
            ManagerState::Planned(m) => m.state.install_size_change,
            _ => 0,
        }
    }

    pub fn list(&self) -> &[PackageInfo] {
        self.shared().list.as_slice()
    }

    pub fn get_package(&self, index: usize) -> Option<&PackageInfo> {
        self.shared().list.get(index)
    }

    pub fn package_count(&self) -> usize {
        self.shared().list.len()
    }

    pub fn is_user_marked(&self, id: PackageId) -> bool {
        self.shared().user_intent.contains_key(&id)
    }

    pub fn selected_filter(&self) -> FilterCategory {
        self.shared().selected_filter
    }

    pub fn upgradable_count(&self) -> usize {
        self.shared().upgradable_count
    }

    pub fn search_query(&self) -> &str {
        &self.shared().search.query
    }

    pub fn search_result_count(&self) -> Option<usize> {
        self.shared().search.results.as_ref().map(std::collections::HashSet::len)
    }

    pub fn get_dependencies(&self, name: &str) -> Vec<(String, String)> {
        self.shared().cache.get_dependencies(name)
    }

    pub fn get_reverse_dependencies(&self, name: &str) -> Vec<(String, String)> {
        self.shared().cache.get_reverse_dependencies(name)
    }

    pub fn fetch_changelog(&self, name: &str) -> Result<Vec<String>, String> {
        match std::process::Command::new("apt")
            .args(["changelog", name])
            .output()
        {
            Ok(output) => {
                if output.status.success() {
                    let content = String::from_utf8_lossy(&output.stdout);
                    let lines: Vec<String> = content.lines().map(std::string::ToString::to_string).collect();
                    if lines.is_empty() {
                        Ok(vec!["No changelog available.".to_string()])
                    } else {
                        Ok(lines)
                    }
                } else {
                    let err = String::from_utf8_lossy(&output.stderr);
                    Err(format!("Error: {err}"))
                }
            }
            Err(e) => Err(format!("Failed to run apt changelog: {e}")),
        }
    }

    // Mutating methods that work in any state

    pub fn apply_filter(&mut self, filter: FilterCategory) {
        self.shared_mut().selected_filter = filter;
        self.rebuild_list();
    }

    /// Set the filter category without rebuilding the list.
    /// Caller is responsible for calling rebuild_list() afterwards.
    pub fn set_filter(&mut self, filter: FilterCategory) {
        self.shared_mut().selected_filter = filter;
    }

    pub fn rebuild_list(&mut self) -> ColumnWidths {
        match self {
            ManagerState::Clean(m) => m.rebuild_list(),
            ManagerState::Dirty(m) => m.rebuild_list(),
            ManagerState::Planned(m) => {
                let col_widths = m.rebuild_list();
                // Apply planned changes to update statuses for dependencies
                m.apply_planned_statuses();
                col_widths
            }
            ManagerState::Transitioning => panic!("Transitioning state observed"),
        }
    }

    /// Pre-warm the filter cache by building the list for all filters.
    /// Called once at startup so subsequent filter switches are instant.
    /// Restores the original filter afterwards.
    pub fn pre_warm_filter_cache(&mut self) {
        let original_filter = self.selected_filter();
        for &filter in FilterCategory::all() {
            if filter == original_filter {
                continue; // Already built by initial refresh_ui_state
            }
            self.set_filter(filter);
            self.rebuild_list();
        }
        // Restore original filter and rebuild
        self.set_filter(original_filter);
        self.rebuild_list();
    }

    pub fn set_sort(&mut self, sort_by: SortBy, ascending: bool) {
        let shared = self.shared_mut();
        shared.sort_settings.sort_by = sort_by;
        shared.sort_settings.ascending = ascending;
        // Re-sort the current list in place
        let asc = shared.sort_settings.ascending;
        shared.list.sort_by(|a, b| {
            let ord = match sort_by {
                SortBy::Name => a.name.cmp(&b.name),
                SortBy::Section => a.section.cmp(&b.section),
                SortBy::InstalledVersion => a.installed_version.cmp(&b.installed_version),
                SortBy::CandidateVersion => a.candidate_version.cmp(&b.candidate_version),
            };
            if asc { ord } else { ord.reverse() }
        });
    }

    pub fn ensure_search_index(&mut self) -> Result<std::time::Duration> {
        let shared = self.shared_mut();
        if shared.search.index.is_none() {
            let mut index = SearchIndex::new()?;
            let (_count, duration) = index.build(&shared.cache)?;
            shared.search.index = Some(index);
            return Ok(duration);
        }
        Ok(std::time::Duration::ZERO)
    }

    pub fn set_search_query(&mut self, query: &str) -> Result<()> {
        let shared = self.shared_mut();
        shared.search.query = query.to_string();
        if query.is_empty() {
            shared.search.results = None;
        } else if let Some(ref index) = shared.search.index {
            shared.search.results = Some(index.search(query)?);
        }
        Ok(())
    }

    pub fn clear_search(&mut self) {
        let shared = self.shared_mut();
        shared.search.query.clear();
        shared.search.results = None;
    }

    pub fn has_search_results(&self) -> bool {
        self.shared().search.results.is_some()
    }

    pub fn search_query_pop(&mut self) {
        self.shared_mut().search.query.pop();
    }

    pub fn search_query_push(&mut self, c: char) {
        self.shared_mut().search.query.push(c);
    }

    pub fn refresh(&mut self) -> Result<(), String> {
        let shared = self.shared_mut();
        shared.cache.refresh().map_err(|e| e.to_string())?;
        shared.user_intent.clear();
        shared.filter_cache.clear();
        shared.search.index = None;
        shared.search.query.clear();
        shared.search.results = None;
        shared.compute_cache_counts();
        // Transition to Clean to discard any stale Planned/Dirty state
        self.reset();
        Ok(())
    }

    pub fn update_cache_counts(&mut self) {
        self.shared_mut().compute_cache_counts();
    }

    /// Get the count for a filter category
    pub fn filter_count(&self, filter: FilterCategory) -> usize {
        let shared = self.shared();
        let (upgradable, installed, total, user_marks) =
            (shared.upgradable_count, shared.installed_count, shared.total_count, shared.user_intent.len());

        match filter {
            FilterCategory::Upgradable => upgradable,
            FilterCategory::MarkedChanges => {
                // Include both user-marked and dependency-marked packages
                // from planned_changes, not just user_intent count.
                self.planned_changes()
                    .map(|changes| changes.len())
                    .unwrap_or(user_marks)
            }
            FilterCategory::Installed => installed,
            FilterCategory::NotInstalled => total - installed,
            FilterCategory::All => total,
        }
    }

    /// Mark all upgradable packages in the entire cache (not just filtered view)
    pub fn mark_all_upgradable(&mut self) {
        let upgradable_ids: Vec<PackageId> = {
            let cache = self.cache();
            cache.packages(&PackageSort::default().upgradable())
                .map(|pkg| pkg.fullname(false))
                .filter_map(|name| cache.get_id(&name))
                .collect()
        };

        for id in upgradable_ids {
            self.mark_install(id);
        }
    }

    /// Get reference to the APT cache for ID lookups
    pub fn cache(&self) -> &AptCache {
        &self.shared().cache
    }
}

// ============================================================================
// Macros for reducing boilerplate in ManagerState
// ============================================================================

/// Helper to take ownership and perform state transition
impl ManagerState {
    /// Mark a package for install, handling state transitions
    pub fn mark_install(&mut self, id: PackageId) {
        *self = match std::mem::take(self) {
            ManagerState::Clean(m) => ManagerState::Dirty(m.mark_install(id)),
            ManagerState::Dirty(m) => ManagerState::Dirty(m.mark_install(id)),
            ManagerState::Planned(m) => ManagerState::Dirty(m.modify().mark_install(id)),
            ManagerState::Transitioning => panic!("ManagerState::Transitioning should not be observed"),
        };
    }

    /// Unmark a package from user_intent (low-level, doesn't handle cascade).
    /// For proper toggle behavior with cascade, use `toggle()` instead.
    pub fn unmark(&mut self, id: PackageId) {
        if !self.is_user_marked(id) {
            return;
        }

        *self = match std::mem::take(self) {
            ManagerState::Clean(m) => ManagerState::Clean(m),
            ManagerState::Dirty(m) => ManagerState::Dirty(m.unmark(id)),
            ManagerState::Planned(m) => ManagerState::Dirty(m.modify().unmark(id)),
            ManagerState::Transitioning => panic!("ManagerState::Transitioning should not be observed"),
        };
    }

    /// Toggle a package's mark state with full cascade/orphan handling.
    /// Returns (packages_affected, is_marking) for UI confirmation.
    ///
    /// - If not marked: marks it + computes plan (deps shown in plan)
    /// - If marked (user or dep): unmarks with cascade, returns affected packages
    #[hotpath::measure]
    pub fn toggle(&mut self, id: PackageId) -> ToggleResult {
        // First, compute plan if needed to know current marked state
        self.compute_plan();

        // Check if package is in the current planned change set.
        // This covers user-marked and dependency-marked packages without
        // a full rebuild_list() (which would iterate the entire APT cache).
        let is_currently_marked = self.planned_changes()
            .is_some_and(|changes| changes.iter().any(|c| c.package == id));

        if is_currently_marked {
            // UNMARK flow
            self.toggle_unmark(id)
        } else {
            // MARK flow
            self.toggle_mark_impl(id)
        }
    }

    /// Internal: handle marking a package
    fn toggle_mark_impl(&mut self, id: PackageId) -> ToggleResult {
        // Snapshot planned changes before marking (small set, not full list)
        let planned_before: HashSet<PackageId> = self.planned_changes()
            .map(|changes| changes.iter().map(|c| c.package).collect())
            .unwrap_or_default();

        // Mark and compute plan
        self.mark_install(id);
        self.compute_plan();
        self.rebuild_list();

        // Find newly planned packages (deps) by diffing the small planned sets
        let newly_marked: Vec<PackageId> = self.planned_changes()
            .map(|changes| {
                changes.iter()
                    .filter(|c| c.package != id && !planned_before.contains(&c.package))
                    .map(|c| c.package)
                    .collect()
            })
            .unwrap_or_default();

        ToggleResult::Marked {
            package: id,
            additional: newly_marked,
        }
    }

    /// Internal: handle unmarking a package with cascade
    fn toggle_unmark(&mut self, id: PackageId) -> ToggleResult {
        // Snapshot planned changes before unmarking (small set, not full list)
        let planned_before: HashSet<PackageId> = self.planned_changes()
            .map(|changes| changes.iter().map(|c| c.package).collect())
            .unwrap_or_default();

        // Determine what to remove from user_intent
        let to_remove: Vec<PackageId> = if self.is_user_marked(id) {
            vec![id]
        } else {
            // Package is a dependency: find user_intent packages that depend on it
            self.find_user_intent_depending_on(id)
        };

        // Remove from user_intent
        for pkg_id in &to_remove {
            self.unmark(*pkg_id);
        }

        // Recompute plan (orphans automatically disappear)
        self.compute_plan();
        self.rebuild_list();

        // Diff planned sets to find what got unmarked
        let planned_after: HashSet<PackageId> = self.planned_changes()
            .map(|changes| changes.iter().map(|c| c.package).collect())
            .unwrap_or_default();

        // Check if the target package is still planned (unmark failed)
        if planned_after.contains(&id) {
            return ToggleResult::NoChange { package: id };
        }

        let also_unmarked: Vec<PackageId> = planned_before.iter()
            .filter(|pkg_id| !planned_after.contains(pkg_id) && **pkg_id != id)
            .copied()
            .collect();

        ToggleResult::Unmarked {
            package: id,
            also_unmarked,
        }
    }

    /// Find user_intent packages that (transitively) depend on the given package
    fn find_user_intent_depending_on(&self, target_id: PackageId) -> Vec<PackageId> {
        let cache = self.cache();
        let target_name = match cache.fullname_of(target_id) {
            Some(n) => n,
            None => return Vec::new(),
        };
        let target_base = target_name.split(':').next().unwrap_or(target_name);

        let mut result = Vec::new();

        // Check each user_intent package
        let intent_ids: Vec<PackageId> = self.user_intent_ids().copied().collect();

        for intent_id in intent_ids {
            if let Some(intent_name) = cache.fullname_of(intent_id)
                && self.package_depends_on(intent_name, target_base) {
                    result.push(intent_id);
            }
        }

        result
    }

    /// Check if package A (transitively) depends on package B
    fn package_depends_on(&self, pkg_name: &str, target_base: &str) -> bool {
        let cache = self.cache();
        let mut visited = HashSet::new();
        let mut to_check = vec![pkg_name.to_string()];

        while let Some(current) = to_check.pop() {
            if visited.contains(&current) {
                continue;
            }
            visited.insert(current.clone());

            let deps = cache.get_dependencies(&current);
            for (dep_type, dep_name) in deps {
                if dep_type != "Depends" && dep_type != "PreDepends" {
                    continue;
                }

                if dep_name == target_base {
                    return true;
                }

                // Add to check list for transitive deps
                if let Some(&dep_id) = cache.fullname_to_id.get(&dep_name)
                    .or_else(|| cache.fullname_to_id.get(&format!("{}:{}", dep_name, cache.native_arch())))
                    && let Some(fullname) = cache.fullname_of(dep_id) {
                        to_check.push(fullname.to_string());
                }
            }
        }

        false
    }

    /// Get iterator over user_intent PackageIds
    fn user_intent_ids(&self) -> impl Iterator<Item = &PackageId> {
        self.shared().user_intent.keys()
    }

    /// Reset all marks
    pub fn reset(&mut self) {
        *self = match std::mem::take(self) {
            ManagerState::Clean(m) => ManagerState::Clean(m),
            ManagerState::Dirty(m) => ManagerState::Clean(m.reset()),
            ManagerState::Planned(m) => ManagerState::Clean(m.modify().reset()),
            ManagerState::Transitioning => panic!("ManagerState::Transitioning should not be observed"),
        };
    }

    /// Compute plan from current marks
    pub fn compute_plan(&mut self) {
        *self = match std::mem::take(self) {
            ManagerState::Clean(m) => ManagerState::Clean(m), // No marks, stay clean
            ManagerState::Dirty(m) => {
                let planned = m.plan();
                ManagerState::Planned(planned)
            }
            ManagerState::Planned(m) => ManagerState::Planned(m), // Already planned
            ManagerState::Transitioning => panic!("ManagerState::Transitioning should not be observed"),
        };
        // Marks changed — invalidate MarkedChanges cache only.
        // Other filters (Installed/Upgradable/etc) are unaffected by marks.
        self.invalidate_filter_cache(Some(FilterCategory::MarkedChanges));
    }

    /// Invalidate per-filter memoization cache.
    /// None = clear all entries; Some(filter) = clear only that filter.
    fn invalidate_filter_cache(&mut self, filter: Option<FilterCategory>) {
        // Transitioning is allowed here (no-op) since compute_plan() calls this
        // after reassigning *self, but guard against edge cases.
        if matches!(self, ManagerState::Transitioning) {
            return;
        }
        let shared = self.shared_mut();
        match filter {
            Some(f) => { shared.filter_cache.remove(&f); }
            None => shared.filter_cache.clear(),
        }
    }

    /// Commit planned changes with caller-provided progress implementations.
    ///
    /// NOTE: We split the take-match-assign into two phases so that a failed
    /// commit never leaves `*self` as `Transitioning`. The inner commit
    /// consumes the `PackageManager`, so on error we must reinitialize.
    pub fn commit_with_progress(
        &mut self,
        acquire_progress: &mut rust_apt::progress::AcquireProgress,
        install_progress: &mut rust_apt::progress::InstallProgress,
    ) -> Result<()> {
        let taken = std::mem::take(self);
        let result = match taken {
            ManagerState::Clean(m) => {
                *self = ManagerState::Clean(m);
                return Ok(());
            }
            ManagerState::Dirty(m) => {
                let planned = m.plan();
                planned.commit_with_progress(acquire_progress, install_progress)
            }
            ManagerState::Planned(m) => {
                m.commit_with_progress(acquire_progress, install_progress)
            }
            ManagerState::Transitioning => panic!("ManagerState::Transitioning should not be observed"),
        };
        // *self is still Transitioning here — always assign before returning.
        match result {
            Ok(clean) => {
                *self = ManagerState::Clean(clean);
                Ok(())
            }
            Err(e) => {
                // Inner PackageManager was consumed by the failed commit.
                // Reinitialize a fresh cache so we don't leave Transitioning.
                match ManagerState::new() {
                    Ok(fresh) => *self = fresh,
                    Err(reinit_err) => {
                        // Double fault: commit failed AND cache won't reopen.
                        // *self stays Transitioning — app cannot recover.
                        return Err(e.wrap_err(format!(
                            "additionally, failed to reinitialize package cache: {reinit_err}"
                        )));
                    }
                }
                Err(e)
            }
        }
    }

    /// Run `apt update` with caller-provided progress
    pub fn update_with_progress(
        &mut self,
        acquire_progress: &mut rust_apt::progress::AcquireProgress,
    ) -> Result<(), String> {
        let shared = self.shared_mut();
        shared.cache.update_with_progress(acquire_progress)
            .map_err(|e| e.to_string())?;
        shared.user_intent.clear();
        shared.filter_cache.clear();
        shared.search.index = None;
        shared.search.query.clear();
        shared.search.results = None;
        shared.compute_cache_counts();
        // Transition to Clean to discard any stale Planned/Dirty state
        self.reset();
        Ok(())
    }

    /// Build a MarkPreview from the current Planned state's changes.
    /// Call this after marking a package and computing the plan.
    /// `previously_planned` contains PackageIds that were already in the plan
    /// before this mark — they are excluded from the "additional" lists.
    pub fn build_mark_preview(
        &self,
        marked_pkg_id: PackageId,
        previously_planned: &HashSet<PackageId>,
    ) -> Option<MarkPreview> {
        let changes = self.planned_changes()?;
        let cache = self.cache();

        // Use display name (strips native arch suffix)
        let marked_pkg_name = cache.fullname_of(marked_pkg_id)
            .map(|n| cache.display_name(n).to_string())?;

        let mut additional_installs = Vec::new();
        let mut additional_upgrades = Vec::new();
        let mut additional_removes = Vec::new();
        let mut download_size = 0u64;
        let mut is_upgrade = false;

        for change in changes {
            // Check if the marked package is an upgrade vs install
            if change.package == marked_pkg_id {
                download_size += change.download_size;
                is_upgrade = change.action == ChangeAction::Upgrade;
                continue;
            }

            // Skip packages that were already planned before this mark
            if previously_planned.contains(&change.package) {
                continue;
            }

            download_size += change.download_size;

            // Derive display name from PackageId (strips native arch suffix)
            let name = cache.fullname_of(change.package)
                .map(|n| cache.display_name(n).to_string())
                .unwrap_or_else(|| format!("(unknown:{})", change.package.index()));

            match change.action {
                ChangeAction::Install => additional_installs.push(name),
                ChangeAction::Upgrade => additional_upgrades.push(name),
                ChangeAction::Remove => additional_removes.push(name),
                ChangeAction::Downgrade => additional_upgrades.push(name),
            }
        }

        Some(MarkPreview::Mark {
            package_name: marked_pkg_name,
            is_upgrade,
            additional_installs,
            additional_upgrades,
            additional_removes,
            download_size,
            bulk_acted_ids: Vec::new(),
        })
    }
}

// ============================================================================
// Standalone utility functions
// ============================================================================

/// Check if running as root
pub fn is_root() -> bool {
    unsafe { libc::geteuid() == 0 }
}

/// Check if APT lock files are held by another process
pub fn check_apt_lock() -> Option<String> {
    let lock_paths = [
        "/var/lib/dpkg/lock-frontend",
        "/var/lib/dpkg/lock",
        "/var/lib/apt/lists/lock",
    ];

    for path in &lock_paths {
        if let Ok(file) = File::open(path) {
            let fd = file.as_raw_fd();
            let ret = unsafe { libc::flock(fd, libc::LOCK_EX | libc::LOCK_NB) };
            if ret != 0 {
                return Some(format!(
                    "Another package manager is running ({path}). Close it and try again."
                ));
            }
            unsafe { libc::flock(fd, libc::LOCK_UN) };
        }
    }
    None
}