fonts 0.2.0

High-performance font parsing and analysis library for Grida Canvas
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
//! Font Selection Module
//!
//! This module provides font selection functionality, including face classification,
//! family aggregation, and selection logic. It's designed to work with the Blink
//! (Chrome) font selection model.

use std::collections::HashMap;
use ttf_parser::{Face, Style};

/// Represents the classification result for a single font face.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum FontStyle {
    /// Normal/upright face
    Normal,
    /// Italic face (true italic, not oblique)
    Italic,
}

/// Recipe for variable font axis values to achieve specific styling.
#[derive(Debug, Clone, PartialEq)]
pub struct VfRecipe {
    /// Axis values to apply (e.g., {"ital": 1.0})
    pub axis_values: HashMap<String, f32>,
}

impl VfRecipe {
    /// Creates a new recipe with a single axis value.
    pub fn new(axis_tag: &str, value: f32) -> Self {
        let mut axis_values = HashMap::new();
        axis_values.insert(axis_tag.to_string(), value);
        Self { axis_values }
    }

    /// Creates an empty recipe (for static fonts).
    pub fn empty() -> Self {
        Self {
            axis_values: HashMap::new(),
        }
    }
}

/// Classification result for a single font face.
#[derive(Debug, Clone)]
pub struct FaceClassification {
    /// Whether this face is italic or normal
    pub font_style: FontStyle,
    /// Variable font recipe to achieve italic (if applicable)
    pub vf_recipe: Option<VfRecipe>,
    /// Weight key for family aggregation
    pub weight_key: u16,
    /// Stretch key for family aggregation  
    pub stretch_key: u16,
    /// Whether this is a variable font
    pub is_variable: bool,
    /// Instance information for Scenario 3-1 fonts (slnt axis with italic instances)
    pub instance_info: Option<InstanceInfo>,
}

impl FaceClassification {
    /// Legacy compatibility getter for italic_kind field.
    /// This provides backward compatibility with existing code.
    pub fn italic_kind(&self) -> FontStyle {
        self.font_style
    }
}

/// Information about italic instances found in a variable font (Scenario 3-1).
#[derive(Debug, Clone)]
pub struct InstanceInfo {
    /// List of italic instance names found in the name table
    pub italic_instances: Vec<String>,
    /// PostScript name of the font
    pub ps_name: String,
    /// Style name of the font
    pub style_name: String,
}

/// Configuration for the font selection parser.
/// Level 1: Always trusts user font style declarations (non-configurable).
#[derive(Debug, Clone)]
pub struct ParserConfig {
    /// Whether to trust user font style declarations (Level 1: always true)
    pub trust_user_font_style: bool,
}

impl Default for ParserConfig {
    fn default() -> Self {
        Self {
            trust_user_font_style: true,
        }
    }
}

impl ParserConfig {
    /// Creates a Level 1 configuration (always trusts user declarations).
    pub fn level1() -> Self {
        Self {
            trust_user_font_style: true,
        }
    }
}

/// Input record for a font face to be classified.
#[derive(Debug, Clone)]
pub struct FaceRecord {
    /// Stable identifier for the font file
    pub face_id: String,
    /// PostScript name (NameID 6)
    pub ps_name: String,
    /// Legacy family name (NameID 1)
    pub family_name: String,
    /// Typographic family name (NameID 16), if present
    pub typographic_family: Option<String>,
    /// Legacy subfamily name (NameID 2)
    pub subfamily_name: String,
    /// Typographic subfamily name (NameID 17), if present
    pub typographic_subfamily: Option<String>,
    /// Whether this is a variable font
    pub is_variable: bool,
    /// Variable font axes with their ranges
    pub axes: HashMap<String, (f32, f32, f32)>, // (min, default, max)
    /// OS/2 fsSelection bit 0 (ITALIC)
    pub os2_italic_bit: bool,
    /// OS/2 usWeightClass
    pub weight_class: u16,
    /// OS/2 usWidthClass
    pub width_class: u16,
    /// Optional explicit user declaration that this face is italic.
    ///
    /// When `Some(true)`, the face is treated as italic regardless of axes/variants.
    /// When `Some(false)` or `None`, automatic detection is performed.
    ///
    /// This is semantically clearer than an enum because users should only set this
    /// to `true` when they're confident the face is italic. If unsure, they should
    /// leave it as `None` to let the system detect it automatically.
    pub user_font_style_italic: Option<bool>,
}

