guidebook 0.1.71

HonKit/GitBook compatible static book generator
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
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
mod images;
mod nunjucks;
mod openapi;
mod renderer;
mod sitemap;
pub mod svg;
mod template;

use crate::parser::{
    self, apply_glossary, parse_front_matter, BookConfig, Glossary, Language, Summary, SummaryItem,
};
use anyhow::{Context, Result};
use regex::Regex;
use serde::Serialize;
use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
use std::time::Instant;

/// Regex for matching `<!-- @import("path") -->` directives
static IMPORT_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r#"<!--\s*@import\s*\(\s*"([^"]+)"\s*\)\s*-->"#).unwrap());

// nunjucks module is used internally for template processing
pub use renderer::{
    extract_headings, extract_headings_from_asciidoc, render_asciidoc, render_asciidoc_with_path,
    render_markdown, render_markdown_with_hardbreaks, render_markdown_with_path, TocItem,
};
pub use template::Templates;

/// Check if a file is an AsciiDoc file based on its extension
pub fn is_asciidoc_file(path: &Path) -> bool {
    matches!(
        path.extension().and_then(|s| s.to_str()),
        Some("adoc") | Some("asciidoc")
    )
}

/// Search index entry
#[derive(Serialize)]
struct SearchEntry {
    title: String,
    path: String,
    content: String,
}

/// Build statistics
#[derive(Default)]
struct BuildStats {
    pages: usize,
    assets: usize,
}

// Embed static assets at compile time
const GITBOOK_CSS: &str = include_str!("../../templates/gitbook.css");
const GITBOOK_JS: &str = include_str!("../../templates/gitbook.js");
const COLLAPSIBLE_JS: &str = include_str!("../../templates/collapsible.js");
const FONTSETTINGS_JS: &str = include_str!("../../templates/fontsettings.js");
const SEARCH_JS: &str = include_str!("../../templates/search.js");

/// Build the book from source directory to output directory
pub fn build(source: &Path, output: &Path) -> Result<()> {
    build_with_options(source, output, false)
}

/// Build the book with options (skip_search_index for hot reload)
pub fn build_with_options(source: &Path, output: &Path, skip_search_index: bool) -> Result<()> {
    let start_time = Instant::now();
    let source = source
        .canonicalize()
        .context("Source directory not found")?;

    println!("Loading book configuration...");
    let config = BookConfig::load(&source)?;
    println!(
        "  Title: {}",
        if config.title.is_empty() {
            "(untitled)"
        } else {
            &config.title
        }
    );

    // Check for multi-language book
    let languages = parser::langs::parse_langs(&source)?;

    // Remove stale files from a previous build (deleted/renamed pages would
    // otherwise live in the output forever). Skipped on hot reload; dot
    // entries (.git, .nojekyll, ...) are preserved.
    if !skip_search_index {
        clean_output_dir(output, &source)?;
    }

    let stats = if languages.is_empty() {
        // Single language book
        println!("Building single-language book...");
        build_single_book(&source, output, &config, skip_search_index, None)?
    } else {
        // Multi-language book
        println!(
            "Building multi-language book with {} languages:",
            languages.len()
        );
        for lang in &languages {
            println!("  - {} ({})", lang.title, lang.code);
        }

        build_multi_lang_book(&source, output, &config, &languages, skip_search_index)?
    };

    // Generate Swagger UI if openapi is configured (at root level)
    if let Some(openapi_config) = &config.openapi {
        openapi::generate_swagger_ui(&source, output, openapi_config)?;
    }

    let elapsed = start_time.elapsed();
    let elapsed_secs = elapsed.as_secs_f64();

    println!();
    println!(
        ">> generation finished with success in {:.1}s !",
        elapsed_secs
    );
    println!(
        "   {} pages built, {} asset files copied",
        stats.pages, stats.assets
    );

    Ok(())
}

