folder-auto-banner 0.6.2

Folder Auto Banner — A directory listing with instant context
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
use anyhow::Result;
use inotify::{Inotify, WatchMask};
use std::collections::HashMap;
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant, SystemTime};

use folder_auto_banner::daemon_types::{BannerData, Request, Response};
use folder_auto_banner::fs::{DirEntry, DirSummary};

// Cache entry with TTL
#[derive(Clone)]
struct CacheEntry {
    data: BannerData,
    computed_at: Instant,
}

const CACHE_TTL: Duration = Duration::from_secs(300); // 5 minutes
const SIZE_CACHE_REFRESH_TIMEOUT: Duration = Duration::from_millis(1000);
const SOCKET_NAME: &str = "fabd.sock";
const IDLE_TIMEOUT: Duration = Duration::from_secs(600); // 10 minutes

struct Daemon {
    cache: Arc<Mutex<HashMap<PathBuf, CacheEntry>>>,
    /// Global directory size cache — populated by proactive scan
    dir_sizes: Arc<Mutex<HashMap<PathBuf, u64>>>,
    /// Last observed mtime for each cached directory size
    dir_size_mtimes: Arc<Mutex<HashMap<PathBuf, Option<SystemTime>>>>,
    socket_path: PathBuf,
}

impl Daemon {
    fn new() -> Result<Self> {
        let socket_dir = directories::ProjectDirs::from("com", "fab", "fab")
            .ok_or_else(|| anyhow::anyhow!("Cannot determine data directory"))?
            .data_dir()
            .to_path_buf();

        std::fs::create_dir_all(&socket_dir)?;

        let socket_path = socket_dir.join(SOCKET_NAME);

        // Remove stale socket
        if socket_path.exists() {
            std::fs::remove_file(&socket_path)?;
        }

        // Load persistent size cache from disk
        let dir_sizes = load_size_cache(&socket_dir);

        Ok(Self {
            cache: Arc::new(Mutex::new(HashMap::new())),
            dir_sizes: Arc::new(Mutex::new(dir_sizes)),
            dir_size_mtimes: Arc::new(Mutex::new(HashMap::new())),
            socket_path,
        })
    }

    fn run(&self) -> Result<()> {
        let listener = UnixListener::bind(&self.socket_path)?;
        listener.set_nonblocking(true)?;

        tracing::info!("fabd listening on {}", self.socket_path.display());

        // Load persisted banner cache from disk
        let socket_dir =
            directories::ProjectDirs::from("com", "fab", "fab").map(|p| p.data_dir().to_path_buf());
        if let Some(ref dir) = socket_dir {
            let persisted = load_banner_cache(dir);
            let mut cache = self.cache.lock().unwrap_or_else(|e| {
                tracing::warn!("Cache mutex poisoned, recovering: {}", e);
                e.into_inner()
            });
            for (path, data) in persisted {
                cache.insert(
                    path,
                    CacheEntry {
                        data,
                        computed_at: Instant::now(),
                    },
                );
            }
            tracing::info!("Loaded {} banner caches from disk", cache.len());
        }

        // Start inotify watcher thread
        let cache_clone = self.cache.clone();
        let _watcher_handle = thread::spawn(move || {
            watch_loop(cache_clone);
        });

        // Start proactive scan of home directory in background
        let dir_sizes_clone = self.dir_sizes.clone();
        let dir_size_mtimes_clone = self.dir_size_mtimes.clone();
        let cache_clone = self.cache.clone();
        let socket_dir =
            directories::ProjectDirs::from("com", "fab", "fab").map(|p| p.data_dir().to_path_buf());
        thread::spawn(move || {
            proactive_scan(
                dir_sizes_clone.clone(),
                dir_size_mtimes_clone,
                cache_clone.clone(),
            );
            // Save to disk when done
            if let Some(dir) = socket_dir {
                let sizes = dir_sizes_clone.lock().unwrap_or_else(|e| {
                    tracing::warn!("Mutex poisoned, recovering");
                    e.into_inner()
                });
                save_size_cache(&dir, &sizes);
            }
        });

        let mut last_activity = Instant::now();
        let mut last_save = Instant::now();

        loop {
            match listener.accept() {
                Ok((stream, _)) => {
                    last_activity = Instant::now();
                    let cache = self.cache.clone();
                    let dir_sizes = self.dir_sizes.clone();
                    let dir_size_mtimes = self.dir_size_mtimes.clone();
                    thread::spawn(move || {
                        if let Err(e) = handle_client(stream, cache, dir_sizes, dir_size_mtimes) {
                            tracing::error!("Client error: {}", e);
                        }
                    });
                }
                Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                    // No pending connections — check idle timeout
                    if last_activity.elapsed() > IDLE_TIMEOUT {
                        tracing::info!("Idle timeout, shutting down");
                        break;
                    }

                    // Check for signal-based shutdown request
                    #[cfg(unix)]
                    if SHUTDOWN_REQUESTED.load(std::sync::atomic::Ordering::SeqCst) {
                        tracing::info!("Shutdown signal received, shutting down gracefully");
                        break;
                    }

                    // Periodic save every 5 minutes
                    if last_save.elapsed() > Duration::from_secs(300) {
                        let socket_dir = directories::ProjectDirs::from("com", "fab", "fab")
                            .map(|p| p.data_dir().to_path_buf());
                        if let Some(dir) = socket_dir {
                            let cache = self.cache.lock().unwrap_or_else(|e| {
                                tracing::warn!("Mutex poisoned, recovering");
                                e.into_inner()
                            });
                            save_banner_cache(&dir, &cache);
                        }
                        last_save = Instant::now();
                    }

                    thread::sleep(Duration::from_millis(10));
                }
                Err(e) => {
                    tracing::error!("Accept error: {}", e);
                    thread::sleep(Duration::from_millis(10));
                }
            }
        }