/// A face with its classification result and recipe information.
#[derive(Debug, Clone)]
pub struct ClassifiedFace {
    /// The original face record
    pub face: FaceRecord,
    /// The classification result
    pub classification: FaceClassification,
}

/// Represents a face or variable font with recipe for font selection.
#[derive(Debug, Clone)]
pub struct FaceOrVfWithRecipe {
    /// Face identifier
    pub face_id: String,
    /// Variable font recipe (if applicable)
    pub vf_recipe: Option<VfRecipe>,
    /// Instance information for Scenario 3-1 fonts (slnt axis with italic instances)
    pub instance_info: Option<InstanceInfo>,
}

/// Font selection capability map for a font family.
#[derive(Debug, Clone)]
pub struct FontSelectionCapabilityMap {
    /// Upright faces organized by (weight, stretch) keys
    pub upright_slots: HashMap<(u16, u16), FaceOrVfWithRecipe>,
    /// Italic faces organized by (weight, stretch) keys
    pub italic_slots: HashMap<(u16, u16), FaceOrVfWithRecipe>,
    /// Scenario type for diagnostics
    pub scenario: FamilyScenario,
}

/// Family scenario type for diagnostics and selection policy.
#[derive(Debug, Clone, PartialEq)]
pub enum FamilyScenario {
    /// Single static font only
    SingleStatic,
    /// Multiple static fonts with at least one italic
    MultiStatic,
    /// Single variable font providing upright and italic
    SingleVf,
    /// Two variable fonts: Roman VF and Italic VF
    DualVf,
}

/// Font selection result for a specific style request.
#[derive(Debug, Clone)]
pub enum FontSelection {
    /// Selected face with optional variable font recipe
    Selected {
        face_id: String,
        vf_recipe: Option<VfRecipe>,
        instance_info: Option<InstanceInfo>,
    },
    /// No suitable face found
    Unavailable,
}

impl FontSelection {
    /// Creates a font selection from a face and recipe.
    pub fn from_face(face: &FaceOrVfWithRecipe) -> Self {
        Self::Selected {
            face_id: face.face_id.clone(),
            vf_recipe: face.vf_recipe.clone(),
            instance_info: face.instance_info.clone(),
        }
    }

    /// Creates a font selection from a face record.
    pub fn from_face_record(face: &FaceRecord, recipe: Option<VfRecipe>) -> Self {
        Self::Selected {
            face_id: face.face_id.clone(),
            vf_recipe: recipe,
            instance_info: None,
        }
    }
}

/// Level 1 font selection parser.
pub struct FontSelectionParser {
    pub config: ParserConfig,
}

impl FontSelectionParser {
    /// Creates a new Level 1 parser (always trusts user declarations).
    pub fn new() -> Self {
        Self {
            config: ParserConfig::level1(),
        }
    }

    /// Creates a new parser with custom configuration (Level 2+ feature).
    /// Note: Level 1 should always use the default configuration.
    pub fn with_config(config: ParserConfig) -> Self {
        Self { config }
    }

    /// Classifies a single font face according to Level 1 rules.
    pub fn classify_face(&self, face_record: FaceRecord) -> ClassifiedFace {
        let classification = self.classify_face_internal(&face_record);
        ClassifiedFace {
            face: face_record,
            classification,
        }
    }

