pacsea 0.8.2

A fast, friendly TUI for browsing and installing Arch and AUR packages with built-in news and security scanning
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
use std::{collections::HashMap, fs, path::Path, time::Instant};

use crate::index as pkgindex;
use crate::state::{AppState, PackageDetails, PackageItem};

use super::super::deps_cache;
use super::super::files_cache;
use super::super::sandbox_cache;
use super::super::services_cache;

/// What: Initialize the locale system: resolve locale, load translations, set up fallbacks.
///
/// Inputs:
/// - `app`: Application state to populate with locale and translations
/// - `locale_pref`: Locale preference from `settings.conf` (empty = auto-detect)
/// - `_prefs`: Settings struct (unused but kept for future use)
///
/// Output:
/// - Populates `app.locale`, `app.translations`, and `app.translations_fallback`
///
/// Details:
/// - Resolves locale using fallback chain (settings -> system -> default)
/// - Loads English fallback translations first (required)
/// - Loads primary locale translations if different from English
/// - Handles errors gracefully: falls back to English if locale file missing/invalid
/// - Logs warnings for missing files but continues execution
pub fn initialize_locale_system(
    app: &mut AppState,
    locale_pref: &str,
    _prefs: &crate::theme::Settings,
) {
    // Get paths - try both development and installed locations
    let locales_dir = crate::i18n::find_locales_dir().unwrap_or_else(|| {
        std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("config")
            .join("locales")
    });
    let Some(i18n_config_path) = crate::i18n::find_config_file("i18n.yml") else {
        tracing::error!(
            "i18n config file not found in development or installed locations. Using default locale 'en-US'."
        );
        app.locale = "en-US".to_string();
        app.translations = std::collections::HashMap::new();
        app.translations_fallback = std::collections::HashMap::new();
        return;
    };

    // Resolve locale
    let resolver = crate::i18n::LocaleResolver::new(&i18n_config_path);
    let resolved_locale = resolver.resolve(locale_pref);

    tracing::info!(
        "Resolved locale: '{}' (from settings: '{}')",
        &resolved_locale,
        if locale_pref.trim().is_empty() {
            "<auto-detect>"
        } else {
            locale_pref
        }
    );
    app.locale.clone_from(&resolved_locale);

    // Load translations
    let mut loader = crate::i18n::LocaleLoader::new(locales_dir);

    // Load fallback (English) translations first - this is required
    match loader.load("en-US") {
        Ok(fallback) => {
            let key_count = fallback.len();
            app.translations_fallback = fallback;
            tracing::debug!("Loaded English fallback translations ({} keys)", key_count);
        }
        Err(e) => {
            tracing::error!(
                "Failed to load English fallback translations: {}. Application may show untranslated keys.",
                e
            );
            app.translations_fallback = std::collections::HashMap::new();
        }
    }

    // Load primary locale translations
    if resolved_locale == "en-US" {
        // Already loaded English as fallback, use it as primary too
        app.translations = app.translations_fallback.clone();
        tracing::debug!("Using English as primary locale");
    } else {
        match loader.load(&resolved_locale) {
            Ok(translations) => {
                let key_count = translations.len();
                app.translations = translations;
                tracing::info!(
                    "Loaded translations for locale '{}' ({} keys)",
                    resolved_locale,
                    key_count
                );
                // Debug: Check if specific keys exist
                let test_keys = [
                    "app.details.footer.search_hint",
                    "app.details.footer.confirm_installation",
                ];
                for key in &test_keys {
                    if app.translations.contains_key(*key) {
                        tracing::debug!("  ✓ Key '{}' found in translations", key);
                    } else {
                        tracing::debug!("  ✗ Key '{}' NOT found in translations", key);
                    }
                }
            }
            Err(e) => {
                tracing::warn!(
                    "Failed to load translations for locale '{}': {}. Using English fallback.",
                    resolved_locale,
                    e
                );
                // Use empty map - translate_with_fallback will use English fallback
                app.translations = std::collections::HashMap::new();
            }
        }
    }
}

/// What: Run startup config preflight exactly once and return resolved settings.
///
/// Inputs:
/// - None.
///
/// Output:
/// - Returns the current `Settings` after legacy migration and key ensure operations.
///
/// Details:
/// - Migrates legacy config layout into split config files when needed.
/// - Ensures `theme.conf` and `settings.conf` include all known keys.
/// - Reads and returns settings from disk after preflight so downstream initialization
///   can reuse the same resolved snapshot.
pub fn run_startup_config_preflight() -> crate::theme::Settings {
    crate::theme::maybe_migrate_legacy_confs();
    crate::theme::ensure_theme_keys_present();
    let prefs = crate::theme::settings();
    crate::theme::ensure_settings_keys_present(&prefs);
    prefs
}

