ggsql 0.4.0

A declarative visualization language that extends SQL with powerful data visualization capabilities.
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
//! Aesthetic classification and validation utilities
//!
//! This module provides centralized functions and constants for working with
//! aesthetic names in ggsql. Aesthetics are visual properties that can be mapped
//! to data columns or set to literal values.
//!
//! # Position vs Material Aesthetics
//!
//! Aesthetics fall into two categories:
//! - **Position**: Map to axes (x, y, and variants like xmin, xmax, etc.)
//! - **Material**: Map to visual properties shown in legends (color, size, shape, etc.)
//!
//! # Aesthetic Families
//!
//! Some aesthetics belong to "families" where variants map to a primary aesthetic.
//! For example, `xmin`, `xmax`, and `xend` all belong to the "x" family.
//! This is used for scale resolution and label computation.
//!
//! # Internal vs User-Facing Aesthetics
//!
//! The pipeline uses internal position aesthetic names (pos1, pos2, etc.) that are
//! transformed from user-facing names (x/y or angle/radius) early in the pipeline
//! and transformed back for output. This is handled by `AestheticContext`.

use std::collections::HashMap;

// =============================================================================
// Position Suffixes (applied to primary names automatically)
// =============================================================================

/// Position aesthetic suffixes - applied to primary names to create variant aesthetics
/// e.g., "x" + "min" = "xmin", "pos1" + "end" = "pos1end"
///
/// Note: "offset" is intentionally NOT included here because it's a positioning
/// adjustment that shouldn't influence scale training or be part of aesthetic families.
/// The `flip_position` method handles offset correctly via prefix detection.
pub const POSITION_SUFFIXES: &[&str] = &["min", "max", "end"];

// =============================================================================
// Static Constants (for backward compatibility with existing code)
// =============================================================================

/// User-facing facet aesthetics (for creating small multiples)
///
/// These aesthetics control faceting layout:
/// - `panel`: Single variable faceting (wrap layout)
/// - `row`: Row variable for grid faceting
/// - `column`: Column variable for grid faceting
///
/// After aesthetic transformation, these become internal names:
/// - `panel` → `facet1`
/// - `row` → `facet1`, `column` → `facet2`
pub const USER_FACET_AESTHETICS: &[&str] = &["panel", "row", "column"];

/// Material aesthetics (visual properties shown in legends or applied to marks)
///
/// These include:
/// - Color aesthetics: color, colour, fill, stroke, opacity
/// - Size/shape aesthetics: size, shape, linetype, linewidth
/// - Dimension aesthetics: width, height
/// - Text aesthetics: label, typeface, fontweight, italic, hjust, vjust
pub const MATERIAL_AESTHETICS: &[&str] = &[
    "color",
    "colour",
    "fill",
    "stroke",
    "opacity",
    "size",
    "shape",
    "linetype",
    "linewidth",
    "width",
    "height",
    "label",
    "typeface",
    "fontweight",
    "italic",
    "fontsize",
    "hjust",
    "vjust",
];

// =============================================================================
// AestheticContext - Comprehensive context for aesthetic operations
// =============================================================================

/// Comprehensive context for aesthetic operations.
///
/// Uses HashMaps for efficient O(1) lookups between user-facing and internal aesthetic names.
/// Used to transform between user-facing aesthetic names (x/y or angle/radius)
/// and internal names (pos1/pos2), as well as facet aesthetics (panel/row/column)
/// to internal facet names (facet1/facet2).
///
/// # Example
///
/// ```ignore
/// use ggsql::plot::AestheticContext;
///
/// // For cartesian coords
/// let ctx = AestheticContext::from_static(&["x", "y"], &[]);
/// assert_eq!(ctx.map_user_to_internal("x"), Some("pos1"));
/// assert_eq!(ctx.map_user_to_internal("ymin"), Some("pos2min"));
///
/// // For polar coords
/// let ctx = AestheticContext::from_static(&["angle", "radius"], &[]);
/// assert_eq!(ctx.map_user_to_internal("angle"), Some("pos1"));
/// assert_eq!(ctx.map_user_to_internal("radius"), Some("pos2"));
///
/// // With facets
/// let ctx = AestheticContext::from_static(&["x", "y"], &["panel"]);
/// assert_eq!(ctx.map_user_to_internal("panel"), Some("facet1"));
///
/// let ctx = AestheticContext::from_static(&["x", "y"], &["row", "column"]);
/// assert_eq!(ctx.map_user_to_internal("row"), Some("facet1"));
/// assert_eq!(ctx.map_user_to_internal("column"), Some("facet2"));
/// ```
#[derive(Debug, Clone)]
pub struct AestheticContext {
    // User → Internal mapping (O(1) lookups)
    user_to_internal: HashMap<String, String>,

