auditmysite 1.4.0

Resource-efficient WCAG 2.1 AA (+ select 2.2 criteria) Accessibility Checker in Rust
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
//! Commerce / shop audit.
//!
//! Derive-only analysis (no CDP). Two signal groups, both gated to shop context
//! (Product/Offer schema present, or an e-commerce tech stack detected) so it
//! never fires on landing/editorial pages:
//!
//! - **Product completeness** (slice 1): from the JSON-LD the SEO module already
//!   collected — price, availability/delivery, shipping, returns, reviews.
//! - **Mandatory pages** (slice 2): whether the page links to the legally/UX
//!   expected pages (Impressum, AGB, Widerruf/Retoure, Versand, Zahlungsarten,
//!   Kontakt), detected from the screen-reader link inventory's anchor texts.
//!   The batch layer aggregates these per-page booleans into a site-wide view.
//! - **BFSGV §19 Nr. 3 scope signal**: whether this page exposes an
//!   identification/authentication function (a form control whose
//!   `autocomplete` token is `current-password`/`new-password`/
//!   `one-time-code`/`username`), detected from the screen-reader form
//!   control inventory. Presence-only, never an automated pass/fail — see
//!   `screen_reader::bfsg`'s module doc comment for why only this one
//!   sub-item of §19 is incorporated (Nr. 1/Nr. 2 stay explicitly out of
//!   scope).
//!
//! Localization (#406): stored struct is canonical English; findings carry a
//! `kind` enum and `commerce_finding_text(kind, en)` is the single text source.
//! Honest wording: absence means "not exposed as structured data" / "not linked
//! from this page", never a claim of legal (non-)compliance. The §19 signal
//! follows the same convention: `identification_function_detected == false`
//! never claims no such function exists on the page, only that none was
//! identified via the tracked `autocomplete` signal.

pub mod module;

pub use module::CommerceModule;

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::seo::StructuredData;
use crate::taxonomy::Severity;

/// Commerce signals for one shop page.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CommerceAnalysis {
    /// Coarse commerce page type (foundation for page-type-specific heuristics).
    pub page_kind: CommercePageKind,
    /// Product structured-data completeness; `None` when the page carries no
    /// `Product`/`Offer` schema (e.g. a category or info page of a shop).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub product: Option<ProductCommerce>,
    /// Which mandatory/trust pages this page links to.
    pub trust_pages: TrustPages,
    /// Whether this page exposes an identification/authentication function
    /// (a form control with an `autocomplete` purpose of
    /// `current-password`/`new-password`/`one-time-code`/`username`) —
    /// brings this page into BFSGV §19 Nr. 3's additional e-commerce
    /// accessibility scope. Presence-only: this tool has no session state to
    /// exercise the actual identification/authentication flow end-to-end, so
    /// this is never an automated pass/fail, only a flag that this page's
    /// WCAG findings additionally fall under §19 Nr. 3 and that a manual
    /// review of the flow's perceivability/operability/understandability/
    /// robustness is warranted. `false` never claims no such function exists
    /// on the page — see this module's doc comment.
    pub identification_function_detected: bool,
    /// BFSGV citation for `identification_function_detected`, present only
    /// when that signal is `true` (out of scope for this page otherwise).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub identification_function_bfsg_reference: Option<String>,
    /// Findings across all groups.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub findings: Vec<CommerceFinding>,
}

/// Coarse classification of a shop page, from URL path + product schema.
/// Foundation for page-type-specific commerce heuristics (category).
///
/// `Cart`/`Checkout` were deliberately removed (#commerce-cart-checkout-removal):
/// this tool audits one page per visit with no cross-page session/cart state,
/// so a cart or checkout URL reached cold is (almost) always empty or redirects
/// before rendering anything meaningful — there was never real content for any
/// page-kind-gated heuristic to act on.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CommercePageKind {
    ProductDetail,
    Category,
    #[default]
    Other,
}

/// Classify a shop page from its URL path and whether it carries Product schema.
pub fn detect_page_kind(url: &str, has_product_schema: bool) -> CommercePageKind {
    // Path including the leading slash (so "/kategorie/" needles match), host stripped.
    let after_scheme = url.split_once("://").map(|(_, rest)| rest).unwrap_or(url);
    let path = match after_scheme.find('/') {
        Some(i) => after_scheme[i..].to_lowercase(),
        None => String::new(),
    };
    let has = |needles: &[&str]| needles.iter().any(|n| path.contains(n));

    if has_product_schema || has(&["/product/", "/produkt/", "/p/", "/dp/", "/artikel/"]) {
        CommercePageKind::ProductDetail
    } else if has(&[
        "/category/",
        "/kategorie/",
        "/collection",
        "/collections/",
        "/c/",
        "/shop/",
        "/kategorien/",
    ]) {
        CommercePageKind::Category
    } else {
        CommercePageKind::Other
    }
}