        // Cleanup — save banner cache to disk before exiting
        let socket_dir =
            directories::ProjectDirs::from("com", "fab", "fab").map(|p| p.data_dir().to_path_buf());
        if let Some(dir) = socket_dir {
            let cache = self.cache.lock().unwrap_or_else(|e| {
                tracing::warn!("Mutex poisoned, recovering");
                e.into_inner()
            });
            save_banner_cache(&dir, &cache);
        }
        std::fs::remove_file(&self.socket_path).ok();
        Ok(())
    }
}

/// inotify watcher loop — monitors cached directories for changes
fn watch_loop(cache: Arc<Mutex<HashMap<PathBuf, CacheEntry>>>) {
    let mut inotify = match Inotify::init() {
        Ok(i) => i,
        Err(e) => {
            tracing::error!("Failed to init inotify: {}", e);
            return;
        }
    };

    let mut watched: HashMap<PathBuf, inotify::WatchDescriptor> = HashMap::new();
    let mut failed_watches: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();

    loop {
        // Check for new directories to watch
        {
            let cache = cache.lock().unwrap_or_else(|e| {
                tracing::warn!("Mutex poisoned, recovering");
                e.into_inner()
            });
            for path in cache.keys() {
                if !watched.contains_key(path) && !failed_watches.contains(path) {
                    // Skip non-existent directories and dead symlinks
                    if !path.exists() {
                        failed_watches.insert(path.clone());
                        continue;
                    }
                    // For symlinks, check if target exists
                    if let Ok(meta) = std::fs::symlink_metadata(path) {
                        if meta.is_symlink() && std::fs::metadata(path).is_err() {
                            failed_watches.insert(path.clone());
                            continue; // Dead symlink, skip
                        }
                    }
                    match inotify.watches().add(
                        path,
                        WatchMask::CREATE
                            | WatchMask::DELETE
                            | WatchMask::MODIFY
                            | WatchMask::MOVE
                            | WatchMask::CLOSE_WRITE,
                    ) {
                        Ok(wd) => {
                            tracing::info!("Watching: {}", path.display());
                            watched.insert(path.clone(), wd);
                        }
                        Err(e) => {
                            tracing::warn!("Failed to watch {}: {}", path.display(), e);
                            failed_watches.insert(path.clone());
                        }
                    }
                }
            }
        }

        // Read inotify events (non-blocking)
        let mut buffer = [0u8; 4096];
        match inotify.read_events(&mut buffer) {
            Ok(events) => {
                for event in events {
                    // Find which cached directory this event belongs to
                    let mut invalidated = Vec::new();
                    for (path, wd) in &watched {
                        if event.wd == *wd {
                            invalidated.push(path.clone());
                        }
                    }

                    // Invalidate affected cache entries
                    if !invalidated.is_empty() {
                        let mut cache_guard = cache.lock().unwrap_or_else(|e| {
                            tracing::warn!("Mutex poisoned, recovering");
                            e.into_inner()
                        });
                        for path in &invalidated {
                            cache_guard.remove(path);
                            tracing::info!("Cache invalidated: {}", path.display());
                        }
                    }
                }
            }
            Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                // No events — continue
            }
            Err(_) => {
                // Error — continue loop
            }
        }

        // Remove stale watchers for directories no longer in cache or no longer exist
        {
            let cache = cache.lock().unwrap_or_else(|e| {
                tracing::warn!("Mutex poisoned, recovering");
                e.into_inner()
            });
            let to_remove: Vec<PathBuf> = watched
                .keys()
                .filter(|p| !cache.contains_key(*p) || !p.exists())
                .cloned()
                .collect();
            for path in to_remove {
                if let Some(wd) = watched.remove(&path) {
                    inotify.watches().remove(wd).ok();
                    tracing::info!("Stopped watching: {}", path.display());
                }
            }
            // Also clear failed watches for paths no longer in cache
            failed_watches.retain(|p| cache.contains_key(p));
        }

        thread::sleep(Duration::from_millis(100));
    }
}