fn build_single_book(
    source: &Path,
    output: &Path,
    config: &BookConfig,
    skip_search_index: bool,
    lang_prefix: Option<&str>,
) -> Result<BuildStats> {
    let summary = Summary::parse(source)?;
    let templates = Templates::new(config)?;
    let mut stats = BuildStats::default();

    // Load glossary if exists
    let glossary = Glossary::load(source)?;
    if !glossary.is_empty() {
        println!("  Loaded glossary with {} terms", glossary.entries.len());
    }

    // Create output directory
    fs::create_dir_all(output)?;

    // Write embedded static assets
    write_static_assets(output, config)?;

    // Copy assets
    stats.assets += copy_assets(source, output)?;

    // Copy custom styles if configured
    if let Some(style_path) = config.get_website_style() {
        let src_style = source.join(style_path);
        if src_style.exists() {
            let dest_style = output.join("gitbook/style.css");
            fs::create_dir_all(dest_style.parent().unwrap())?;
            fs::copy(&src_style, &dest_style)?;
        }
    }

    // Build each chapter
    stats.pages += build_chapters(
        source,
        output,
        &summary.items,
        config,
        &templates,
        &summary,
        &glossary,
        lang_prefix,
    )?;

    // Generate index.html from README.md if exists
    let readme_path = source.join("README.md");
    if readme_path.exists() {
        let raw_content = read_text_lossy(&readme_path)?;
        // Parse front matter
        let parsed = parse_front_matter(&raw_content);
        let front_matter = parsed.front_matter;
        // Process @import directives before template processing
        let imported_content = process_imports_for_file(&parsed.content, &readme_path)?;
        // Process Nunjucks templates (conditionals, loops, filters, variables)
        let content = nunjucks::process_nunjucks_templates(&imported_content, config)
            .unwrap_or_else(|e| {
                eprintln!("  Warning: Template error in README.md: {}", e);
                imported_content.clone()
            });
        let html_content = render_markdown_with_hardbreaks(&content, config.hardbreaks);
        // Apply glossary terms
        let html_content = apply_glossary(&html_content, &glossary);
        // Process sitemap directives
        let html_content = sitemap::process_sitemap_directives(&html_content, &summary);
        let toc_items = extract_headings(&content);
        // Use front matter title if available, otherwise use config title
        let page_title = front_matter
            .as_ref()
            .and_then(|fm| fm.title.as_deref())
            .unwrap_or(&config.title);
        let page_html = templates.render_page_with_meta(
            page_title,
            &html_content,
            "./",
            config,
            &summary,
            Some("index.html"),
            &toc_items,
            front_matter.as_ref(),
            lang_prefix,
        )?;
        // Apply SVG processing if configured
        let page_html = apply_svg_processing(page_html, output, "./", config)?;
        fs::write(output.join("index.html"), page_html)?;
        stats.pages += 1;
    }

    // Generate search index (skip on hot reload for performance)
    if !skip_search_index {
        generate_search_index(source, output, &summary, config)?;
    }

    // Download remote images if enabled
    if config.fetch_remote_images {
        println!("Downloading remote images...");
        let downloaded = process_remote_images(output)?;
        if downloaded > 0 {
            println!("  Downloaded {} remote images", downloaded);
        }
    }

    Ok(stats)
}

fn write_static_assets(output: &Path, config: &BookConfig) -> Result<()> {
    let gitbook_dir = output.join("gitbook");
    fs::create_dir_all(&gitbook_dir)?;

    // Write CSS (including sitemap styles)
    let css_content = format!("{}\n{}", GITBOOK_CSS, sitemap::get_sitemap_css());
    fs::write(gitbook_dir.join("gitbook.css"), css_content)?;

    // Write JS
    fs::write(gitbook_dir.join("gitbook.js"), GITBOOK_JS)?;

    // Write collapsible JS only if plugin is enabled
    if config.is_plugin_enabled("collapsible-chapters") {
        fs::write(gitbook_dir.join("collapsible.js"), COLLAPSIBLE_JS)?;
    }

    // Write fontsettings JS only if plugin is enabled
    if config.is_plugin_enabled("fontsettings") {
        fs::write(gitbook_dir.join("fontsettings.js"), FONTSETTINGS_JS)?;
    }

    // Write search JS
    fs::write(gitbook_dir.join("search.js"), SEARCH_JS)?;

    // Write favicon / touch icon referenced by the page templates
    write_favicon_assets(&gitbook_dir)?;

    Ok(())
}

fn build_multi_lang_book(
    source: &Path,
    output: &Path,
    config: &BookConfig,
    languages: &[Language],
    skip_search_index: bool,
) -> Result<BuildStats> {
    let mut stats = BuildStats::default();

    // Create output directory
    fs::create_dir_all(output)?;

    // Generate language index page
    generate_lang_index(output, languages, config)?;

    // Build each language
    for lang in languages {
        println!("\nBuilding {} ({})...", lang.title, lang.code);
        let lang_source = source.join(&lang.code);
        let lang_output = output.join(&lang.code);

        // Use language-specific config if exists, otherwise use root config
        let lang_config_path = lang_source.join("book.json");
        let lang_config = if lang_config_path.exists() {
            BookConfig::load(&lang_source)?
        } else {
            config.clone()
        };

        let lang_stats = build_single_book(
            &lang_source,
            &lang_output,
            &lang_config,
            skip_search_index,
            Some(&lang.code),
        )?;
        stats.pages += lang_stats.pages;
        stats.assets += lang_stats.assets;
    }

    // Copy root assets if they exist
    let assets_dir = source.join("assets");
    if assets_dir.exists() {
        stats.assets += copy_dir_recursive_count(&assets_dir, &output.join("assets"))?;
    }

    Ok(stats)
}

#[allow(clippy::too_many_arguments)]
fn build_chapters(
    source: &Path,
    output: &Path,
    items: &[SummaryItem],
    config: &BookConfig,
    templates: &Templates,
    summary: &Summary,
    glossary: &Glossary,
    lang_prefix: Option<&str>,
) -> Result<usize> {
    let mut built_files: std::collections::HashSet<String> = std::collections::HashSet::new();
    build_chapters_inner(
        source,
        output,
        items,
        config,
        templates,
        summary,
        glossary,
        &mut built_files,
        lang_prefix,
    )
}