    // Family lookups (internal names only)
    internal_to_primary: HashMap<String, String>,
    primary_to_internal_family: HashMap<String, Vec<String>>,

    // For iteration (ordered lists)
    user_primaries: Vec<String>,
    internal_primaries: Vec<String>,

    // Facet mappings
    user_facet: Vec<&'static str>,
    internal_facet: Vec<String>,

    // Material (static reference)
    material: &'static [&'static str],
}

impl AestheticContext {
    /// Create context from coord's position names and facet's aesthetic names.
    ///
    /// # Arguments
    ///
    /// * `position_names` - Primary position aesthetic names (e.g., ["x", "y"] or custom names)
    /// * `facet_names` - User-facing facet aesthetic names from facet layout
    ///   (e.g., ["panel"] for wrap, ["row", "column"] for grid)
    pub fn new(position_names: &[String], facet_names: &[&'static str]) -> Self {
        // Initialize all HashMaps and vectors
        let mut user_to_internal = HashMap::new();
        let mut internal_to_primary = HashMap::new();
        let mut primary_to_internal_family = HashMap::new();

        let mut user_primaries = Vec::new();
        let mut internal_primaries = Vec::new();

        // Build position mappings
        for (i, user_primary) in position_names.iter().enumerate() {
            let pos_num = i + 1;
            let internal_primary = format!("pos{}", pos_num);

            // Track primaries
            user_primaries.push(user_primary.clone());
            internal_primaries.push(internal_primary.clone());

            // Build internal family
            let mut internal_family = vec![internal_primary.clone()];

            // Add primary to mappings
            user_to_internal.insert(user_primary.clone(), internal_primary.clone());
            internal_to_primary.insert(internal_primary.clone(), internal_primary.clone());

            // Add suffixed variants
            for suffix in POSITION_SUFFIXES {
                let user_variant = format!("{}{}", user_primary, suffix);
                let internal_variant = format!("{}{}", internal_primary, suffix);

                user_to_internal.insert(user_variant, internal_variant.clone());
                internal_to_primary.insert(internal_variant.clone(), internal_primary.clone());
                internal_family.push(internal_variant);
            }

            // Store internal family
            primary_to_internal_family.insert(internal_primary, internal_family);
        }

        // Build internal facet names for active facets (from FACET clause or layer mappings)
        let internal_facet: Vec<String> = (1..=facet_names.len())
            .map(|i| format!("facet{}", i))
            .collect();

        Self {
            user_to_internal,
            internal_to_primary,
            primary_to_internal_family,
            user_primaries,
            internal_primaries,
            user_facet: facet_names.to_vec(),
            internal_facet,
            material: MATERIAL_AESTHETICS,
        }
    }

    /// Create context from static position names and facet names.
    ///
    /// Convenience method for creating context from static string slices (e.g., from coord defaults).
    pub fn from_static(position_names: &[&'static str], facet_names: &[&'static str]) -> Self {
        let owned_position: Vec<String> = position_names.iter().map(|s| s.to_string()).collect();
        Self::new(&owned_position, facet_names)
    }

    // === Mapping: User → Internal ===

    /// Map user aesthetic (position or facet) to internal name.
    ///
    /// Position: "x" → "pos1", "ymin" → "pos2min", "angle" → "pos1"
    /// Facet: "panel" → "facet1", "row" → "facet1", "column" → "facet2"
    ///
    /// Note: Facet mappings work regardless of whether a FACET clause exists,
    /// allowing layer-declared facet aesthetics to be transformed.
    pub fn map_user_to_internal(&self, user_aesthetic: &str) -> Option<&str> {
        // Check position first (O(1) HashMap lookup)
        if let Some(internal) = self.user_to_internal.get(user_aesthetic) {
            return Some(internal.as_str());
        }

        // Check active facet (from FACET clause)
        if let Some(idx) = self.user_facet.iter().position(|u| *u == user_aesthetic) {
            return Some(self.internal_facet[idx].as_str());
        }

        // Always map user-facing facet names to internal names,
        // even when no FACET clause exists (allows layer-declared facets)
        // panel → facet1 (wrap layout)
        // row → facet1, column → facet2 (grid layout)
        match user_aesthetic {
            "panel" => Some("facet1"),
            "row" => Some("facet1"),
            "column" => Some("facet2"),
            _ => None,
        }
    }

    /// Map internal aesthetic to user-facing name (reverse of map_user_to_internal).
    ///
    /// Position: "pos1" → "x", "pos2min" → "ymin", "pos1" → "angle" (for polar)
    /// Facet: "facet1" → "panel" (wrap), "facet1" → "row" (grid), "facet2" → "column" (grid)
    /// Material: "color" → "color" (unchanged)
    ///
    /// Returns None if the internal aesthetic is not recognized.
    pub fn map_internal_to_user(&self, internal_aesthetic: &str) -> String {
        // Check internal facet (facet1, facet2)
        if let Some(idx) = self
            .internal_facet
            .iter()
            .position(|i| i == internal_aesthetic)
        {
            return self.user_facet[idx].to_string();
        }

        // Check internal position (pos1, pos1min, pos2, etc.)
        // Iterate through user_to_internal to find reverse mapping
        for (user, internal) in &self.user_to_internal {
            if internal == internal_aesthetic {
                return user.to_string();
            }
        }

        // Material aesthetics (color, size, etc.)
        // Internal is the same as external
        internal_aesthetic.to_string()
    }

    // === Checking (O(1) HashMap lookups) ===

    /// Check if internal aesthetic is primary position (pos1, pos2, ...)
    pub fn is_primary_internal(&self, name: &str) -> bool {
        self.internal_primaries.iter().any(|s| s == name)
    }

    /// Check if aesthetic is material (color, size, etc.)
    pub fn is_material(&self, name: &str) -> bool {
        self.material.contains(&name)
    }

    /// Check if name is a user-facing facet aesthetic (panel, row, column)
    pub fn is_user_facet(&self, name: &str) -> bool {
        self.user_facet.contains(&name)
    }

    /// Check if name is an internal facet aesthetic (facet1, facet2)
    pub fn is_internal_facet(&self, name: &str) -> bool {
        self.internal_facet.iter().any(|f| f == name)
    }

    /// Check if name is a facet aesthetic (user or internal)
    pub fn is_facet(&self, name: &str) -> bool {
        self.is_user_facet(name) || self.is_internal_facet(name)
    }

    // === Aesthetic Families (O(1) HashMap lookups) ===

    /// Get the primary aesthetic for an internal family member.
    ///
    /// e.g., "pos1min" → "pos1", "pos2end" → "pos2"
    /// Material aesthetics return themselves.
    pub fn primary_internal_position<'a>(&'a self, name: &'a str) -> Option<&'a str> {
        // Check internal position (O(1) lookup)
        if let Some(primary) = self.internal_to_primary.get(name) {
            return Some(primary.as_str());
        }
        // Material aesthetics are their own primary
        if self.is_material(name) {
            return Some(name);
        }
        None
    }

    /// Get the internal aesthetic family for a primary aesthetic.
    ///
    /// e.g., "pos1" → ["pos1", "pos1min", "pos1max", "pos1end"]
    pub fn internal_position_family(&self, primary: &str) -> Option<&[String]> {
        self.primary_to_internal_family
            .get(primary)
            .map(|v| v.as_slice())
    }

    // === Accessors ===

    /// Get primary internal position aesthetics (pos1, pos2, ...)
    pub fn internal_position(&self) -> &[String] {
        &self.internal_primaries
    }

    /// Get user position aesthetics (x, y or angle, radius or custom names)
    pub fn user_position(&self) -> &[String] {
        &self.user_primaries
    }

    /// Get user-facing facet aesthetics (panel, row, column)
    pub fn user_facet(&self) -> &[&'static str] {
        &self.user_facet
    }

    // === Orientation Flipping ===

    /// Flip a position aesthetic to its opposite position.
    ///
    /// Swaps pos1 ↔ pos2 (and their suffixed variants like pos1min ↔ pos2min).
    /// Material aesthetics are returned unchanged.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let ctx = AestheticContext::from_static(&["x", "y"], &[]);
    /// assert_eq!(ctx.flip_position("pos1"), "pos2");
    /// assert_eq!(ctx.flip_position("pos2min"), "pos1min");
    /// assert_eq!(ctx.flip_position("pos1end"), "pos2end");
    /// assert_eq!(ctx.flip_position("color"), "color"); // unchanged
    /// ```
    pub fn flip_position(&self, name: &str) -> String {
        // Only flip if we have exactly 2 position aesthetics
        if self.internal_primaries.len() != 2 {
            return name.to_string();
        }

        // Check if it's a pos1 or pos2 variant
        if let Some(rest) = name.strip_prefix("pos1") {
            return format!("pos2{}", rest);
        }
        if let Some(rest) = name.strip_prefix("pos2") {
            return format!("pos1{}", rest);
        }

        // Not a position aesthetic, return unchanged
        name.to_string()
    }
}

/// Check if aesthetic is a user-facing facet aesthetic (panel, row, column)
///
/// Use this function for checks BEFORE aesthetic transformation.
/// For checks after transformation, use `is_facet_aesthetic`.
#[inline]
pub fn is_user_facet_aesthetic(aesthetic: &str) -> bool {
    USER_FACET_AESTHETICS.contains(&aesthetic)
}

/// Check if aesthetic is an internal facet aesthetic (facet1, facet2, etc.)
///
/// Facet aesthetics control the creation of small multiples (faceted plots).
/// They only support Discrete and Binned scale types, and cannot have output ranges (TO clause).
///
/// This function works with **internal** aesthetic names after transformation.
/// For user-facing checks before transformation, use `is_user_facet_aesthetic`.
#[inline]
pub fn is_facet_aesthetic(aesthetic: &str) -> bool {
    // Check pattern: facet followed by digits only (facet1, facet2, etc.)
    if aesthetic.starts_with("facet") && aesthetic.len() > 5 {
        return aesthetic[5..].chars().all(|c| c.is_ascii_digit());
    }
    false
}

/// Check if aesthetic is an internal position (pos1, pos1min, pos2max, etc.)
///
/// This function works with **internal** aesthetic names after transformation.
/// Matches patterns like: pos1, pos2, pos1min, pos2max, pos1end, etc.
///
/// For user-facing checks before transformation, use `AestheticContext::is_user_position()`.
#[inline]
pub fn is_position_aesthetic(name: &str) -> bool {
    if !name.starts_with("pos") || name.len() <= 3 {
        return false;
    }

    // Check for primary: pos followed by only digits (pos1, pos2, pos10, etc.)
    let after_pos = &name[3..];
    if after_pos.chars().all(|c| c.is_ascii_digit()) {
        return true;
    }

    // Check for variants: posN followed by a suffix
    for suffix in POSITION_SUFFIXES {
        if let Some(base) = name.strip_suffix(suffix) {
            if base.starts_with("pos") && base.len() > 3 {
                let num_part = &base[3..];
                if num_part.chars().all(|c| c.is_ascii_digit()) {
                    return true;
                }
            }
        }
    }

    false
}

/// Parse a position aesthetic name to extract its slot number and suffix.
///
/// Returns `Some((slot, suffix))` for position aesthetics:
/// - `pos1` → (1, "")
/// - `pos2min` → (2, "min")
/// - `pos1end` → (1, "end")
///
/// Returns `None` for material aesthetics.
pub fn parse_position(name: &str) -> Option<(u8, &str)> {
    if !name.starts_with("pos") {
        return None;
    }
    let rest = &name[3..];
    let slot_char = rest.chars().next()?;
    let slot = slot_char.to_digit(10)? as u8;
    let suffix = &rest[1..];
    Some((slot, suffix))
}

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