    /// Builds a font selection capability map for a collection of faces belonging to the same family.
    pub fn build_capability_map(&self, faces: Vec<FaceRecord>) -> FontSelectionCapabilityMap {
        if faces.is_empty() {
            return FontSelectionCapabilityMap {
                upright_slots: HashMap::new(),
                italic_slots: HashMap::new(),
                scenario: FamilyScenario::SingleStatic,
            };
        }

        // Classify all faces
        let classified_faces: Vec<ClassifiedFace> = faces
            .into_iter()
            .map(|face| self.classify_face(face))
            .collect();

        // Determine scenario
        let scenario = self.determine_scenario(&classified_faces);

        // Aggregate into slots
        let mut upright_slots = HashMap::new();
        let mut italic_slots = HashMap::new();

        for classified_face in classified_faces {
            let key = (
                classified_face.classification.weight_key,
                classified_face.classification.stretch_key,
            );

            let face_or_vf = FaceOrVfWithRecipe {
                face_id: classified_face.face.face_id,
                vf_recipe: classified_face.classification.vf_recipe,
                instance_info: classified_face.classification.instance_info,
            };

            match classified_face.classification.font_style {
                FontStyle::Normal => {
                    upright_slots.insert(key, face_or_vf);
                }
                FontStyle::Italic => {
                    italic_slots.insert(key, face_or_vf);
                }
            }
        }

        FontSelectionCapabilityMap {
            upright_slots,
            italic_slots,
            scenario,
        }
    }

    /// Selects a font face based on weight, stretch, and style requirements.
    pub fn select_face(
        &self,
        capability_map: &FontSelectionCapabilityMap,
        weight: u16,
        stretch: u16,
        style: FontStyle,
    ) -> FontSelection {
        match style {
            FontStyle::Italic => {
                // Look for exact match first
                if let Some(face) = capability_map.italic_slots.get(&(weight, stretch)) {
                    return FontSelection::from_face(face);
                }

                // Look for nearest match
                if let Some(face) = self.find_nearest_italic(capability_map, weight, stretch) {
                    return FontSelection::from_face(face);
                }

                // Try to synthesize from variable font
                if let Some(face) = self.synthesize_italic_from_vf(capability_map, weight, stretch) {
                    return FontSelection::from_face(&face);
                }

                FontSelection::Unavailable
            }
            FontStyle::Normal => {
                // Look for exact match first
                if let Some(face) = capability_map.upright_slots.get(&(weight, stretch)) {
                    return FontSelection::from_face(face);
                }

                // Look for nearest match
                if let Some(face) = self.find_nearest_upright(capability_map, weight, stretch) {
                    return FontSelection::from_face(face);
                }

                FontSelection::Unavailable
            }
        }
    }