#[allow(clippy::too_many_arguments)]
fn build_chapters_inner(
    source: &Path,
    output: &Path,
    items: &[SummaryItem],
    config: &BookConfig,
    templates: &Templates,
    summary: &Summary,
    glossary: &Glossary,
    built_files: &mut std::collections::HashSet<String>,
    lang_prefix: Option<&str>,
) -> Result<usize> {
    let mut count = 0;

    for item in items {
        if let SummaryItem::Link {
            title,
            path,
            children,
        } = item
        {
            if let Some(md_path) = path {
                // Extract base file path (remove anchor #xxx if present)
                // Also strip leading slash to handle absolute-style paths in SUMMARY.md
                let base_path = if let Some(hash_pos) = md_path.find('#') {
                    md_path[..hash_pos].trim_start_matches('/')
                } else {
                    md_path.trim_start_matches('/')
                };

                // Skip if already built (avoid duplicate builds for anchor-only references)
                if base_path.is_empty() || built_files.contains(base_path) {
                    // Still need to process children
                    if !children.is_empty() {
                        count += build_chapters_inner(
                            source,
                            output,
                            children,
                            config,
                            templates,
                            summary,
                            glossary,
                            built_files,
                            lang_prefix,
                        )?;
                    }
                    continue;
                }

                let src_file = source.join(base_path);
                if src_file.exists() {
                    // Mark as built before processing
                    built_files.insert(base_path.to_string());

                    // Read file content
                    let raw_content = read_text_lossy(&src_file)?;
                    // Parse front matter
                    let parsed = parse_front_matter(&raw_content);
                    let front_matter = parsed.front_matter;

                    // Check if this is an AsciiDoc file
                    let is_asciidoc = is_asciidoc_file(&src_file);

                    // For multi-language books, prepend language prefix to calculate correct relative paths
                    // e.g., "Customer/File.md" becomes "jp/Customer/File.md" for depth calculation
                    // This is needed for root-relative links like "/api-docs/" to be converted to
                    // the correct relative path (e.g., "../../../api-docs/" instead of "../../api-docs/")
                    let full_path = match lang_prefix {
                        Some(prefix) => format!("{}/{}", prefix, base_path),
                        None => base_path.to_string(),
                    };

                    // Render content based on file type
                    let (html_content, toc_items) = if is_asciidoc {
                        // AsciiDoc rendering
                        let html = render_asciidoc_with_path(&parsed.content, Some(&full_path));
                        let toc = extract_headings_from_asciidoc(&parsed.content);
                        (html, toc)
                    } else {
                        // Markdown rendering
                        // Process @import directives before template processing
                        let imported_content =
                            process_imports_for_file(&parsed.content, &src_file)?;
                        // Process Nunjucks templates (conditionals, loops, filters, variables)
                        let content =
                            nunjucks::process_nunjucks_templates(&imported_content, config)
                                .unwrap_or_else(|e| {
                                    eprintln!("  Warning: Template error in {}: {}", base_path, e);
                                    imported_content.clone()
                                });
                        let html = render_markdown_with_path(
                            &content,
                            Some(&full_path),
                            config.hardbreaks,
                        );
                        let toc = extract_headings(&content);
                        (html, toc)
                    };

                    // Apply glossary terms
                    let html_content = apply_glossary(&html_content, glossary);
                    // Process sitemap directives
                    let html_content = sitemap::process_sitemap_directives(&html_content, summary);

                    // Generate output path (use base_path without anchor)
                    // Handle .md, .adoc, and .asciidoc extensions
                    let html_path = template::source_path_to_html(base_path);
                    let dest_file = output.join(&html_path);

                    // Calculate relative path to root
                    let depth = html_path.matches('/').count();
                    let root_path = if depth > 0 {
                        "../".repeat(depth)
                    } else {
                        "./".to_string()
                    };

                    // Use front matter title if available, otherwise use summary title
                    let page_title = front_matter
                        .as_ref()
                        .and_then(|fm| fm.title.as_deref())
                        .unwrap_or(title);

                    // Render with template
                    let page_html = templates.render_page_with_meta(
                        page_title,
                        &html_content,
                        &root_path,
                        config,
                        summary,
                        Some(&html_path),
                        &toc_items,
                        front_matter.as_ref(),
                        lang_prefix,
                    )?;

                    // Apply SVG processing if configured
                    let page_html = apply_svg_processing(page_html, output, &root_path, config)?;

                    // Write output
                    if let Some(parent) = dest_file.parent() {
                        fs::create_dir_all(parent)?;
                    }
                    fs::write(&dest_file, page_html)?;
                    count += 1;
                } else {
                    println!("  Warning: {} not found", base_path);
                }
            }

            // Build children recursively
            if !children.is_empty() {
                count += build_chapters_inner(
                    source,
                    output,
                    children,
                    config,
                    templates,
                    summary,
                    glossary,
                    built_files,
                    lang_prefix,
                )?;
            }
        }
    }

    Ok(count)
}

/// Remove previous build output so deleted/renamed pages don't linger.
/// Dot entries (.git, .nojekyll, ...) are preserved — publishing setups keep
/// them inside the output directory. Never cleans when the output directory
/// IS the source (or contains it): that would delete the book itself.
fn clean_output_dir(output: &Path, source: &Path) -> Result<()> {
    if !output.exists() {
        return Ok(());
    }
    let (Ok(out_canonical), Ok(src_canonical)) = (output.canonicalize(), source.canonicalize())
    else {
        return Ok(());
    };
    if src_canonical.starts_with(&out_canonical) {
        return Ok(());
    }

    for entry in fs::read_dir(&out_canonical)? {
        let entry = entry?;
        if entry.file_name().to_string_lossy().starts_with('.') {
            continue;
        }
        let path = entry.path();
        if entry.file_type()?.is_dir() {
            fs::remove_dir_all(&path)?;
        } else {
            fs::remove_file(&path)?;
        }
    }
    Ok(())
}