    #[test]
    fn test_facet_aesthetic() {
        // Internal facet aesthetics (after transformation)
        assert!(is_facet_aesthetic("facet1"));
        assert!(is_facet_aesthetic("facet2"));
        assert!(is_facet_aesthetic("facet10")); // supports any number
        assert!(!is_facet_aesthetic("facet")); // too short
        assert!(!is_facet_aesthetic("facetx")); // not a number

        // User-facing names are NOT internal facet aesthetics
        assert!(!is_facet_aesthetic("panel"));
        assert!(!is_facet_aesthetic("row"));
        assert!(!is_facet_aesthetic("column"));

        // Other aesthetics
        assert!(!is_facet_aesthetic("x"));
        assert!(!is_facet_aesthetic("color"));
        assert!(!is_facet_aesthetic("pos1"));
    }

    #[test]
    fn test_user_facet_aesthetic() {
        // User-facing facet aesthetics (before transformation)
        assert!(is_user_facet_aesthetic("panel"));
        assert!(is_user_facet_aesthetic("row"));
        assert!(is_user_facet_aesthetic("column"));

        // Internal names are NOT user-facing
        assert!(!is_user_facet_aesthetic("facet1"));
        assert!(!is_user_facet_aesthetic("facet2"));

        // Other aesthetics
        assert!(!is_user_facet_aesthetic("x"));
        assert!(!is_user_facet_aesthetic("color"));
    }

