makeover 0.10.0

Shared theme loading for the make-family apps: TOML theme files parsed into intent-based color tokens, with perceptual derivations and WCAG contrast.
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
//! Shared theme loading + intent resolution for TOML-based theme files.
//!
//! Used by GoingsOn, Balanced Breakfast (Tauri apps), audiofiles (egui), and the
//! MNW web server. Themes are authored by **intent** ("human design"): colors are
//! declared by role (surface / content / action / status / line / category), not
//! by hue. This crate is the single place that resolves an authored theme into a
//! full set of intent tokens — including the derived interactive states
//! (hover/active/selection/row-stripe/contrast) that each app used to recompute
//! itself — and emits them as CSS variables or RGB tuples.
//!
//! Theme file shape:
//! ```text
//! [meta]
//! name = "Nord"
//! variant = "dark"          # or "light"
//!
//! [surface]                 # container backgrounds by role/elevation
//! page = "#2e3440"; raised = "#3b4252"; sunken = "#434c5e"; overlay = "#3b4252"
//!
//! [content]                 # text/ink by emphasis
//! primary = "#d8dee9"; secondary = "#e5e9f0"; muted = "#616e88"
//!
//! [action]                  # interactive / brand color
//! primary = "#81a1c1"
//!
//! [status]                  # state semantics
//! danger = "#bf616a"; success = "#a3be8c"; warning = "#ebcb8b"; info = "#88c0d0"
//!
//! [line]
//! border = "#4c566a"
//!
//! [category]                # distinct decorative colors for tags/badges/charts
//! one = "#bf616a"; two = "#a3be8c"; three = "#81a1c1"
//! four = "#ebcb8b"; five = "#b48ead"; six = "#88c0d0"
//! ```

use serde::Serialize;
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};

/// The color sections an authored theme may declare.
pub const COLOR_SECTIONS: &[&str] = &["surface", "content", "action", "status", "line", "category"];

/// Theme metadata parsed from the `[meta]` section.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThemeMeta {
    pub id: String,
    pub name: String,
    pub variant: String,
    pub is_custom: bool,
}

/// A loaded theme: metadata plus the authored colors, flattened to dotted keys
/// (e.g. `"surface.page"`, `"status.danger"`, `"category.one"`).
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThemeColors {
    pub meta: ThemeMeta,
    pub colors: HashMap<String, String>,
}

// ============================================================================
// Color math — perceptual (OKLab) derivations + WCAG contrast.
//
// Interactive states (hover/active/selection/surfaces) are derived in OKLab so
// equal steps look equal across every theme's hues (Ottosson 2020; the modern
// CIELAB). Text-on-color is picked by the WCAG 2.x contrast ratio, not a naive
// luminance threshold, so the choice actually meets AA where achievable.
// This is the single source of truth shared by every product.
// ============================================================================

/// An sRGB color. Hex round-trips losslessly.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Rgb {
    pub r: u8,
    pub g: u8,
    pub b: u8,
}

impl Rgb {
    /// Parse `#rgb` or `#rrggbb` (case-insensitive). Returns `None` otherwise.
    pub fn from_hex(s: &str) -> Option<Rgb> {
        let h = s.strip_prefix('#')?;
        let (r, g, b) = match h.len() {
            6 => (
                u8::from_str_radix(&h[0..2], 16).ok()?,
                u8::from_str_radix(&h[2..4], 16).ok()?,
                u8::from_str_radix(&h[4..6], 16).ok()?,
            ),
            3 => {
                let d = |c: &str| u8::from_str_radix(c, 16).ok().map(|v| v * 17);
                (d(&h[0..1])?, d(&h[1..2])?, d(&h[2..3])?)
            }
            _ => return None,
        };
        Some(Rgb { r, g, b })
    }

    /// Lowercase `#rrggbb`.
    pub fn to_hex(self) -> String {
        format!("#{:02x}{:02x}{:02x}", self.r, self.g, self.b)
    }

    pub fn tuple(self) -> (u8, u8, u8) {
        (self.r, self.g, self.b)
    }
}

/// A color in OKLab (perceptually uniform): `l` lightness in [0,1], `a`/`b` opponent axes.
#[derive(Clone, Copy, Debug)]
pub struct Oklab {
    pub l: f32,
    pub a: f32,
    pub b: f32,
}

fn srgb_to_linear(c: u8) -> f32 {
    let c = c as f32 / 255.0;
    if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
}

fn linear_to_srgb(c: f32) -> u8 {
    let c = c.clamp(0.0, 1.0);
    let v = if c <= 0.0031308 { c * 12.92 } else { 1.055 * c.powf(1.0 / 2.4) - 0.055 };
    (v * 255.0).round().clamp(0.0, 255.0) as u8
}

impl Rgb {
    /// Convert to OKLab (Ottosson's sRGB matrices).
    pub fn to_oklab(self) -> Oklab {
        let (r, g, b) = (srgb_to_linear(self.r), srgb_to_linear(self.g), srgb_to_linear(self.b));
        let l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b;
        let m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b;
        let s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b;
        let (l_, m_, s_) = (l.cbrt(), m.cbrt(), s.cbrt());
        Oklab {
            l: 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_,
            a: 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_,
            b: 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_,
        }
    }