/// What: Initialize application state: load settings, caches, and persisted data.
///
/// Inputs:
/// - `app`: Application state to initialize
/// - `dry_run_flag`: When `true`, install/remove/downgrade actions are displayed but not executed
/// - `headless`: When `true`, skip terminal-dependent operations
///
/// Output:
/// - Returns flags indicating which caches need background resolution
///
/// Details:
/// - Migrates legacy configs and loads settings
/// - Loads persisted caches (details, recent, install list, dependencies, files, services, sandbox)
/// - Initializes locale system
/// - Checks for GNOME terminal if on GNOME desktop
#[allow(clippy::struct_excessive_bools)]
pub struct InitFlags {
    /// Whether dependency resolution is needed (cache missing or invalid).
    pub needs_deps_resolution: bool,
    /// Whether file analysis is needed (cache missing or invalid).
    pub needs_files_resolution: bool,
    /// Whether service analysis is needed (cache missing or invalid).
    pub needs_services_resolution: bool,
    /// Whether sandbox analysis is needed (cache missing or invalid).
    pub needs_sandbox_resolution: bool,
}

/// What: Load a cache with signature validation, returning whether resolution is needed.
///
/// Inputs:
/// - `install_list`: Current install list to compute signature from
/// - `cache_path`: Path to the cache file
/// - `compute_signature`: Function to compute signature from install list
/// - `load_cache`: Function to load cache from path and signature
/// - `cache_name`: Name of the cache for logging
///
/// Output:
/// - `(Option<T>, bool)` where first is the loaded cache (if valid) and second indicates if resolution is needed
///
/// Details:
/// - Returns `(None, true)` if install list is empty or cache is missing/invalid
/// - Returns `(Some(cache), false)` if cache is valid
fn load_cache_with_signature<T>(
    install_list: &[crate::state::PackageItem],
    cache_path: &std::path::PathBuf,
    compute_signature: impl Fn(&[crate::state::PackageItem]) -> Vec<String>,
    load_cache: impl Fn(&std::path::PathBuf, &[String]) -> Option<T>,
    cache_name: &str,
) -> (Option<T>, bool) {
    if install_list.is_empty() {
        return (None, false);
    }

    let signature = compute_signature(install_list);
    load_cache(cache_path, &signature).map_or_else(
        || {
            tracing::info!(
                "{} cache missing or invalid, will trigger background resolution",
                cache_name
            );
            (None, true)
        },
        |cached| (Some(cached), false),
    )
}

/// What: Ensure cache directories exist before writing placeholder files.
///
/// Inputs:
/// - `path`: Target cache file path whose parent directory should exist.
///
/// Output:
/// - Parent directory is created if missing; logs a warning on failure.
///
/// Details:
/// - No-op when the path has no parent.
fn ensure_cache_parent_dir(path: &Path) {
    if let Some(parent) = path.parent()
        && let Err(error) = fs::create_dir_all(parent)
    {
        tracing::warn!(
            path = %parent.display(),
            %error,
            "[Init] Failed to create cache directory"
        );
    }
}

/// What: Create empty cache files at startup so they always exist on disk.
///
/// Inputs:
/// - `app`: Application state providing cache paths.
///
/// Output:
/// - Writes empty dependency, file, service, and sandbox caches if the files are missing.
///
/// Details:
/// - Uses empty signatures and payloads; leaves existing files untouched.
/// - Ensures parent directories exist before writing.
fn initialize_cache_files(app: &AppState) {
    let empty_signature: Vec<String> = Vec::new();

    if !app.deps_cache_path.exists() {
        ensure_cache_parent_dir(&app.deps_cache_path);
        deps_cache::save_cache(&app.deps_cache_path, &empty_signature, &[]);
        tracing::debug!(
            path = %app.deps_cache_path.display(),
            "[Init] Created empty dependency cache"
        );
    }

    if !app.files_cache_path.exists() {
        ensure_cache_parent_dir(&app.files_cache_path);
        files_cache::save_cache(&app.files_cache_path, &empty_signature, &[]);
        tracing::debug!(
            path = %app.files_cache_path.display(),
            "[Init] Created empty file cache"
        );
    }

    if !app.services_cache_path.exists() {
        ensure_cache_parent_dir(&app.services_cache_path);
        services_cache::save_cache(&app.services_cache_path, &empty_signature, &[]);
        tracing::debug!(
            path = %app.services_cache_path.display(),
            "[Init] Created empty service cache"
        );
    }

    if !app.sandbox_cache_path.exists() {
        ensure_cache_parent_dir(&app.sandbox_cache_path);
        sandbox_cache::save_cache(&app.sandbox_cache_path, &empty_signature, &[]);
        tracing::debug!(
            path = %app.sandbox_cache_path.display(),
            "[Init] Created empty sandbox cache"
        );
    }
}