    /// Internal classification logic following Level 1 priority rules.
    fn classify_face_internal(&self, face: &FaceRecord) -> FaceClassification {
        // Priority 0: User font style declaration (highest priority)
        if self.config.trust_user_font_style {
            if let Some(user_italic) = face.user_font_style_italic {
                if user_italic {
                    return FaceClassification {
                        font_style: FontStyle::Italic,
                        vf_recipe: None,
                        weight_key: face.weight_class,
                        stretch_key: face.width_class,
                        is_variable: face.is_variable,
                        instance_info: None,
                    };
                }
                // If user_italic is false, continue with automatic detection
            }
        }

        // Priority 1: OS/2 ITALIC bit (bit 0)
        if face.os2_italic_bit {
            return FaceClassification {
                font_style: FontStyle::Italic,
                vf_recipe: None,
                weight_key: face.weight_class,
                stretch_key: face.width_class,
                is_variable: face.is_variable,
                instance_info: None,
            };
        }

        // Priority 2: Variable font `ital` axis
        if let Some((min, default, max)) = face.axes.get("ital") {
            // Check if default location has ital=1
            if (*default - 1.0).abs() < f32::EPSILON {
                return FaceClassification {
                    font_style: FontStyle::Italic,
                    vf_recipe: Some(VfRecipe::new("ital", 1.0)),
                    weight_key: face.weight_class,
                    stretch_key: face.width_class,
                    is_variable: face.is_variable,
                    instance_info: None,
                };
            }
            // Check if any value in the range could be 1.0
            if *min <= 1.0 && *max >= 1.0 {
                return FaceClassification {
                    font_style: FontStyle::Italic,
                    vf_recipe: Some(VfRecipe::new("ital", 1.0)),
                    weight_key: face.weight_class,
                    stretch_key: face.width_class,
                    is_variable: face.is_variable,
                    instance_info: None,
                };
            }
        }

        // Priority 3: VF with `slnt` axis (Scenario 3-1)
        if let Some((_min, default, _max)) = face.axes.get("slnt") {
            // Scenario 3-1 REQUIRES both slnt axis AND italic-named instances
            if self.has_italic_named_instances(face) {
                // Use the default slnt value or a reasonable italic angle
                let slnt_value = if (*default).abs() > 0.1 {
                    *default
                } else {
                    -10.0
                };

                // Extract instance information for Scenario 3-1 fonts
                let italic_instances = self.extract_italic_instances(face);
                let instance_info = if !italic_instances.is_empty() {
                    Some(InstanceInfo {
                        italic_instances,
                        ps_name: face.ps_name.clone(),
                        style_name: face.subfamily_name.clone(),
                    })
                } else {
                    // For Level 1, even if no italic names found in main entries,
                    // we still provide instance info for slnt-capable fonts
                    Some(InstanceInfo {
                        italic_instances: vec!["slnt-axis-capable".to_string()],
                        ps_name: face.ps_name.clone(),
                        style_name: face.subfamily_name.clone(),
                    })
                };

                return FaceClassification {
                    font_style: FontStyle::Italic,
                    vf_recipe: Some(VfRecipe::new("slnt", slnt_value)),
                    weight_key: face.weight_class,
                    stretch_key: face.width_class,
                    is_variable: face.is_variable,
                    instance_info,
                };
            }
        }

        // Priority 4: Level 1 permissive slnt detection (NOT Scenario 3-1)
        if let Some((_min, default, _max)) = face.axes.get("slnt") {
            // Level 1 permissive detection: any font with slnt axis is italic-capable
            // This is separate from Scenario 3-1 which requires italic-named instances
            let slnt_value = if (*default).abs() > 0.1 {
                *default
            } else {
                -10.0
            };

            return FaceClassification {
                font_style: FontStyle::Italic,
                vf_recipe: Some(VfRecipe::new("slnt", slnt_value)),
                weight_key: face.weight_class,
                stretch_key: face.width_class,
                is_variable: face.is_variable,
                instance_info: Some(InstanceInfo {
                    italic_instances: vec!["slnt-axis-capable".to_string()],
                    ps_name: face.ps_name.clone(),
                    style_name: face.subfamily_name.clone(),
                }),
            };
        }

        // Priority 5: Name-based fallback (with warnings)
        if self.is_italic_by_name(face) {
            // Log warning for name-based detection
            eprintln!(
                "WARNING: Using name-based italic detection for face: {}",
                face.face_id
            );
            return FaceClassification {
                font_style: FontStyle::Italic,
                vf_recipe: None,
                weight_key: face.weight_class,
                stretch_key: face.width_class,
                is_variable: face.is_variable,
                instance_info: None,
            };
        }

        // Default: Normal
        FaceClassification {
            font_style: FontStyle::Normal,
            vf_recipe: None,
            weight_key: face.weight_class,
            stretch_key: face.width_class,
            is_variable: face.is_variable,
            instance_info: None,
        }
    }

    /// Checks if a face has italic-named instances via name table analysis (Scenario 3-1).
    pub fn has_italic_named_instances(&self, face: &FaceRecord) -> bool {
        // For Scenario 3-1, we MUST have italic-named instances in the name table
        // This is strict - we only check the main name table entries
        self.extract_italic_instances(face).len() > 0
    }