    /// Convert from OKLab back to the nearest in-gamut sRGB.
    pub fn from_oklab(c: Oklab) -> Rgb {
        let l_ = c.l + 0.3963377774 * c.a + 0.2158037573 * c.b;
        let m_ = c.l - 0.1055613458 * c.a - 0.0638541728 * c.b;
        let s_ = c.l - 0.0894841775 * c.a - 1.2914855480 * c.b;
        let (l, m, s) = (l_ * l_ * l_, m_ * m_ * m_, s_ * s_ * s_);
        Rgb {
            r: linear_to_srgb(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s),
            g: linear_to_srgb(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),
            b: linear_to_srgb(-0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s),
        }
    }
}

/// WCAG 2.x relative luminance of an sRGB color.
fn rel_luminance(c: Rgb) -> f32 {
    0.2126 * srgb_to_linear(c.r) + 0.7152 * srgb_to_linear(c.g) + 0.0722 * srgb_to_linear(c.b)
}

/// WCAG 2.x contrast ratio between two colors, in [1, 21].
pub fn wcag_contrast(a: Rgb, b: Rgb) -> f32 {
    let (la, lb) = (rel_luminance(a), rel_luminance(b));
    let (hi, lo) = if la >= lb { (la, lb) } else { (lb, la) };
    (hi + 0.05) / (lo + 0.05)
}

/// Pick black or white for legible text on `bg`, by the higher WCAG contrast
/// ratio (so the choice meets AA wherever the background allows it).
pub fn readable_on(bg: Rgb) -> Rgb {
    let white = Rgb { r: 255, g: 255, b: 255 };
    let black = Rgb { r: 0, g: 0, b: 0 };
    if wcag_contrast(white, bg) >= wcag_contrast(black, bg) { white } else { black }
}

/// Shift OKLab lightness by `delta` (perceptually uniform). Positive lightens.
pub fn lighten(c: Rgb, delta: f32) -> Rgb {
    let mut lab = c.to_oklab();
    lab.l = (lab.l + delta).clamp(0.0, 1.0);
    Rgb::from_oklab(lab)
}

/// Shift OKLab lightness down by `delta` (perceptually uniform).
pub fn darken(c: Rgb, delta: f32) -> Rgb {
    lighten(c, -delta)
}

/// Interpolate between `a` and `b` by `t` in [0,1] in OKLab (perceptual blend).
pub fn mix(a: Rgb, b: Rgb, t: f32) -> Rgb {
    let (x, y) = (a.to_oklab(), b.to_oklab());
    Rgb::from_oklab(Oklab {
        l: x.l + (y.l - x.l) * t,
        a: x.a + (y.a - x.a) * t,
        b: x.b + (y.b - x.b) * t,
    })
}

// ============================================================================
// Intent resolution
// ============================================================================

/// Authored base intents: (TOML dotted source key, canonical token key).
/// These are read straight from the theme; the token key is the CSS-var stem
/// (`--{token}`) and the `rgb()` lookup key.
pub const BASE_INTENTS: &[(&str, &str)] = &[
    ("surface.page", "surface-page"),
    ("surface.raised", "surface-raised"),
    ("surface.sunken", "surface-sunken"),
    ("surface.overlay", "surface-overlay"),
    ("content.primary", "content"),
    ("content.secondary", "content-secondary"),
    ("content.muted", "content-muted"),
    ("action.primary", "action"),
    ("status.danger", "danger"),
    ("status.success", "success"),
    ("status.warning", "warning"),
    ("status.info", "info"),
    ("line.border", "border"),
    ("category.one", "category-one"),
    ("category.two", "category-two"),
    ("category.three", "category-three"),
    ("category.four", "category-four"),
    ("category.five", "category-five"),
    ("category.six", "category-six"),
];

/// A fully resolved intent layer: every token key → concrete `#rrggbb`.
/// Includes both authored base intents and the computed derived intents.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SemanticTokens {
    pub meta: ThemeMeta,
    /// token-key → resolved hex. Stable, deterministic ordering.
    pub intents: BTreeMap<String, String>,
}

impl SemanticTokens {
    /// Resolved hex for a token key, if present.
    pub fn hex(&self, key: &str) -> Option<&str> {
        self.intents.get(key).map(String::as_str)
    }

    /// Resolved RGB tuple for a token key (for egui / native consumers).
    pub fn rgb(&self, key: &str) -> Option<(u8, u8, u8)> {
        self.intents.get(key).and_then(|h| Rgb::from_hex(h)).map(Rgb::tuple)
    }
}