/// What: Apply settings from configuration to application state.
///
/// Inputs:
/// - `app`: Application state to update
/// - `prefs`: Settings to apply
///
/// Output: None (modifies app state in place)
///
/// Details:
/// - Applies layout percentages, keymap, sort mode, package marker, and pane visibility
pub fn apply_settings_to_app_state(app: &mut AppState, prefs: &crate::theme::Settings) {
    app.layout_left_pct = prefs.layout_left_pct;
    app.layout_center_pct = prefs.layout_center_pct;
    app.layout_right_pct = prefs.layout_right_pct;
    app.main_pane_order = prefs.main_pane_order;
    app.vertical_layout_limits = crate::state::VerticalLayoutLimits::from_u16s(
        prefs.vertical_min_results,
        prefs.vertical_max_results,
        prefs.vertical_min_middle,
        prefs.vertical_max_middle,
        prefs.vertical_min_package_info,
    );
    app.keymap = prefs.keymap.clone();
    app.sort_mode = prefs.sort_mode;
    app.package_marker = prefs.package_marker;
    app.show_recent_pane = prefs.show_recent_pane;
    app.show_install_pane = prefs.show_install_pane;
    app.show_keybinds_footer = prefs.show_keybinds_footer;
    app.search_normal_mode = prefs.search_startup_mode;
    app.fuzzy_search_enabled = prefs.fuzzy_search;
    app.installed_packages_mode = prefs.installed_packages_mode;
    app.app_mode = if prefs.start_in_news {
        crate::state::types::AppMode::News
    } else {
        crate::state::types::AppMode::Package
    };
    app.news_filter_show_arch_news = prefs.news_filter_show_arch_news;
    app.news_filter_show_advisories = prefs.news_filter_show_advisories;
    app.news_filter_show_pkg_updates = prefs.news_filter_show_pkg_updates;
    app.news_filter_show_aur_updates = prefs.news_filter_show_aur_updates;
    app.news_filter_show_aur_comments = prefs.news_filter_show_aur_comments;
    app.news_filter_installed_only = prefs.news_filter_installed_only;
    app.news_max_age_days = prefs.news_max_age_days;
    // Recompute news results with loaded filters/age
    app.refresh_news_results();
    crate::logic::repos::refresh_dynamic_filters_in_app(app, prefs);
}

/// What: Check if GNOME terminal is needed and set modal if required.
///
/// Inputs:
/// - `app`: Application state to update
/// - `headless`: When `true`, skip the check
///
/// Output: None (modifies app state in place)
///
/// Details:
/// - Checks if running on GNOME desktop without `gnome-terminal` or `gnome-console`/`kgx`
/// - Sets modal to `GnomeTerminalPrompt` if terminal is missing
fn check_gnome_terminal(app: &mut AppState, headless: bool) {
    if headless {
        return;
    }

    let is_gnome = std::env::var("XDG_CURRENT_DESKTOP")
        .ok()
        .is_some_and(|v| v.to_uppercase().contains("GNOME"));

    if !is_gnome {
        return;
    }

    let has_gterm = crate::install::command_on_path("gnome-terminal");
    let has_gconsole =
        crate::install::command_on_path("gnome-console") || crate::install::command_on_path("kgx");

    if !(has_gterm || has_gconsole) {
        app.modal = crate::state::Modal::GnomeTerminalPrompt;
    }
}

/// What: Load details cache from disk.
///
/// Inputs:
/// - `app`: Application state to update
///
/// Output: None (modifies app state in place)
///
/// Details:
/// - Attempts to deserialize details cache from JSON file
fn load_details_cache(app: &mut AppState) {
    if let Ok(s) = std::fs::read_to_string(&app.cache_path)
        && let Ok(map) = serde_json::from_str::<HashMap<String, PackageDetails>>(&s)
    {
        app.details_cache = map;
        tracing::info!(path = %app.cache_path.display(), "loaded details cache");
    }
}

/// What: Load recent searches from disk.
///
/// Inputs:
/// - `app`: Application state to update
///
/// Output: None (modifies app state in place)
///
/// Details:
/// - Attempts to deserialize recent searches list from JSON file
/// - Selects first item if list is not empty
fn load_recent_searches(app: &mut AppState) {
    if let Ok(s) = std::fs::read_to_string(&app.recent_path)
        && let Ok(list) = serde_json::from_str::<Vec<String>>(&s)
    {
        let count = list.len();
        app.load_recent_items(&list);
        if count > 0 {
            app.history_state.select(Some(0));
        }
        tracing::info!(
            path = %app.recent_path.display(),
            count = count,
            "loaded recent searches"
        );
    }
}

/// What: Load install list from disk.
///
/// Inputs:
/// - `app`: Application state to update
///
/// Output: None (modifies app state in place)
///
/// Details:
/// - Attempts to deserialize install list from JSON file
/// - Selects first item if list is not empty
fn load_install_list(app: &mut AppState) {
    if let Ok(s) = std::fs::read_to_string(&app.install_path)
        && let Ok(list) = serde_json::from_str::<Vec<PackageItem>>(&s)
    {
        app.install_list = list;
        if !app.install_list.is_empty() {
            app.install_state.select(Some(0));
        }
        tracing::info!(
            path = %app.install_path.display(),
            count = app.install_list.len(),
            "loaded install list"
        );
    }
}