fn handle_client(
    stream: UnixStream,
    cache: Arc<Mutex<HashMap<PathBuf, CacheEntry>>>,
    dir_sizes: Arc<Mutex<HashMap<PathBuf, u64>>>,
    dir_size_mtimes: Arc<Mutex<HashMap<PathBuf, Option<SystemTime>>>>,
) -> Result<()> {
    stream.set_read_timeout(Some(Duration::from_secs(5)))?;
    stream.set_write_timeout(Some(Duration::from_secs(5)))?;

    let mut stream = stream;

    let t_start = std::time::Instant::now();
    // Length-prefixed JSON: read 4-byte LE length, then payload.
    let mut len_bytes = [0u8; 4];
    stream.read_exact(&mut len_bytes)?;
    let t_read = std::time::Instant::now();
    let req_len = u32::from_le_bytes(len_bytes) as usize;
    let mut req_buf = vec![0u8; req_len];
    stream.read_exact(&mut req_buf)?;
    let request: Request = serde_json::from_slice(&req_buf)?;
    let t_parse = std::time::Instant::now();
    tracing::debug!(
        "Received request: {:?} (read={:?}, parse={:?})",
        request,
        t_read - t_start,
        t_parse - t_read
    );

    let response = match request {
        Request::Banner { path } => {
            let path = path.canonicalize().unwrap_or(path);

            // Check cache — if hit, validate the shallow folder snapshot and refresh sizes.
            let cached_entry = {
                let cache = cache.lock().unwrap_or_else(|e| {
                    tracing::warn!("Mutex poisoned, recovering");
                    e.into_inner()
                });
                tracing::debug!("Cache lookup: path={:?}, entries={}", path, cache.len());
                cache
                    .get(&path)
                    .filter(|entry| entry.computed_at.elapsed() < CACHE_TTL)
                    .cloned()
            };

            if let Some(entry) = cached_entry {
                let t0 = std::time::Instant::now();
                let mut data = entry.data;
                let t1 = std::time::Instant::now();
                if !cached_summary_is_fresh(&data.summary, &path) {
                    data = compute_banner_data(&path)?;
                    let mut cache = cache.lock().unwrap_or_else(|e| {
                        tracing::warn!("Mutex poisoned, recovering");
                        e.into_inner()
                    });
                    cache.insert(
                        path.clone(),
                        CacheEntry {
                            data: data.clone(),
                            computed_at: Instant::now(),
                        },
                    );
                }
                refresh_displayed_dir_sizes(
                    &mut data.summary.top_items,
                    &dir_sizes,
                    &dir_size_mtimes,
                );
                data.summary.total_size = data.summary.top_items.iter().map(|item| item.size).sum();
                let t2 = std::time::Instant::now();
                let t3 = std::time::Instant::now();
                send_response(&mut stream, &Response::Banner(Box::new(data)))?;
                let t4 = std::time::Instant::now();
                tracing::debug!(
                    "Cache hit: clone={:?} refresh={:?} send={:?}",
                    t1 - t0,
                    t2 - t1,
                    t4 - t3
                );
                // Keep stream alive while client reads
                let mut discard = [0u8; 256];
                loop {
                    match stream.read(&mut discard) {
                        Ok(0) => break,
                        Ok(_) => continue,
                        Err(_) => break,
                    }
                }
                return Ok(());
            }

            // Cache miss or stale shallow snapshot — do full scan
            let mut data = compute_banner_data(&path)?;

            refresh_displayed_dir_sizes(&mut data.summary.top_items, &dir_sizes, &dir_size_mtimes);
            data.summary.total_size = data.summary.top_items.iter().map(|item| item.size).sum();

            // Store in cache
            {
                let mut cache = cache.lock().unwrap_or_else(|e| {
                    tracing::warn!("Mutex poisoned, recovering");
                    e.into_inner()
                });
                cache.insert(
                    path.clone(),
                    CacheEntry {
                        data: data.clone(),
                        computed_at: Instant::now(),
                    },
                );
            }

            Response::Banner(Box::new(data))
        }
        Request::Warm { path } => {
            let path = path.canonicalize().unwrap_or(path);
            let cache = cache.clone();
            // Pre-compute in background — don't block the client
            thread::spawn(move || {
                let cache_hit = {
                    let c = cache.lock().unwrap_or_else(|e| {
                        tracing::warn!("Mutex poisoned, recovering");
                        e.into_inner()
                    });
                    c.get(&path)
                        .map(|e| e.computed_at.elapsed() < CACHE_TTL)
                        .unwrap_or(false)
                };
                if !cache_hit {
                    if let Ok(data) = compute_banner_data(&path) {
                        let mut c = cache.lock().unwrap_or_else(|e| {
                            tracing::warn!("Mutex poisoned, recovering");
                            e.into_inner()
                        });
                        c.insert(
                            path,
                            CacheEntry {
                                data,
                                computed_at: Instant::now(),
                            },
                        );
                    }
                }
            });
            return Ok(()); // No response needed — fire and forget
        }
        Request::DirSize { path } => {
            let mut sizes = dir_sizes.lock().unwrap_or_else(|e| {
                tracing::warn!("Mutex poisoned, recovering");
                e.into_inner()
            });
            let mut mtimes = dir_size_mtimes.lock().unwrap_or_else(|e| {
                tracing::warn!("Mutex poisoned, recovering");
                e.into_inner()
            });
            let size = match sizes.get(&path).copied() {
                Some(size) if mtimes.get(&path).copied().flatten() == current_dir_mtime(&path) => {
                    size
                }
                _ => {
                    let size = compute_dir_size(&path);
                    sizes.insert(path.clone(), size);
                    mtimes.insert(path.clone(), current_dir_mtime(&path));
                    size
                }
            };
            Response::DirSize { path, size }
        }
        Request::Ping => Response::Pong,
        Request::Shutdown => {
            tracing::info!("Shutdown requested");
            // Save banner cache before exiting
            let socket_dir = directories::ProjectDirs::from("com", "fab", "fab")
                .map(|p| p.data_dir().to_path_buf());
            if let Some(dir) = socket_dir {
                let c = cache.lock().unwrap_or_else(|e| {
                    tracing::warn!("Mutex poisoned, recovering");
                    e.into_inner()
                });
                save_banner_cache(&dir, &c);
            }
            std::process::exit(0);
        }
    };

    send_response(&mut stream, &response)?;
    tracing::trace!("Sent response successfully");

    // Keep stream alive while client reads. The client signals it's done by
    // closing the connection (dropping its UnixStream). Until then, the client
    // may still be reading the response.
    use std::io::Read;
    let mut discard = [0u8; 256];
    loop {
        match stream.read(&mut discard) {
            Ok(0) => break, // EOF — client closed
            Ok(_) => continue,
            Err(_) => break, // timeout or error
        }
    }
    Ok(())
}