/// Read a text file, tolerating invalid UTF-8 with a lossy conversion and a
/// warning. A single non-UTF-8 page must not abort the whole build.
fn read_text_lossy(path: &Path) -> Result<String> {
    let bytes = fs::read(path)?;
    match String::from_utf8(bytes) {
        Ok(s) => Ok(s),
        Err(e) => {
            eprintln!(
                "  Warning: {} is not valid UTF-8; replacing invalid sequences",
                path.display()
            );
            Ok(String::from_utf8_lossy(e.as_bytes()).into_owned())
        }
    }
}

fn copy_assets(source: &Path, output: &Path) -> Result<usize> {
    let mut count = 0;
    let asset_dir_names: &[&str] = &["assets", "images", "image", "img"];

    // Canonical output path: when the output dir lives INSIDE the source
    // (e.g. `build . -o out`), it must be excluded from the walk or its own
    // asset dirs get re-copied into out/out/... one level deeper per build
    let output_canonical = output.canonicalize().ok();

    // Copy root-level asset directories
    for dir_name in asset_dir_names {
        let src_dir = source.join(dir_name);
        if src_dir.exists() {
            let dest_dir = output.join(dir_name);
            count += copy_dir_recursive_count(&src_dir, &dest_dir)?;
        }
    }

    // Also copy nested asset directories (e.g., chapter/image/)
    for entry in walkdir::WalkDir::new(source).into_iter().filter_entry(|e| {
        // Skip root-level asset dirs (already copied) and output directories
        let name = e.file_name().to_string_lossy();
        if (e.depth() == 1 && asset_dir_names.contains(&name.as_ref()))
            || name == "_book"
            || name == "node_modules"
        {
            return false;
        }
        // Skip the output directory itself wherever it is
        if e.file_type().is_dir() {
            if let (Some(out), Ok(entry_canonical)) =
                (output_canonical.as_ref(), e.path().canonicalize())
            {
                if &entry_canonical == out {
                    return false;
                }
            }
        }
        true
    }) {
        let entry = entry?;
        if entry.file_type().is_dir() {
            let name = entry.file_name().to_string_lossy();
            if asset_dir_names.contains(&name.as_ref()) {
                // Found a nested asset directory
                let relative = entry.path().strip_prefix(source)?;
                let dest_dir = output.join(relative);
                count += copy_dir_recursive_count(entry.path(), &dest_dir)?;
            }
        }
    }

    Ok(count)
}

fn copy_dir_recursive_count(src: &Path, dest: &Path) -> Result<usize> {
    fs::create_dir_all(dest)?;
    let mut count = 0;

    for entry in walkdir::WalkDir::new(src) {
        let entry = entry?;
        let relative = entry.path().strip_prefix(src)?;
        let dest_path = dest.join(relative);

        if entry.file_type().is_dir() {
            fs::create_dir_all(&dest_path)?;
            continue;
        }

        if let Some(parent) = dest_path.parent() {
            fs::create_dir_all(parent)?;
        }

        // A broken symlink among the assets must not abort the whole build
        let src_meta = match entry.path().metadata() {
            Ok(m) => m,
            Err(e) => {
                eprintln!(
                    "  Warning: skipping asset {} ({})",
                    entry.path().display(),
                    e
                );
                continue;
            }
        };

        if let Ok(dest_meta) = dest_path.symlink_metadata() {
            if dest_meta.file_type().is_symlink() {
                // Output written by an older guidebook version used symlinks;
                // replace with a real copy so the output is self-contained
                fs::remove_file(&dest_path)?;
            } else {
                // Up-to-date check: previously ANY existing destination was
                // skipped, so changed assets were never refreshed on rebuild
                let up_to_date = dest_meta.len() == src_meta.len()
                    && match (dest_meta.modified(), src_meta.modified()) {
                        (Ok(d), Ok(s)) => d >= s,
                        _ => false,
                    };
                if up_to_date {
                    continue;
                }
            }
        }

        // Real copy, not a symlink: symlinked output broke as soon as _book
        // was deployed elsewhere (tar/rsync/CI artifacts → dangling links)
        if let Err(e) = fs::copy(entry.path(), &dest_path) {
            eprintln!(
                "  Warning: failed to copy asset {}: {}",
                entry.path().display(),
                e
            );
            continue;
        }
        count += 1;
    }

    Ok(count)
}

fn generate_lang_index(output: &Path, languages: &[Language], config: &BookConfig) -> Result<()> {
    let title = if config.title.is_empty() {
        "Select Language"
    } else {
        &config.title
    };

    let mut lang_links = String::new();
    for lang in languages {
        lang_links.push_str(&format!(
            r#"
            <li>
                <a href="{}/">{}</a>
            </li>
        "#,
            lang.code, lang.title
        ));
    }

    let html = format!(
        r#"<!DOCTYPE HTML>
<html lang="" data-guidebook>
    <head>
        <meta charset="UTF-8">
        <title>Choose a language · {}</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="description" content="">
        <meta name="generator" content="guidebook">
        <link rel="stylesheet" href="gitbook/style.css">
        <meta name="HandheldFriendly" content="true"/>
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="black">
        <link rel="apple-touch-icon-precomposed" sizes="152x152" href="gitbook/images/apple-touch-icon-precomposed-152.png">
        <link rel="shortcut icon" href="gitbook/images/favicon.ico" type="image/x-icon">
    </head>
    <body>

<div class="book-langs-index" role="navigation">
    <div class="inner">
        <h3>Choose a language</h3>

        <ul class="languages">
        {}
        </ul>
    </div>
</div>

    </body>
</html>"#,
        title, lang_links
    );

    fs::write(output.join("index.html"), html)?;

    // Copy gitbook static files to root for the language selector page
    copy_gitbook_static_to_root(output)?;

    Ok(())
}