/// What: Load news read URLs from disk.
///
/// Inputs:
/// - `app`: Application state to update
///
/// Output: None (modifies app state in place)
///
/// Details:
/// - Attempts to deserialize news read URLs set from JSON file
fn load_news_read_urls(app: &mut AppState) {
    if let Ok(s) = std::fs::read_to_string(&app.news_read_path)
        && let Ok(set) = serde_json::from_str::<std::collections::HashSet<String>>(&s)
    {
        app.news_read_urls = set;
        tracing::info!(
            path = %app.news_read_path.display(),
            count = app.news_read_urls.len(),
            "loaded read news urls"
        );
    }
}

/// What: Load news read IDs from disk (feed-level tracking).
///
/// Inputs:
/// - `app`: Application state to update
///
/// Output: None (modifies app state in place)
///
/// Details:
/// - Attempts to deserialize news read IDs set from JSON file.
/// - If no IDs file is found, falls back to populated `news_read_urls` for migration.
fn load_news_read_ids(app: &mut AppState) {
    if let Ok(s) = std::fs::read_to_string(&app.news_read_ids_path)
        && let Ok(set) = serde_json::from_str::<std::collections::HashSet<String>>(&s)
    {
        app.news_read_ids = set;
        tracing::info!(
            path = %app.news_read_ids_path.display(),
            count = app.news_read_ids.len(),
            "loaded read news ids"
        );
        return;
    }

    if app.news_read_ids.is_empty() && !app.news_read_urls.is_empty() {
        app.news_read_ids.extend(app.news_read_urls.iter().cloned());
        tracing::info!(
            copied = app.news_read_ids.len(),
            "seeded news read ids from legacy URL set"
        );
        app.news_read_ids_dirty = true;
    }
}

/// What: Load announcement read IDs from disk.
///
/// Inputs:
/// - `app`: Application state to update
///
/// Output: None (modifies app state in place)
///
/// Details:
/// - Attempts to deserialize announcement read IDs set from JSON file
/// - Handles both old format (single hash) and new format (set of IDs) for migration
fn load_announcement_state(app: &mut AppState) {
    // Try old format for migration ({ "hash": "..." })
    /// What: Legacy announcement read state structure.
    ///
    /// Inputs: Deserialized from old announcement read file.
    ///
    /// Output: Old state structure for migration.
    ///
    /// Details: Used for migrating from old announcement read state format.
    #[derive(serde::Deserialize)]
    struct OldAnnouncementReadState {
        /// Announcement hash if read.
        hash: Option<String>,
    }
    if let Ok(s) = std::fs::read_to_string(&app.announcement_read_path) {
        // Try new format first (HashSet<String>)
        if let Ok(ids) = serde_json::from_str::<std::collections::HashSet<String>>(&s) {
            app.announcements_read_ids = ids;
            tracing::info!(
                path = %app.announcement_read_path.display(),
                count = app.announcements_read_ids.len(),
                "loaded announcement read IDs"
            );
            return;
        }
        if let Ok(old_state) = serde_json::from_str::<OldAnnouncementReadState>(&s)
            && let Some(hash) = old_state.hash
        {
            app.announcements_read_ids.insert(format!("hash:{hash}"));
            app.announcement_dirty = true; // Mark dirty to migrate to new format
            tracing::info!(
                path = %app.announcement_read_path.display(),
                "migrated old announcement read state"
            );
        }
    }
}

/// What: Check for version-embedded announcement and show modal if not read.
///
/// Inputs:
/// - `app`: Application state to update
///
/// Output: None (modifies app state in place)
///
/// Details:
/// - Checks embedded announcements for current app version
/// - If version announcement exists and hasn't been marked as read, shows modal
fn check_version_announcement(app: &mut AppState) {
    const CURRENT_VERSION: &str = env!("CARGO_PKG_VERSION");

    // Extract base version (X.X.X) from current version, ignoring suffixes
    let current_base_version = crate::announcements::extract_base_version(CURRENT_VERSION);

    // Find announcement matching the base version (compares only X.X.X part)
    if let Some(announcement) = crate::announcements::VERSION_ANNOUNCEMENTS
        .iter()
        .find(|a| {
            let announcement_base_version = crate::announcements::extract_base_version(a.version);
            announcement_base_version == current_base_version
        })
    {
        // Use full current version (including suffix) for the ID
        // This ensures announcements show again when suffix changes (e.g., 0.6.0-pr#85 -> 0.6.0-pr#86)
        let version_id = format!("v{CURRENT_VERSION}");

        // Check if this version announcement has been marked as read
        if app.announcements_read_ids.contains(&version_id) {
            tracing::info!(
                current_version = CURRENT_VERSION,
                base_version = %current_base_version,
                "version announcement already marked as read"
            );
            return;
        }

        if matches!(app.modal, crate::state::Modal::None) {
            // Show version announcement modal immediately.
            app.modal = crate::state::Modal::Announcement {
                title: announcement.title.to_string(),
                content: announcement.content.to_string(),
                id: version_id,
                scroll: 0,
            };
            tracing::info!(
                current_version = CURRENT_VERSION,
                base_version = %current_base_version,
                announcement_version = announcement.version,
                "showing version announcement modal"
            );
        } else {
            // Keep first-run/setup modal flow intact and defer version announcement.
            app.pending_announcements
                .push(crate::announcements::RemoteAnnouncement {
                    id: version_id,
                    title: announcement.title.to_string(),
                    content: announcement.content.to_string(),
                    min_version: None,
                    max_version: None,
                    expires: None,
                });
            tracing::info!(
                current_version = CURRENT_VERSION,
                base_version = %current_base_version,
                announcement_version = announcement.version,
                queue_size = app.pending_announcements.len(),
                "queued version announcement modal because another modal is open"
            );
        }
    }
    // Note: Remote announcements will be queued if they arrive while embedded is showing
    // and will be shown when embedded is dismissed via show_next_pending_announcement()
}