    #[test]
    fn test_position_aesthetic() {
        // Checks internal position names (pos1, pos2, etc. and variants)
        // For user-facing checks, use AestheticContext::is_user_position()

        // Primary internal
        assert!(is_position_aesthetic("pos1"));
        assert!(is_position_aesthetic("pos2"));
        assert!(is_position_aesthetic("pos10")); // supports any number

        // Variants
        assert!(is_position_aesthetic("pos1min"));
        assert!(is_position_aesthetic("pos1max"));
        assert!(is_position_aesthetic("pos2min"));
        assert!(is_position_aesthetic("pos2max"));
        assert!(is_position_aesthetic("pos1end"));
        assert!(is_position_aesthetic("pos2end"));

        // User-facing names are NOT position (handled by AestheticContext)
        assert!(!is_position_aesthetic("x"));
        assert!(!is_position_aesthetic("y"));
        assert!(!is_position_aesthetic("xmin"));
        assert!(!is_position_aesthetic("angle"));

        // Material
        assert!(!is_position_aesthetic("color"));
        assert!(!is_position_aesthetic("size"));
        assert!(!is_position_aesthetic("fill"));

        // Edge cases
        assert!(!is_position_aesthetic("pos")); // too short
        assert!(!is_position_aesthetic("position")); // not a valid pattern
    }