/// Resolve an authored theme into the full intent token set.
///
/// 1. Copy each present base intent from the authored colors.
/// 2. Compute the derived interactive states from the base intents, using the
///    same math the apps used to apply individually (so output is identical).
/// Each derived token is emitted only when its source intents exist, mirroring
/// the skip-missing behavior of the rest of the crate.
pub fn resolve(theme: &ThemeColors) -> SemanticTokens {
    let mut intents: BTreeMap<String, String> = BTreeMap::new();

    // 1. Base intents (authored). Copy only values that parse as a hex color and
    // re-emit them in canonical `#rrggbb` form, so an authored value can never
    // carry arbitrary bytes into the emitted CSS (the resolved tokens are inlined
    // raw into a `<style>` block by the web server). A malformed value is skipped,
    // mirroring the skip-missing behavior for absent intents.
    for (src, token) in BASE_INTENTS {
        if let Some(rgb) = theme.colors.get(*src).and_then(|v| Rgb::from_hex(v)) {
            intents.insert((*token).to_string(), rgb.to_hex());
        }
    }

    // Helper: parse an already-resolved token to Rgb.
    let get = |m: &BTreeMap<String, String>, k: &str| m.get(k).and_then(|h| Rgb::from_hex(h));

    // 2. Derived intents — perceptual (OKLab) steps + WCAG-picked text.
    // Lightness deltas are in OKLab L units; mix ratios interpolate in OKLab.
    let mut derived: Vec<(String, Rgb)> = Vec::new();
    if let Some(action) = get(&intents, "action") {
        derived.push(("action-hover".into(), lighten(action, 0.05)));
        derived.push(("content-on-action".into(), readable_on(action)));
        derived.push(("focus-ring".into(), action));
    }
    if let Some(page) = get(&intents, "surface-page") {
        // Modal scrim: a near-black tone carrying a faint hint of the theme's
        // hue, at 50% alpha. Anchored very dark (OKLab L=0.08) so it dims the
        // page on light *and* dark themes. Emitted as rgba (not a flat hex), so
        // it is inserted directly rather than through the hex loop below.
        let mut o = page.to_oklab();
        o.l = 0.08;
        let s = Rgb::from_oklab(o);
        intents.insert("overlay".into(), format!("rgba({}, {}, {}, 0.5)", s.r, s.g, s.b));
    }
    if let Some(sunken) = get(&intents, "surface-sunken") {
        derived.push(("hover-surface".into(), sunken));
    }
    if let Some(border) = get(&intents, "border") {
        derived.push(("border-strong".into(), darken(border, 0.05)));
    }

    for (token, rgb) in derived {
        intents.insert(token, rgb.to_hex());
    }

    SemanticTokens { meta: theme.meta.clone(), intents }
}

/// Emit the resolved intent layer as CSS declarations (no selector), one
/// `  --token: #hex;` line each, in deterministic (BTreeMap) order.
pub fn intent_css_declarations(tokens: &SemanticTokens) -> String {
    let mut out = String::new();
    for (token, hex) in &tokens.intents {
        out.push_str("  --");
        out.push_str(token);
        out.push_str(": ");
        out.push_str(hex);
        out.push_str(";\n");
    }
    out
}

/// Emit the resolved intent layer as a `:root { … }` block — the single TOML →
/// CSS mapping every web surface injects.
pub fn intent_css_vars(tokens: &SemanticTokens) -> String {
    format!(":root {{\n{}}}\n", intent_css_declarations(tokens))
}

// ============================================================================
// Loading / parsing
// ============================================================================

/// Validate a theme ID contains only safe characters (alphanumeric, hyphens, underscores).
pub fn validate_theme_id(id: &str) -> Result<(), String> {
    if !id
        .chars()
        .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
    {
        return Err(format!("Invalid theme ID: {}", id));
    }
    Ok(())
}

/// Parse the `[meta]` section into `ThemeMeta`.
///
/// Falls back to the file ID as the name and `"dark"` as the variant.
pub fn parse_meta(id: &str, table: &toml::Table, is_custom: bool) -> ThemeMeta {
    let meta = table.get("meta").and_then(|m| m.as_table());
    let name = meta
        .and_then(|m| m.get("name"))
        .and_then(|v| v.as_str())
        .unwrap_or(id)
        .to_string();
    let variant = meta
        .and_then(|m| m.get("variant"))
        .and_then(|v| v.as_str())
        .unwrap_or("dark")
        .to_string();

    ThemeMeta { id: id.to_string(), name, variant, is_custom }
}

/// Extract the intent color sections into a flat `HashMap` with dotted keys
/// like `"surface.page"`, `"status.danger"`, `"category.one"`.
pub fn extract_colors(table: &toml::Table) -> HashMap<String, String> {
    let mut colors = HashMap::new();
    for section in COLOR_SECTIONS {
        if let Some(sect) = table.get(*section).and_then(|s| s.as_table()) {
            for (key, val) in sect {
                if let Some(color) = val.as_str() {
                    colors.insert(format!("{}.{}", section, key), color.to_string());
                }
            }
        }
    }
    colors
}

/// Scan directories for `.toml` theme files and return metadata for each.
///
/// Directories are checked in order; later entries override earlier ones by ID.
/// Each entry in `dirs` is `(path, is_custom)`.
pub fn list_themes_from_dirs(dirs: &[(PathBuf, bool)]) -> Vec<ThemeMeta> {
    let mut seen: HashMap<String, ThemeMeta> = HashMap::new();

    for (dir, is_custom) in dirs {
        let entries = match std::fs::read_dir(dir) {
            Ok(e) => e,
            Err(_) => continue,
        };

        for entry in entries {
            let entry = match entry {
                Ok(e) => e,
                Err(_) => continue,
            };
            let path = entry.path();
            if path.extension().and_then(|e| e.to_str()) != Some("toml") {
                continue;
            }

            let id = path
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or_default()
                .to_string();

            let content = match std::fs::read_to_string(&path) {
                Ok(c) => c,
                Err(_) => continue,
            };
            let table: toml::Table = match content.parse() {
                Ok(t) => t,
                Err(_) => continue,
            };

            seen.insert(id.clone(), parse_meta(&id, &table, *is_custom));
        }
    }

    let mut themes: Vec<ThemeMeta> = seen.into_values().collect();
    themes.sort_by(|a, b| a.name.cmp(&b.name));
    themes
}

