ublx 0.1.1

TUI to index once, enrich with metadata, and browse a flat snapshot in a 3-pane layout with multiple modes.
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
use anyhow::Result;
use std::{
    collections::{HashSet, hash_map::Entry},
    env,
    ffi::OsStr,
    fs,
    hash::{Hash, Hasher},
    path::{Path, PathBuf},
    time::{SystemTime, UNIX_EPOCH},
};

use log::debug;

/// Stable names for on-disk artifacts under an indexed root (`ubli/` cache, project `ublx.toml`, export dirs).
///
/// Values follow the Cargo package name where noted (`ublx` → e.g. `ublx.toml`, `.ublx`, `ublx-export/`).
pub struct UblxNames {
    /// Crate / CLI name (`CARGO_PKG_NAME`).
    pub pkg_name: &'static str,
    /// User cache directory name for per-root DB files (e.g. `ubli`).
    pub pkg_name_plural: &'static str,
    /// Index `SQLite` file extension (e.g. `.ublx`).
    pub index_db_file_ext: &'static str,
    /// Visible local config basename (e.g. `ublx.toml`).
    pub local_config_visible_toml: &'static str,
    /// Hidden local config basename (e.g. `.ublx.toml`).
    pub local_config_hidden_toml: &'static str,
    /// Nefaxer DB directory name
    pub nefax_db: &'static str,
    /// Subdirectory for Zahir JSON export (e.g. `ublx-export/`; CLI `-x` / Command Mode).
    pub zahir_export_dir_name: &'static str,
    /// Subdirectory for lens Markdown export (e.g. `ublx-lenses/`; Command Mode).
    pub lens_export_dir_name: &'static str,
}

impl Default for UblxNames {
    fn default() -> Self {
        Self::new()
    }
}

impl UblxNames {
    #[must_use]
    pub const fn new() -> Self {
        Self {
            pkg_name: env!("CARGO_PKG_NAME"),
            pkg_name_plural: "ubli",
            index_db_file_ext: concat!(".", env!("CARGO_PKG_NAME")),
            local_config_visible_toml: concat!(env!("CARGO_PKG_NAME"), ".toml"),
            local_config_hidden_toml: concat!(".", env!("CARGO_PKG_NAME"), ".toml"),
            nefax_db: ".nefaxer",
            zahir_export_dir_name: concat!(env!("CARGO_PKG_NAME"), "-export"),
            lens_export_dir_name: concat!(env!("CARGO_PKG_NAME"), "-lenses"),
        }
    }
}

pub const UBLX_NAMES: UblxNames = UblxNames::new();

/// `path_to_hex` / DB stem suffix length (16 hex chars from `DefaultHasher`).
const PATH_HASH_HEX_LEN: usize = 16;

/// True if `s` is exactly 16 ASCII hex digits (matches [`path_to_hex`] output).
#[must_use]
pub fn is_hex_hash16(s: &str) -> bool {
    s.len() == PATH_HASH_HEX_LEN && s.chars().all(|c| c.is_ascii_hexdigit())
}

/// Last segment of a DB stem after the final `_`, when it is a 16-char path hash (`{safe}_{hash}`).
#[must_use]
pub fn hash_suffix_from_db_stem(stem: &str) -> Option<&str> {
    let (_, rest) = stem.rsplit_once('_')?;
    is_hex_hash16(rest).then_some(rest)
}

/// Stable hex string for a path (for cache filenames). Same path => same string.
#[must_use]
pub fn path_to_hex(path: &Path) -> String {
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    path.to_string_lossy().hash(&mut hasher);
    format!("{:016x}", hasher.finish())
}

fn sanitize_name_for_fs(name: &str) -> String {
    let mut out = String::with_capacity(name.len());
    for ch in name.chars() {
        if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
            out.push(ch);
        } else {
            out.push('_');
        }
    }
    let trimmed = out.trim_matches('_');
    if trimmed.is_empty() {
        "root".to_string()
    } else {
        trimmed.to_string()
    }
}