/// What: Initialize application state by loading settings, caches, and persisted data.
///
/// Inputs:
/// - `app`: Mutable application state to initialize
/// - `dry_run_flag`: Whether to enable dry-run mode for this session
/// - `headless`: Whether running in headless/test mode
/// - `prefs`: Preflighted settings snapshot to apply during initialization
///
/// Output:
/// - Returns `InitFlags` indicating which caches need background resolution
///
/// Details:
/// - Applies startup settings that were preflighted before runtime initialization
/// - Initializes locale system and translations
/// - Loads persisted data: recent searches, install list, details cache, dependency/file/service/sandbox caches
/// - Loads news read URLs and announcement state
/// - Loads official package index from disk
/// - Checks for version-embedded announcements
pub fn initialize_app_state(
    app: &mut AppState,
    dry_run_flag: bool,
    headless: bool,
    prefs: &crate::theme::Settings,
) -> InitFlags {
    app.dry_run = if dry_run_flag {
        true
    } else {
        prefs.app_dry_run_default
    };
    app.last_input_change = Instant::now();

    // Log resolved configuration/state file locations at startup
    tracing::info!(
        recent = %app.recent_path.display(),
        install = %app.install_path.display(),
        details_cache = %app.cache_path.display(),
        index = %app.official_index_path.display(),
        news_read = %app.news_read_path.display(),
        news_read_ids = %app.news_read_ids_path.display(),
        announcement_read = %app.announcement_read_path.display(),
        "resolved state file paths"
    );

    crate::logic::repos::load_repos_config_into_app(app, crate::theme::resolve_repos_config_path());
    apply_settings_to_app_state(app, prefs);

    // Initialize locale system
    initialize_locale_system(app, &prefs.locale, prefs);

    check_gnome_terminal(app, headless);

    // Show startup setup selector modal on first launch if startup news is not configured.
    if !headless && !prefs.startup_news_configured {
        // Only show if no other modal is already set (e.g., GnomeTerminalPrompt)
        if matches!(app.modal, crate::state::Modal::None) {
            let ssh_command = crate::theme::settings().aur_vote_ssh_command;
            app.pending_aur_ssh_help_check_result = Some(
                crate::logic::ssh_setup::spawn_aur_ssh_help_check(ssh_command),
            );
            app.aur_ssh_help_ready = None;
            app.modal = crate::state::Modal::StartupSetupSelector {
                cursor: 0,
                selected: std::collections::HashSet::new(),
                active_privilege_tool: crate::logic::privilege::active_tool().ok(),
            };
        }
    } else if !headless && prefs.startup_news_configured {
        // Always fetch fresh news in background (using last startup timestamp for incremental updates)
        // Show loading toast while fetching, but cached items will be displayed immediately
        app.news_loading = true;
        app.toast_message = Some(crate::i18n::t(app, "app.news_button.loading"));
        app.toast_expires_at = None; // No expiration - toast stays until news loading completes
    }

    // Check faillock status at startup
    if !headless {
        let username = std::env::var("USER").unwrap_or_else(|_| "user".to_string());
        let (is_locked, lockout_until, remaining_minutes) =
            crate::logic::faillock::get_lockout_info(&username);
        app.faillock_locked = is_locked;
        app.faillock_lockout_until = lockout_until;
        app.faillock_remaining_minutes = remaining_minutes;
    }

    load_details_cache(app);
    load_recent_searches(app);
    load_install_list(app);
    initialize_cache_files(app);

    // Load dependency cache after install list is loaded (but before channels are created)
    let (deps_cache, needs_deps_resolution) = load_cache_with_signature(
        &app.install_list,
        &app.deps_cache_path,
        deps_cache::compute_signature,
        deps_cache::load_cache,
        "dependency",
    );
    if let Some(cached_deps) = deps_cache {
        app.install_list_deps = cached_deps;
        tracing::info!(
            path = %app.deps_cache_path.display(),
            count = app.install_list_deps.len(),
            "loaded dependency cache"
        );
    }

    // Load file cache after install list is loaded (but before channels are created)
    let (files_cache, needs_files_resolution) = load_cache_with_signature(
        &app.install_list,
        &app.files_cache_path,
        files_cache::compute_signature,
        files_cache::load_cache,
        "file",
    );
    if let Some(cached_files) = files_cache {
        app.install_list_files = cached_files;
        tracing::info!(
            path = %app.files_cache_path.display(),
            count = app.install_list_files.len(),
            "loaded file cache"
        );
    }

    // Load service cache after install list is loaded (but before channels are created)
    let (services_cache, needs_services_resolution) = load_cache_with_signature(
        &app.install_list,
        &app.services_cache_path,
        services_cache::compute_signature,
        services_cache::load_cache,
        "service",
    );
    if let Some(cached_services) = services_cache {
        app.install_list_services = cached_services;
        tracing::info!(
            path = %app.services_cache_path.display(),
            count = app.install_list_services.len(),
            "loaded service cache"
        );
    }

    // Load sandbox cache after install list is loaded (but before channels are created)
    let (sandbox_cache, needs_sandbox_resolution) = load_cache_with_signature(
        &app.install_list,
        &app.sandbox_cache_path,
        sandbox_cache::compute_signature,
        sandbox_cache::load_cache,
        "sandbox",
    );
    if let Some(cached_sandbox) = sandbox_cache {
        app.install_list_sandbox = cached_sandbox;
        tracing::info!(
            path = %app.sandbox_cache_path.display(),
            count = app.install_list_sandbox.len(),
            "loaded sandbox cache"
        );
    }

    load_news_read_urls(app);
    load_news_read_ids(app);
    load_announcement_state(app);

    pkgindex::load_from_disk(&app.official_index_path);

    // Check for version-embedded announcement after loading state
    check_version_announcement(app);
    tracing::info!(
        path = %app.official_index_path.display(),
        "attempted to load official index from disk"
    );

    InitFlags {
        needs_deps_resolution,
        needs_files_resolution,
        needs_services_resolution,
        needs_sandbox_resolution,
    }
}