fn send_response(stream: &mut UnixStream, response: &Response) -> Result<()> {
    use std::io::Write;
    // Length-prefixed JSON: 4-byte LE length, then payload.
    // Using JSON instead of bincode because bincode validates UTF-8 on
    // String fields. JSON always produces valid UTF-8. The key insight:
    // to_vec on a Vec<u8> buffers the entire output, then a single
    // write_all sends it in one syscall — avoiding 1-byte-at-a-time I/O.
    let resp_bytes = serde_json::to_vec(response)?;
    let resp_len = resp_bytes.len() as u32;
    let mut combined = Vec::with_capacity(4 + resp_bytes.len());
    let len_bytes = resp_len.to_le_bytes();
    combined.extend_from_slice(&len_bytes);
    combined.extend_from_slice(&resp_bytes);
    stream.write_all(&combined)?;
    stream.flush()?;
    Ok(())
}

fn compute_banner_data(path: &Path) -> Result<BannerData> {
    let summary = DirSummary::scan_with_options(path, false, true, true, true, true)?;

    // Build filter list for git status collection:
    // - For files at root: just the filename (e.g., "Cargo.toml")
    // - For directories: the directory name (e.g., "src") to match all children
    // This tells git2 to only collect statuses for files we'll actually display
    let filter_paths: Vec<String> = summary
        .top_items
        .iter()
        .map(|item| item.name.clone())
        .collect();

    // Use filtered git info — only collects statuses for top_items (much faster for large repos)
    let mut git_info = folder_auto_banner::git::get_git_info_filtered(path, &filter_paths).ok();

    // For directories, we need to also collect statuses for their immediate children
    // because git pathspec "src" matches src/*, but we display src/daemon.rs etc.
    // The filter already handles this via pathspec matching.
    // Additionally, filter file_statuses to only keep depth 0 or 1 entries.
    if let Some(ref mut gi) = git_info {
        if !gi.file_statuses.is_empty() {
            let keep: std::collections::HashSet<_> = summary
                .top_items
                .iter()
                .map(|item| item.name.clone())
                .collect();
            gi.file_statuses.retain(|path_str, _| {
                let components: Vec<_> = std::path::Path::new(path_str)
                    .components()
                    .map(|c| c.as_os_str().to_string_lossy().to_string())
                    .collect();
                match components.len() {
                    0 => false,
                    1 => keep.contains(&components[0]),
                    2 => keep.contains(&components[0]), // "src/daemon.rs"
                    _ => false,                         // "target/debug/build/..." — exclude
                }
            });
        }
    }

    // Return immediately — sizes come from global cache
    Ok(BannerData { summary, git_info })
}