    /// Extracts italic instances from the name table for Scenario 3-1 fonts.
    /// Takes instances as input and returns italic instance names found.
    /// IMPORTANT: Only "italic" (case-insensitive) is considered valid, NOT "oblique".
    pub fn extract_italic_instances(&self, face: &FaceRecord) -> Vec<String> {
        let mut italic_instances = Vec::new();

        // Check the subfamily name first (most common case)
        let subfamily_lower = face.subfamily_name.to_lowercase();
        if subfamily_lower.contains("italic") {
            italic_instances.push(face.subfamily_name.clone());
        }

        // Check the PostScript name
        let ps_name_lower = face.ps_name.to_lowercase();
        if ps_name_lower.contains("italic") {
            italic_instances.push(face.ps_name.clone());
        }

        // For Level 1, we focus on the main name table entries
        // In Level 2+, we would parse all name table entries for comprehensive italic detection

        italic_instances
    }

    /// Checks if a face is italic based on name analysis (Priority 5 fallback).
    /// IMPORTANT: Only "italic" (case-insensitive) is considered valid, NOT "oblique".
    pub fn is_italic_by_name(&self, face: &FaceRecord) -> bool {
        let subfamily_lower = face.subfamily_name.to_lowercase();
        let ps_name_lower = face.ps_name.to_lowercase();

        // Check for italic indicators in names (only "italic", not "oblique")
        subfamily_lower.contains("italic") || ps_name_lower.contains("italic")
    }

    /// Determines the family scenario for diagnostics.
    fn determine_scenario(&self, faces: &[ClassifiedFace]) -> FamilyScenario {
        if faces.len() == 1 {
            if faces[0].classification.is_variable {
                FamilyScenario::SingleVf
            } else {
                FamilyScenario::SingleStatic
            }
        } else {
            let has_italic = faces
                .iter()
                .any(|f| f.classification.font_style == FontStyle::Italic);
            let has_variable = faces.iter().any(|f| f.classification.is_variable);

            if has_variable && has_italic {
                FamilyScenario::DualVf
            } else {
                FamilyScenario::MultiStatic
            }
        }
    }

    /// Finds the nearest italic face to the requested weight and stretch.
    fn find_nearest_italic<'a>(
        &self,
        capability_map: &'a FontSelectionCapabilityMap,
        weight: u16,
        stretch: u16,
    ) -> Option<&'a FaceOrVfWithRecipe> {
        // Simple nearest neighbor search
        let mut best_face = None;
        let mut best_distance = f32::INFINITY;

        for ((w, s), face) in &capability_map.italic_slots {
            let distance = ((*w as f32 - weight as f32).powi(2) + (*s as f32 - stretch as f32).powi(2)).sqrt();
            if distance < best_distance {
                best_distance = distance;
                best_face = Some(face);
            }
        }

        best_face
    }

    /// Finds the nearest upright face to the requested weight and stretch.
    fn find_nearest_upright<'a>(
        &self,
        capability_map: &'a FontSelectionCapabilityMap,
        weight: u16,
        stretch: u16,
    ) -> Option<&'a FaceOrVfWithRecipe> {
        // Simple nearest neighbor search
        let mut best_face = None;
        let mut best_distance = f32::INFINITY;

        for ((w, s), face) in &capability_map.upright_slots {
            let distance = ((*w as f32 - weight as f32).powi(2) + (*s as f32 - stretch as f32).powi(2)).sqrt();
            if distance < best_distance {
                best_distance = distance;
                best_face = Some(face);
            }
        }

        best_face
    }

    /// Attempts to synthesize an italic face from a variable font.
    fn synthesize_italic_from_vf(
        &self,
        capability_map: &FontSelectionCapabilityMap,
        _weight: u16,
        _stretch: u16,
    ) -> Option<FaceOrVfWithRecipe> {
        // Look for a variable font that can synthesize italic
        for face in capability_map.upright_slots.values() {
            if face.vf_recipe.is_some() {
                // This is a variable font, try to create an italic recipe
                let italic_recipe = VfRecipe::new("ital", 1.0);
                return Some(FaceOrVfWithRecipe {
                    face_id: face.face_id.clone(),
                    vf_recipe: Some(italic_recipe),
                    instance_info: face.instance_info.clone(),
                });
            }
        }

        None
    }
}

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

