cooklang-import 0.8.2

A tool for importing recipes into Cooklang format
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
use super::{Extractor, ParsingContext};
use crate::model::Recipe;
use html_escape::decode_html_entities;
use log::debug;
use scraper::Selector;
use serde::Deserialize;
use serde_json::Value;
use std::collections::HashMap;
use std::convert::TryFrom;

pub struct JsonLdExtractor;

impl JsonLdExtractor {
    fn convert_to_recipe(&self, json_ld_recipe: JsonLdRecipe, url: &str) -> Recipe {
        let mut metadata = HashMap::new();

        // Add source URL (primary key: source)
        metadata.insert("source".to_string(), url.to_string());

        // Map author
        if let Some(author) = json_ld_recipe.author {
            let author_name = match author {
                Author::String(name) => Some(name),
                Author::Object(obj) => obj.name,
                Author::Multiple(authors) => {
                    let names: Vec<String> = authors.into_iter().filter_map(|a| a.name).collect();
                    if names.is_empty() {
                        None
                    } else {
                        Some(names.join(", "))
                    }
                }
            };
            if let Some(name) = author_name {
                if !name.is_empty() {
                    metadata.insert("author".to_string(), name);
                }
            }
        }

        // Map servings (primary key according to Cooklang conventions)
        if let Some(yield_val) = json_ld_recipe.recipe_yield {
            let yield_str = match yield_val {
                RecipeYield::String(s) => s,
                RecipeYield::Number(n) => n.to_string(),
                RecipeYield::Array(arr) => {
                    // For arrays, prefer the descriptive version (e.g., "15 Stück") over just the number
                    arr.iter()
                        .find(|s| s.contains(char::is_alphabetic))
                        .or_else(|| arr.first())
                        .cloned()
                        .unwrap_or_default()
                }
            };
            if !yield_str.is_empty() {
                metadata.insert("servings".to_string(), yield_str);
            }
        }

        // Map course (primary key according to Cooklang conventions)
        if let Some(category) = json_ld_recipe.recipe_category {
            let category_str = match category {
                RecipeCategory::String(s) => s,
                RecipeCategory::Multiple(v) => v.join(", "),
            };
            if !category_str.is_empty() {
                metadata.insert("course".to_string(), category_str);
            }
        }

        // Map time fields (use specific keys, not duplicates)
        if let Some(total_time) = json_ld_recipe.total_time {
            if !total_time.is_empty() {
                metadata.insert("time required".to_string(), convert_duration(&total_time));
            }
        }

        if let Some(prep_time) = json_ld_recipe.prep_time {
            if !prep_time.is_empty() {
                metadata.insert("prep time".to_string(), convert_duration(&prep_time));
            }
        }

        if let Some(cook_time) = json_ld_recipe.cook_time {
            if !cook_time.is_empty() {
                metadata.insert("cook time".to_string(), convert_duration(&cook_time));
            }
        }

        // Map cuisine
        if let Some(cuisine) = json_ld_recipe.recipe_cuisine {
            let cuisine_str = match cuisine {
                RecipeCuisine::String(s) => s,
                RecipeCuisine::Multiple(v) => v.join(", "),
            };
            if !cuisine_str.is_empty() {
                metadata.insert("cuisine".to_string(), cuisine_str);
            }
        }

        // Map diet restrictions
        if let Some(diet) = json_ld_recipe.suitable_for_diet {
            let diet_str = match diet {
                SuitableForDiet::String(s) => clean_diet_value(&s),
                SuitableForDiet::Multiple(v) => v
                    .iter()
                    .map(|d| clean_diet_value(d))
                    .collect::<Vec<String>>()
                    .join(", "),
            };
            metadata.insert("diet".to_string(), diet_str);
        }

        // Map keywords as tags
        if let Some(keywords) = json_ld_recipe.keywords {
            let tags = match keywords {
                Keywords::String(s) => s,
                Keywords::Multiple(v) => v.join(", "),
            };
            if !tags.is_empty() {
                metadata.insert("tags".to_string(), tags);
            }
        }

        // Map image (use the first image if multiple are available)
        if let Some(ref img) = json_ld_recipe.image {
            let image_url = match img {
                ImageType::String(i) => Some(decode_html_symbols(i)),
                ImageType::MultipleStrings(imgs) if !imgs.is_empty() => {
                    Some(decode_html_symbols(&imgs[0]))
                }
                ImageType::Object(i) => Some(i.url.clone()),
                ImageType::MultipleObjects(imgs) if !imgs.is_empty() => Some(imgs[0].url.clone()),
                _ => None,
            };
            if let Some(url) = image_url {
                if !url.is_empty() {
                    metadata.insert("image".to_string(), url);
                }
            }
        }

        // Extract ingredients as Vec<String>
        let ingredients = match json_ld_recipe.recipe_ingredient {
            Some(RecipeIngredients::Strings(ingredients)) => ingredients
                .into_iter()
                .filter(|ing| !ing.trim().is_empty())
                .map(|ing| decode_html_symbols(&ing))
                .collect::<Vec<String>>(),
            Some(RecipeIngredients::Objects(ingredients)) => ingredients
                .into_iter()
                .filter(|ing| !ing.name.trim().is_empty())
                .map(|ing| {
                    let amount = ing.amount.as_deref().unwrap_or("").trim();
                    let name = decode_html_symbols(&ing.name);
                    if amount.is_empty() {
                        name
                    } else {
                        format!("{amount} {name}")
                    }
                })
                .collect::<Vec<String>>(),
            None => Vec::new(),
        };

        let instructions = match json_ld_recipe.recipe_instructions {
            Some(instructions) => match instructions {
                RecipeInstructions::String(instructions) => decode_html_symbols(&instructions),
                RecipeInstructions::Multiple(instructions) => instructions
                    .into_iter()
                    .map(|step| decode_html_symbols(&step))
                    .collect::<Vec<String>>()
                    .join("\n\n"),
                RecipeInstructions::MultipleObject(instructions) => instructions
                    .iter()
                    .map(|obj| decode_html_symbols(&obj.text))
                    .collect::<Vec<String>>()
                    .join("\n\n"),
                RecipeInstructions::HowTo(sections) => {
                    let mut texts = Vec::new();
                    for howto in sections {
                        match howto {
                            HowTo::HowToStep(step) => {
                                // Prefer text over name
                                if let Some(text) = step.text {
                                    texts.push(decode_html_symbols(&text));
                                } else if let Some(name) = step.name {
                                    texts.push(decode_html_symbols(&name));
                                }
                                if let Some(desc) = step.description {
                                    texts.push(decode_html_symbols(&desc));
                                }
                            }
                            HowTo::HowToSection(section) => {
                                // Add section header if present (with extra blank line before)
                                if let Some(section_name) = section.name {
                                    let header = format!(
                                        "\n## {}",
                                        decode_html_symbols(&section_name).trim_end_matches(':')
                                    );
                                    texts.push(header);
                                }
                                // Add steps from section
                                for step in section.item_list_element {
                                    if let Some(text) = step.text {
                                        texts.push(decode_html_symbols(&text));
                                    } else if let Some(name) = step.name {
                                        texts.push(decode_html_symbols(&name));
                                    }
                                    if let Some(desc) = step.description {
                                        texts.push(decode_html_symbols(&desc));
                                    }
                                }
                            }
                        }
                    }
                    texts.join("\n\n")
                }
                RecipeInstructions::NestedSections(sections) => {
                    let mut texts = Vec::new();
                    for outer_section in sections {
                        for howto in outer_section {
                            match howto {
                                HowTo::HowToStep(step) => {
                                    if let Some(text) = step.text {
                                        texts.push(decode_html_symbols(&text));
                                    } else if let Some(name) = step.name {
                                        texts.push(decode_html_symbols(&name));
                                    }
                                    if let Some(desc) = step.description {
                                        texts.push(decode_html_symbols(&desc));
                                    }
                                }
                                HowTo::HowToSection(section) => {
                                    // Add section header if present
                                    if let Some(section_name) = section.name {
                                        let header = format!(
                                            "## {}",
                                            decode_html_symbols(&section_name)
                                                .trim_end_matches(':')
                                        );
                                        texts.push(header);
                                    }
                                    // Add steps from section
                                    for step in section.item_list_element {
                                        if let Some(text) = step.text {
                                            texts.push(decode_html_symbols(&text));
                                        } else if let Some(name) = step.name {
                                            texts.push(decode_html_symbols(&name));
                                        }
                                        if let Some(desc) = step.description {
                                            texts.push(decode_html_symbols(&desc));
                                        }
                                    }
                                }
                            }
                        }
                    }
                    texts.join("\n\n")
                }
            },
            None => String::new(),
        };

        Recipe {
            name: decode_html_symbols(&json_ld_recipe.name),
            description: json_ld_recipe.description.and_then(|desc| match desc {
                DescriptionType::String(d) => {
                    let decoded = decode_html_symbols(&d);
                    if decoded.is_empty() {
                        None
                    } else {
                        Some(decoded)
                    }
                }
                DescriptionType::Object(d) => {
                    let decoded = decode_html_symbols(&d.text);
                    if decoded.is_empty() {
                        None
                    } else {
                        Some(decoded)
                    }
                }
            }),
            image: json_ld_recipe.image.map_or(vec![], |img| match img {
                ImageType::String(i) => vec![decode_html_symbols(&i)],
                ImageType::MultipleStrings(imgs) => {
                    imgs.into_iter().map(|i| decode_html_symbols(&i)).collect()
                }
                ImageType::MultipleObjects(imgs) => imgs.into_iter().map(|i| i.url).collect(),
                ImageType::None => vec![],
                ImageType::Object(i) => vec![i.url],
            }),
            ingredients,
            instructions,
            metadata,
        }
    }
}