    // ========================================================================
    // AestheticContext Tests
    // ========================================================================

    #[test]
    fn test_aesthetic_context_cartesian() {
        let ctx = AestheticContext::from_static(&["x", "y"], &[]);

        // User position names
        assert_eq!(ctx.user_position(), &["x", "y"]);

        // Primary internal names
        let primary: Vec<&str> = ctx.internal_position().iter().map(|s| s.as_str()).collect();
        assert_eq!(primary, vec!["pos1", "pos2"]);
    }

    #[test]
    fn test_aesthetic_context_polar() {
        let ctx = AestheticContext::from_static(&["angle", "radius"], &[]);

        // User position names
        assert_eq!(ctx.user_position(), &["angle", "radius"]);

        // Primary internal names
        let primary: Vec<&str> = ctx.internal_position().iter().map(|s| s.as_str()).collect();
        assert_eq!(primary, vec!["pos1", "pos2"]);
    }

    #[test]
    fn test_aesthetic_context_user_to_internal() {
        let ctx = AestheticContext::from_static(&["x", "y"], &[]);

        // Primary aesthetics
        assert_eq!(ctx.map_user_to_internal("x"), Some("pos1"));
        assert_eq!(ctx.map_user_to_internal("y"), Some("pos2"));

        // Variants
        assert_eq!(ctx.map_user_to_internal("xmin"), Some("pos1min"));
        assert_eq!(ctx.map_user_to_internal("xmax"), Some("pos1max"));
        assert_eq!(ctx.map_user_to_internal("xend"), Some("pos1end"));
        assert_eq!(ctx.map_user_to_internal("ymin"), Some("pos2min"));
        assert_eq!(ctx.map_user_to_internal("ymax"), Some("pos2max"));
        assert_eq!(ctx.map_user_to_internal("yend"), Some("pos2end"));

        // Material returns None
        assert_eq!(ctx.map_user_to_internal("color"), None);
        assert_eq!(ctx.map_user_to_internal("fill"), None);
    }