/// User config directory for ublx. Global config lives here (e.g. `ublx.toml`).
/// - **Unix (macOS, Linux):** `~/.config/ublx`
/// - **Windows:** `%APPDATA%\ublx`
///   Returns `None` if the underlying env (e.g. `HOME`, `APPDATA`) is not set.
fn config_dir() -> Option<PathBuf> {
    #[cfg(windows)]
    {
        env::var("APPDATA")
            .ok()
            .map(|p| PathBuf::from(p).join(UBLX_NAMES.pkg_name))
    }
    #[cfg(not(windows))]
    {
        env::var("HOME")
            .ok()
            .map(|h| PathBuf::from(h).join(".config").join(UBLX_NAMES.pkg_name))
    }
}

/// User cache/data directory for ublx.
/// - **Unix (macOS, Linux):** `~/.local/share/ublx`
/// - **Windows:** `%LOCALAPPDATA%\ublx`
///   Returns `None` if the underlying env (e.g. `HOME`, `LOCALAPPDATA`) is not set.
fn cache_dir() -> Option<PathBuf> {
    #[cfg(windows)]
    {
        env::var("LOCALAPPDATA")
            .ok()
            .map(|p| PathBuf::from(p).join(UBLX_NAMES.pkg_name))
    }
    #[cfg(not(windows))]
    {
        env::var("HOME").ok().map(|h| {
            PathBuf::from(h)
                .join(".local")
                .join("share")
                .join(UBLX_NAMES.pkg_name)
        })
    }
}

/// Per-project `SQLite` files live under `cache_dir()/ubli/` (e.g. `~/.local/share/ublx/ubli`).
#[must_use]
fn db_dir() -> Option<PathBuf> {
    cache_dir().map(|c| c.join(UBLX_NAMES.pkg_name_plural))
}

/// Per-indexed-dir metadata for welcome-screen recents: `cache_dir()/recents/<path_hash>.txt`.
const RECENTS_SUBDIR: &str = "recents";

/// Weight for [`times_opened`] in [`recents_composite_score`]: each session open adds this many
/// effective nanoseconds so frequently opened roots stay competitive vs raw `last_open_ns`.
const RECENTS_OPEN_WEIGHT_NS: u128 = 3_600_000_000_000; // 1 hour per open

#[must_use]
fn recents_dir() -> Option<PathBuf> {
    cache_dir().map(|c| c.join(RECENTS_SUBDIR))
}

#[must_use]
fn now_ns() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| u64::try_from(d.as_nanos()).unwrap_or(u64::MAX))
        .unwrap_or(0)
}

#[derive(Debug, Clone)]
struct RecentsFileData {
    path: PathBuf,
    times_opened: u64,
    last_open_ns: u64,
}

fn fmt_recents_txt(data: &RecentsFileData) -> String {
    format!(
        "path={}\ntimes_opened={}\nlast_open_ns={}\n",
        data.path.to_string_lossy(),
        data.times_opened,
        data.last_open_ns
    )
}

fn parse_recents_txt(content: &str) -> Option<RecentsFileData> {
    let trimmed = content.trim();
    if trimmed.is_empty() {
        return None;
    }
    if !trimmed.contains('=') {
        let p = PathBuf::from(trimmed);
        return Some(RecentsFileData {
            path: p,
            times_opened: 0,
            last_open_ns: 0,
        });
    }
    let mut path: Option<PathBuf> = None;
    let mut times_opened: u64 = 0;
    let mut last_open_ns: u64 = 0;
    for line in trimmed.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let (k, v) = line.split_once('=')?;
        match k.trim() {
            "path" => path = Some(PathBuf::from(v.trim())),
            "times_opened" => times_opened = v.trim().parse().unwrap_or(0),
            "last_open_ns" => last_open_ns = v.trim().parse().unwrap_or(0),
            _ => {}
        }
    }
    path.map(|p| RecentsFileData {
        path: p,
        times_opened,
        last_open_ns,
    })
}

fn read_recents_file(path: &Path) -> Option<RecentsFileData> {
    let s = fs::read_to_string(path).ok()?;
    parse_recents_txt(&s)
}