/// Strip HTML tags from content for search indexing
fn strip_html_tags(html: &str) -> String {
    let mut result = String::new();
    let mut in_tag = false;

    for c in html.chars() {
        if c == '<' {
            in_tag = true;
        } else if c == '>' {
            in_tag = false;
        } else if !in_tag {
            result.push(c);
        }
    }

    // Clean up whitespace
    result.split_whitespace().collect::<Vec<_>>().join(" ")
}

/// Collect search entries from summary items
fn collect_search_entries(
    source: &Path,
    items: &[SummaryItem],
    config: &BookConfig,
    seen_paths: &mut HashSet<String>,
    entries: &mut Vec<SearchEntry>,
) -> Result<()> {
    for item in items {
        if let SummaryItem::Link {
            title,
            path,
            children,
        } = item
        {
            if let Some(file_path) = path {
                // Strip leading slash to handle absolute-style paths in SUMMARY.md
                let file_path = file_path.trim_start_matches('/');
                // SUMMARY paths may carry an anchor (guide.md#setup) — strip
                // it before touching the filesystem, or the page silently
                // vanishes from the search index
                let file_only = file_path.split('#').next().unwrap_or(file_path);
                let src_file = source.join(file_only);
                if src_file.exists() {
                    // Generate HTML path for any supported extension
                    let html_path = template::source_path_to_html(file_only);

                    // A file referenced twice (e.g. with different anchors)
                    // must be indexed only once
                    if seen_paths.insert(html_path.clone()) {
                        let raw = read_text_lossy(&src_file)?;

                        // Mirror the page build pipeline (front matter →
                        // @import → templates) so the index matches what the
                        // reader actually sees — previously the raw file was
                        // indexed: front matter leaked in, imported content
                        // and expanded variables were missing
                        let parsed = parse_front_matter(&raw);
                        let imported = process_imports_for_file(&parsed.content, &src_file)?;
                        let content = nunjucks::process_nunjucks_templates(&imported, config)
                            .unwrap_or_else(|_| imported.clone());

                        // Render based on file type
                        let html_content = if is_asciidoc_file(&src_file) {
                            render_asciidoc(&content)
                        } else {
                            render_markdown(&content)
                        };

                        let text_content = strip_html_tags(&html_content);

                        entries.push(SearchEntry {
                            title: title.clone(),
                            path: html_path,
                            content: text_content,
                        });
                    }
                }
            }
            if !children.is_empty() {
                collect_search_entries(source, children, config, seen_paths, entries)?;
            }
        }
    }
    Ok(())
}

/// Generate search index JSON file
fn generate_search_index(
    source: &Path,
    output: &Path,
    summary: &Summary,
    config: &BookConfig,
) -> Result<()> {
    let mut entries = Vec::new();
    let mut seen_paths = HashSet::new();

    // Collect from README.md
    let readme_path = source.join("README.md");
    if readme_path.exists() {
        let raw = read_text_lossy(&readme_path)?;
        let parsed = parse_front_matter(&raw);
        let imported = process_imports_for_file(&parsed.content, &readme_path)?;
        let content = nunjucks::process_nunjucks_templates(&imported, config)
            .unwrap_or_else(|_| imported.clone());
        let html_content = render_markdown(&content);
        let text_content = strip_html_tags(&html_content);

        entries.push(SearchEntry {
            title: "Home".to_string(),
            path: "index.html".to_string(),
            content: text_content,
        });
    }

    // Collect from all chapters
    collect_search_entries(
        source,
        &summary.items,
        config,
        &mut seen_paths,
        &mut entries,
    )?;

    // Write search index
    let json = serde_json::to_string(&entries)?;
    fs::write(output.join("search_index.json"), json)?;

    Ok(())
}

/// Process all HTML files in output directory to download remote images
/// Returns the number of images downloaded
fn process_remote_images(output: &Path) -> Result<usize> {
    use images::ImageDownloader;

    let mut downloader = ImageDownloader::new(output);

    // Walk through all HTML files in output directory
    for entry in walkdir::WalkDir::new(output) {
        let entry = entry?;
        if entry.file_type().is_file() {
            if let Some(ext) = entry.path().extension() {
                if ext == "html" {
                    // Read HTML file
                    let html = fs::read_to_string(entry.path())?;

                    // Depth of this page below the output root — the local
                    // image path needs a matching ../ prefix on nested pages
                    let depth = entry
                        .path()
                        .strip_prefix(output)
                        .map(|rel| rel.components().count().saturating_sub(1))
                        .unwrap_or(0);

                    // Process remote images
                    match downloader.process_html(&html, depth) {
                        Ok(processed_html) => {
                            // Only write back if content changed
                            if processed_html != html {
                                fs::write(entry.path(), processed_html)?;
                            }
                        }
                        Err(e) => {
                            eprintln!(
                                "  Warning: Failed to process {}: {}",
                                entry.path().display(),
                                e
                            );
                        }
                    }
                }
            }
        }
    }

    let (downloaded, _) = downloader.stats();
    Ok(downloaded)
}