/// What: Trigger initial background resolution for caches that were missing or invalid.
///
/// Inputs:
/// - `app`: Application state
/// - `flags`: Initialization flags indicating which caches need resolution
/// - `deps_req_tx`: Channel sender for dependency resolution requests
/// - `files_req_tx`: Channel sender for file resolution requests (with action)
/// - `services_req_tx`: Channel sender for service resolution requests
/// - `sandbox_req_tx`: Channel sender for sandbox resolution requests
///
/// Output:
/// - Sets resolution flags and sends requests to background workers
///
/// Details:
/// - Only triggers resolution if cache was missing/invalid and install list is not empty
pub fn trigger_initial_resolutions(
    app: &mut AppState,
    flags: &InitFlags,
    deps_req_tx: &tokio::sync::mpsc::UnboundedSender<(
        Vec<PackageItem>,
        crate::state::modal::PreflightAction,
    )>,
    files_req_tx: &tokio::sync::mpsc::UnboundedSender<(
        Vec<PackageItem>,
        crate::state::modal::PreflightAction,
    )>,
    services_req_tx: &tokio::sync::mpsc::UnboundedSender<(
        Vec<PackageItem>,
        crate::state::modal::PreflightAction,
    )>,
    sandbox_req_tx: &tokio::sync::mpsc::UnboundedSender<Vec<PackageItem>>,
) {
    if flags.needs_deps_resolution && !app.install_list.is_empty() {
        app.deps_resolving = true;
        // Initial resolution is always for Install action (install_list)
        let _ = deps_req_tx.send((
            app.install_list.clone(),
            crate::state::modal::PreflightAction::Install,
        ));
    }

    if flags.needs_files_resolution && !app.install_list.is_empty() {
        app.files_resolving = true;
        // Initial resolution is always for Install action (install_list)
        let _ = files_req_tx.send((
            app.install_list.clone(),
            crate::state::modal::PreflightAction::Install,
        ));
    }

    if flags.needs_services_resolution && !app.install_list.is_empty() {
        app.services_resolving = true;
        let _ = services_req_tx.send((
            app.install_list.clone(),
            crate::state::modal::PreflightAction::Install,
        ));
    }

    if flags.needs_sandbox_resolution && !app.install_list.is_empty() {
        app.sandbox_resolving = true;
        let _ = sandbox_req_tx.send(app.install_list.clone());
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::runtime::background::Channels;

    /// What: Provide a baseline `AppState` for initialization tests.
    ///
    /// Inputs: None
    /// Output: Fresh `AppState` with default values
    fn new_app() -> AppState {
        AppState::default()
    }

    #[test]
    /// What: Verify that `initialize_locale_system` sets default locale when config file is missing.
    ///
    /// Inputs:
    /// - App state with default locale
    /// - Empty locale preference
    ///
    /// Output:
    /// - Locale is set to "en-US" when config file is missing
    /// - Translations maps are initialized (may be empty)
    ///
    /// Details:
    /// - Tests graceful fallback when i18n config is not found
    fn initialize_locale_system_fallback_when_config_missing() {
        let mut app = new_app();
        let prefs = crate::theme::Settings::default();

        // This will fall back to en-US if config file is missing
        initialize_locale_system(&mut app, "", &prefs);

        // Locale should be set (either resolved or default)
        assert!(!app.locale.is_empty());
        // Translations maps should be initialized
        assert!(app.translations.is_empty() || !app.translations.is_empty());
        assert!(app.translations_fallback.is_empty() || !app.translations_fallback.is_empty());
    }

    #[test]
    /// What: Verify that `initialize_app_state` sets `dry_run` flag correctly.
    ///
    /// Inputs:
    /// - `AppState`
    /// - `dry_run_flag` = true
    /// - headless = false
    ///
    /// Output:
    /// - `app.dry_run` is set to true
    /// - `InitFlags` are returned
    ///
    /// Details:
    /// - Tests that `dry_run` flag is properly initialized
    fn initialize_app_state_sets_dry_run_flag() {
        let mut app = new_app();
        let prefs = crate::theme::settings();
        let flags = initialize_app_state(&mut app, true, false, &prefs);

        assert!(app.dry_run);
        // Flags should be returned (InitFlags struct is created)
        // The actual values depend on cache state, so we just verify flags exist
        let _ = flags;
    }

    #[test]
    /// What: Verify that `initialize_app_state` loads settings correctly.
    ///
    /// Inputs:
    /// - `AppState`
    /// - `dry_run_flag` = false
    /// - headless = false
    ///
    /// Output:
    /// - `AppState` has layout percentages set
    /// - Keymap is set
    /// - Sort mode is set
    ///
    /// Details:
    /// - Tests that settings are properly applied to app state
    fn initialize_app_state_loads_settings() {
        let mut app = new_app();
        let prefs = crate::theme::settings();
        let _flags = initialize_app_state(&mut app, false, false, &prefs);

        // Settings should be loaded (values depend on config, but should be set)
        assert!(app.layout_left_pct > 0);
        assert!(app.layout_center_pct > 0);
        assert!(app.layout_right_pct > 0);
        // Keymap should be initialized (it's a struct, not a string)
        // Just verify it's not the default empty state by checking a field
        // (KeyMap has many fields, we just verify it's been set)
    }

    #[test]
    /// What: Verify first startup shows startup setup selector modal.
    fn initialize_app_state_shows_startup_selector_when_news_unconfigured() {
        let mut app = new_app();
        let mut prefs = crate::theme::settings();
        prefs.startup_news_configured = false;
        let _flags = initialize_app_state(&mut app, false, false, &prefs);
        assert!(matches!(
            app.modal,
            crate::state::Modal::StartupSetupSelector { .. }
        ));
    }

    #[test]
    /// What: Verify version announcement is queued when another startup modal is already open.
    ///
    /// Inputs:
    /// - `AppState` with `StartupSetupSelector` already open.
    ///
    /// Output:
    /// - Existing modal remains `StartupSetupSelector`.
    /// - Version announcement is pushed into `pending_announcements`.
    ///
    /// Details:
    /// - Prevents first-run setup flow from being overwritten by version announcement display.
    fn check_version_announcement_queues_when_modal_already_open() {
        let mut app = new_app();
        app.modal = crate::state::Modal::StartupSetupSelector {
            cursor: 0,
            selected: std::collections::HashSet::new(),
            active_privilege_tool: None,
        };
        let pending_before = app.pending_announcements.len();

        check_version_announcement(&mut app);

        assert!(matches!(
            app.modal,
            crate::state::Modal::StartupSetupSelector { .. }
        ));
        assert_eq!(
            app.pending_announcements.len(),
            pending_before.saturating_add(1)
        );
    }

    #[test]
    /// What: Verify that `initialize_cache_files` creates placeholder cache files when missing.
    ///
    /// Inputs:
    /// - `AppState` with cache paths pointed to temporary locations that do not yet exist.
    ///
    /// Output:
    /// - Empty dependency, file, service, and sandbox cache files are created.
    ///
    /// Details:
    /// - Validates that startup eagerly materializes cache files instead of delaying until first use.
    fn initialize_cache_files_creates_empty_placeholders() {
        let mut app = new_app();
        let mut deps_path = std::env::temp_dir();
        deps_path.push(format!(
            "pacsea_init_deps_cache_{}_{}.json",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("System time is before UNIX epoch")
                .as_nanos()
        ));
        let mut files_path = deps_path.clone();
        files_path.set_file_name("pacsea_init_files_cache.json");
        let mut services_path = deps_path.clone();
        services_path.set_file_name("pacsea_init_services_cache.json");
        let mut sandbox_path = deps_path.clone();
        sandbox_path.set_file_name("pacsea_init_sandbox_cache.json");

        app.deps_cache_path = deps_path.clone();
        app.files_cache_path = files_path.clone();
        app.services_cache_path = services_path.clone();
        app.sandbox_cache_path = sandbox_path.clone();

        // Ensure paths are clean
        let _ = std::fs::remove_file(&app.deps_cache_path);
        let _ = std::fs::remove_file(&app.files_cache_path);
        let _ = std::fs::remove_file(&app.services_cache_path);
        let _ = std::fs::remove_file(&app.sandbox_cache_path);

        initialize_cache_files(&app);

        let deps_body = std::fs::read_to_string(&app.deps_cache_path)
            .expect("Dependency cache file should exist");
        let deps_cache: crate::app::deps_cache::DependencyCache =
            serde_json::from_str(&deps_body).expect("Dependency cache should parse");
        assert!(deps_cache.install_list_signature.is_empty());
        assert!(deps_cache.dependencies.is_empty());

        let files_body =
            std::fs::read_to_string(&app.files_cache_path).expect("File cache file should exist");
        let files_cache: crate::app::files_cache::FileCache =
            serde_json::from_str(&files_body).expect("File cache should parse");
        assert!(files_cache.install_list_signature.is_empty());
        assert!(files_cache.files.is_empty());

        let services_body = std::fs::read_to_string(&app.services_cache_path)
            .expect("Service cache file should exist");
        let services_cache: crate::app::services_cache::ServiceCache =
            serde_json::from_str(&services_body).expect("Service cache should parse");
        assert!(services_cache.install_list_signature.is_empty());
        assert!(services_cache.services.is_empty());

        let sandbox_body = std::fs::read_to_string(&app.sandbox_cache_path)
            .expect("Sandbox cache file should exist");
        let sandbox_cache: crate::app::sandbox_cache::SandboxCache =
            serde_json::from_str(&sandbox_body).expect("Sandbox cache should parse");
        assert!(sandbox_cache.install_list_signature.is_empty());
        assert!(sandbox_cache.sandbox_info.is_empty());

        let _ = std::fs::remove_file(&app.deps_cache_path);
        let _ = std::fs::remove_file(&app.files_cache_path);
        let _ = std::fs::remove_file(&app.services_cache_path);
        let _ = std::fs::remove_file(&app.sandbox_cache_path);
    }

    #[tokio::test]
    /// What: Verify that `trigger_initial_resolutions` skips when install list is empty.
    ///
    /// Inputs:
    /// - `AppState` with empty install list
    /// - `InitFlags` with `needs_deps_resolution` = true
    /// - Channel senders
    ///
    /// Output:
    /// - No requests sent when install list is empty
    ///
    /// Details:
    /// - Tests that resolution is only triggered when install list is not empty
    async fn trigger_initial_resolutions_skips_when_install_list_empty() {
        let mut app = new_app();
        app.install_list.clear();

        let flags = InitFlags {
            needs_deps_resolution: true,
            needs_files_resolution: true,
            needs_services_resolution: true,
            needs_sandbox_resolution: true,
        };

        // Create channels (we only need the senders)
        let channels = Channels::new(std::path::PathBuf::from("/tmp"));

        // Should not panic even with empty install list
        trigger_initial_resolutions(
            &mut app,
            &flags,
            &channels.deps_req_tx,
            &channels.files_req_tx,
            &channels.services_req_tx,
            &channels.sandbox_req_tx,
        );

        // Flags should not be set when install list is empty
        assert!(!app.deps_resolving);
        assert!(!app.files_resolving);
        assert!(!app.services_resolving);
        assert!(!app.sandbox_resolving);
    }

    #[tokio::test]
    /// What: Verify that `trigger_initial_resolutions` sets flags and sends requests when needed.
    ///
    /// Inputs:
    /// - `AppState` with non-empty install list
    /// - `InitFlags` with `needs_deps_resolution` = true
    /// - Channel senders
    ///
    /// Output:
    /// - `deps_resolving` flag is set
    /// - Request is sent to `deps_req_tx`
    ///
    /// Details:
    /// - Tests that resolution is properly triggered when conditions are met
    async fn trigger_initial_resolutions_triggers_when_needed() {
        let mut app = new_app();
        app.install_list.push(crate::state::PackageItem {
            name: "test-package".to_string(),
            version: "1.0.0".to_string(),
            description: "Test".to_string(),
            source: crate::state::Source::Aur,
            popularity: None,
            out_of_date: None,
            orphaned: false,
        });

        let flags = InitFlags {
            needs_deps_resolution: true,
            needs_files_resolution: false,
            needs_services_resolution: false,
            needs_sandbox_resolution: false,
        };

        let channels = Channels::new(std::path::PathBuf::from("/tmp"));

        trigger_initial_resolutions(
            &mut app,
            &flags,
            &channels.deps_req_tx,
            &channels.files_req_tx,
            &channels.services_req_tx,
            &channels.sandbox_req_tx,
        );

        // Flag should be set
        assert!(app.deps_resolving);
        // Other flags should not be set
        assert!(!app.files_resolving);
        assert!(!app.services_resolving);
        assert!(!app.sandbox_resolving);
    }
}