/// Product structured-data completeness.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProductCommerce {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub price: Option<PriceInfo>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub availability: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delivery_time: Option<String>,
    pub shipping: ShippingInfo,
    pub returns: ReturnsInfo,
    pub reviews: ReviewInfo,
    /// Share of the 5 expected product signals exposed (0–100).
    pub score: u32,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PriceInfo {
    pub value: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub valid_until: Option<String>,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ShippingInfo {
    pub has_shipping_details: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shipping_rate: Option<String>,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ReturnsInfo {
    pub has_return_policy: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub return_days: Option<String>,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ReviewInfo {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rating_value: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub review_count: Option<String>,
}

/// Which mandatory/trust pages the page links to (by anchor text).
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct TrustPages {
    pub impressum: bool,
    pub agb: bool,
    pub widerruf: bool,
    pub versand: bool,
    pub zahlungsarten: bool,
    pub kontakt: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CommerceFindingKind {
    // Product structured data.
    MissingPrice,
    MissingAvailability,
    MissingShippingDetails,
    MissingReturnPolicy,
    MissingReviews,
    // Mandatory / trust pages.
    MissingImpressumLink,
    MissingAgbLink,
    MissingWiderrufLink,
    MissingShippingPageLink,
    MissingPaymentLink,
    MissingContactLink,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CommerceFinding {
    pub kind: CommerceFindingKind,
    pub severity: Severity,
    pub message: String,
}

/// Site-wide commerce roll-up across an audited batch (slice 2b).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CommerceSiteSummary {
    /// Trust pages linked on at least one audited page (union).
    pub trust_pages_linked: TrustPages,
    /// Mandatory/trust categories not linked anywhere in the audited set.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub missing_site_wide: Vec<CommerceFindingKind>,
    /// Number of audited pages carrying Product schema.
    pub product_pages: usize,
}

/// Aggregate per-page commerce results into a site-wide roll-up. Returns `None`
/// when no audited page produced commerce data (i.e. not a shop).
pub fn aggregate_site_commerce<'a>(
    commerces: impl Iterator<Item = &'a CommerceAnalysis>,
) -> Option<CommerceSiteSummary> {
    use CommerceFindingKind::*;
    let mut u = TrustPages::default();
    let mut product_pages = 0usize;
    let mut any = false;
    for c in commerces {
        any = true;
        if c.product.is_some() {
            product_pages += 1;
        }
        u.impressum |= c.trust_pages.impressum;
        u.agb |= c.trust_pages.agb;
        u.widerruf |= c.trust_pages.widerruf;
        u.versand |= c.trust_pages.versand;
        u.zahlungsarten |= c.trust_pages.zahlungsarten;
        u.kontakt |= c.trust_pages.kontakt;
    }
    if !any {
        return None;
    }
    let mut missing = Vec::new();
    if !u.impressum {
        missing.push(MissingImpressumLink);
    }
    if !u.widerruf {
        missing.push(MissingWiderrufLink);
    }
    if !u.agb {
        missing.push(MissingAgbLink);
    }
    if !u.versand {
        missing.push(MissingShippingPageLink);
    }
    if !u.zahlungsarten {
        missing.push(MissingPaymentLink);
    }
    if !u.kontakt {
        missing.push(MissingContactLink);
    }
    Some(CommerceSiteSummary {
        trust_pages_linked: u,
        missing_site_wide: missing,
        product_pages,
    })
}

const EXPECTED_PRODUCT_SIGNALS: u32 = 5;

/// Analyze commerce signals. `anchor_texts` are the page's link anchor texts
/// (from the screen-reader link inventory); `is_ecommerce_stack` is true when a
/// shop system (Shopify/WooCommerce/…) was detected; `has_identification_control`
/// is true when the screen-reader form control inventory found an
/// identification/authentication-purpose field (BFSGV §19 Nr. 3 signal, see
/// this module's doc comment). Returns `None` for pages with neither product
/// schema nor a shop stack (non-shop pages).
pub fn analyze_commerce(
    url: &str,
    structured_data: &StructuredData,
    anchor_texts: &[String],
    is_ecommerce_stack: bool,
    has_identification_control: bool,
) -> Option<CommerceAnalysis> {
    let product = analyze_product(structured_data);
    if product.is_none() && !is_ecommerce_stack {
        return None;
    }

    let page_kind = detect_page_kind(url, product.is_some());
    let trust_pages = detect_trust_pages(anchor_texts);

    let mut findings = Vec::new();
    if let Some(p) = &product {
        push_product_findings(p, &mut findings);
    }
    push_trust_findings(&trust_pages, &mut findings);

    let identification_function_bfsg_reference = has_identification_control
        .then(|| crate::screen_reader::bfsg::BFSG_PARAGRAPH_ECOMMERCE.to_string());

    Some(CommerceAnalysis {
        page_kind,
        product,
        trust_pages,
        identification_function_detected: has_identification_control,
        identification_function_bfsg_reference,
        findings,
    })
}

fn analyze_product(structured_data: &StructuredData) -> Option<ProductCommerce> {
    let product = structured_data
        .json_ld
        .iter()
        .find(|s| schema_is(&s.content, "Product") || schema_is(&s.content, "Offer"))?;
    let content = &product.content;
    let offer = first_offer(content);
    let offer_or_product = offer.unwrap_or(content);

    let price = extract_price(offer_or_product, content);
    let availability = str_field(offer_or_product, "availability").map(normalize_schema_token);
    let shipping = extract_shipping(offer_or_product, content);
    let delivery_time = extract_delivery_time(offer_or_product, content);
    let returns = extract_returns(offer_or_product, content);
    let reviews = extract_reviews(content);

    let present = [
        price.is_some(),
        availability.is_some(),
        shipping.has_shipping_details,
        returns.has_return_policy,
        reviews.rating_value.is_some(),
    ]
    .iter()
    .filter(|p| **p)
    .count() as u32;
    let score = (present * 100) / EXPECTED_PRODUCT_SIGNALS;

    Some(ProductCommerce {
        price,
        availability,
        delivery_time,
        shipping,
        returns,
        reviews,
        score,
    })
}

fn push_product_findings(p: &ProductCommerce, out: &mut Vec<CommerceFinding>) {
    use CommerceFindingKind::*;
    if p.price.is_none() {
        out.push(finding(MissingPrice, Severity::High));
    }
    if p.availability.is_none() {
        out.push(finding(MissingAvailability, Severity::Medium));
    }
    if !p.shipping.has_shipping_details {
        out.push(finding(MissingShippingDetails, Severity::Medium));
    }
    if !p.returns.has_return_policy {
        out.push(finding(MissingReturnPolicy, Severity::Medium));
    }
    if p.reviews.rating_value.is_none() {
        out.push(finding(MissingReviews, Severity::Low));
    }
}

fn push_trust_findings(t: &TrustPages, out: &mut Vec<CommerceFinding>) {
    use CommerceFindingKind::*;
    // German B2C duty pages weigh heaviest; AGB/shipping/payment are strong UX
    // expectations; contact is advisory. Wording stays "not linked", not "absent".
    if !t.impressum {
        out.push(finding(MissingImpressumLink, Severity::High));
    }
    if !t.widerruf {
        out.push(finding(MissingWiderrufLink, Severity::High));
    }
    if !t.agb {
        out.push(finding(MissingAgbLink, Severity::Medium));
    }
    if !t.versand {
        out.push(finding(MissingShippingPageLink, Severity::Medium));
    }
    if !t.zahlungsarten {
        out.push(finding(MissingPaymentLink, Severity::Low));
    }
    if !t.kontakt {
        out.push(finding(MissingContactLink, Severity::Low));
    }
}

/// Detect mandatory/trust page links from anchor texts (case-insensitive).
pub fn detect_trust_pages(anchor_texts: &[String]) -> TrustPages {
    let lower: Vec<String> = anchor_texts.iter().map(|t| t.to_lowercase()).collect();
    let any = |needles: &[&str]| lower.iter().any(|t| needles.iter().any(|n| t.contains(n)));
    TrustPages {
        impressum: any(&["impressum", "imprint", "legal notice"]),
        agb: any(&["agb", "allgemeine geschäftsbedingungen", "terms"]),
        widerruf: any(&["widerruf", "rückgabe", "retoure", "return"]),
        versand: any(&["versand", "lieferung", "shipping", "delivery"]),
        zahlungsarten: any(&["zahlung", "zahlart", "payment"]),
        kontakt: any(&["kontakt", "contact"]),
    }
}

fn finding(kind: CommerceFindingKind, severity: Severity) -> CommerceFinding {
    CommerceFinding {
        kind,
        severity,
        message: commerce_finding_text(kind, true),
    }
}

/// Single source of truth for finding wording (#406).
pub fn commerce_finding_text(kind: CommerceFindingKind, en: bool) -> String {
    use CommerceFindingKind::*;
    match (kind, en) {
        (MissingPrice, true) => {
            "No price exposed in the product's structured data (Offer.price).".into()
        }
        (MissingPrice, false) => {
            "Kein Preis in den strukturierten Produktdaten ausgewiesen (Offer.price).".into()
        }
        (MissingAvailability, true) => {
            "No availability exposed in the structured data (Offer.availability).".into()
        }
        (MissingAvailability, false) => {
            "Keine Verfügbarkeit in den strukturierten Daten ausgewiesen (Offer.availability).".into()
        }
        (MissingShippingDetails, true) => {
            "No shipping details in the structured data (OfferShippingDetails) — shipping cost and delivery time are not machine-readable.".into()
        }
        (MissingShippingDetails, false) => {
            "Keine Versandangaben in den strukturierten Daten (OfferShippingDetails) — Versandkosten und Lieferzeit sind nicht maschinenlesbar.".into()
        }
        (MissingReturnPolicy, true) => {
            "No return policy in the structured data (MerchantReturnPolicy).".into()
        }
        (MissingReturnPolicy, false) => {
            "Keine Rückgaberichtlinie in den strukturierten Daten (MerchantReturnPolicy).".into()
        }
        (MissingReviews, true) => {
            "No aggregate rating in the structured data (aggregateRating) — review stars cannot appear in search results.".into()
        }
        (MissingReviews, false) => {
            "Keine Sammelbewertung in den strukturierten Daten (aggregateRating) — Bewertungssterne können nicht in Suchergebnissen erscheinen.".into()
        }
        (MissingImpressumLink, true) => "No imprint (Impressum) link found on this page.".into(),
        (MissingImpressumLink, false) => "Kein Impressum-Link auf dieser Seite gefunden.".into(),
        (MissingWiderrufLink, true) => {
            "No right-of-withdrawal / returns (Widerruf/Retoure) link found on this page.".into()
        }
        (MissingWiderrufLink, false) => {
            "Kein Widerruf-/Retoure-Link auf dieser Seite gefunden.".into()
        }
        (MissingAgbLink, true) => "No terms (AGB) link found on this page.".into(),
        (MissingAgbLink, false) => "Kein AGB-Link auf dieser Seite gefunden.".into(),
        (MissingShippingPageLink, true) => {
            "No shipping-info (Versand/Lieferung) link found on this page.".into()
        }
        (MissingShippingPageLink, false) => {
            "Kein Versand-/Lieferungs-Link auf dieser Seite gefunden.".into()
        }
        (MissingPaymentLink, true) => {
            "No payment-methods (Zahlungsarten) link found on this page.".into()
        }
        (MissingPaymentLink, false) => {
            "Kein Zahlungsarten-Link auf dieser Seite gefunden.".into()
        }
        (MissingContactLink, true) => "No contact (Kontakt) link found on this page.".into(),
        (MissingContactLink, false) => "Kein Kontakt-Link auf dieser Seite gefunden.".into(),
    }
}

// ─── JSON-LD navigation helpers ────────────────────────────────────────────

fn schema_is(v: &Value, wanted: &str) -> bool {
    match v.get("@type") {
        Some(Value::String(s)) => s == wanted,
        Some(Value::Array(arr)) => arr.iter().any(|t| t.as_str() == Some(wanted)),
        _ => false,
    }
}

fn first_offer(content: &Value) -> Option<&Value> {
    match content.get("offers") {
        Some(Value::Object(_)) => content.get("offers"),
        Some(Value::Array(arr)) => arr.first(),
        _ => {
            if schema_is(content, "Offer") {
                Some(content)
            } else {
                None
            }
        }
    }
}

fn extract_price(offer: &Value, product: &Value) -> Option<PriceInfo> {
    let value = value_to_string(offer.get("price")).or_else(|| {
        offer
            .get("priceSpecification")
            .and_then(|ps| value_to_string(ps.get("price")))
    })?;
    let currency = str_field(offer, "priceCurrency")
        .or_else(|| str_field(product, "priceCurrency"))
        .or_else(|| {
            offer
                .get("priceSpecification")
                .and_then(|ps| str_field(ps, "priceCurrency"))
        });
    let valid_until = str_field(offer, "priceValidUntil");
    Some(PriceInfo {
        value,
        currency,
        valid_until,
    })
}

fn extract_shipping(offer: &Value, product: &Value) -> ShippingInfo {
    let details = offer
        .get("shippingDetails")
        .or_else(|| product.get("shippingDetails"));
    match details {
        Some(d) => ShippingInfo {
            has_shipping_details: true,
            shipping_rate: d
                .get("shippingRate")
                .and_then(|r| value_to_string(r.get("value"))),
        },
        None => ShippingInfo::default(),
    }
}

fn extract_delivery_time(offer: &Value, product: &Value) -> Option<String> {
    let details = offer
        .get("shippingDetails")
        .or_else(|| product.get("shippingDetails"))?;
    let dt = details.get("deliveryTime")?;
    let transit = dt
        .get("transitTime")
        .or_else(|| dt.get("handlingTime"))
        .and_then(|t| t.get("maxValue").or_else(|| t.get("minValue")))
        .and_then(value_to_string_owned);
    Some(transit.unwrap_or_else(|| "specified".to_string()))
}

fn extract_returns(offer: &Value, product: &Value) -> ReturnsInfo {
    let policy = offer
        .get("hasMerchantReturnPolicy")
        .or_else(|| product.get("hasMerchantReturnPolicy"))
        .or_else(|| {
            if schema_is(product, "MerchantReturnPolicy") {
                Some(product)
            } else {
                None
            }
        });
    match policy {
        Some(p) => ReturnsInfo {
            has_return_policy: true,
            return_days: value_to_string(p.get("merchantReturnDays")),
        },
        None => ReturnsInfo::default(),
    }
}

fn extract_reviews(product: &Value) -> ReviewInfo {
    match product.get("aggregateRating") {
        Some(a) => ReviewInfo {
            rating_value: value_to_string(a.get("ratingValue")),
            review_count: value_to_string(a.get("reviewCount"))
                .or_else(|| value_to_string(a.get("ratingCount"))),
        },
        None => ReviewInfo::default(),
    }
}

fn str_field(v: &Value, key: &str) -> Option<String> {
    v.get(key).and_then(|x| x.as_str()).map(str::to_string)
}

fn value_to_string(v: Option<&Value>) -> Option<String> {
    v.and_then(value_to_string_owned)
}

fn value_to_string_owned(v: &Value) -> Option<String> {
    match v {
        Value::String(s) if !s.trim().is_empty() => Some(s.clone()),
        Value::Number(n) => Some(n.to_string()),
        _ => None,
    }
}

fn normalize_schema_token(s: String) -> String {
    s.rsplit('/').next().unwrap_or(&s).to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::seo::schema::JsonLdSchema;

    fn structured(content: Value) -> StructuredData {
        StructuredData {
            json_ld: vec![JsonLdSchema {
                schema_type: content
                    .get("@type")
                    .and_then(|t| t.as_str())
                    .unwrap_or("")
                    .to_string(),
                schema_types: vec![],
                content,
                is_valid: true,
            }],
            types: vec![],
            has_structured_data: true,
            rich_snippets_potential: vec![],
            schema_issues: vec![],
            rule_assessments: vec![],
            fit_assessment: None,
            ..Default::default()
        }
    }

    fn empty() -> StructuredData {
        StructuredData {
            json_ld: vec![],
            types: vec![],
            has_structured_data: false,
            rich_snippets_potential: vec![],
            schema_issues: vec![],
            rule_assessments: vec![],
            fit_assessment: None,
            ..Default::default()
        }
    }

    #[test]
    fn non_shop_page_returns_none() {
        let sd = structured(serde_json::json!({"@type": "Article", "headline": "x"}));
        assert!(analyze_commerce("https://x.de/blog/post", &sd, &[], false, false).is_none());
    }

    #[test]
    fn ecommerce_stack_without_product_schema_still_analyzes_trust_pages() {
        let c = analyze_commerce(
            "https://shop.de/kategorie/schuhe",
            &empty(),
            &["Impressum".into(), "Kontakt".into()],
            true,
            false,
        )
        .expect("ecommerce stack activates commerce");
        assert_eq!(c.page_kind, CommercePageKind::Category);
        assert!(c.product.is_none());
        assert!(c.trust_pages.impressum);
        assert!(c.trust_pages.kontakt);
        assert!(!c.trust_pages.widerruf);
        // Widerruf/AGB/Versand/Zahlung missing → findings.
        assert!(c
            .findings
            .iter()
            .any(|f| f.kind == CommerceFindingKind::MissingWiderrufLink));
        assert!(!c.identification_function_detected);
        assert!(c.identification_function_bfsg_reference.is_none());
    }

    #[test]
    fn identification_control_sets_bfsgv19_scope_signal() {
        let c = analyze_commerce(
            "https://shop.de/mein-konto/anmelden",
            &empty(),
            &[],
            true,
            true,
        )
        .expect("ecommerce stack activates commerce");
        assert!(c.identification_function_detected);
        assert_eq!(
            c.identification_function_bfsg_reference.as_deref(),
            Some("§ 19 Nr. 3 BFSGV")
        );
    }

    #[test]
    fn full_product_with_all_trust_pages_has_no_findings() {
        let sd = structured(serde_json::json!({
            "@type": "Product",
            "aggregateRating": {"ratingValue": "4.6", "reviewCount": "120"},
            "offers": {
                "@type": "Offer",
                "price": "19.99",
                "priceCurrency": "EUR",
                "availability": "https://schema.org/InStock",
                "shippingDetails": {"@type": "OfferShippingDetails", "shippingRate": {"value": "3.90"}},
                "hasMerchantReturnPolicy": {"@type": "MerchantReturnPolicy", "merchantReturnDays": "30"}
            }
        }));
        let anchors: Vec<String> = [
            "Impressum",
            "AGB",
            "Widerruf",
            "Versand",
            "Zahlungsarten",
            "Kontakt",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
        let c = analyze_commerce(
            "https://shop.de/produkt/widget",
            &sd,
            &anchors,
            false,
            false,
        )
        .expect("product");
        assert_eq!(c.page_kind, CommercePageKind::ProductDetail);
        assert_eq!(c.product.unwrap().score, 100);
        assert!(c.findings.is_empty());
    }

    #[test]
    fn page_kind_classification() {
        use CommercePageKind::*;
        assert_eq!(
            detect_page_kind("https://s.de/produkt/abc", false),
            ProductDetail
        );
        // Product schema alone classifies as product detail even on a bare URL.
        assert_eq!(detect_page_kind("https://s.de/x", true), ProductDetail);
        assert_eq!(
            detect_page_kind("https://s.de/kategorie/schuhe", false),
            Category
        );
        assert_eq!(detect_page_kind("https://s.de/ueber-uns", false), Other);
        // Cart/Checkout paths no longer get a dedicated classification (removed —
        // see CommercePageKind's doc comment) and fall through to Other/ProductDetail
        // like any other non-category, non-product-schema URL would.
        assert_eq!(detect_page_kind("https://s.de/warenkorb", false), Other);
        assert_eq!(
            detect_page_kind("https://s.de/checkout/step2", false),
            Other
        );
    }

    #[test]
    fn trust_page_keywords_match_variants() {
        let t = detect_trust_pages(&[
            "Allgemeine Geschäftsbedingungen".into(),
            "Rückgabe & Retoure".into(),
            "Lieferung".into(),
        ]);
        assert!(t.agb);
        assert!(t.widerruf);
        assert!(t.versand);
        assert!(!t.impressum);
    }

    #[test]
    fn english_finding_text_has_no_german_umlauts() {
        for kind in [
            CommerceFindingKind::MissingPrice,
            CommerceFindingKind::MissingAvailability,
            CommerceFindingKind::MissingShippingDetails,
            CommerceFindingKind::MissingReturnPolicy,
            CommerceFindingKind::MissingReviews,
            CommerceFindingKind::MissingImpressumLink,
            CommerceFindingKind::MissingAgbLink,
            CommerceFindingKind::MissingWiderrufLink,
            CommerceFindingKind::MissingShippingPageLink,
            CommerceFindingKind::MissingPaymentLink,
            CommerceFindingKind::MissingContactLink,
        ] {
            let t = commerce_finding_text(kind, true);
            assert!(
                !t.chars().any(|c| "äöüÄÖÜß".contains(c)),
                "EN text has umlaut: {t}"
            );
        }
    }
}