/// Process @import directives in Markdown content
/// Replaces <!-- @import("path/to/file.md") --> with the contents of the referenced file
/// Supports recursive imports with loop prevention
fn process_imports(
    content: &str,
    base_path: &Path,
    visited: &mut HashSet<PathBuf>,
) -> Result<String> {
    let mut result = content.to_string();
    let mut offset: i64 = 0;

    for caps in IMPORT_REGEX.captures_iter(content) {
        let full_match = caps.get(0).unwrap();
        let import_path = &caps[1];

        // Resolve the path relative to the base_path (directory containing the current file)
        let resolved_path = base_path.join(import_path);
        let canonical_path = match resolved_path.canonicalize() {
            Ok(p) => p,
            Err(_) => {
                // File doesn't exist, leave the directive as-is and warn
                eprintln!(
                    "  Warning: @import file not found: {}",
                    resolved_path.display()
                );
                continue;
            }
        };

        // Check for circular imports — `visited` holds the CURRENT import
        // chain (ancestors), not every file ever imported. Importing the same
        // snippet twice on a page, or via a diamond (A→B→D, A→C→D), is
        // legitimate; only a file importing itself through its ancestry is a
        // cycle.
        if visited.contains(&canonical_path) {
            eprintln!(
                "  Warning: Circular @import detected, skipping: {}",
                canonical_path.display()
            );
            continue;
        }

        // Read the imported file
        let imported_content = match read_text_lossy(&canonical_path) {
            Ok(c) => {
                // Strip UTF-8 BOM if present (fixes reference link parsing)
                c.strip_prefix('\u{FEFF}').unwrap_or(&c).to_string()
            }
            Err(e) => {
                eprintln!(
                    "  Warning: Failed to read @import file {}: {}",
                    canonical_path.display(),
                    e
                );
                continue;
            }
        };

        // Recursively process imports with this file pushed onto the chain
        // Use the directory of the imported file as the new base path
        visited.insert(canonical_path.clone());
        let import_base_path = canonical_path.parent().unwrap_or(base_path);
        let processed_content = process_imports(&imported_content, import_base_path, visited)?;
        visited.remove(&canonical_path);

        // Calculate the adjusted positions accounting for previous replacements
        let start = (full_match.start() as i64 + offset) as usize;
        let end = (full_match.end() as i64 + offset) as usize;

        // Replace the directive with the processed content
        result.replace_range(start..end, &processed_content);

        // Update offset for subsequent replacements
        offset += processed_content.len() as i64 - (full_match.end() - full_match.start()) as i64;
    }

    Ok(result)
}

/// Process @import directives starting from a file path
/// This is a convenience wrapper that initializes the visited set
fn process_imports_for_file(content: &str, file_path: &Path) -> Result<String> {
    let mut visited = HashSet::new();

    // Add the current file to visited set to prevent self-imports
    if let Ok(canonical) = file_path.canonicalize() {
        visited.insert(canonical);
    }

    // Get the directory containing the file as the base path
    let base_path = file_path.parent().unwrap_or(Path::new("."));

    process_imports(content, base_path, &mut visited)
}

/// Apply SVG processing to HTML based on config options
/// `root_prefix` is the page's relative prefix back to the output root
/// ("./" at root, "../../" at depth 2)
fn apply_svg_processing(
    html: String,
    output_dir: &Path,
    root_prefix: &str,
    config: &BookConfig,
) -> Result<String> {
    let mut result = html;

    // Apply externalize_svg if enabled
    if config.externalize_svg == Some(true) {
        result = svg::externalize_inline_svg(&result, output_dir, root_prefix)?;
    }

    // Apply inline_svg if enabled
    if config.inline_svg == Some(true) {
        result = svg::inline_svg_files(&result, output_dir)?;
    }

    Ok(result)
}

/// Expand book variables in Markdown content (legacy implementation)
/// Note: This is now superseded by nunjucks::process_nunjucks_templates
/// but kept for backward compatibility tests
/// Replaces {{ book.xxx }} patterns with values from config.variables
/// Preserves variables inside code blocks (``` ... ```) and inline code (` ... `)
#[cfg(test)]
static VAR_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\{\{\s*book\.([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}").unwrap());
#[cfg(test)]
static FENCED_CODE_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?s)```[^\n]*\n.*?```").unwrap());
#[cfg(test)]
static INLINE_CODE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"`[^`\n]+`").unwrap());