    #[test]
    fn test_aesthetic_context_polar_mapping() {
        let ctx = AestheticContext::from_static(&["angle", "radius"], &[]);

        // User to internal
        assert_eq!(ctx.map_user_to_internal("angle"), Some("pos1"));
        assert_eq!(ctx.map_user_to_internal("radius"), Some("pos2"));
        assert_eq!(ctx.map_user_to_internal("angleend"), Some("pos1end"));
        assert_eq!(ctx.map_user_to_internal("radiusmin"), Some("pos2min"));
    }

    #[test]
    fn test_aesthetic_context_is_primary_internal() {
        let ctx = AestheticContext::from_static(&["x", "y"], &[]);

        // Primary internal
        assert!(ctx.is_primary_internal("pos1"));
        assert!(ctx.is_primary_internal("pos2"));
        assert!(!ctx.is_primary_internal("pos1min"));
        assert!(!ctx.is_primary_internal("x"));
        assert!(!ctx.is_primary_internal("color"));
    }

    #[test]
    fn test_aesthetic_context_with_facets() {
        let ctx = AestheticContext::from_static(&["x", "y"], &["panel"]);

        // Check user facet
        assert!(ctx.is_user_facet("panel"));
        assert!(!ctx.is_user_facet("row"));
        assert_eq!(ctx.user_facet(), &["panel"]);

        // Check internal facet
        assert!(ctx.is_internal_facet("facet1"));
        assert!(!ctx.is_internal_facet("panel"));

        // Check mapping
        assert_eq!(ctx.map_user_to_internal("panel"), Some("facet1"));

        // Check combined is_facet
        assert!(ctx.is_facet("panel")); // user
        assert!(ctx.is_facet("facet1")); // internal
    }

    #[test]
    fn test_aesthetic_context_with_grid_facets() {
        let ctx = AestheticContext::from_static(&["x", "y"], &["row", "column"]);

        // Check user facet
        assert!(ctx.is_user_facet("row"));
        assert!(ctx.is_user_facet("column"));
        assert!(!ctx.is_user_facet("panel"));
        assert_eq!(ctx.user_facet(), &["row", "column"]);

        // Check internal facet
        assert!(ctx.is_internal_facet("facet1"));
        assert!(ctx.is_internal_facet("facet2"));

        // Check mappings
        assert_eq!(ctx.map_user_to_internal("row"), Some("facet1"));
        assert_eq!(ctx.map_user_to_internal("column"), Some("facet2"));
    }

    #[test]
    fn test_aesthetic_context_families() {
        let ctx = AestheticContext::from_static(&["x", "y"], &[]);

        // Get internal family (offset not included - it's a positioning adjustment)
        let pos1_family = ctx.internal_position_family("pos1").unwrap();
        let pos1_strs: Vec<&str> = pos1_family.iter().map(|s| s.as_str()).collect();
        assert_eq!(pos1_strs, vec!["pos1", "pos1min", "pos1max", "pos1end"]);

        // Primary internal aesthetic
        assert_eq!(ctx.primary_internal_position("pos1"), Some("pos1"));
        assert_eq!(ctx.primary_internal_position("pos1min"), Some("pos1"));
        assert_eq!(ctx.primary_internal_position("pos2end"), Some("pos2"));
        assert_eq!(ctx.primary_internal_position("color"), Some("color"));
    }