/// Composite ordering: mostly `last_open_ns`, with a boost from `times_opened`.
#[must_use]
fn recents_composite_score(data: &RecentsFileData) -> u128 {
    u128::from(data.last_open_ns)
        .saturating_add(u128::from(data.times_opened).saturating_mul(RECENTS_OPEN_WEIGHT_NS))
}

/// True if `cache_dir()/recents/{path_hash(dir)}.txt` exists (this root was registered after the welcome flow).
#[must_use]
pub fn has_recents_entry_for_dir(dir: &Path) -> bool {
    let Some(recents) = recents_dir() else {
        return false;
    };
    let key = path_to_hex(dir);
    recents.join(format!("{key}.txt")).exists()
}

/// Whether to show the first-run welcome UI for this indexed root.
///
/// **Product rule:** when not in headless snapshot mode, show if the per-root `SQLite` file under [`UblxPaths::db`]
/// (in `cache_dir()/ubli/`) did **not** exist yet **before** [`crate::engine::db_ops::ensure_ublx_and_db`].
/// Recents and local `ublx.toml` are **not** part of this gate.
///
/// Callers should compute `had_ubli_db_file` with `UblxPaths::new(dir).db().exists()` **before**
/// `ensure_ublx_and_db` (same order as [`crate::main`]).
#[must_use]
pub fn should_show_initial_prompt(
    snapshot_only: bool,
    had_index_db_before_ensure: bool,
    had_any_cached_db_before_this_root: bool,
) -> bool {
    let initial_prompt = !snapshot_only && !had_index_db_before_ensure;
    debug!(
        "initial_prompt={initial_prompt} (had_index_db_before_ensure={had_index_db_before_ensure})"
    );
    debug!("cached ublx roots seen before startup: {had_any_cached_db_before_this_root}");
    initial_prompt
}

/// True when the shared `ubli` directory contains at least one DB file.
#[must_use]
pub fn has_any_cached_ublx_db() -> bool {
    let Some(dir) = db_dir() else {
        return false;
    };
    let Ok(rd) = fs::read_dir(dir) else {
        return false;
    };
    rd.flatten().any(|e| {
        e.path()
            .file_name()
            .and_then(|n| n.to_str())
            .is_some_and(|n| n.ends_with(UBLX_NAMES.index_db_file_ext))
    })
}

/// Register this root after first-run **UBLX here**: creates or updates `recents` entry (path, `last_open_ns`; `times_opened` starts at 0 and is incremented by [`record_ublx_session_open`] on each post-prompt session).
///
/// # Errors
///
/// Returns an error if the recents directory cannot be created or the recents file cannot be written.
pub fn remember_indexed_root_path(dir: &Path) -> Result<()> {
    let Some(recents) = recents_dir() else {
        return Ok(());
    };
    fs::create_dir_all(&recents)?;
    let key = path_to_hex(dir);
    let canon = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
    let path_file = recents.join(format!("{key}.txt"));
    let mut data = read_recents_file(&path_file).unwrap_or(RecentsFileData {
        path: canon.clone(),
        times_opened: 0,
        last_open_ns: 0,
    });
    data.path = canon;
    data.last_open_ns = now_ns();
    fs::write(path_file, fmt_recents_txt(&data))?;
    Ok(())
}

/// Refresh `last_open_ns` when the user picks a prior root from the welcome list (does not create a file).
/// Session `times_opened` is updated when the new process runs [`record_ublx_session_open`].
///
/// # Errors
///
/// Returns an error if the recents file cannot be written.
pub fn record_prior_root_selected(dir: &Path) -> Result<()> {
    let Some(recents) = recents_dir() else {
        return Ok(());
    };
    let key = path_to_hex(dir);
    let canon = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
    let path_file = recents.join(format!("{key}.txt"));
    if !path_file.exists() {
        return Ok(());
    }
    let Some(mut data) = read_recents_file(&path_file) else {
        return Ok(());
    };
    data.path = canon;
    data.last_open_ns = now_ns();
    fs::write(path_file, fmt_recents_txt(&data))?;
    Ok(())
}