/// Find a theme file by ID in the given directories.
///
/// Checks directories in reverse order so the highest-priority directory wins.
/// Returns `(path, is_custom)` or `None` if not found.
pub fn find_theme_path(dirs: &[(PathBuf, bool)], id: &str) -> Option<(PathBuf, bool)> {
    let filename = format!("{}.toml", id);

    for (dir, is_custom) in dirs.iter().rev() {
        let path = dir.join(&filename);
        if path.is_file() {
            return Some((path, *is_custom));
        }
    }

    None
}

/// Parse a complete theme (metadata + colors) from raw TOML content, with no
/// filesystem access. For callers that embed themes at compile time.
pub fn parse_theme_str(id: &str, content: &str, is_custom: bool) -> Result<ThemeColors, String> {
    validate_theme_id(id)?;
    let table: toml::Table = content
        .parse()
        .map_err(|e| format!("Failed to parse theme '{}': {}", id, e))?;
    let meta = parse_meta(id, &table, is_custom);
    let colors = extract_colors(&table);
    Ok(ThemeColors { meta, colors })
}

/// Load a complete theme (metadata + colors) by ID from the given directories.
pub fn load_theme(dirs: &[(PathBuf, bool)], id: &str) -> Result<ThemeColors, String> {
    validate_theme_id(id)?;

    let (path, is_custom) =
        find_theme_path(dirs, id).ok_or_else(|| format!("Theme '{}' not found", id))?;

    let content = std::fs::read_to_string(&path)
        .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;

    let table: toml::Table = content
        .parse()
        .map_err(|e| format!("Failed to parse {}: {}", path.display(), e))?;

    let meta = parse_meta(id, &table, is_custom);
    let colors = extract_colors(&table);

    Ok(ThemeColors { meta, colors })
}

/// Load a theme and resolve it to the full intent token set in one step.
pub fn load_semantic(dirs: &[(PathBuf, bool)], id: &str) -> Result<SemanticTokens, String> {
    Ok(resolve(&load_theme(dirs, id)?))
}

/// Import a theme TOML file into the custom themes directory.
///
/// Validates that the file is parseable TOML with at least one intent color
/// section, then copies it to `custom_dir/{id}.toml`. Returns the theme metadata.
pub fn import_theme(source_path: &Path, custom_dir: &Path) -> Result<ThemeMeta, String> {
    let content = std::fs::read_to_string(source_path)
        .map_err(|e| format!("Failed to read {}: {}", source_path.display(), e))?;

    let table: toml::Table = content
        .parse()
        .map_err(|e| format!("Invalid TOML: {}", e))?;

    let has_colors = COLOR_SECTIONS
        .iter()
        .any(|s| table.get(*s).and_then(|v| v.as_table()).is_some());
    if !has_colors {
        return Err(format!(
            "Theme file must have at least one color section ({})",
            COLOR_SECTIONS.join(", ")
        ));
    }

    let id = source_path
        .file_stem()
        .and_then(|s| s.to_str())
        .ok_or("Invalid file name")?
        .to_string();
    validate_theme_id(&id)?;

    std::fs::create_dir_all(custom_dir)
        .map_err(|e| format!("Failed to create {}: {}", custom_dir.display(), e))?;

    let dest = custom_dir.join(format!("{}.toml", id));
    std::fs::copy(source_path, &dest)
        .map_err(|e| format!("Failed to copy theme: {}", e))?;

    Ok(parse_meta(&id, &table, true))
}

/// Delete a custom theme by ID.
///
/// Only operates on `custom_dir` — bundled themes are not deletable through
/// this entry point.
pub fn delete_theme(custom_dir: &Path, id: &str) -> Result<(), String> {
    validate_theme_id(id)?;

    let path = custom_dir.join(format!("{}.toml", id));
    if !path.is_file() {
        return Err(format!("Custom theme '{}' not found", id));
    }

    std::fs::remove_file(&path)
        .map_err(|e| format!("Failed to delete {}: {}", path.display(), e))
}

/// A four-color preview for theme thumbnails: the representative swatch from
/// each of the principal roles.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThemePreview {
    pub meta: ThemeMeta,
    /// Page background (`surface.page`).
    pub background: Option<String>,
    /// Body text (`content.primary`).
    pub foreground: Option<String>,
    /// Brand/interactive color (`action.primary`).
    pub accent: Option<String>,
    /// Divider/outline color (`line.border`).
    pub border: Option<String>,
}

fn color_at(table: &toml::Table, section: &str, key: &str) -> Option<String> {
    table
        .get(section)
        .and_then(|s| s.as_table())
        .and_then(|s| s.get(key))
        .and_then(|v| v.as_str())
        .map(|s| s.to_string())
}

/// Load just the preview swatches for a theme — for UI thumbnails.
pub fn load_theme_preview(dirs: &[(PathBuf, bool)], id: &str) -> Result<ThemePreview, String> {
    validate_theme_id(id)?;

    let (path, is_custom) =
        find_theme_path(dirs, id).ok_or_else(|| format!("Theme '{}' not found", id))?;

    let content = std::fs::read_to_string(&path)
        .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;

    let table: toml::Table = content
        .parse()
        .map_err(|e| format!("Failed to parse {}: {}", path.display(), e))?;

    Ok(ThemePreview {
        meta: parse_meta(id, &table, is_custom),
        background: color_at(&table, "surface", "page"),
        foreground: color_at(&table, "content", "primary"),
        accent: color_at(&table, "action", "primary"),
        border: color_at(&table, "line", "border"),
    })
}