#[cfg(test)]
fn expand_variables(content: &str, config: &BookConfig) -> String {
    if config.variables.is_empty() {
        return content.to_string();
    }

    // Strategy: Find protected regions (code blocks and inline code) first,
    // then only apply variable expansion outside these regions

    // Find all protected regions (fenced code blocks and inline code)
    let protected_regions = find_protected_regions(content);

    let mut result = String::new();
    let mut last_end = 0;

    for caps in VAR_REGEX.captures_iter(content) {
        let full_match = caps.get(0).unwrap();
        let start = full_match.start();
        let end = full_match.end();

        // Check if this match is inside a protected region
        let is_protected = protected_regions
            .iter()
            .any(|(region_start, region_end)| start >= *region_start && end <= *region_end);

        // Add content before this match
        result.push_str(&content[last_end..start]);

        if is_protected {
            // Inside code block/inline code - keep original
            result.push_str(&content[start..end]);
        } else {
            // Outside code - perform replacement
            let var_name = &caps[1];
            if let Some(value) = config.variables.get(var_name) {
                let replacement = match value {
                    serde_json::Value::String(s) => s.clone(),
                    serde_json::Value::Number(n) => n.to_string(),
                    serde_json::Value::Bool(b) => b.to_string(),
                    _ => value.to_string(),
                };
                result.push_str(&replacement);
            } else {
                // Variable not found, keep original text
                result.push_str(&content[start..end]);
            }
        }

        last_end = end;
    }

    // Add remaining content after last match
    result.push_str(&content[last_end..]);

    result
}

/// Find all protected regions in the content (code blocks and inline code)
/// Returns a vector of (start, end) byte positions
/// Note: This is now superseded by nunjucks module's protected region handling
/// but kept for backward compatibility tests
#[cfg(test)]
fn find_protected_regions(content: &str) -> Vec<(usize, usize)> {
    let mut regions = Vec::new();

    // Find fenced code blocks (``` ... ```) - must come first as they take priority
    for m in FENCED_CODE_REGEX.find_iter(content) {
        regions.push((m.start(), m.end()));
    }

    // Find inline code (` ... `) but not if inside fenced blocks
    for m in INLINE_CODE_REGEX.find_iter(content) {
        // Only add if not overlapping with existing regions
        let overlaps = regions
            .iter()
            .any(|(start, end)| m.start() >= *start && m.end() <= *end);
        if !overlaps {
            regions.push((m.start(), m.end()));
        }
    }

    regions
}