/// Each normal TUI session for a root that already has a recents file: increment `times_opened`, refresh `last_open_ns`.
/// Does not create a file (first registration is only via [`remember_indexed_root_path`] after **UBLX here**).
///
/// # Errors
///
/// Returns an error if the recents file cannot be written.
pub fn record_ublx_session_open(dir: &Path) -> Result<()> {
    let Some(recents) = recents_dir() else {
        return Ok(());
    };
    let key = path_to_hex(dir);
    let canon = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
    let path_file = recents.join(format!("{key}.txt"));
    if !path_file.exists() {
        return Ok(());
    }
    let Some(mut data) = read_recents_file(&path_file) else {
        return Ok(());
    };
    data.path = canon;
    data.times_opened = data.times_opened.saturating_add(1);
    data.last_open_ns = now_ns();
    fs::write(path_file, fmt_recents_txt(&data))?;
    Ok(())
}

/// Collect all recents entries (deduped by canonical path).
fn collect_recents_entries() -> Vec<RecentsFileData> {
    let Some(dir) = recents_dir() else {
        return Vec::new();
    };
    let Ok(rd) = fs::read_dir(&dir) else {
        return Vec::new();
    };
    let mut best: std::collections::HashMap<PathBuf, RecentsFileData> =
        std::collections::HashMap::new();
    for entry in rd.flatten() {
        let p = entry.path();
        if p.extension().and_then(|e| e.to_str()) != Some("txt") {
            continue;
        }
        let Some(mut data) = read_recents_file(&p) else {
            continue;
        };
        let canon = data
            .path
            .canonicalize()
            .unwrap_or_else(|_| data.path.clone());
        data.path.clone_from(&canon);
        match best.entry(canon) {
            Entry::Occupied(mut o) => {
                let ex = o.get_mut();
                if data.last_open_ns > ex.last_open_ns
                    || (data.last_open_ns == ex.last_open_ns && data.times_opened > ex.times_opened)
                {
                    *ex = data;
                }
            }
            Entry::Vacant(v) => {
                v.insert(data);
            }
        }
    }
    best.into_values().collect()
}

/// Indexed roots that have **both** a valid `recents/{hash}.txt` and the matching **main** DB under `ubli/`.
///
/// For each recents file, the path in the file must resolve to a directory whose expected DB exists, and the
/// **16-hex hash in the recents filename** must match the **hash suffix** of that DB file’s stem (same rule as
/// [`UblxPaths::db_stem`]). Entries with a missing DB, wrong hash, or non-hex filename are skipped.
#[must_use]
pub fn all_indexed_roots_alphabetical() -> Vec<PathBuf> {
    let Some(recents) = recents_dir() else {
        return Vec::new();
    };
    let Ok(rd) = fs::read_dir(&recents) else {
        return Vec::new();
    };

    let mut out: HashSet<PathBuf> = HashSet::new();
    for entry in rd.flatten() {
        let p = entry.path();
        if p.extension().and_then(|e| e.to_str()) != Some("txt") {
            continue;
        }
        let Some(fname) = p.file_stem().and_then(|s| s.to_str()) else {
            continue;
        };
        if !is_hex_hash16(fname) {
            continue;
        }
        let Some(data) = read_recents_file(&p) else {
            continue;
        };
        let path = data
            .path
            .canonicalize()
            .unwrap_or_else(|_| data.path.clone());
        if !path.is_dir() {
            continue;
        }
        let db_path = UblxPaths::new(&path).db();
        if !db_path.exists() {
            continue;
        }
        let Some(db_stem) = db_path.file_stem().and_then(|s| s.to_str()) else {
            continue;
        };
        let Some(hash_from_db) = hash_suffix_from_db_stem(db_stem) else {
            continue;
        };
        if hash_from_db != fname {
            continue;
        }
        out.insert(path);
    }

    let mut paths: Vec<PathBuf> = out.into_iter().collect();
    paths.sort_by_key(|a| a.display().to_string());
    paths
}

/// Prior indexed roots that still look valid (directory exists and has a DB file), excluding `current`.
#[must_use]
pub fn prior_indexed_roots(current: &Path) -> Vec<PathBuf> {
    prior_indexed_roots_scored(current, usize::MAX)
        .into_iter()
        .map(|(p, _)| p)
        .collect()
}