    #[test]
    fn test_aesthetic_context_internal_to_user_cartesian() {
        let ctx = AestheticContext::from_static(&["x", "y"], &[]);

        // Primary aesthetics
        assert_eq!(ctx.map_internal_to_user("pos1"), "x");
        assert_eq!(ctx.map_internal_to_user("pos2"), "y");

        // Variants
        assert_eq!(ctx.map_internal_to_user("pos1min"), "xmin");
        assert_eq!(ctx.map_internal_to_user("pos1max"), "xmax");
        assert_eq!(ctx.map_internal_to_user("pos1end"), "xend");
        assert_eq!(ctx.map_internal_to_user("pos2min"), "ymin");
        assert_eq!(ctx.map_internal_to_user("pos2max"), "ymax");
        assert_eq!(ctx.map_internal_to_user("pos2end"), "yend");

        // Material aesthetics remain unchanged
        assert_eq!(ctx.map_internal_to_user("color"), "color");
        assert_eq!(ctx.map_internal_to_user("size"), "size");
        assert_eq!(ctx.map_internal_to_user("fill"), "fill");
    }

    #[test]
    fn test_aesthetic_context_internal_to_user_polar() {
        let ctx = AestheticContext::from_static(&["angle", "radius"], &[]);

        // Primary aesthetics map to polar names
        assert_eq!(ctx.map_internal_to_user("pos1"), "angle");
        assert_eq!(ctx.map_internal_to_user("pos2"), "radius");

        // Variants
        assert_eq!(ctx.map_internal_to_user("pos1end"), "angleend");
        assert_eq!(ctx.map_internal_to_user("pos2min"), "radiusmin");
        assert_eq!(ctx.map_internal_to_user("pos2max"), "radiusmax");
    }

    #[test]
    fn test_aesthetic_context_internal_to_user_facets() {
        // Wrap facet (panel)
        let ctx_wrap = AestheticContext::from_static(&["x", "y"], &["panel"]);
        assert_eq!(ctx_wrap.map_internal_to_user("facet1"), "panel");

        // Grid facet (row, column)
        let ctx_grid = AestheticContext::from_static(&["x", "y"], &["row", "column"]);
        assert_eq!(ctx_grid.map_internal_to_user("facet1"), "row");
        assert_eq!(ctx_grid.map_internal_to_user("facet2"), "column");
    }

    #[test]
    fn test_aesthetic_context_roundtrip() {
        // Test that user -> internal -> user roundtrips correctly
        let ctx = AestheticContext::from_static(&["x", "y"], &["panel"]);

        // Position
        let internal = ctx.map_user_to_internal("x").unwrap();
        assert_eq!(ctx.map_internal_to_user(internal), "x");

        let internal = ctx.map_user_to_internal("ymin").unwrap();
        assert_eq!(ctx.map_internal_to_user(internal), "ymin");

        // Facet
        let internal = ctx.map_user_to_internal("panel").unwrap();
        assert_eq!(ctx.map_internal_to_user(internal), "panel");
    }
    #[test]
    fn test_parse_position() {
        // Primary position
        assert_eq!(parse_position("pos1"), Some((1, "")));
        assert_eq!(parse_position("pos2"), Some((2, "")));

        // Variants with suffixes
        assert_eq!(parse_position("pos1min"), Some((1, "min")));
        assert_eq!(parse_position("pos2max"), Some((2, "max")));
        assert_eq!(parse_position("pos1end"), Some((1, "end")));

        // Material
        assert_eq!(parse_position("color"), None);
        assert_eq!(parse_position("x"), None);
        assert_eq!(parse_position("xmin"), None);
    }
}