fn copy_gitbook_static_to_root(output: &Path) -> Result<()> {
    let gitbook_dir = output.join("gitbook");
    fs::create_dir_all(&gitbook_dir)?;

    // Create a minimal style.css for the language selector page
    let style_css = r#"
.book-langs-index {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.book-langs-index .inner {
    text-align: center;
}

.book-langs-index h3 {
    color: #333;
    font-size: 1.5em;
    margin-bottom: 1em;
}

.book-langs-index .languages {
    list-style: none;
    padding: 0;
    margin: 0;
}

.book-langs-index .languages li {
    margin: 0.5em 0;
}

.book-langs-index .languages a {
    color: #4183c4;
    text-decoration: none;
    font-size: 1.2em;
}

.book-langs-index .languages a:hover {
    text-decoration: underline;
}
"#;

    fs::write(gitbook_dir.join("style.css"), style_css)?;

    // Write the favicon files the templates link to (previously only the
    // empty directory was created and every page 404'd on the icons)
    write_favicon_assets(&gitbook_dir)?;

    Ok(())
}

/// Write favicon / touch-icon files into <gitbook_dir>/images/
fn write_favicon_assets(gitbook_dir: &Path) -> Result<()> {
    let images_dir = gitbook_dir.join("images");
    fs::create_dir_all(&images_dir)?;
    fs::write(
        images_dir.join("favicon.ico"),
        include_bytes!("../../assets/favicon.ico"),
    )?;
    fs::write(
        images_dir.join("apple-touch-icon-precomposed-152.png"),
        include_bytes!("../../assets/apple-touch-icon-precomposed-152.png"),
    )?;
    Ok(())
}

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

    fn create_test_config(variables: HashMap<String, serde_json::Value>) -> BookConfig {
        BookConfig {
            variables,
            ..Default::default()
        }
    }

    #[test]
    fn test_expand_variables_basic() {
        let mut vars = HashMap::new();
        vars.insert("version".to_string(), serde_json::json!("1.0.0"));
        vars.insert("author".to_string(), serde_json::json!("Guide Inc"));

        let config = create_test_config(vars);
        let content = "Version: {{ book.version }}\nAuthor: {{ book.author }}";
        let result = expand_variables(content, &config);

        assert_eq!(result, "Version: 1.0.0\nAuthor: Guide Inc");
    }

    #[test]
    fn test_expand_variables_no_spaces() {
        let mut vars = HashMap::new();
        vars.insert("version".to_string(), serde_json::json!("2.0.0"));

        let config = create_test_config(vars);
        let content = "Version: {{book.version}}";
        let result = expand_variables(content, &config);

        assert_eq!(result, "Version: 2.0.0");
    }

    #[test]
    fn test_expand_variables_with_extra_spaces() {
        let mut vars = HashMap::new();
        vars.insert("name".to_string(), serde_json::json!("Test"));

        let config = create_test_config(vars);
        let content = "Name: {{  book.name  }}";
        let result = expand_variables(content, &config);

        assert_eq!(result, "Name: Test");
    }

    #[test]
    fn test_expand_variables_number() {
        let mut vars = HashMap::new();
        vars.insert("year".to_string(), serde_json::json!(2024));

        let config = create_test_config(vars);
        let content = "Year: {{ book.year }}";
        let result = expand_variables(content, &config);

        assert_eq!(result, "Year: 2024");
    }

    #[test]
    fn test_expand_variables_boolean() {
        let mut vars = HashMap::new();
        vars.insert("published".to_string(), serde_json::json!(true));

        let config = create_test_config(vars);
        let content = "Published: {{ book.published }}";
        let result = expand_variables(content, &config);

        assert_eq!(result, "Published: true");
    }

    #[test]
    fn test_expand_variables_unknown_variable() {
        let mut vars = HashMap::new();
        vars.insert("known".to_string(), serde_json::json!("value"));

        let config = create_test_config(vars);
        let content = "Known: {{ book.known }}, Unknown: {{ book.unknown }}";
        let result = expand_variables(content, &config);

        // Unknown variable should remain unchanged
        assert_eq!(result, "Known: value, Unknown: {{ book.unknown }}");
    }

    #[test]
    fn test_expand_variables_empty_config() {
        let config = create_test_config(HashMap::new());
        let content = "No variables: {{ book.test }}";
        let result = expand_variables(content, &config);

        // Should return content unchanged
        assert_eq!(result, "No variables: {{ book.test }}");
    }

    #[test]
    fn test_expand_variables_in_markdown() {
        let mut vars = HashMap::new();
        vars.insert("version".to_string(), serde_json::json!("1.0.0"));

        let config = create_test_config(vars);
        let content = "# Version {{ book.version }}\n\nThis is version {{ book.version }}.";
        let result = expand_variables(content, &config);

        assert_eq!(result, "# Version 1.0.0\n\nThis is version 1.0.0.");
    }

    #[test]
    fn test_expand_variables_preserves_code_blocks() {
        let mut vars = HashMap::new();
        vars.insert("version".to_string(), serde_json::json!("1.0.0"));

        let config = create_test_config(vars);
        let content = r#"Version: {{ book.version }}

```javascript
// This should not be expanded
const version = "{{ book.version }}";
console.log(version);
```

After code block: {{ book.version }}"#;

        let result = expand_variables(content, &config);

        // Variables outside code blocks should be expanded
        assert!(result.contains("Version: 1.0.0"));
        assert!(result.contains("After code block: 1.0.0"));
        // Variables inside code blocks should NOT be expanded
        assert!(result.contains(r#"const version = "{{ book.version }}";"#));
    }

    #[test]
    fn test_expand_variables_preserves_inline_code() {
        let mut vars = HashMap::new();
        vars.insert("var".to_string(), serde_json::json!("value"));

        let config = create_test_config(vars);
        let content = "Normal: {{ book.var }}, inline: `{{ book.var }}`, after: {{ book.var }}";
        let result = expand_variables(content, &config);

        assert_eq!(
            result,
            "Normal: value, inline: `{{ book.var }}`, after: value"
        );
    }

    #[test]
    fn test_expand_variables_multiple_code_blocks() {
        let mut vars = HashMap::new();
        vars.insert("x".to_string(), serde_json::json!("X"));

        let config = create_test_config(vars);
        let content = r#"{{ book.x }}
```
{{ book.x }}
```
{{ book.x }}
```rust
{{ book.x }}
```
{{ book.x }}"#;

        let result = expand_variables(content, &config);

        // Count occurrences of "X" (expanded) and "{{ book.x }}" (not expanded)
        let x_count = result.matches("X").count();
        let template_count = result.matches("{{ book.x }}").count();

        // 3 outside code blocks should be expanded
        assert_eq!(x_count, 3);
        // 2 inside code blocks should NOT be expanded
        assert_eq!(template_count, 2);
    }

    #[test]
    fn test_find_protected_regions_fenced_code() {
        let content = "text\n```\ncode\n```\nmore text";
        let regions = find_protected_regions(content);

        assert_eq!(regions.len(), 1);
        // The region should cover the entire code block
        let (start, end) = regions[0];
        assert!(content[start..end].starts_with("```"));
        assert!(content[start..end].ends_with("```"));
    }

    #[test]
    fn test_find_protected_regions_inline_code() {
        let content = "text `inline` more text";
        let regions = find_protected_regions(content);

        assert_eq!(regions.len(), 1);
        let (start, end) = regions[0];
        assert_eq!(&content[start..end], "`inline`");
    }

    #[test]
    fn test_find_protected_regions_multiple() {
        let content = "`a` text `b` more\n```\nblock\n```\nend";
        let regions = find_protected_regions(content);

        // Should find: 1 fenced block + 2 inline codes
        assert_eq!(regions.len(), 3);
    }

    #[test]
    fn test_process_imports_regex_pattern() {
        // Test the regex pattern matches correctly
        let re = Regex::new(r#"<!--\s*@import\s*\(\s*"([^"]+)"\s*\)\s*-->"#).unwrap();

        // Should match
        assert!(re.is_match(r#"<!-- @import("file.md") -->"#));
        assert!(re.is_match(r#"<!--@import("file.md")-->"#));
        assert!(re.is_match(r#"<!--  @import( "file.md" )  -->"#));
        assert!(re.is_match(r#"<!-- @import("path/to/file.md") -->"#));

        // Should not match
        assert!(!re.is_match(r#"@import("file.md")"#)); // No HTML comment
        assert!(!re.is_match(r#"<!-- @import('file.md') -->"#)); // Single quotes
    }
}