webpage_quality_analyzer 1.0.2

High-performance webpage quality analyzer with 115 comprehensive metrics - Rust library with WASM, C++, and Python bindings
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
/// Content Expectation Validation for Phase 3
/// Validates content expectations against actual page content and structure
use crate::config::enhanced_models::*;
use crate::constants::*;
use crate::models::models::{PageMetrics, ProcessedDocument};
// MetricValue import removed as not used in this context
use std::collections::HashMap;

/// Content validation errors
#[derive(Debug, thiserror::Error)]
pub enum ContentValidationError {
    #[error("Word count validation failed: {0}")]
    WordCount(String),

    #[error("Heading structure validation failed: {0}")]
    HeadingStructure(String),

    #[error("Media requirement validation failed: {0}")]
    MediaRequirement(String),

    #[error("Technical requirement validation failed: {0}")]
    TechnicalRequirement(String),

    #[error("SEO requirement validation failed: {0}")]
    SeoRequirement(String),

    #[error("General validation error: {0}")]
    General(String),
}

/// Content validation result with detailed breakdown
#[derive(Debug, Clone)]
pub struct ContentValidationResult {
    pub violations: Vec<ContentViolation>,
    pub penalties: Vec<ContentPenalty>,
    pub compliance_score: f32,
    pub detailed_analysis: ContentAnalysis,
}

/// Individual content violation
#[derive(Debug, Clone)]
pub enum ContentViolation {
    InsufficientWordCount {
        actual: usize,
        minimum: usize,
        severity: ViolationSeverity,
    },
    ExcessiveWordCount {
        actual: usize,
        maximum_useful: usize,
        severity: ViolationSeverity,
    },
    MissingRequiredHeading {
        heading_type: String,
        severity: ViolationSeverity,
    },
    InvalidHeadingStructure {
        issue: String,
        severity: ViolationSeverity,
    },
    InsufficientMedia {
        media_type: String,
        actual: usize,
        required: usize,
        severity: ViolationSeverity,
    },
    PoorAltTextCoverage {
        actual_coverage: f32,
        required_coverage: f32,
        severity: ViolationSeverity,
    },
    MissingTechnicalRequirement {
        requirement: String,
        severity: ViolationSeverity,
    },
    MissingSeoElement {
        element: String,
        severity: ViolationSeverity,
    },
    SeoElementOutOfRange {
        element: String,
        actual_length: usize,
        required_range: (usize, usize),
        severity: ViolationSeverity,
    },
}

/// Severity levels for violations
#[derive(Debug, Clone, PartialEq)]
pub enum ViolationSeverity {
    Critical, // Major impact on quality
    High,     // Significant impact
    Medium,   // Moderate impact
    Low,      // Minor impact
}

/// Content penalty applied due to violations
#[derive(Debug, Clone)]
pub struct ContentPenalty {
    pub penalty_type: String,
    pub penalty_amount: f32,
    pub reason: String,
    pub severity: ViolationSeverity,
}

/// Detailed content analysis breakdown
#[derive(Debug, Clone)]
pub struct ContentAnalysis {
    pub word_count_analysis: Option<WordCountAnalysis>,
    pub heading_analysis: Option<HeadingAnalysis>,
    pub media_analysis: Option<MediaAnalysis>,
    pub technical_analysis: Option<TechnicalAnalysis>,
    pub seo_analysis: Option<SeoAnalysis>,
}

#[derive(Debug, Clone)]
pub struct WordCountAnalysis {
    pub actual_count: usize,
    pub expected_range: (usize, usize),
    pub minimum_threshold: usize,
    pub compliance_percentage: f32,
    pub recommendation: String,
}