/// Scoring prior indexed roots based on time last opened and times opened
fn prior_indexed_roots_scored(current: &Path, max: usize) -> Vec<(PathBuf, RecentsFileData)> {
    let current_canon = current
        .canonicalize()
        .unwrap_or_else(|_| current.to_path_buf());
    let mut scored: Vec<(PathBuf, RecentsFileData)> = Vec::new();
    for mut data in collect_recents_entries() {
        let dir = data
            .path
            .canonicalize()
            .unwrap_or_else(|_| data.path.clone());
        if dir == current_canon || !dir.is_dir() {
            continue;
        }
        let db = UblxPaths::new(&dir).db();
        if !db.exists() {
            continue;
        }
        data.path.clone_from(&dir);
        scored.push((dir, data));
    }
    scored.sort_by(|a, b| {
        recents_composite_score(&b.1)
            .cmp(&recents_composite_score(&a.1))
            .then_with(|| a.0.cmp(&b.0))
    });
    scored.truncate(max);
    scored
}

/// Same as [`prior_indexed_roots`], but sorted by [`recents_composite_score`], capped.
#[must_use]
pub fn prior_indexed_roots_recent(current: &Path, max: usize) -> Vec<PathBuf> {
    prior_indexed_roots_scored(current, max)
        .into_iter()
        .map(|(p, _)| p)
        .collect()
}

/// Path to the global config file: `config_dir()/ublx.toml`. `None` if [`config_dir`] is unavailable.
#[must_use]
pub fn global_config_toml() -> Option<PathBuf> {
    config_dir().map(|c| c.join(UBLX_NAMES.local_config_visible_toml))
}

/// Path to the cached "last applied" config for this dir: `cache_dir()/configs/[path_hex].toml`.
/// Per-indexed-dir so global + local overlay is cached by path. Fallback when hot reload gets invalid config.
#[must_use]
pub fn last_applied_config_path(dir: &Path) -> Option<PathBuf> {
    cache_dir().map(|c| c.join("configs").join(format!("{}.toml", path_to_hex(dir))))
}

/// True if `path_str` is a relative snapshot path equal only to [`LOCAL_CONFIG_VISIBLE_TOML`] / [`LOCAL_CONFIG_HIDDEN_TOML`] at the indexed root (normalized).
#[must_use]
pub fn rel_path_is_exact_local_config_toml(path_str: &str) -> bool {
    let trim = path_str.trim();
    if Path::new(trim).is_absolute() {
        return false;
    }
    let norm = trim.replace('\\', "/");
    let norm = norm.trim_start_matches("./");
    norm == UBLX_NAMES.local_config_visible_toml || norm == UBLX_NAMES.local_config_hidden_toml
}

/// Paths for the index DB and related files under an indexed `dir_to_ublx_abs`. Filenames use [`INDEX_DB_FILE_EXT`] and related suffixes (`_tmp`, `-wal`, `-shm`).
#[derive(Clone, Debug)]
pub struct UblxPaths {
    pub dir_to_ublx_abs: PathBuf,
}

impl UblxPaths {
    #[must_use]
    pub fn new(dir_to_ublx: &Path) -> Self {
        Self {
            dir_to_ublx_abs: dir_to_ublx.to_path_buf(),
        }
    }

    /// Filename stem (no extension) for the index DB: sanitized dir name + path hash.
    fn db_stem(&self) -> String {
        let dir_name = self
            .dir_to_ublx_abs
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("root");
        let safe_name = sanitize_name_for_fs(dir_name);
        let hash = path_to_hex(&self.dir_to_ublx_abs);
        format!("{safe_name}_{hash}")
    }

    /// Full filename for the index DB under [`Self::db_dir`] (stem + [`INDEX_DB_FILE_EXT`]).
    #[must_use]
    fn db_filename(&self) -> String {
        format!("{}{}", self.db_stem(), UBLX_NAMES.index_db_file_ext)
    }

    #[must_use]
    pub fn db_dir(&self) -> Option<PathBuf> {
        db_dir()
    }