/// Helper function to extract face record from ttf-parser Face.
pub fn extract_face_record(
    face: &Face<'_>,
    face_id: String,
    user_font_style_italic: Option<bool>,
) -> Result<FaceRecord, String> {
    // Extract basic name information using ttf-parser's names() method
    let ps_name = face
        .names()
        .into_iter()
        .find(|n| n.name_id == 6 && n.is_unicode()) // PostScript name (NameID 6)
        .and_then(|n| n.to_string())
        .unwrap_or_default();

    let family_name = face
        .names()
        .into_iter()
        .find(|n| n.name_id == 1 && n.is_unicode()) // Family name (NameID 1)
        .and_then(|n| n.to_string())
        .unwrap_or_default();

    let subfamily_name = face
        .names()
        .into_iter()
        .find(|n| n.name_id == 2 && n.is_unicode()) // Subfamily name (NameID 2)
        .and_then(|n| n.to_string())
        .unwrap_or_default();

    // Extract OS/2 information using ttf-parser's built-in methods
    // Use style() instead of is_italic() to only check OS/2 bits, not post.italicAngle
    let os2_italic_bit = face.style() == Style::Italic;
    let weight_class = face.weight().to_number();
    let width_class = face.width().to_number();

    // Extract variable font information using ttf-parser's built-in methods
    let is_variable = face.is_variable();
    let axes = if is_variable {
        extract_variation_axes(face)
    } else {
        HashMap::new()
    };

    Ok(FaceRecord {
        face_id,
        ps_name,
        family_name,
        typographic_family: None, // Not implemented in Level 1
        subfamily_name,
        typographic_subfamily: None, // Not implemented in Level 1
        is_variable,
        axes,
        os2_italic_bit,
        weight_class,
        width_class,
        user_font_style_italic,
    })
}