#[derive(Debug, Deserialize)]
struct JsonLdRecipe {
    name: String,
    description: Option<DescriptionType>,
    image: Option<ImageType>,
    #[serde(rename = "recipeIngredient")]
    recipe_ingredient: Option<RecipeIngredients>,
    #[serde(rename = "recipeInstructions")]
    recipe_instructions: Option<RecipeInstructions>,
    #[serde(rename = "recipeYield")]
    recipe_yield: Option<RecipeYield>,
    #[serde(rename = "prepTime")]
    prep_time: Option<String>,
    #[serde(rename = "cookTime")]
    cook_time: Option<String>,
    #[serde(rename = "totalTime")]
    total_time: Option<String>,
    #[serde(rename = "suitableForDiet")]
    suitable_for_diet: Option<SuitableForDiet>,
    #[serde(rename = "recipeCategory")]
    recipe_category: Option<RecipeCategory>,
    #[serde(rename = "recipeCuisine")]
    recipe_cuisine: Option<RecipeCuisine>,
    keywords: Option<Keywords>,
    author: Option<Author>,
}

#[derive(Debug, Deserialize)]
struct ImageObject {
    url: String,
}

#[derive(Debug, Deserialize)]
struct TextObject {
    text: String,
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum DescriptionType {
    String(String),
    Object(TextObject),
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum ImageType {
    None,
    String(String),
    Object(ImageObject),
    // potentially multiple images as objects
    MultipleStrings(Vec<String>),
    MultipleObjects(Vec<ImageObject>),
}

#[derive(Debug, Deserialize)]
struct RecipeInstructionObject {
    text: String,
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum RecipeIngredients {
    Strings(Vec<String>),
    Objects(Vec<IngredientObject>),
}

#[derive(Debug, Deserialize)]
struct IngredientObject {
    name: String,
    amount: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum RecipeInstructions {
    String(String),
    Multiple(Vec<String>),
    MultipleObject(Vec<RecipeInstructionObject>),
    HowTo(Vec<HowTo>),
    NestedSections(Vec<Vec<HowTo>>),
}

#[derive(Debug, Deserialize)]
#[serde(tag = "@type")]
enum HowTo {
    HowToStep(HowToStep),
    HowToSection(HowToSection),
}

#[derive(Debug, Deserialize)]
#[serde(tag = "@type")]
struct HowToStep {
    text: Option<String>,
    description: Option<String>,
    name: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(tag = "@type")]
struct HowToSection {
    /// Section name/title (e.g., "How to Make Meat Sauce")
    name: Option<String>,
    #[serde(rename = "itemListElement")]
    item_list_element: Vec<HowToStep>,
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum RecipeYield {
    String(String),
    Number(i32),
    Array(Vec<String>),
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum SuitableForDiet {
    String(String),
    Multiple(Vec<String>),
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum Keywords {
    String(String),
    Multiple(Vec<String>),
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum Author {
    String(String),
    Object(AuthorObject),
    Multiple(Vec<AuthorObject>),
}

#[derive(Debug, Deserialize)]
struct AuthorObject {
    name: Option<String>,
    #[serde(rename = "@id")]
    _id: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum RecipeCategory {
    String(String),
    Multiple(Vec<String>),
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum RecipeCuisine {
    String(String),
    Multiple(Vec<String>),
}

impl TryFrom<&Value> for JsonLdRecipe {
    type Error = serde_json::Error;

    fn try_from(value: &Value) -> Result<Self, Self::Error> {
        serde_json::from_value(value.clone())
    }
}

fn decode_html_symbols(text: &str) -> String {
    // for some reason need to decode twice to get the correct string
    decode_html_entities(&decode_html_entities(text)).into_owned()
}

fn clean_diet_value(diet: &str) -> String {
    // Remove schema.org URLs and clean up diet values
    diet.trim_start_matches("https://schema.org/")
        .trim_start_matches("http://schema.org/")
        .replace("Diet", "")
        .trim()
        .to_string()
}

fn convert_duration(duration: &str) -> String {
    // Convert ISO 8601 duration to human-readable format
    // e.g., PT30M -> 30 minutes, PT1H30M -> 1 hour 30 minutes
    // Also handle ranges like PT15-20M and seconds like PT5400.0S
    if let Some(duration) = duration.strip_prefix("PT") {
        let mut result = String::new();

        // Handle hours
        if let Some(h_pos) = duration.find('H') {
            let hours: u32 = duration[..h_pos].parse().unwrap_or(0);
            result.push_str(&format!(
                "{} hour{}",
                hours,
                if hours == 1 { "" } else { "s" }
            ));
        }

        // Handle minutes (including ranges)
        if let Some(m_pos) = duration.find('M') {
            let start = duration.find('H').map(|p| p + 1).unwrap_or(0);
            let minutes_str = &duration[start..m_pos];

            // Check if it's a range (e.g., "15-20")
            if minutes_str.contains('-') {
                // For ranges, just use the full range string
                if !result.is_empty() {
                    result.push(' ');
                }
                result.push_str(&format!("{minutes_str} minutes"));
            } else if let Ok(minutes) = minutes_str.parse::<u32>() {
                // Convert minutes > 60 to hours and minutes
                if minutes >= 60 {
                    let hours = minutes / 60;
                    let remaining_minutes = minutes % 60;

                    if !result.is_empty() {
                        result.push(' ');
                    }
                    result.push_str(&format!(
                        "{} hour{}",
                        hours,
                        if hours == 1 { "" } else { "s" }
                    ));

                    if remaining_minutes > 0 {
                        result.push_str(&format!(
                            " {} minute{}",
                            remaining_minutes,
                            if remaining_minutes == 1 { "" } else { "s" }
                        ));
                    }
                } else {
                    if !result.is_empty() {
                        result.push(' ');
                    }
                    result.push_str(&format!(
                        "{} minute{}",
                        minutes,
                        if minutes == 1 { "" } else { "s" }
                    ));
                }
            }
        }

        // Handle seconds (including decimal values like 5400.0S)
        if let Some(s_pos) = duration.find('S') {
            let start = duration.rfind(['H', 'M']).map(|p| p + 1).unwrap_or(0);
            let seconds_str = &duration[start..s_pos];

            if let Ok(seconds) = seconds_str.parse::<f64>() {
                let total_minutes = (seconds / 60.0).round() as u32;
                let hours = total_minutes / 60;
                let minutes = total_minutes % 60;

                result.clear(); // Clear any existing result

                if hours > 0 {
                    result.push_str(&format!(
                        "{} hour{}",
                        hours,
                        if hours == 1 { "" } else { "s" }
                    ));
                }

                if minutes > 0 {
                    if !result.is_empty() {
                        result.push(' ');
                    }
                    result.push_str(&format!(
                        "{} minute{}",
                        minutes,
                        if minutes == 1 { "" } else { "s" }
                    ));
                }
            }
        }

        if result.is_empty() {
            duration.to_string()
        } else {
            result
        }
    } else {
        duration.to_string()
    }
}

fn is_recipe_type(value: &Value) -> bool {
    if let Some(type_value) = value.get("@type") {
        if let Some(type_str) = type_value.as_str() {
            return type_str.eq_ignore_ascii_case("recipe");
        }
    }
    false
}

impl Extractor for JsonLdExtractor {
    fn parse(&self, context: &ParsingContext) -> Result<Recipe, Box<dyn std::error::Error>> {
        debug!("JsonLdExtractor: Starting parse for URL: {}", context.url);
        let selector = Selector::parse("script[type='application/ld+json']").unwrap();
        let document = &context.document;

        let scripts: Vec<_> = document.select(&selector).collect();
        debug!(
            "JsonLdExtractor: Found {} JSON-LD script tags",
            scripts.len()
        );

        // Try each script element until we find a valid recipe
        for (index, script) in scripts.iter().enumerate() {
            let raw_json = script.inner_html();
            debug!(
                "JsonLdExtractor: Script {} raw content: {}",
                index, raw_json
            );

            let cleaned_json = sanitize_json(&raw_json);
            match serde_json::from_str::<Value>(&cleaned_json) {
                Ok(json_ld) => {
                    debug!(
                        "JsonLdExtractor: Successfully parsed JSON-LD {}: {:#?}",
                        index, json_ld
                    );

                    let recipe_json = if json_ld.is_array() {
                        debug!("JsonLdExtractor: JSON-LD is an array");
                        json_ld.as_array().and_then(|arr| {
                            arr.iter()
                                .find(|item| {
                                    let has_instructions = item.get("recipeInstructions").is_some();
                                    let is_recipe = is_recipe_type(item);
                                    debug!("JsonLdExtractor: Array item - has_instructions: {}, is_recipe: {}", has_instructions, is_recipe);
                                    has_instructions || is_recipe
                                })
                        })
                    } else if is_recipe_type(&json_ld) {
                        debug!("JsonLdExtractor: Found Recipe type in root");
                        Some(&json_ld)
                    } else if let Some(graph) = json_ld.get("@graph") {
                        debug!("JsonLdExtractor: Found @graph");
                        graph.as_array().and_then(|arr| {
                            arr.iter().find(|item| {
                                let is_recipe = is_recipe_type(item);
                                debug!("JsonLdExtractor: @graph item - is_recipe: {}", is_recipe);
                                is_recipe
                            })
                        })
                    } else {
                        debug!("JsonLdExtractor: No recipe found in this JSON-LD");
                        None
                    };

                    if let Some(recipe) = recipe_json {
                        debug!("JsonLdExtractor: Found recipe JSON: {:#?}", recipe);
                        match JsonLdRecipe::try_from(recipe) {
                            Ok(recipe) => {
                                debug!("JsonLdExtractor: Successfully converted to JsonLdRecipe");
                                return Ok(self.convert_to_recipe(recipe, &context.url));
                            }
                            Err(e) => {
                                debug!("JsonLdExtractor: Failed to convert to JsonLdRecipe: {}", e);
                            }
                        }
                    }
                }
                Err(e) => {
                    debug!("JsonLdExtractor: Failed to parse JSON-LD {}: {}", index, e);
                }
            }
        }

        let error_msg = "No valid recipe found in any JSON-LD script";
        debug!("JsonLdExtractor: {}", error_msg);
        Err(error_msg.into())
    }
}

fn sanitize_json(json_str: &str) -> String {
    debug!("Original JSON: {}", json_str);

    let mut minified = String::with_capacity(json_str.len());
    let mut in_string = false;
    let mut prev_char = None;
    let mut depth = 0;
    let chars: Vec<char> = json_str.chars().collect();

    for (i, &c) in chars.iter().enumerate() {
        match c {
            '"' if prev_char != Some('\\') => {
                in_string = !in_string;
                if !in_string {
                    // We're ending a string - check if we need a comma
                    let rest_chars = chars.get(i + 1..).unwrap_or(&[]);
                    let next_char = rest_chars.iter().find(|c| !c.is_whitespace());
                    if !matches!(prev_char, Some(',') | Some('[') | Some('{'))
                        && matches!(next_char, Some('"' | '[' | '{'))
                    {
                        debug!("Adding missing comma after string");
                        minified.push('"');
                        minified.push(',');
                        prev_char = Some(',');
                        continue;
                    }
                }
                minified.push(c);
            }
            '[' | '{' if !in_string => {
                depth += 1;
                minified.push(c);
            }
            ']' | '}' if !in_string => {
                depth -= 1;
                minified.push(c);
                // Check if we need a comma after array/object closing
                if let Some(rest_chars) = chars.get(i + 1..) {
                    let next_char = rest_chars.iter().find(|&&c| !c.is_whitespace());
                    if depth > 0 && matches!(next_char, Some(&'"')) {
                        debug!("Adding missing comma after array/object closing");
                        minified.push(',');
                        prev_char = Some(',');
                        continue;
                    }
                }
            }
            ',' if !in_string => {
                // Avoid duplicate commas
                if prev_char != Some(',') {
                    minified.push(c);
                }
            }
            ':' if !in_string => {
                // Handle malformed key-value pairs
                if prev_char == Some(',') {
                    minified.pop(); // Remove the extra comma
                }
                minified.push(c);
            }
            _ => {
                if in_string || !c.is_whitespace() {
                    minified.push(c);
                }
            }
        }
        prev_char = Some(c);
    }

    // Clean up any remaining issues
    let cleaned = minified
        .replace(",]", "]")
        .replace(",}", "}")
        .replace(",,", ",")
        .replace(",:,", ":")
        .replace(":,", ":")
        .replace(",:", ":");

    debug!("Sanitized JSON: {}", cleaned);
    cleaned
}

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

    fn create_html_document(json_ld: &str) -> String {
        format!(
            r#"
            <!DOCTYPE html>
            <html>
            <head>
                <script type="application/ld+json">
                    {json_ld}
                </script>
            </head>
            <body></body>
            </html>
            "#
        )
    }

    #[test]
    fn test_parse_success() {
        let html = "<html><body>Test</body></html>";
        let document = Html::parse_document(html);
        let context = ParsingContext {
            url: "http://example.com".to_string(),
            document,
            texts: None,
        };
        let extractor = JsonLdExtractor;
        // Just verify that parse returns an error for invalid input
        assert!(extractor.parse(&context).is_err());
    }

    #[test]
    fn test_parse_basic_recipe() {
        let extractor = JsonLdExtractor;
        let json_ld = r#"
        {
            "@context": "https://schema.org/",
            "@type": "Recipe",
            "name": "Chocolate Chip Cookies",
            "description": "Delicious homemade cookies",
            "image": "https://example.com/cookie.jpg",
            "recipeIngredient": ["flour", "sugar", "chocolate chips"],
            "recipeInstructions": "Mix ingredients. Bake at 350F for 10 minutes.",
            "author": "Jane Doe",
            "prepTime": "PT15M",
            "cookTime": "PT10M",
            "totalTime": "PT25M",
            "recipeYield": "24 cookies",
            "recipeCategory": "Dessert",
            "recipeCuisine": "American",
            "keywords": "chocolate, cookies, baking"
        }
        "#;
        let html_str = create_html_document(json_ld);
        let document = Html::parse_document(&html_str);
        let context = ParsingContext {
            url: "http://example.com".to_string(),
            document,
            texts: None,
        };

        let result = extractor.parse(&context).unwrap();

        assert_eq!(result.name, "Chocolate Chip Cookies");
        assert_eq!(
            result.description,
            Some("Delicious homemade cookies".to_string())
        );
        assert_eq!(result.image, vec!["https://example.com/cookie.jpg"]);
        assert_eq!(
            result.ingredients,
            vec!["flour", "sugar", "chocolate chips"]
        );
        assert_eq!(
            result.instructions,
            "Mix ingredients. Bake at 350F for 10 minutes."
        );

        // Test metadata mappings
        assert_eq!(result.metadata.get("source").unwrap(), "http://example.com");
        assert_eq!(result.metadata.get("author").unwrap(), "Jane Doe");
        assert_eq!(result.metadata.get("prep time").unwrap(), "15 minutes");
        assert_eq!(result.metadata.get("cook time").unwrap(), "10 minutes");
        assert_eq!(result.metadata.get("time required").unwrap(), "25 minutes");
        assert_eq!(result.metadata.get("servings").unwrap(), "24 cookies");
        assert_eq!(result.metadata.get("course").unwrap(), "Dessert");
        assert_eq!(result.metadata.get("cuisine").unwrap(), "American");
        assert_eq!(
            result.metadata.get("tags").unwrap(),
            "chocolate, cookies, baking"
        );
    }

    #[test]
    fn test_duration_conversion() {
        assert_eq!(convert_duration("PT30M"), "30 minutes");
        assert_eq!(convert_duration("PT1H"), "1 hour");
        assert_eq!(convert_duration("PT1H30M"), "1 hour 30 minutes");
        assert_eq!(convert_duration("PT90M"), "1 hour 30 minutes");
        assert_eq!(convert_duration("PT2H15M"), "2 hours 15 minutes");
        assert_eq!(convert_duration("invalid"), "invalid");
        // Test ranges
        assert_eq!(convert_duration("PT15-20M"), "15-20 minutes");
        assert_eq!(convert_duration("PT25-30M"), "25-30 minutes");
        // Test seconds
        assert_eq!(convert_duration("PT5400S"), "1 hour 30 minutes");
        assert_eq!(convert_duration("PT5400.0S"), "1 hour 30 minutes");
        assert_eq!(convert_duration("PT300S"), "5 minutes");
        // Test large minute values
        assert_eq!(convert_duration("PT150M"), "2 hours 30 minutes");
        assert_eq!(convert_duration("PT180M"), "3 hours");
        assert_eq!(convert_duration("PT65M"), "1 hour 5 minutes");
    }

    #[test]
    fn test_metadata_with_source_url() {
        let extractor = JsonLdExtractor;
        let json_ld = r#"
        {
            "@context": "https://schema.org/",
            "@type": "Recipe",
            "name": "Test Recipe",
            "description": "A test recipe",
            "image": "https://example.com/image.jpg",
            "recipeIngredient": ["ingredient 1"],
            "recipeInstructions": "Step 1",
            "suitableForDiet": "GlutenFree",
            "keywords": ["healthy", "quick", "easy"]
        }
        "#;
        let html_str = create_html_document(json_ld);
        let document = Html::parse_document(&html_str);
        let context = ParsingContext {
            url: "http://example.com".to_string(),
            document,
            texts: None,
        };

        let result = extractor.parse(&context).unwrap();

        assert_eq!(result.metadata.get("diet").unwrap(), "GlutenFree");
        assert_eq!(result.metadata.get("tags").unwrap(), "healthy, quick, easy");
    }

    #[test]
    fn test_parse_recipe_with_array() {
        let extractor = JsonLdExtractor;
        let json_ld = r#"
        [
            {
                "@context": "https://schema.org/",
                "@type": "Recipe",
                "name": "Pasta Carbonara",
                "description": "Classic Italian pasta dish",
                "image": ["https://example.com/carbonara1.jpg", "https://example.com/carbonara2.jpg"],
                "recipeIngredient": ["spaghetti", "eggs", "bacon", "cheese"],
                "recipeInstructions": [
                    {"@type": "HowToStep", "text": "Cook pasta"},
                    {"@type": "HowToStep", "text": "Fry bacon"},
                    {"@type": "HowToStep", "text": "Mix eggs and cheese"},
                    {"@type": "HowToStep", "text": "Combine all ingredients"}
                ],
                "author": {
                    "@type": "Person",
                    "name": "Chef Mario"
                },
                "recipeYield": 4,
                "suitableForDiet": ["GlutenFree", "LowCarb"],
                "recipeCuisine": "Italian"
            },
            {
                "@type": "WebSite",
                "name": "Recipe Website"
            }
        ]
        "#;
        let html_str = create_html_document(json_ld);
        let document = Html::parse_document(&html_str);
        let context = ParsingContext {
            url: "http://example.com".to_string(),
            document,
            texts: None,
        };

        let result = extractor.parse(&context).unwrap();

        assert_eq!(result.name, "Pasta Carbonara");
        assert_eq!(
            result.description,
            Some("Classic Italian pasta dish".to_string())
        );
        assert_eq!(
            result.image,
            vec![
                "https://example.com/carbonara1.jpg",
                "https://example.com/carbonara2.jpg"
            ]
        );
        assert_eq!(
            result.ingredients,
            vec!["spaghetti", "eggs", "bacon", "cheese"]
        );
        assert_eq!(
            result.instructions,
            "Cook pasta\n\nFry bacon\n\nMix eggs and cheese\n\nCombine all ingredients"
        );

        // Test metadata extraction for complex types
        assert_eq!(result.metadata.get("author").unwrap(), "Chef Mario");
        assert_eq!(result.metadata.get("servings").unwrap(), "4");
        assert_eq!(result.metadata.get("diet").unwrap(), "GlutenFree, LowCarb");
        assert_eq!(result.metadata.get("cuisine").unwrap(), "Italian");
    }
}