#[derive(Debug, Clone)]
pub struct HeadingAnalysis {
    pub total_headings: usize,
    pub heading_distribution: HashMap<String, usize>, // H1, H2, etc.
    pub structure_valid: bool,
    pub missing_h1: bool,
    pub compliance_percentage: f32,
    pub recommendations: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct MediaAnalysis {
    pub image_count: usize,
    pub video_count: usize,
    pub audio_count: usize,
    pub alt_text_coverage: f32,
    pub media_to_text_ratio: f32,
    pub compliance_percentage: f32,
    pub recommendations: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct TechnicalAnalysis {
    pub page_size_compliant: bool,
    pub mobile_friendly: bool,
    pub required_meta_tags: Vec<String>,
    pub missing_meta_tags: Vec<String>,
    pub ssl_enabled: bool,
    pub compliance_percentage: f32,
    pub recommendations: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct SeoAnalysis {
    pub title_compliant: bool,
    pub meta_description_present: bool,
    pub meta_description_length_compliant: bool,
    pub canonical_url_present: bool,
    pub structured_data_present: bool,
    pub open_graph_present: bool,
    pub keyword_density_compliant: bool,
    pub compliance_percentage: f32,
    pub recommendations: Vec<String>,
}

/// Content validator implementation
pub struct ContentValidator;

impl ContentValidator {
    /// Create a new content validator
    pub fn new() -> Self {
        Self
    }

    /// Validate content expectations against actual content
    pub fn validate_content_expectations(
        &self,
        expectations: &ContentExpectations,
        metrics: &PageMetrics,
        document: &ProcessedDocument,
    ) -> Result<ContentValidationResult, ContentValidationError> {
        let mut violations = Vec::new();
        let mut penalties = Vec::new();
        let mut compliance_scores = Vec::new();

        // Analyze word count expectations
        let word_count_analysis = if let Some(word_exp) = &expectations.word_count {
            let analysis = self.validate_word_count_expectations(
                word_exp,
                metrics,
                &mut violations,
                &mut penalties,
            )?;
            compliance_scores.push(analysis.compliance_percentage);
            Some(analysis)
        } else {
            None
        };

        // Analyze heading structure expectations
        let heading_analysis = if let Some(heading_exp) = &expectations.heading_structure {
            let analysis = self.validate_heading_expectations(
                heading_exp,
                metrics,
                document,
                &mut violations,
                &mut penalties,
            )?;
            compliance_scores.push(analysis.compliance_percentage);
            Some(analysis)
        } else {
            None
        };

        // Analyze media requirements
        let media_analysis = if let Some(media_exp) = &expectations.media_requirements {
            let analysis = self.validate_media_expectations(
                media_exp,
                metrics,
                &mut violations,
                &mut penalties,
            )?;
            compliance_scores.push(analysis.compliance_percentage);
            Some(analysis)
        } else {
            None
        };

        // Analyze technical requirements
        let technical_analysis = if let Some(tech_exp) = &expectations.technical_requirements {
            let analysis = self.validate_technical_expectations(
                tech_exp,
                metrics,
                &mut violations,
                &mut penalties,
            )?;
            compliance_scores.push(analysis.compliance_percentage);
            Some(analysis)
        } else {
            None
        };

        // Analyze SEO requirements
        let seo_analysis = if let Some(seo_exp) = &expectations.seo_requirements {
            let analysis =
                self.validate_seo_expectations(seo_exp, metrics, &mut violations, &mut penalties)?;
            compliance_scores.push(analysis.compliance_percentage);
            Some(analysis)
        } else {
            None
        };

        // Calculate overall compliance score
        let compliance_score = if compliance_scores.is_empty() {
            100.0 // No expectations = perfect compliance
        } else {
            compliance_scores.iter().sum::<f32>() / compliance_scores.len() as f32
        };

        Ok(ContentValidationResult {
            violations,
            penalties,
            compliance_score,
            detailed_analysis: ContentAnalysis {
                word_count_analysis,
                heading_analysis,
                media_analysis,
                technical_analysis,
                seo_analysis,
            },
        })
    }

    /// Validate word count expectations
    fn validate_word_count_expectations(
        &self,
        expectation: &WordCountExpectation,
        metrics: &PageMetrics,
        violations: &mut Vec<ContentViolation>,
        penalties: &mut Vec<ContentPenalty>,
    ) -> Result<WordCountAnalysis, ContentValidationError> {
        let actual_count = metrics.html_analysis.content.word_count;
        let expected_range = expectation.optimal_range;
        let minimum_threshold = expectation.minimum;

        let mut compliance_percentage: f32 = 100.0;
        let mut recommendation = String::new();

        // Check for violations
        if actual_count < minimum_threshold {
            let severity =
                self.calculate_word_count_deficiency_severity(actual_count, minimum_threshold);
            violations.push(ContentViolation::InsufficientWordCount {
                actual: actual_count,
                minimum: minimum_threshold,
                severity: severity.clone(),
            });

            let penalty_amount = self.calculate_word_count_penalty(actual_count, expectation);
            penalties.push(ContentPenalty {
                penalty_type: PENALTY_WORD_COUNT_DEFICIENCY.to_string(),
                penalty_amount,
                reason: format!(
                    "Content has only {} words, minimum required is {}",
                    actual_count, minimum_threshold
                ),
                severity,
            });

            compliance_percentage = (actual_count as f32 / minimum_threshold as f32) * 60.0;
            recommendation = format!(
                "Add {} more words to reach minimum requirement",
                minimum_threshold - actual_count
            );
        } else if actual_count < expected_range.0 {
            compliance_percentage = 60.0
                + ((actual_count - minimum_threshold) as f32
                    / (expected_range.0 - minimum_threshold) as f32)
                    * 25.0;
            recommendation = format!(
                "Consider adding {} more words to reach optimal range",
                expected_range.0 - actual_count
            );
        } else if actual_count > expected_range.1 {
            if let Some(max_useful) = expectation.maximum_useful {
                if actual_count > max_useful {
                    violations.push(ContentViolation::ExcessiveWordCount {
                        actual: actual_count,
                        maximum_useful: max_useful,
                        severity: ViolationSeverity::Low,
                    });
                    compliance_percentage = 85.0;
                    recommendation = format!(
                        "Content is quite long ({}+ words). Consider breaking into multiple pages",
                        actual_count
                    );
                } else {
                    compliance_percentage = 95.0;
                    recommendation = RECOMMENDATION_WORD_COUNT_OPTIMAL_ABOVE.to_string();
                }
            } else {
                compliance_percentage = 95.0;
                recommendation = RECOMMENDATION_WORD_COUNT_ABOVE_RANGE.to_string();
            }
        } else {
            // Within optimal range
            compliance_percentage = 100.0;
            recommendation = RECOMMENDATION_WORD_COUNT_OPTIMAL.to_string();
        }

        Ok(WordCountAnalysis {
            actual_count,
            expected_range,
            minimum_threshold,
            compliance_percentage,
            recommendation,
        })
    }

    /// Validate heading structure expectations
    fn validate_heading_expectations(
        &self,
        expectation: &HeadingExpectation,
        metrics: &PageMetrics,
        document: &ProcessedDocument,
        violations: &mut Vec<ContentViolation>,
        penalties: &mut Vec<ContentPenalty>,
    ) -> Result<HeadingAnalysis, ContentValidationError> {
        let total_headings = metrics.html_analysis.structure.headings_count;
        let mut heading_distribution = HashMap::new();
        let mut structure_valid = true;
        let mut missing_h1 = false;
        let mut compliance_percentage: f32 = 100.0;
        let mut recommendations = Vec::new();

        // Analyze heading distribution from document
        self.analyze_heading_distribution(document, &mut heading_distribution);

        // Check if H1 is required and present
        if expectation.require_h1 && heading_distribution.get(HEADING_H1).unwrap_or(&0) == &0 {
            missing_h1 = true;
            structure_valid = false;
            violations.push(ContentViolation::MissingRequiredHeading {
                heading_type: HEADING_H1.to_string(),
                severity: ViolationSeverity::High,
            });
            penalties.push(ContentPenalty {
                penalty_type: PENALTY_MISSING_H1.to_string(),
                penalty_amount: 15.0,
                reason: REASON_MISSING_H1.to_string(),
                severity: ViolationSeverity::High,
            });
            compliance_percentage -= 20.0;
            recommendations.push(RECOMMENDATION_ADD_H1.to_string());
        }

        // Check minimum headings requirement
        if total_headings < expectation.minimum_headings {
            violations.push(ContentViolation::InvalidHeadingStructure {
                issue: format!(
                    "Only {} headings found, minimum {} required",
                    total_headings, expectation.minimum_headings
                ),
                severity: ViolationSeverity::Medium,
            });
            penalties.push(ContentPenalty {
                penalty_type: PENALTY_INSUFFICIENT_HEADINGS.to_string(),
                penalty_amount: 10.0,
                reason: format!(
                    "Insufficient heading structure: {} < {}",
                    total_headings, expectation.minimum_headings
                ),
                severity: ViolationSeverity::Medium,
            });
            compliance_percentage -= 15.0;
            recommendations.push(format!(
                "Add {} more headings to improve content structure",
                expectation.minimum_headings - total_headings
            ));
        }

        // Check heading depth
        if self.check_heading_depth_violations(
            &heading_distribution,
            expectation.maximum_heading_depth,
        ) {
            violations.push(ContentViolation::InvalidHeadingStructure {
                issue: format!(
                    "Heading depth exceeds maximum of {}",
                    expectation.maximum_heading_depth
                ),
                severity: ViolationSeverity::Low,
            });
            compliance_percentage -= 5.0;
            recommendations.push(RECOMMENDATION_SIMPLIFY_HIERARCHY.to_string());
        }

        // Check logical hierarchy if required
        if expectation.logical_hierarchy && !self.validate_heading_hierarchy(&heading_distribution)
        {
            violations.push(ContentViolation::InvalidHeadingStructure {
                issue: ISSUE_HEADING_HIERARCHY_ILLOGICAL.to_string(),
                severity: ViolationSeverity::Medium,
            });
            compliance_percentage -= 10.0;
            recommendations.push(RECOMMENDATION_HEADING_ORDER.to_string());
        }

        Ok(HeadingAnalysis {
            total_headings,
            heading_distribution,
            structure_valid,
            missing_h1,
            compliance_percentage: compliance_percentage.max(0.0),
            recommendations,
        })
    }

    /// Validate media expectations
    fn validate_media_expectations(
        &self,
        expectation: &MediaExpectation,
        metrics: &PageMetrics,
        violations: &mut Vec<ContentViolation>,
        penalties: &mut Vec<ContentPenalty>,
    ) -> Result<MediaAnalysis, ContentValidationError> {
        let image_count = metrics.html_analysis.media.images_count;
        let video_count = metrics.html_analysis.media.video_count;
        let audio_count = metrics.html_analysis.media.audio_count;
        let alt_text_coverage = metrics.html_analysis.media.image_alt_coverage;
        let word_count = metrics.html_analysis.content.word_count as f32;
        let media_to_text_ratio = if word_count > 0.0 {
            image_count as f32 / word_count
        } else {
            0.0
        };

        let mut compliance_percentage: f32 = 100.0;
        let mut recommendations = Vec::new();

        // Check minimum images requirement
        if image_count < expectation.minimum_images {
            violations.push(ContentViolation::InsufficientMedia {
                media_type: MEDIA_TYPE_IMAGES.to_string(),
                actual: image_count,
                required: expectation.minimum_images,
                severity: ViolationSeverity::Medium,
            });
            penalties.push(ContentPenalty {
                penalty_type: PENALTY_INSUFFICIENT_IMAGES.to_string(),
                penalty_amount: 10.0,
                reason: format!(
                    "Only {} images found, {} required",
                    image_count, expectation.minimum_images
                ),
                severity: ViolationSeverity::Medium,
            });
            compliance_percentage -= 20.0;
            recommendations.push(format!(
                "Add {} more images to meet requirements",
                expectation.minimum_images - image_count
            ));
        }

        // Check alt text coverage
        if alt_text_coverage < expectation.alt_text_coverage {
            violations.push(ContentViolation::PoorAltTextCoverage {
                actual_coverage: alt_text_coverage,
                required_coverage: expectation.alt_text_coverage,
                severity: ViolationSeverity::High,
            });
            penalties.push(ContentPenalty {
                penalty_type: PENALTY_POOR_ALT_TEXT.to_string(),
                penalty_amount: 15.0,
                reason: format!(
                    "Alt text coverage is {:.1}%, required {:.1}%",
                    alt_text_coverage * 100.0,
                    expectation.alt_text_coverage * 100.0
                ),
                severity: ViolationSeverity::High,
            });
            compliance_percentage -= 25.0;
            recommendations.push(RECOMMENDATION_ADD_ALT_TEXT.to_string());
        }

        // Check image to text ratio if specified
        if let Some((min_ratio, max_ratio)) = expectation.image_to_text_ratio {
            if media_to_text_ratio < min_ratio {
                compliance_percentage -= 10.0;
                recommendations.push(RECOMMENDATION_VISUAL_BALANCE.to_string());
            } else if media_to_text_ratio > max_ratio {
                compliance_percentage -= 5.0;
                recommendations.push(RECOMMENDATION_MEDIA_SUPPORT_TEXT.to_string());
            }
        }

        // Check audio/video requirements
        if expectation.require_audio == Some(true) && audio_count == 0 {
            violations.push(ContentViolation::InsufficientMedia {
                media_type: MEDIA_TYPE_AUDIO.to_string(),
                actual: audio_count,
                required: 1,
                severity: ViolationSeverity::Medium,
            });
            compliance_percentage -= 15.0;
            recommendations.push(RECOMMENDATION_ADD_AUDIO.to_string());
        }

        if expectation.require_video == Some(true) && video_count == 0 {
            violations.push(ContentViolation::InsufficientMedia {
                media_type: MEDIA_TYPE_VIDEO.to_string(),
                actual: video_count,
                required: 1,
                severity: ViolationSeverity::Medium,
            });
            compliance_percentage -= 15.0;
            recommendations.push(RECOMMENDATION_ADD_VIDEO.to_string());
        }

        Ok(MediaAnalysis {
            image_count,
            video_count,
            audio_count,
            alt_text_coverage,
            media_to_text_ratio,
            compliance_percentage: compliance_percentage.max(0.0),
            recommendations,
        })
    }

    /// Validate technical expectations
    fn validate_technical_expectations(
        &self,
        expectation: &TechnicalExpectation,
        metrics: &PageMetrics,
        violations: &mut Vec<ContentViolation>,
        _penalties: &mut Vec<ContentPenalty>,
    ) -> Result<TechnicalAnalysis, ContentValidationError> {
        let mut compliance_percentage: f32 = 100.0;
        let mut recommendations = Vec::new();
        let mut missing_meta_tags = Vec::new();

        // Check SSL requirement
        let ssl_enabled = expectation.ssl_required; // Would need actual SSL check
        if expectation.ssl_required && !ssl_enabled {
            violations.push(ContentViolation::MissingTechnicalRequirement {
                requirement: REQUIREMENT_SSL_HTTPS.to_string(),
                severity: ViolationSeverity::High,
            });
            compliance_percentage -= 20.0;
            recommendations.push(RECOMMENDATION_SSL_HTTPS.to_string());
        }

        // Check required meta tags
        for tag in &expectation.required_meta_tags {
            if !self.has_meta_tag(tag, metrics) {
                missing_meta_tags.push(tag.clone());
                violations.push(ContentViolation::MissingTechnicalRequirement {
                    requirement: format!("Meta tag: {}", tag),
                    severity: ViolationSeverity::Medium,
                });
                compliance_percentage -= 10.0;
                recommendations.push(format!("Add required meta tag: {}", tag));
            }
        }

        Ok(TechnicalAnalysis {
            page_size_compliant: true, // Would need actual page size check
            mobile_friendly: true,     // Would need actual mobile check
            required_meta_tags: expectation.required_meta_tags.clone(),
            missing_meta_tags,
            ssl_enabled,
            compliance_percentage: compliance_percentage.max(0.0),
            recommendations,
        })
    }

    /// Validate SEO expectations
    fn validate_seo_expectations(
        &self,
        expectation: &SeoExpectation,
        metrics: &PageMetrics,
        violations: &mut Vec<ContentViolation>,
        penalties: &mut Vec<ContentPenalty>,
    ) -> Result<SeoAnalysis, ContentValidationError> {
        let mut compliance_percentage: f32 = 100.0;
        let mut recommendations = Vec::new();

        // Check title length
        let title_compliant = if let Some((min_len, max_len)) = expectation.title_length_range {
            let title_len = metrics.html_analysis.seo.title_len;
            if title_len < min_len || title_len > max_len {
                violations.push(ContentViolation::SeoElementOutOfRange {
                    element: ELEMENT_TITLE.to_string(),
                    actual_length: title_len,
                    required_range: (min_len, max_len),
                    severity: ViolationSeverity::Medium,
                });
                compliance_percentage -= 15.0;
                recommendations.push(format!(
                    "Adjust title length to {}-{} characters",
                    min_len, max_len
                ));
                false
            } else {
                true
            }
        } else {
            true
        };

        // Check meta description
        let meta_description_present = metrics.html_analysis.seo.meta_desc_len.is_some();
        let mut meta_description_length_compliant = true;

        if expectation.meta_description_required && !meta_description_present {
            violations.push(ContentViolation::MissingSeoElement {
                element: "meta description".to_string(),
                severity: ViolationSeverity::High,
            });
            penalties.push(ContentPenalty {
                penalty_type: PENALTY_MISSING_META_DESC.to_string(),
                penalty_amount: 20.0,
                reason: REASON_META_DESC_REQUIRED.to_string(),
                severity: ViolationSeverity::High,
            });
            compliance_percentage -= 25.0;
            recommendations.push(RECOMMENDATION_ADD_META_DESC.to_string());
        } else if let Some((min_len, max_len)) = expectation.meta_description_length_range {
            if let Some(desc_len) = metrics.html_analysis.seo.meta_desc_len {
                if desc_len < min_len || desc_len > max_len {
                    violations.push(ContentViolation::SeoElementOutOfRange {
                        element: ELEMENT_META_DESC.to_string(),
                        actual_length: desc_len,
                        required_range: (min_len, max_len),
                        severity: ViolationSeverity::Medium,
                    });
                    compliance_percentage -= 10.0;
                    recommendations.push(format!(
                        "Adjust meta description length to {}-{} characters",
                        min_len, max_len
                    ));
                    meta_description_length_compliant = false;
                }
            }
        }

        // Check other SEO requirements (simplified for now)
        let canonical_url_present = !expectation.canonical_url_required; // Would need actual check
        let structured_data_present = !expectation.structured_data_required; // Would need actual check
        let open_graph_present = !expectation.open_graph_required; // Would need actual check
        let keyword_density_compliant = true; // Would need actual keyword analysis

        Ok(SeoAnalysis {
            title_compliant,
            meta_description_present,
            meta_description_length_compliant,
            canonical_url_present,
            structured_data_present,
            open_graph_present,
            keyword_density_compliant,
            compliance_percentage: compliance_percentage.max(0.0),
            recommendations,
        })
    }

    // Helper methods

    fn calculate_word_count_deficiency_severity(
        &self,
        actual: usize,
        minimum: usize,
    ) -> ViolationSeverity {
        let ratio = actual as f32 / minimum as f32;
        if ratio < 0.25 {
            ViolationSeverity::Critical
        } else if ratio < 0.5 {
            ViolationSeverity::High
        } else if ratio < 0.8 {
            ViolationSeverity::Medium
        } else {
            ViolationSeverity::Low
        }
    }

    fn calculate_word_count_penalty(
        &self,
        actual: usize,
        expectation: &WordCountExpectation,
    ) -> f32 {
        let ratio = actual as f32 / expectation.minimum as f32;
        match &expectation.penalty_curve {
            PenaltyCurve::Linear => (1.0 - ratio) * 30.0,
            PenaltyCurve::Exponential { base } => {
                let penalty = (1.0 - ratio).powf(*base) * 40.0;
                penalty.min(50.0)
            }
            PenaltyCurve::StepFunction { steps } => {
                for (threshold, penalty) in steps {
                    if ratio <= *threshold {
                        return *penalty;
                    }
                }
                0.0
            }
        }
    }

    fn analyze_heading_distribution(
        &self,
        _document: &ProcessedDocument,
        distribution: &mut HashMap<String, usize>,
    ) {
        // This would analyze the actual document structure
        // For now, provide a simplified implementation
        distribution.insert("H1".to_string(), 1);
        distribution.insert("H2".to_string(), 3);
        distribution.insert("H3".to_string(), 2);
    }

    fn check_heading_depth_violations(
        &self,
        distribution: &HashMap<String, usize>,
        max_depth: usize,
    ) -> bool {
        let heading_levels = ["H1", "H2", "H3", "H4", "H5", "H6"];
        for (i, level) in heading_levels.iter().enumerate() {
            if i >= max_depth && distribution.get(*level).unwrap_or(&0) > &0 {
                return true;
            }
        }
        false
    }

    fn validate_heading_hierarchy(&self, distribution: &HashMap<String, usize>) -> bool {
        // Check for logical heading progression
        // This is a simplified check - full implementation would analyze document order
        let h1_count = distribution.get("H1").unwrap_or(&0);
        let h2_count = distribution.get("H2").unwrap_or(&0);
        let h3_count = distribution.get("H3").unwrap_or(&0);

        // Basic rule: if you have H3, you should have H2; if you have H2, you should have H1
        if *h3_count > 0 && *h2_count == 0 {
            return false;
        }
        if *h2_count > 0 && *h1_count == 0 {
            return false;
        }

        true
    }

    fn has_meta_tag(&self, tag: &str, metrics: &PageMetrics) -> bool {
        // This would check actual meta tags - simplified for now
        match tag {
            "description" => metrics.html_analysis.seo.meta_desc_len.is_some(),
            _ => false, // Other meta tags would need additional tracking
        }
    }

    /// Calculate overall compliance score from violations
    pub fn calculate_compliance_score(&self, violations: &[ContentViolation]) -> f32 {
        if violations.is_empty() {
            return 100.0;
        }

        let mut total_penalty = 0.0;
        for violation in violations {
            let penalty = match violation {
                ContentViolation::InsufficientWordCount { severity, .. } => {
                    self.severity_to_penalty(severity)
                }
                ContentViolation::ExcessiveWordCount { severity, .. } => {
                    self.severity_to_penalty(severity)
                }
                ContentViolation::MissingRequiredHeading { severity, .. } => {
                    self.severity_to_penalty(severity)
                }
                ContentViolation::InvalidHeadingStructure { severity, .. } => {
                    self.severity_to_penalty(severity)
                }
                ContentViolation::InsufficientMedia { severity, .. } => {
                    self.severity_to_penalty(severity)
                }
                ContentViolation::PoorAltTextCoverage { severity, .. } => {
                    self.severity_to_penalty(severity)
                }
                ContentViolation::MissingTechnicalRequirement { severity, .. } => {
                    self.severity_to_penalty(severity)
                }
                ContentViolation::MissingSeoElement { severity, .. } => {
                    self.severity_to_penalty(severity)
                }
                ContentViolation::SeoElementOutOfRange { severity, .. } => {
                    self.severity_to_penalty(severity)
                }
            };
            total_penalty += penalty;
        }

        (100.0 - total_penalty).max(0.0)
    }

    fn severity_to_penalty(&self, severity: &ViolationSeverity) -> f32 {
        match severity {
            ViolationSeverity::Critical => 30.0,
            ViolationSeverity::High => 20.0,
            ViolationSeverity::Medium => 10.0,
            ViolationSeverity::Low => 5.0,
        }
    }
}

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