/// Extract variation axes using ttf-parser's built-in methods.
fn extract_variation_axes(face: &Face<'_>) -> HashMap<String, (f32, f32, f32)> {
    let mut axes = HashMap::new();

    for axis in face.variation_axes() {
        let tag = axis.tag.to_string();
        let min = axis.min_value;
        let default = axis.def_value;
        let max = axis.max_value;

        axes.insert(tag, (min, default, max));
    }

    axes
}

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

    #[test]
    fn test_font_selection_parser_default_config() {
        let parser = FontSelectionParser::new();
        assert!(parser.config.trust_user_font_style);
    }

    #[test]
    fn test_vf_recipe_creation() {
        let recipe = VfRecipe::new("ital", 1.0);
        assert_eq!(recipe.axis_values.get("ital"), Some(&1.0));

        let empty = VfRecipe::empty();
        assert!(empty.axis_values.is_empty());
    }

    #[test]
    fn test_face_classification_user_style_priority() {
        let parser = FontSelectionParser::new();
        let face = FaceRecord {
            face_id: "test".to_string(),
            ps_name: "TestFont".to_string(),
            family_name: "Test".to_string(),
            typographic_family: None,
            subfamily_name: "Regular".to_string(),
            typographic_subfamily: None,
            is_variable: false,
            axes: HashMap::new(),
            os2_italic_bit: false, // OS/2 says not italic
            weight_class: 400,
            width_class: 5,
            user_font_style_italic: Some(true), // But user says it is italic
        };

        let classification = parser.classify_face(face);
        assert_eq!(
            classification.classification.font_style,
            FontStyle::Italic
        );
    }

    #[test]
    fn test_face_classification_os2_italic() {
        let parser = FontSelectionParser::new();
        let face = FaceRecord {
            face_id: "test".to_string(),
            ps_name: "TestFont-Italic".to_string(),
            family_name: "Test".to_string(),
            typographic_family: None,
            subfamily_name: "Italic".to_string(),
            typographic_subfamily: None,
            is_variable: false,
            axes: HashMap::new(),
            os2_italic_bit: true,
            weight_class: 400,
            width_class: 5,
            user_font_style_italic: None,
        };

        let classification = parser.classify_face(face);
        assert_eq!(
            classification.classification.font_style,
            FontStyle::Italic
        );
        assert!(classification.classification.vf_recipe.is_none());
    }

    #[test]
    fn test_face_classification_ital_axis() {
        let parser = FontSelectionParser::new();
        let mut axes = HashMap::new();
        axes.insert("ital".to_string(), (0.0, 1.0, 1.0)); // Default ital=1

        let face = FaceRecord {
            face_id: "test".to_string(),
            ps_name: "TestFont-VF".to_string(),
            family_name: "Test".to_string(),
            typographic_family: None,
            subfamily_name: "Variable".to_string(),
            typographic_subfamily: None,
            is_variable: true,
            axes,
            os2_italic_bit: false,
            weight_class: 400,
            width_class: 5,
            user_font_style_italic: None,
        };

        let classification = parser.classify_face(face);
        assert_eq!(
            classification.classification.font_style,
            FontStyle::Italic
        );
        assert!(classification.classification.vf_recipe.is_some());
        assert_eq!(
            classification
                .classification
                .vf_recipe
                .unwrap()
                .axis_values
                .get("ital"),
            Some(&1.0)
        );
    }

    #[test]
    fn test_face_classification_normal() {
        let parser = FontSelectionParser::new();
        let face = FaceRecord {
            face_id: "test".to_string(),
            ps_name: "TestFont-Regular".to_string(),
            family_name: "Test".to_string(),
            typographic_family: None,
            subfamily_name: "Regular".to_string(),
            typographic_subfamily: None,
            is_variable: false,
            axes: HashMap::new(),
            os2_italic_bit: false,
            weight_class: 400,
            width_class: 5,
            user_font_style_italic: None,
        };

        let classification = parser.classify_face(face);
        assert_eq!(
            classification.classification.font_style,
            FontStyle::Normal
        );
        assert!(classification.classification.vf_recipe.is_none());
    }

    #[test]
    fn test_capability_map_single_static() {
        let parser = FontSelectionParser::new();
        let face = FaceRecord {
            face_id: "test".to_string(),
            ps_name: "TestFont-Regular".to_string(),
            family_name: "Test".to_string(),
            typographic_family: None,
            subfamily_name: "Regular".to_string(),
            typographic_subfamily: None,
            is_variable: false,
            axes: HashMap::new(),
            os2_italic_bit: false,
            weight_class: 400,
            width_class: 5,
            user_font_style_italic: None,
        };

        let map = parser.build_capability_map(vec![face]);
        assert_eq!(map.scenario, FamilyScenario::SingleStatic);
        assert_eq!(map.upright_slots.len(), 1);
        assert_eq!(map.italic_slots.len(), 0);
    }

    #[test]
    fn test_capability_map_multi_static() {
        let parser = FontSelectionParser::new();
        let regular = FaceRecord {
            face_id: "regular".to_string(),
            ps_name: "TestFont-Regular".to_string(),
            family_name: "Test".to_string(),
            typographic_family: None,
            subfamily_name: "Regular".to_string(),
            typographic_subfamily: None,
            is_variable: false,
            axes: HashMap::new(),
            os2_italic_bit: false,
            weight_class: 400,
            width_class: 5,
            user_font_style_italic: None,
        };

        let italic = FaceRecord {
            face_id: "italic".to_string(),
            ps_name: "TestFont-Italic".to_string(),
            family_name: "Test".to_string(),
            typographic_family: None,
            subfamily_name: "Italic".to_string(),
            typographic_subfamily: None,
            is_variable: false,
            axes: HashMap::new(),
            os2_italic_bit: true,
            weight_class: 400,
            width_class: 5,
            user_font_style_italic: None,
        };

        let map = parser.build_capability_map(vec![regular, italic]);
        assert_eq!(map.scenario, FamilyScenario::MultiStatic);
        assert_eq!(map.upright_slots.len(), 1);
        assert_eq!(map.italic_slots.len(), 1);
    }
}