/// Export a theme to a user-chosen path.
pub fn export_theme(dirs: &[(PathBuf, bool)], id: &str, dest_path: &Path) -> Result<(), String> {
    validate_theme_id(id)?;

    let (source, _) =
        find_theme_path(dirs, id).ok_or_else(|| format!("Theme '{}' not found", id))?;

    std::fs::copy(&source, dest_path)
        .map_err(|e| format!("Failed to export theme: {}", e))?;

    Ok(())
}

/// The themes this crate ships, embedded at compile time.
///
/// `include_dir` is an implementation detail: the public API hands back plain
/// `(id, toml_source)` pairs, so how the data is embedded can change without
/// a breaking release.
static EMBEDDED: include_dir::Dir<'static> =
    include_dir::include_dir!("$CARGO_MANIFEST_DIR/themes");

/// The themes this crate ships, as `(id, toml_source)` pairs.
///
/// This is the path-free way to reach the bundled set, for consumers that
/// cannot rely on a directory existing at runtime: a crate pulled from
/// crates.io lives in a registry checkout whose location is not knowable at
/// compile time, so `include_dir!` and asset-bundling globs in the depending
/// crate have nothing stable to point at. Embedding here and re-exporting the
/// contents gives them one source of truth without a path.
///
/// Ordering follows the embedded directory and is not guaranteed; collect and
/// sort by id where a stable order matters (a theme picker, say).
pub fn embedded_themes() -> impl Iterator<Item = (&'static str, &'static str)> {
    EMBEDDED.files().filter_map(|file| {
        let path = file.path();
        if path.extension().and_then(|e| e.to_str()) != Some("toml") {
            return None;
        }
        let id = path.file_stem()?.to_str()?;
        Some((id, file.contents_utf8()?))
    })
}

/// The theme directory this crate ships, for use as a build-from-source
/// fallback.
///
/// Resolves against `makeover`'s own manifest directory, fixed at compile
/// time, so it works from a path dependency and from a cargo git checkout
/// alike. Installed systems should put their packaged theme directory ahead
/// of this in the search path; this is the entry that keeps `cargo run` in a
/// fresh clone from coming up with no themes at all.
///
/// Returns `None` when the directory is absent — a cargo cache that has been
/// cleaned, or a vendored copy that dropped the data — so callers degrade to
/// their remaining search path rather than failing.
pub fn bundled_themes_dir() -> Option<PathBuf> {
    let themes = Path::new(env!("CARGO_MANIFEST_DIR")).join("themes");
    if themes.is_dir() { Some(themes) } else { None }
}

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

    // ---- id validation ----

    #[test]
    fn validate_theme_id_alphanumeric() {
        assert!(validate_theme_id("darkmode").is_ok());
        assert!(validate_theme_id("Theme123").is_ok());
    }

    #[test]
    fn validate_theme_id_hyphens_underscores() {
        assert!(validate_theme_id("dark-mode").is_ok());
        assert!(validate_theme_id("my_theme_v2").is_ok());
    }

    #[test]
    fn validate_theme_id_rejects_path_traversal() {
        assert!(validate_theme_id("../etc/passwd").is_err());
        assert!(validate_theme_id("foo/bar").is_err());
        assert!(validate_theme_id("theme.toml").is_err());
    }

    // ---- meta ----

    #[test]
    fn parse_meta_with_name_and_variant() {
        let table: toml::Table = "[meta]\nname = \"Nord\"\nvariant = \"light\"\n".parse().unwrap();
        let meta = parse_meta("nord", &table, false);
        assert_eq!(meta.id, "nord");
        assert_eq!(meta.name, "Nord");
        assert_eq!(meta.variant, "light");
        assert!(!meta.is_custom);
    }

    #[test]
    fn parse_meta_defaults_to_id_and_dark() {
        let table: toml::Table = "".parse().unwrap();
        let meta = parse_meta("fallback", &table, true);
        assert_eq!(meta.name, "fallback");
        assert_eq!(meta.variant, "dark");
        assert!(meta.is_custom);
    }

    // ---- color math (formulas must match the apps they came from) ----

    #[test]
    fn rgb_hex_roundtrip() {
        assert_eq!(Rgb::from_hex("#6196FF").unwrap(), Rgb { r: 0x61, g: 0x96, b: 0xff });
        assert_eq!(Rgb::from_hex("#abc").unwrap(), Rgb { r: 0xaa, g: 0xbb, b: 0xcc });
        assert_eq!(Rgb { r: 0x61, g: 0x96, b: 0xff }.to_hex(), "#6196ff");
        assert!(Rgb::from_hex("not-a-color").is_none());
    }

    #[test]
    fn oklab_roundtrips_within_tolerance() {
        for hex in ["#6196ff", "#2e3440", "#ffffff", "#000000", "#c0392b"] {
            let c = Rgb::from_hex(hex).unwrap();
            let back = Rgb::from_oklab(c.to_oklab());
            // Gamut round-trip is near-exact (±1 per channel from rounding).
            assert!((c.r as i16 - back.r as i16).abs() <= 1, "{hex} r");
            assert!((c.g as i16 - back.g as i16).abs() <= 1, "{hex} g");
            assert!((c.b as i16 - back.b as i16).abs() <= 1, "{hex} b");
        }
    }

    #[test]
    fn wcag_contrast_known_pairs() {
        let white = Rgb { r: 255, g: 255, b: 255 };
        let black = Rgb { r: 0, g: 0, b: 0 };
        assert!((wcag_contrast(white, black) - 21.0).abs() < 0.01);
        assert!((wcag_contrast(white, white) - 1.0).abs() < 0.01);
    }

    #[test]
    fn readable_on_picks_by_wcag() {
        assert_eq!(readable_on(Rgb { r: 255, g: 255, b: 255 }), Rgb { r: 0, g: 0, b: 0 });
        assert_eq!(readable_on(Rgb { r: 0, g: 0, b: 0 }), Rgb { r: 255, g: 255, b: 255 });
        // A light blue action -> black text reads better.
        let action = Rgb::from_hex("#6196ff").unwrap();
        assert_eq!(readable_on(action), Rgb { r: 0, g: 0, b: 0 });
    }

    #[test]
    fn lighten_darken_move_oklab_lightness() {
        let c = Rgb::from_hex("#6196ff").unwrap();
        let l0 = c.to_oklab().l;
        assert!(lighten(c, 0.05).to_oklab().l > l0);
        assert!(darken(c, 0.05).to_oklab().l < l0);
    }

    #[test]
    fn mix_endpoints_and_midpoint() {
        let a = Rgb::from_hex("#000000").unwrap();
        let b = Rgb::from_hex("#6196ff").unwrap();
        assert_eq!(mix(a, b, 0.0), a);
        assert_eq!(mix(a, b, 1.0), b);
        // Midpoint sits between the endpoints in OKLab lightness.
        let mid = mix(a, b, 0.5).to_oklab().l;
        assert!(mid > a.to_oklab().l && mid < b.to_oklab().l);
    }

    // ---- extract + resolve ----

    fn nord_toml() -> &'static str {
        r##"