fn cached_summary_is_fresh(cached: &DirSummary, path: &Path) -> bool {
    let Ok(fresh) = DirSummary::scan_with_options(path, false, false, false, false, false) else {
        return false;
    };

    cached.total_items == fresh.total_items
        && cached.total_size == fresh.total_size
        && cached.files == fresh.files
        && cached.dirs == fresh.dirs
        && cached.project_type == fresh.project_type
        && cached.last_modified == fresh.last_modified
        && cached.top_items.len() == fresh.top_items.len()
        && cached
            .top_items
            .iter()
            .zip(fresh.top_items.iter())
            .all(|(a, b)| {
                a.name == b.name
                    && a.is_dir == b.is_dir
                    && a.is_file == b.is_file
                    && a.is_symlink == b.is_symlink
                    && a.size == b.size
                    && a.modified == b.modified
                    && a.symlink_valid == b.symlink_valid
            })
}

fn refresh_displayed_dir_sizes(
    items: &mut [DirEntry],
    dir_sizes: &Arc<Mutex<HashMap<PathBuf, u64>>>,
    dir_size_mtimes: &Arc<Mutex<HashMap<PathBuf, Option<SystemTime>>>>,
) {
    let sizes = dir_sizes.lock().unwrap_or_else(|e| {
        tracing::warn!("Mutex poisoned, recovering");
        e.into_inner()
    });
    let mtimes = dir_size_mtimes.lock().unwrap_or_else(|e| {
        tracing::warn!("Mutex poisoned, recovering");
        e.into_inner()
    });

    let mut to_compute = Vec::new();
    for item in items.iter_mut().filter(|item| item.is_dir) {
        let current_mtime = current_dir_mtime(&item.path);
        let cached_mtime = mtimes.get(&item.path).copied().flatten();
        let cached_size = sizes.get(&item.path).copied();

        if cached_size.is_none() || cached_mtime != current_mtime {
            to_compute.push((item.path.clone(), current_mtime));
        } else if let Some(size) = cached_size {
            item.size = size;
        }
    }

    drop(mtimes);
    drop(sizes);

    for (path, mtime) in to_compute {
        let size = compute_dir_size(&path);
        let mut sizes = dir_sizes.lock().unwrap_or_else(|e| {
            tracing::warn!("Mutex poisoned, recovering");
            e.into_inner()
        });
        sizes.insert(path.clone(), size);
        drop(sizes);

        let mut mtimes = dir_size_mtimes.lock().unwrap_or_else(|e| {
            tracing::warn!("Mutex poisoned, recovering");
            e.into_inner()
        });
        mtimes.insert(path, mtime);
    }

    let sizes = dir_sizes.lock().unwrap_or_else(|e| {
        tracing::warn!("Mutex poisoned, recovering");
        e.into_inner()
    });
    for item in items.iter_mut().filter(|item| item.is_dir) {
        if let Some(size) = sizes.get(&item.path) {
            item.size = *size;
        }
    }
}

fn current_dir_mtime(path: &Path) -> Option<SystemTime> {
    std::fs::metadata(path)
        .ok()
        .and_then(|metadata| metadata.modified().ok())
}

fn compute_dir_size(path: &Path) -> u64 {
    // Use `du -s` which is much faster than recursive Rust, but keep it
    // bounded so a pathological directory cannot hang banner responses.
    let path_arg = path.to_string_lossy();
    if let Ok(stdout) = folder_auto_banner::utils::run_with_timeout_stdout(
        "du",
        &["-s", "--bytes", path_arg.as_ref()],
        SIZE_CACHE_REFRESH_TIMEOUT,
    ) {
        let stdout = stdout.trim();
        if !stdout.is_empty() {
            let size_str = stdout.split_whitespace().next().unwrap_or("0");
            if let Ok(size) = size_str.parse::<u64>() {
                return size;
            }
        }
    }
    // Fallback: just the directory inode size
    std::fs::metadata(path).map(|m| m.len()).unwrap_or(0)
}

const SIZE_CACHE_FILE: &str = "dir_sizes.json";
const BANNER_CACHE_FILE: &str = "banner_cache.json";

fn size_cache_path(socket_dir: &Path) -> PathBuf {
    socket_dir.join(SIZE_CACHE_FILE)
}

fn banner_cache_path(socket_dir: &Path) -> PathBuf {
    socket_dir.join(BANNER_CACHE_FILE)
}

fn load_size_cache(socket_dir: &Path) -> HashMap<PathBuf, u64> {
    let path = size_cache_path(socket_dir);
    if let Ok(data) = std::fs::read_to_string(&path) {
        if let Ok(map) = serde_json::from_str::<HashMap<String, u64>>(&data) {
            let result: HashMap<PathBuf, u64> = map
                .into_iter()
                .map(|(k, v)| (PathBuf::from(k), v))
                .collect();
            tracing::info!("Loaded {} cached directory sizes from disk", result.len());
            return result;
        }
    }
    HashMap::new()
}