    /// Ensure the cache db folder exists.
    ///
    /// # Errors
    ///
    /// Returns [`anyhow::Error`] when creating the db directory fails.
    pub fn ensure_db_dir(&self) -> Result<PathBuf> {
        let dir = self
            .db_dir()
            .ok_or_else(|| anyhow::anyhow!("could not resolve user cache directory"))?;
        fs::create_dir_all(&dir)?;
        Ok(dir)
    }

    #[must_use]
    pub fn log_path(&self) -> PathBuf {
        self.dir_to_ublx_abs
            .join(format!("{}.log", UBLX_NAMES.pkg_name))
    }

    /// Hidden config path: `dir_to_ublx_abs/.ublx.toml`.
    #[must_use]
    pub fn hidden_toml(&self) -> PathBuf {
        self.dir_to_ublx_abs
            .join(UBLX_NAMES.local_config_hidden_toml)
    }

    /// Visible config path: `dir_to_ublx_abs/ublx.toml`.
    #[must_use]
    pub fn visible_toml(&self) -> PathBuf {
        self.dir_to_ublx_abs
            .join(UBLX_NAMES.local_config_visible_toml)
    }

    /// True if `path` (relative to `dir_to_ublx_abs`) is the hidden or visible ublx config file.
    #[must_use]
    pub fn is_config_file(&self, path: &Path) -> bool {
        let Some(name) = path.file_name() else {
            return false;
        };
        name == OsStr::new(UBLX_NAMES.local_config_visible_toml)
            || name == OsStr::new(UBLX_NAMES.local_config_hidden_toml)
    }

    /// Path to the config file to use: checks for `dir_to_ublx_abs/.ublx.toml` then `dir_to_ublx_abs/ublx.toml`; returns the first that exists, or `None`.
    #[must_use]
    pub fn toml_path(&self) -> Option<PathBuf> {
        let hidden = self.hidden_toml();
        let visible = self.visible_toml();
        if hidden.exists() {
            Some(hidden)
        } else if visible.exists() {
            Some(visible)
        } else {
            None
        }
    }

    /// Path used when creating or updating local config: existing hidden or visible file if present, otherwise
    /// [`Self::hidden_toml`] (same default as other local-config writers in this crate).
    #[must_use]
    pub fn local_config_path_for_write(&self) -> PathBuf {
        self.toml_path().unwrap_or_else(|| self.hidden_toml())
    }

    /// Main DB file under `cache_dir()` / [`UBLX_NAMES.pkg_name_plural`] (basename + [`INDEX_DB_FILE_EXT`]). `SQLite` creates it if missing.
    #[must_use]
    pub fn db(&self) -> PathBuf {
        self.db_dir()
            .unwrap_or_else(|| self.dir_to_ublx_abs.clone())
            .join(self.db_filename())
    }

    /// Nefaxer index file (e.g. `dir_to_ublx_abs/.nefaxer`). When present, used as prior snapshot before ublx snapshot.
    #[must_use]
    pub fn nefax_db(&self) -> PathBuf {
        self.dir_to_ublx_abs.join(UBLX_NAMES.nefax_db)
    }

    /// Temp file (write-then-rename to [`Self::db`]). Same stem as DB with `_tmp` before [`INDEX_DB_FILE_EXT`].
    #[must_use]
    pub fn tmp(&self) -> PathBuf {
        self.db_dir()
            .unwrap_or_else(|| self.dir_to_ublx_abs.clone())
            .join(format!(
                "{}_tmp{}",
                self.db_stem(),
                UBLX_NAMES.index_db_file_ext
            ))
    }

    /// WAL file for [`Self::tmp`] when snapshot build uses `journal_mode=WAL`.
    #[must_use]
    pub fn tmp_wal(&self) -> PathBuf {
        self.db_dir()
            .unwrap_or_else(|| self.dir_to_ublx_abs.clone())
            .join(format!(
                "{}_tmp{}-wal",
                self.db_stem(),
                UBLX_NAMES.index_db_file_ext
            ))
    }