[meta]
name = "Nord"
variant = "dark"

[surface]
page = "#2e3440"
raised = "#3b4252"
sunken = "#434c5e"
overlay = "#3b4252"

[content]
primary = "#d8dee9"
secondary = "#e5e9f0"
muted = "#616e88"

[action]
primary = "#81a1c1"

[status]
danger = "#bf616a"
success = "#a3be8c"
warning = "#ebcb8b"
info = "#88c0d0"

[line]
border = "#4c566a"

[category]
one = "#bf616a"
two = "#a3be8c"
three = "#81a1c1"
four = "#ebcb8b"
five = "#b48ead"
six = "#88c0d0"
"##
    }

    #[test]
    fn extract_colors_reads_intent_sections() {
        let table: toml::Table = nord_toml().parse().unwrap();
        let colors = extract_colors(&table);
        assert_eq!(colors.get("surface.page").unwrap(), "#2e3440");
        assert_eq!(colors.get("content.primary").unwrap(), "#d8dee9");
        assert_eq!(colors.get("action.primary").unwrap(), "#81a1c1");
        assert_eq!(colors.get("status.danger").unwrap(), "#bf616a");
        assert_eq!(colors.get("line.border").unwrap(), "#4c566a");
        assert_eq!(colors.get("category.five").unwrap(), "#b48ead");
        assert_eq!(colors.len(), 19);
    }

    #[test]
    fn resolve_base_intents_passthrough() {
        let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
        let t = resolve(&theme);
        assert_eq!(t.hex("surface-page"), Some("#2e3440"));
        assert_eq!(t.hex("content"), Some("#d8dee9")); // content.primary -> content
        assert_eq!(t.hex("content-muted"), Some("#616e88"));
        assert_eq!(t.hex("action"), Some("#81a1c1"));
        assert_eq!(t.hex("danger"), Some("#bf616a"));
        assert_eq!(t.hex("border"), Some("#4c566a"));
        assert_eq!(t.hex("category-five"), Some("#b48ead"));
    }

    #[test]
    fn resolve_derived_intents() {
        let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
        let t = resolve(&theme);
        let action = Rgb::from_hex("#81a1c1").unwrap();
        let page = Rgb::from_hex("#2e3440").unwrap();
        let _ = page;
        assert_eq!(t.hex("action-hover").unwrap(), lighten(action, 0.05).to_hex());
        assert_eq!(t.hex("content-on-action").unwrap(), readable_on(action).to_hex());
        assert_eq!(t.hex("focus-ring"), Some("#81a1c1"));
        assert_eq!(t.hex("hover-surface"), Some("#434c5e")); // = surface.sunken
        // Pruned by the usage audit (0 consumers): action-active, the *-surface
        // tints, selection, row-stripe. Apps that need them derive inline via
        // the shared mix().
        assert!(t.hex("action-active").is_none());
        assert!(t.hex("danger-surface").is_none());
        assert!(t.hex("selection").is_none());
        assert!(t.hex("row-stripe").is_none());
    }

    #[test]
    fn resolve_overlay_is_dark_translucent_scrim() {
        let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
        let t = resolve(&theme);
        let overlay = t.hex("overlay").unwrap();
        assert!(overlay.starts_with("rgba("), "overlay is translucent: {overlay}");
        assert!(overlay.ends_with(", 0.5)"));
        // The scrim tone is anchored very dark regardless of theme.
        let inner = overlay.trim_start_matches("rgba(").trim_end_matches(", 0.5)");
        let parts: Vec<u8> = inner.split(", ").map(|p| p.parse().unwrap()).collect();
        let scrim = Rgb { r: parts[0], g: parts[1], b: parts[2] };
        assert!(scrim.to_oklab().l < 0.2, "scrim must be near-black");
    }

    #[test]
    fn resolve_drops_non_hex_base_intent() {
        // A base intent that isn't a hex color must never reach the resolved
        // token set (it would otherwise be inlined verbatim into a <style>
        // block). Skipped like a missing intent; valid siblings survive.
        let theme = parse_theme_str(
            "x",
            "[surface]\npage = \"</style><script>alert(1)</script>\"\n[content]\nprimary = \"#111111\"\n",
            false,
        )
        .unwrap();
        let t = resolve(&theme);
        assert!(t.hex("surface-page").is_none(), "non-hex base intent leaked");
        assert_eq!(t.hex("content").unwrap(), "#111111");
        // The injected markup appears in no resolved value.
        assert!(!t.intents.values().any(|v| v.contains('<')));
    }

    #[test]
    fn resolve_skips_derived_when_source_missing() {
        // No [action] => no action-derived tokens.
        let theme = parse_theme_str(
            "x",
            "[surface]\npage = \"#000000\"\n[line]\nborder = \"#222222\"\n",
            false,
        )
        .unwrap();
        let t = resolve(&theme);
        assert!(t.hex("action").is_none());
        assert!(t.hex("action-hover").is_none());
        assert!(t.hex("selection").is_none());
        assert_eq!(t.hex("border-strong").unwrap(), darken(Rgb::from_hex("#222222").unwrap(), 0.05).to_hex());
    }

    #[test]
    fn rgb_accessor_for_native_consumers() {
        let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
        let t = resolve(&theme);
        assert_eq!(t.rgb("action"), Some((0x81, 0xa1, 0xc1)));
        assert_eq!(t.rgb("nonexistent"), None);
    }

    // ---- css emit ----

    #[test]
    fn intent_css_vars_wraps_root_and_includes_tokens() {
        let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
        let css = intent_css_vars(&resolve(&theme));
        assert!(css.starts_with(":root {\n"));
        assert!(css.contains("  --surface-page: #2e3440;\n"));
        assert!(css.contains("  --danger: #bf616a;\n"));
        assert!(css.contains("  --action-hover: "));
        assert!(css.trim_end().ends_with('}'));
    }

    // ---- loading / fs ----

    #[test]
    fn load_and_resolve_round_trip() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("nord.toml"), nord_toml()).unwrap();
        let dirs = vec![(dir.path().to_path_buf(), false)];
        let t = load_semantic(&dirs, "nord").unwrap();
        assert_eq!(t.meta.name, "Nord");
        assert_eq!(t.hex("action"), Some("#81a1c1"));
    }

    #[test]
    fn load_theme_rejects_invalid_id() {
        assert!(load_theme(&[], "../evil").is_err());
    }

    #[test]
    fn list_themes_from_dirs_finds_toml_files() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("t.toml"), "[meta]\nname = \"T\"\n").unwrap();
        fs::write(dir.path().join("x.txt"), "ignored").unwrap();
        let dirs = vec![(dir.path().to_path_buf(), false)];
        let themes = list_themes_from_dirs(&dirs);
        assert_eq!(themes.len(), 1);
        assert_eq!(themes[0].id, "t");
    }

    #[test]
    fn find_theme_path_reverse_priority() {
        let d1 = tempfile::tempdir().unwrap();
        let d2 = tempfile::tempdir().unwrap();
        fs::write(d1.path().join("s.toml"), "[meta]\n").unwrap();
        fs::write(d2.path().join("s.toml"), "[meta]\n").unwrap();
        let dirs = vec![(d1.path().to_path_buf(), false), (d2.path().to_path_buf(), true)];
        let (path, is_custom) = find_theme_path(&dirs, "s").unwrap();
        assert!(is_custom);
        assert_eq!(path, d2.path().join("s.toml"));
    }

    #[test]
    fn import_theme_valid_and_rejects_empty() {
        let src_dir = tempfile::tempdir().unwrap();
        let custom_dir = tempfile::tempdir().unwrap();

        let good = src_dir.path().join("my-theme.toml");
        fs::write(&good, "[surface]\npage = \"#1a1b26\"\n").unwrap();
        let meta = import_theme(&good, custom_dir.path()).unwrap();
        assert_eq!(meta.id, "my-theme");
        assert!(custom_dir.path().join("my-theme.toml").exists());

        let empty = src_dir.path().join("empty.toml");
        fs::write(&empty, "[meta]\nname = \"E\"\n").unwrap();
        assert!(import_theme(&empty, custom_dir.path()).is_err());
    }

    #[test]
    fn import_theme_rejects_invalid_toml() {
        let src_dir = tempfile::tempdir().unwrap();
        let custom_dir = tempfile::tempdir().unwrap();
        let src = src_dir.path().join("bad.toml");
        fs::write(&src, "this is not [valid toml [[[").unwrap();
        assert!(import_theme(&src, custom_dir.path()).is_err());
    }

    #[test]
    fn delete_theme_removes_and_guards() {
        let custom = tempfile::tempdir().unwrap();
        let path = custom.path().join("doomed.toml");
        fs::write(&path, "[surface]\npage = \"#000\"\n").unwrap();
        delete_theme(custom.path(), "doomed").unwrap();
        assert!(!path.exists());
        assert!(delete_theme(custom.path(), "../etc/passwd").is_err());
        assert!(delete_theme(custom.path(), "ghost").is_err());
    }

    #[test]
    fn export_theme_copies_file() {
        let src_dir = tempfile::tempdir().unwrap();
        let dest_dir = tempfile::tempdir().unwrap();
        let content = "[meta]\nname = \"E\"\n[surface]\npage = \"#ffffff\"\n";
        fs::write(src_dir.path().join("e.toml"), content).unwrap();
        let dirs = vec![(src_dir.path().to_path_buf(), false)];
        let dest = dest_dir.path().join("out.toml");
        export_theme(&dirs, "e", &dest).unwrap();
        assert_eq!(fs::read_to_string(&dest).unwrap(), content);
        assert!(export_theme(&dirs, "missing", &dest).is_err());
    }

    #[test]
    fn load_theme_preview_returns_role_swatches() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("nord.toml"), nord_toml()).unwrap();
        let dirs = vec![(dir.path().to_path_buf(), false)];
        let p = load_theme_preview(&dirs, "nord").unwrap();
        assert_eq!(p.background.as_deref(), Some("#2e3440")); // surface.page
        assert_eq!(p.foreground.as_deref(), Some("#d8dee9")); // content.primary
        assert_eq!(p.accent.as_deref(), Some("#81a1c1")); // action.primary
        assert_eq!(p.border.as_deref(), Some("#4c566a")); // line.border
    }

    #[test]
    fn bundled_themes_dir_resolves_to_shipped_themes() {
        // The crate ships its themes, so this must resolve in-tree and the
        // Akari defaults the console falls back to must be present.
        let dir = bundled_themes_dir().expect("makeover ships a themes/ directory");
        assert!(dir.join("akari-dawn.toml").is_file());
        assert!(dir.join("akari-night.toml").is_file());
    }

    #[test]
    fn every_theme_is_accounted_for_in_third_party_notices() {
        // Attribution is a redistribution obligation, not a nicety: adding a
        // theme without a notice entry silently ships someone's work
        // uncredited. Fail here instead.
        let notices = std::fs::read_to_string(
            Path::new(env!("CARGO_MANIFEST_DIR")).join("THIRD-PARTY-NOTICES.md"),
        )
        .expect("THIRD-PARTY-NOTICES.md must exist");
        let missing: Vec<&str> = embedded_themes()
            .map(|(id, _)| id)
            .filter(|id| !notices.contains(*id))
            .collect();
        assert!(
            missing.is_empty(),
            "themes missing from THIRD-PARTY-NOTICES.md: {missing:?}"
        );
    }

    #[test]
    fn adapted_themes_carry_inline_attribution() {
        // Each adapted file must name its upstream in-file, so the credit
        // survives someone copying a single .toml out of the crate.
        const ORIGINALS: [&str; 5] =
                ["makenotwork", "goingson", "audiofiles", "high-contrast", "neobrute"];
        for (id, source) in embedded_themes() {
            if ORIGINALS.contains(&id) {
                continue;
            }
            assert!(
                source.contains("adapted from"),
                "adapted theme `{id}` is missing its inline attribution header"
            );
        }
    }

    #[test]
    fn embedded_themes_match_the_directory() {
        // The embedded copy and themes/ are two views of one source. If they
        // ever disagree, path-based and path-free consumers render different
        // theme sets, which is exactly the drift shipping the data was meant
        // to prevent.
        let dir = bundled_themes_dir().unwrap();
        let mut on_disk: Vec<String> = std::fs::read_dir(&dir)
            .unwrap()
            .filter_map(|e| {
                let path = e.ok()?.path();
                if path.extension()? != "toml" {
                    return None;
                }
                Some(path.file_stem()?.to_str()?.to_string())
            })
            .collect();
        let mut embedded: Vec<String> =
            embedded_themes().map(|(id, _)| id.to_string()).collect();
        on_disk.sort();
        embedded.sort();
        assert_eq!(embedded, on_disk, "embedded theme set drifted from themes/");
    }

    #[test]
    fn every_embedded_theme_parses() {
        // Guards the path-free consumers (MNW server, the Tauri build steps)
        // the same way every_shipped_theme_loads guards the path-based ones.
        let mut count = 0;
        for (id, source) in embedded_themes() {
            parse_theme_str(id, source, false)
                .unwrap_or_else(|e| panic!("embedded theme `{id}` failed to parse: {e}"));
            count += 1;
        }
        assert!(count >= 30, "expected the full theme set, got {count}");
    }

    #[test]
    fn every_shipped_theme_loads() {
        // Guards the data, not just the loader: a malformed or truncated
        // .toml in themes/ is a shipping bug, and it should fail here rather
        // than at a user's first launch.
        let dir = bundled_themes_dir().unwrap();
        let dirs = vec![(dir.clone(), false)];
        let themes = list_themes_from_dirs(&dirs);
        assert!(themes.len() >= 30, "expected the full theme set, got {}", themes.len());
        for meta in &themes {
            load_theme(&dirs, &meta.id)
                .unwrap_or_else(|e| panic!("shipped theme `{}` failed to load: {e}", meta.id));
        }
    }
}