fn save_size_cache(socket_dir: &Path, sizes: &HashMap<PathBuf, u64>) {
    let path = size_cache_path(socket_dir);
    let map: HashMap<String, u64> = sizes
        .iter()
        .map(|(k, v)| (k.to_string_lossy().to_string(), *v))
        .collect();
    if let Ok(data) = serde_json::to_string(&map) {
        if std::fs::write(&path, data).is_ok() {
            tracing::info!("Saved {} directory sizes to disk", sizes.len());
        }
    }
}

fn load_banner_cache(socket_dir: &Path) -> HashMap<PathBuf, BannerData> {
    let path = banner_cache_path(socket_dir);
    if let Ok(data) = std::fs::read_to_string(&path) {
        if let Ok(map) = serde_json::from_str::<HashMap<String, BannerData>>(&data) {
            let result: HashMap<PathBuf, BannerData> = map
                .into_iter()
                .map(|(k, v)| (PathBuf::from(k), v))
                .collect();
            tracing::info!("Loaded {} cached banners from disk", result.len());
            return result;
        }
    }
    HashMap::new()
}

fn save_banner_cache(socket_dir: &Path, cache: &HashMap<PathBuf, CacheEntry>) {
    let path = banner_cache_path(socket_dir);
    let map: HashMap<String, &BannerData> = cache
        .iter()
        .map(|(k, v)| (k.to_string_lossy().to_string(), &v.data))
        .collect();
    if let Ok(data) = serde_json::to_string(&map) {
        if std::fs::write(&path, data).is_ok() {
            tracing::info!("Saved {} banner caches to disk", cache.len());
        }
    }
}