    /// Shared-memory file for [`Self::tmp`] in WAL mode.
    #[must_use]
    pub fn tmp_shm(&self) -> PathBuf {
        self.db_dir()
            .unwrap_or_else(|| self.dir_to_ublx_abs.clone())
            .join(format!(
                "{}_tmp{}-shm",
                self.db_stem(),
                UBLX_NAMES.index_db_file_ext
            ))
    }

    /// `SQLite` WAL file for [`Self::db`] when WAL mode is on.
    #[must_use]
    pub fn wal(&self) -> PathBuf {
        self.db_dir()
            .unwrap_or_else(|| self.dir_to_ublx_abs.clone())
            .join(format!(
                "{}{}-wal",
                self.db_stem(),
                UBLX_NAMES.index_db_file_ext
            ))
    }

    /// `SQLite` shared-memory file for [`Self::db`] in WAL mode.
    #[must_use]
    pub fn shm(&self) -> PathBuf {
        self.db_dir()
            .unwrap_or_else(|| self.dir_to_ublx_abs.clone())
            .join(format!(
                "{}{}-shm",
                self.db_stem(),
                UBLX_NAMES.index_db_file_ext
            ))
    }

    /// Paths to exclude from indexing (nefax + local config). DB files under `ubli/` use [`INDEX_DB_FILE_EXT`] and are not listed here (nefax matches path components).
    /// Local `ublx.toml` / `.ublx.toml` are edited from the Settings tab, not listed as a snapshot category.
    /// [`UblxNames::zahir_export_dir_name`] (flat Zahir JSON export) and [`UblxNames::lens_export_dir_name`] (lens Markdown export) are excluded so re-indexing does not ingest them.
    #[must_use]
    pub fn exclude(&self) -> Vec<String> {
        vec![
            UBLX_NAMES.nefax_db.to_string(),
            UBLX_NAMES.local_config_visible_toml.to_string(),
            UBLX_NAMES.local_config_hidden_toml.to_string(),
            UBLX_NAMES.zahir_export_dir_name.to_string(),
            UBLX_NAMES.lens_export_dir_name.to_string(),
        ]
    }

    /// Remove tmp, WAL, and SHM files if they exist. No error if any are missing.
    /// Close the DB connection before calling if you use WAL mode.
    ///
    /// # Errors
    ///
    /// Returns [`anyhow::Error`] when removing an existing auxiliary file fails (e.g. I/O permission denied).
    pub fn remove_aux_files(&self) -> Result<(), anyhow::Error> {
        for p in [
            self.tmp(),
            self.tmp_wal(),
            self.tmp_shm(),
            self.wal(),
            self.shm(),
        ] {
            if p.exists() {
                fs::remove_file(&p)?;
            }
        }
        Ok(())
    }

    #[must_use]
    pub fn global_config(&self) -> Option<PathBuf> {
        global_config_toml()
    }

    /// User cache dir (`~/.local/share/ublx` or Windows equivalent). Used for last-applied config and future hot-reload fallback.
    #[allow(dead_code)]
    #[must_use]
    pub fn cache_dir(&self) -> Option<PathBuf> {
        cache_dir()
    }

    #[must_use]
    pub fn last_applied_config_path(&self) -> Option<PathBuf> {
        last_applied_config_path(&self.dir_to_ublx_abs)
    }
}

#[must_use]
pub fn get_log_path(dir_to_ublx: &Path) -> PathBuf {
    UblxPaths::new(dir_to_ublx).log_path()
}

#[must_use]
/// Normalize a path string for policy matching (e.g. `photos/vacation` → `photos/vacation`)
pub fn normalize_rel_path_for_policy(s: &str) -> String {
    let s = s.replace('\\', "/");
    let s = s.trim_start_matches("./");
    s.trim_end_matches('/').to_string()
}

/// True if `rel` (relative path) is under or equal to `prefix` (e.g. `photos/vacation` is under `photos`).
#[must_use]
pub fn path_is_under_or_equal(rel: &str, prefix: &str) -> bool {
    rel == prefix || (rel.starts_with(prefix) && rel.as_bytes().get(prefix.len()) == Some(&b'/'))
}