/// Proactively scan home directory and populate global size cache + banner cache
fn proactive_scan(
    dir_sizes: Arc<Mutex<HashMap<PathBuf, u64>>>,
    dir_size_mtimes: Arc<Mutex<HashMap<PathBuf, Option<SystemTime>>>>,
    banner_cache: Arc<Mutex<HashMap<PathBuf, CacheEntry>>>,
) {
    let home = match std::env::var("HOME") {
        Ok(h) => PathBuf::from(h),
        Err(_) => return,
    };

    tracing::info!("Starting proactive scan of {}", home.display());

    // Find all directories in home (up to 2 levels deep for speed)
    let mut dirs_to_scan: Vec<PathBuf> = Vec::new();

    // Level 1: direct children of home
    if let Ok(entries) = std::fs::read_dir(&home) {
        for entry in entries.flatten() {
            // Use symlink_metadata to detect symlinks without following them
            let meta = match std::fs::symlink_metadata(entry.path()) {
                Ok(m) => m,
                Err(_) => continue,
            };

            if meta.is_symlink() {
                // For symlinks, try to resolve the target
                if let Ok(target_meta) = std::fs::metadata(entry.path()) {
                    if target_meta.is_dir() && !entry.file_name().to_string_lossy().starts_with('.')
                    {
                        dirs_to_scan.push(entry.path());
                    }
                }
                // Skip dead symlinks (target doesn't exist)
            } else if meta.is_dir() && !entry.file_name().to_string_lossy().starts_with('.') {
                dirs_to_scan.push(entry.path());
            }
        }
    }

    // Level 2: subdirectories of visible dirs (for projects like ~/Dev/project)
    let level1: Vec<PathBuf> = dirs_to_scan.clone();
    for dir in &level1 {
        if let Ok(entries) = std::fs::read_dir(dir) {
            for entry in entries.flatten().take(50) {
                let meta = match std::fs::symlink_metadata(entry.path()) {
                    Ok(m) => m,
                    Err(_) => continue,
                };

                if meta.is_symlink() {
                    if let Ok(target_meta) = std::fs::metadata(entry.path()) {
                        if target_meta.is_dir() {
                            dirs_to_scan.push(entry.path());
                        }
                    }
                } else if meta.is_dir() {
                    dirs_to_scan.push(entry.path());
                }
            }
        }
    }

    // Track where level 1+2 end (most likely navigation targets)
    let level2_end = dirs_to_scan.len();

    // Level 3: subdirectories of level 2 dirs (for projects like ~/Dev/project/src)
    let level2: Vec<PathBuf> = dirs_to_scan[level1.len()..].to_vec();
    for dir in &level2 {
        if let Ok(entries) = std::fs::read_dir(dir) {
            for entry in entries.flatten().take(20) {
                let meta = match std::fs::symlink_metadata(entry.path()) {
                    Ok(m) => m,
                    Err(_) => continue,
                };

                if meta.is_symlink() {
                    if let Ok(target_meta) = std::fs::metadata(entry.path()) {
                        if target_meta.is_dir() {
                            dirs_to_scan.push(entry.path());
                        }
                    }
                } else if meta.is_dir() {
                    dirs_to_scan.push(entry.path());
                }
            }
        }
    }

    // Also scan ALL hidden dirs in home
    if let Ok(entries) = std::fs::read_dir(&home) {
        for entry in entries.flatten() {
            let name = entry.file_name().to_string_lossy().to_string();
            if name.starts_with('.') {
                let meta = match std::fs::symlink_metadata(entry.path()) {
                    Ok(m) => m,
                    Err(_) => continue,
                };

                let is_dir = if meta.is_symlink() {
                    std::fs::metadata(entry.path())
                        .map(|m| m.is_dir())
                        .unwrap_or(false)
                } else {
                    meta.is_dir()
                };

                if is_dir {
                    dirs_to_scan.push(entry.path());
                }
            }
        }
    }

    tracing::info!("Scanning {} directories", dirs_to_scan.len());

    // Run du in batches to avoid ARG_MAX limits
    // Lock per-batch to avoid blocking banner requests for the entire scan
    let batch_size = 50;
    let mut count = 0;

    for chunk in dirs_to_scan.chunks(batch_size) {
        let mut du_args: Vec<String> = vec!["-s".to_string(), "--bytes".to_string()];
        for dir in chunk {
            du_args.push(dir.to_string_lossy().to_string());
        }

        if let Ok(output) = std::process::Command::new("du").args(&du_args).output() {
            let mut batch_sizes = Vec::new();
            let stdout = String::from_utf8_lossy(&output.stdout);
            for line in stdout.lines() {
                let parts: Vec<&str> = line.splitn(2, '\t').collect();
                if parts.len() >= 2 {
                    if let Ok(size) = parts[0].parse::<u64>() {
                        let dir_path = PathBuf::from(parts[1]);
                        batch_sizes.push((dir_path, size));
                        count += 1;
                    }
                }
            }
            // Brief lock to insert batch, then release
            let mut sizes = dir_sizes.lock().unwrap_or_else(|e| {
                tracing::warn!("Mutex poisoned, recovering");
                e.into_inner()
            });
            for (path, size) in &batch_sizes {
                sizes.insert(path.clone(), *size);
            }
            drop(sizes);

            let mut mtimes = dir_size_mtimes.lock().unwrap_or_else(|e| {
                tracing::warn!("Mutex poisoned, recovering");
                e.into_inner()
            });
            for (path, _) in &batch_sizes {
                mtimes.insert(path.clone(), current_dir_mtime(path));
            }
            drop(mtimes);
        }
    }

    tracing::info!("Proactive scan complete: {} directory sizes cached", count);

    // Pre-compute banner data for level 1 + level 2 dirs (most likely navigation targets)
    let banner_targets: Vec<PathBuf> = dirs_to_scan[..level2_end.min(dirs_to_scan.len())].to_vec();
    tracing::info!(
        "Pre-computing banners for {} directories",
        banner_targets.len()
    );

    let mut banner_count = 0;
    for path in &banner_targets {
        // Check cache with brief lock, compute outside lock
        let should_compute = {
            let cache = banner_cache.lock().unwrap_or_else(|e| {
                tracing::warn!("Mutex poisoned, recovering");
                e.into_inner()
            });
            !cache
                .get(path)
                .map(|e| e.computed_at.elapsed() < CACHE_TTL)
                .unwrap_or(false)
        };

        if !should_compute {
            continue;
        }

        // Compute banner data outside the lock (expensive operation)
        if let Ok(data) = compute_banner_data(path) {
            // Brief lock to insert
            let mut cache = banner_cache.lock().unwrap_or_else(|e| {
                tracing::warn!("Mutex poisoned, recovering");
                e.into_inner()
            });
            cache.insert(
                path.clone(),
                CacheEntry {
                    data,
                    computed_at: Instant::now(),
                },
            );
            banner_count += 1;
        }
    }

    tracing::info!("Pre-computed {} banner caches", banner_count);

    // Save banner cache to disk
    let socket_dir =
        directories::ProjectDirs::from("com", "fab", "fab").map(|p| p.data_dir().to_path_buf());
    if let Some(dir) = socket_dir {
        let cache = banner_cache.lock().unwrap_or_else(|e| {
            tracing::warn!("Mutex poisoned, recovering");
            e.into_inner()
        });
        save_banner_cache(&dir, &cache);
    }
}

fn main() -> Result<()> {
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
        )
        .init();

    // Set resource limits: low CPU priority and idle IO priority
    #[cfg(unix)]
    {
        // nice: 10 = lower priority (range -20 to 19, higher = lower priority)
        unsafe {
            libc::nice(10);
        }
        // ionice: 3 = idle priority class
        let _ = std::process::Command::new("ionice")
            .args(["-c", "3", "-p", &std::process::id().to_string()])
            .output();
    }

    // Install signal handler for graceful shutdown (SIGTERM/SIGINT)
    #[cfg(unix)]
    {
        let handler = signal_wrapper as *const () as libc::sighandler_t;
        unsafe {
            libc::signal(libc::SIGTERM, handler);
            libc::signal(libc::SIGINT, handler);
        }
    }

    tracing::info!("fabd started with resource limits (nice=10, ionice=idle)");

    let daemon = Daemon::new()?;
    daemon.run()
}

// Global shutdown flag — set by signal handler, checked by daemon loop
#[cfg(unix)]
static SHUTDOWN_REQUESTED: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(false);

#[cfg(unix)]
extern "C" fn signal_wrapper(_sig: libc::c_int) {
    SHUTDOWN_REQUESTED.store(true, std::sync::atomic::Ordering::SeqCst);
}

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

    #[test]
    fn test_socket_path() {
        let path = directories::ProjectDirs::from("com", "fab", "fab")
            .unwrap()
            .data_dir()
            .join(SOCKET_NAME);
        assert!(path.to_string_lossy().contains("fabd.sock"));
    }

    #[test]
    fn test_cache_entry_creation() {
        let summary = DirSummary::scan(Path::new("/tmp")).unwrap();
        let data = BannerData {
            summary,
            git_info: None,
        };
        let entry = CacheEntry {
            data,
            computed_at: Instant::now(),
        };
        assert!(entry.computed_at.elapsed() < Duration::from_secs(1));
    }

    #[test]
    fn test_cache_ttl() {
        let summary = DirSummary::scan(Path::new("/tmp")).unwrap();
        let entry = CacheEntry {
            data: BannerData {
                summary,
                git_info: None,
            },
            computed_at: Instant::now() - Duration::from_secs(600), // 10 minutes ago
        };
        assert!(entry.computed_at.elapsed() > CACHE_TTL);
    }

    #[test]
    fn test_request_serialization() {
        let request = Request::Banner {
            path: PathBuf::from("/tmp"),
        };
        let json = serde_json::to_string(&request).unwrap();
        assert!(json.contains("Banner"));
        assert!(json.contains("/tmp"));
    }

    #[test]
    fn test_response_serialization() {
        let response = Response::Pong;
        let json = serde_json::to_string(&response).unwrap();
        assert!(json.contains("Pong"));
    }

    #[test]
    fn test_banner_data_serialization() {
        let summary = DirSummary::scan(Path::new("/tmp")).unwrap();
        let data = BannerData {
            summary,
            git_info: None,
        };
        let json = serde_json::to_string(&data).unwrap();
        assert!(json.contains("summary"));
    }

    #[test]
    fn test_daemon_new() {
        let daemon = Daemon::new();
        assert!(daemon.is_ok());
    }

    #[test]
    fn test_compute_dir_size() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("sample.txt"), "hello").unwrap();
        let size = compute_dir_size(tmp.path());
        assert!(size > 0);
    }

    #[test]
    fn test_cached_summary_is_fresh_detects_new_item() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("a.txt"), "a").unwrap();
        let summary =
            DirSummary::scan_with_options(tmp.path(), false, false, false, false, false).unwrap();

        assert!(cached_summary_is_fresh(&summary, tmp.path()));

        std::fs::write(tmp.path().join("b.txt"), "b").unwrap();
        assert!(!cached_summary_is_fresh(&summary, tmp.path()));
    }

    #[test]
    fn test_cached_summary_is_fresh_detects_nested_change() {
        let tmp = tempfile::tempdir().unwrap();
        let child = tmp.path().join("child");
        std::fs::create_dir(&child).unwrap();
        std::fs::write(child.join("nested.txt"), "before").unwrap();
        let summary =
            DirSummary::scan_with_options(tmp.path(), false, false, false, false, false).unwrap();

        assert!(cached_summary_is_fresh(&summary, tmp.path()));

        std::thread::sleep(Duration::from_millis(20));
        std::fs::write(child.join("nested-new.txt"), "after").unwrap();
        assert!(!cached_summary_is_fresh(&summary, tmp.path()));
    }

    #[test]
    fn test_refresh_displayed_dir_sizes_updates_changed_directory_size() {
        let tmp = tempfile::tempdir().unwrap();
        let child = tmp.path().join("child");
        std::fs::create_dir(&child).unwrap();
        std::fs::write(child.join("one.txt"), "one").unwrap();

        let mut items = vec![DirEntry {
            name: "child".to_string(),
            path: child.clone(),
            is_dir: true,
            is_file: false,
            is_symlink: false,
            is_exec: true,
            size: 0,
            modified: None,
            perms: String::new(),
            owner: String::new(),
            group: String::new(),
            symlink_target: None,
            symlink_valid: true,
        }];
        let dir_sizes = Arc::new(Mutex::new(HashMap::new()));
        let dir_size_mtimes = Arc::new(Mutex::new(HashMap::new()));

        refresh_displayed_dir_sizes(&mut items, &dir_sizes, &dir_size_mtimes);
        let first_size = items[0].size;
        assert!(first_size > 0);

        std::thread::sleep(Duration::from_millis(20));
        std::fs::write(child.join("two.txt"), "two").unwrap();
        refresh_displayed_dir_sizes(&mut items, &dir_sizes, &dir_size_mtimes);

        assert!(items[0].size > first_size);
    }
}