typstify-generator 0.1.8

Static site generation engine
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
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
//! Build orchestration.
//!
//! Coordinates the full site build process.

use std::{
    fs,
    path::{Path, PathBuf},
    time::Instant,
};

use rayon::prelude::*;
use thiserror::Error;
use tracing::{debug, info, warn};
use typstify_core::{Config, Page};
use typstify_search::SimpleSearchIndex;

use crate::{
    assets::{AssetError, AssetManifest, AssetProcessor},
    collector::{CollectorError, ContentCollector, SiteContent, paginate},
    html::{
        HtmlError, HtmlGenerator, list_item_html, pagination_html, shorts_with_separators_html,
    },
    robots::{RobotsError, RobotsGenerator},
    rss::{RssError, RssGenerator},
    sitemap::{SitemapError, SitemapGenerator},
};

/// Build errors.
#[derive(Debug, Error)]
pub enum BuildError {
    /// IO error.
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    /// Collector error.
    #[error("collector error: {0}")]
    Collector(#[from] CollectorError),

    /// HTML generation error.
    #[error("HTML error: {0}")]
    Html(#[from] HtmlError),

    /// RSS generation error.
    #[error("RSS error: {0}")]
    Rss(#[from] RssError),

    /// Sitemap generation error.
    #[error("sitemap error: {0}")]
    Sitemap(#[from] SitemapError),

    /// Robots generation error.
    #[error("robots error: {0}")]
    Robots(#[from] RobotsError),

    /// Asset error.
    #[error("asset error: {0}")]
    Asset(#[from] AssetError),

    /// Configuration error.
    #[error("config error: {0}")]
    Config(String),

    /// Page generation failed.
    #[error("page generation failed: {} errors", errors.len())]
    PageGenerationFailed { errors: Vec<String> },
}

/// Result type for build operations.
pub type Result<T> = std::result::Result<T, BuildError>;

/// Build statistics.
#[derive(Debug, Clone, Default)]
pub struct BuildStats {
    /// Number of pages generated.
    pub pages: usize,

    /// Number of taxonomy pages generated.
    pub taxonomy_pages: usize,

    /// Number of redirect pages generated.
    pub redirects: usize,

    /// Number of auto-generated index pages (archives, tags index, section indices).
    pub auto_pages: usize,

    /// Number of assets processed.
    pub assets: usize,

    /// Build duration in milliseconds.
    pub duration_ms: u64,
}

/// Site builder that orchestrates the build process.
#[derive(Debug)]
pub struct Builder {
    config: Config,
    content_dir: PathBuf,
    output_dir: PathBuf,
    static_dir: Option<PathBuf>,
}

impl Builder {
    /// Create a new builder.
    #[must_use]
    pub fn new(
        config: Config,
        content_dir: impl Into<PathBuf>,
        output_dir: impl Into<PathBuf>,
    ) -> Self {
        Self {
            config,
            content_dir: content_dir.into(),
            output_dir: output_dir.into(),
            static_dir: None,
        }
    }

    /// Set the static assets directory.
    #[must_use]
    pub fn with_static_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.static_dir = Some(dir.into());
        self
    }

    /// Execute the full build process.
    pub fn build(&self) -> Result<BuildStats> {
        let start = Instant::now();
        let mut stats = BuildStats::default();

        info!(
            content = %self.content_dir.display(),
            output = %self.output_dir.display(),
            "starting build"
        );

        // 1. Clean output directory
        self.clean_output()?;

        // 2. Collect content
        let collector = ContentCollector::new(&self.config, &self.content_dir);
        let content = collector.collect()?;

        // 3. Extract sections for dynamic navigation
        let sections: Vec<String> = content.sections.keys().cloned().collect();

        // 4. Generate HTML pages
        stats.pages = self.generate_pages(&content, &sections)?;

        // 5. Generate taxonomy pages
        stats.taxonomy_pages = self.generate_taxonomy_pages(&content, &sections)?;

        // 6. Generate auto-generated index pages (archives, tags index, section indices)
        stats.auto_pages = self.generate_auto_pages(&content, &sections)?;

        // 6. Generate redirects
        stats.redirects = self.generate_redirects(&content)?;

        // 7. Generate RSS feed
        if self.config.rss.enabled {
            self.generate_rss(&content)?;
        }

        // 8. Generate sitemap
        self.generate_sitemap(&content)?;

        // 9. Generate robots.txt
        self.generate_robots()?;

        // 10. Generate search index (per language)
        if self.config.search.enabled {
            self.generate_search_indexes(&content)?;
        }

        // 11. Generate static CSS/JS assets for better caching
        crate::static_assets::generate_static_assets(&self.output_dir)
            .map_err(|e| BuildError::Io(std::io::Error::other(e.to_string())))?;

        // 12. Process user-provided assets
        if let Some(ref static_dir) = self.static_dir {
            let manifest = self.process_assets(static_dir)?;
            stats.assets = manifest.assets().len();
        }

        stats.duration_ms = start.elapsed().as_millis() as u64;

        info!(
            pages = stats.pages,
            taxonomy_pages = stats.taxonomy_pages,
            auto_pages = stats.auto_pages,
            redirects = stats.redirects,
            assets = stats.assets,
            duration_ms = stats.duration_ms,
            "build complete"
        );

        Ok(stats)
    }

    /// Clean the output directory.
    fn clean_output(&self) -> Result<()> {
        if self.output_dir.exists() {
            debug!(dir = %self.output_dir.display(), "cleaning output directory");
            fs::remove_dir_all(&self.output_dir)?;
        }
        fs::create_dir_all(&self.output_dir)?;
        Ok(())
    }

    /// Generate HTML pages for all content.
    fn generate_pages(&self, content: &SiteContent, sections: &[String]) -> Result<usize> {
        let generator = HtmlGenerator::new(&self.config).with_sections(sections.to_vec());
        let pages: Vec<_> = content.pages.values().collect();

        info!(count = pages.len(), "generating HTML pages");

        // Generate pages in parallel
        let results: Vec<_> = pages
            .par_iter()
            .map(|page| {
                // Collect alternate language versions
                let mut alternates = Vec::new();
                if let Some(slugs) = content.translations.get(&page.canonical_id) {
                    for slug in slugs {
                        if let Some(alt_page) = content.pages.get(slug) {
                            alternates.push((alt_page.lang.as_str(), alt_page.url.as_str()));
                        }
                    }
                }

                let html = generator.generate_page(page, &alternates)?;
                let output_path = generator.output_path(page, &self.output_dir);

                // Write HTML file
                if let Some(parent) = output_path.parent() {
                    fs::create_dir_all(parent)?;
                }
                fs::write(&output_path, &html)?;

                debug!(path = %output_path.display(), "wrote page");
                Ok::<_, BuildError>(())
            })
            .collect();

        // Check for errors
        let mut count = 0;
        let mut errors = Vec::new();
        for result in results {
            match result {
                Ok(()) => count += 1,
                Err(e) => {
                    warn!(error = %e, "failed to generate page");
                    errors.push(e.to_string());
                }
            }
        }

        if !errors.is_empty() {
            return Err(BuildError::PageGenerationFailed { errors });
        }

        Ok(count)
    }

    /// Generate taxonomy (tag/category) pages.
    fn generate_taxonomy_pages(&self, content: &SiteContent, sections: &[String]) -> Result<usize> {
        let generator = HtmlGenerator::new(&self.config).with_sections(sections.to_vec());
        let per_page = self.config.taxonomies.tags.paginate;
        let mut count = 0;

        // Generate tag pages
        for (tag, slugs) in &content.taxonomies.tags {
            let pages: Vec<_> = slugs.iter().filter_map(|s| content.pages.get(s)).collect();
            count += self
                .generate_taxonomy_term_pages(&generator, "Tags", tag, &pages, per_page, "tags")?;
        }

        // Generate category pages
        for (category, slugs) in &content.taxonomies.categories {
            let pages: Vec<_> = slugs.iter().filter_map(|s| content.pages.get(s)).collect();
            count += self.generate_taxonomy_term_pages(
                &generator,
                "Categories",
                category,
                &pages,
                per_page,
                "categories",
            )?;
        }

        Ok(count)
    }

    /// Generate paginated pages for a taxonomy term.
    fn generate_taxonomy_term_pages(
        &self,
        generator: &HtmlGenerator,
        taxonomy_name: &str,
        term: &str,
        pages: &[&typstify_core::Page],
        per_page: usize,
        url_prefix: &str,
    ) -> Result<usize> {
        use crate::collector::paginate;

        let term_slug = term.to_lowercase().replace(' ', "-");
        let base_url = format!("/{url_prefix}/{term_slug}");
        let total_pages = (pages.len() + per_page - 1).max(1) / per_page.max(1);
        let mut count = 0;

        for page_num in 1..=total_pages.max(1) {
            let (page_items, _) = paginate(pages, page_num, per_page);

            let items_html: String = page_items.iter().map(|p| list_item_html(p)).collect();

            let pagination = pagination_html(page_num, total_pages, &base_url);

            let html = generator.generate_taxonomy_page(
                taxonomy_name,
                term,
                &items_html,
                pagination.as_deref(),
            )?;

            // Determine output path
            let output_path = if page_num == 1 {
                self.output_dir
                    .join(url_prefix)
                    .join(&term_slug)
                    .join("index.html")
            } else {
                self.output_dir
                    .join(url_prefix)
                    .join(&term_slug)
                    .join("page")
                    .join(page_num.to_string())
                    .join("index.html")
            };

            if let Some(parent) = output_path.parent() {
                fs::create_dir_all(parent)?;
            }
            fs::write(&output_path, &html)?;
            count += 1;
        }

        Ok(count)
    }

    /// Generate auto-generated index pages: archives, tags index, categories index, section indices.
    /// Generates per-language versions when multiple languages are configured.
    fn generate_auto_pages(&self, content: &SiteContent, sections: &[String]) -> Result<usize> {
        let generator = HtmlGenerator::new(&self.config).with_sections(sections.to_vec());
        let mut count = 0;

        // Get all languages
        let all_languages = self.config.all_languages();
        let default_lang = &self.config.site.default_language;

        // Generate pages for each language
        for lang in &all_languages {
            let is_default = *lang == default_lang.as_str();
            let lang_prefix = if is_default {
                String::new()
            } else {
                lang.to_string()
            };

            // Filter pages by language
            let lang_pages: Vec<_> = content.pages.values().filter(|p| p.lang == *lang).collect();

            // 1. Generate tags index page (/tags/ or /{lang}/tags/)
            let lang_tags: std::collections::HashMap<String, Vec<String>> = lang_pages
                .iter()
                .flat_map(|p| p.tags.iter().map(|t| (t.clone(), p.url.clone())))
                .fold(std::collections::HashMap::new(), |mut acc, (tag, url)| {
                    acc.entry(tag).or_default().push(url);
                    acc
                });

            if !lang_tags.is_empty() {
                let html = generator.generate_tags_index_page(&lang_tags, lang)?;
                let output_path = if is_default {
                    self.output_dir.join("tags").join("index.html")
                } else {
                    self.output_dir
                        .join(&lang_prefix)
                        .join("tags")
                        .join("index.html")
                };
                if let Some(parent) = output_path.parent() {
                    fs::create_dir_all(parent)?;
                }
                fs::write(&output_path, &html)?;
                count += 1;
                info!(path = %output_path.display(), lang = lang, "generated tags index page");
            }

            // 2. Generate categories index page (/categories/ or /{lang}/categories/)
            let lang_categories: std::collections::HashMap<String, Vec<String>> = lang_pages
                .iter()
                .flat_map(|p| p.categories.iter().map(|c| (c.clone(), p.url.clone())))
                .fold(std::collections::HashMap::new(), |mut acc, (cat, url)| {
                    acc.entry(cat).or_default().push(url);
                    acc
                });

            if !lang_categories.is_empty() {
                let html = generator.generate_categories_index_page(&lang_categories, lang)?;
                let output_path = if is_default {
                    self.output_dir.join("categories").join("index.html")
                } else {
                    self.output_dir
                        .join(&lang_prefix)
                        .join("categories")
                        .join("index.html")
                };
                if let Some(parent) = output_path.parent() {
                    fs::create_dir_all(parent)?;
                }
                fs::write(&output_path, &html)?;
                count += 1;
                info!(path = %output_path.display(), lang = lang, "generated categories index page");
            }

            // 3. Generate archives page (/archives/ or /{lang}/archives/)
            let mut lang_posts: Vec<_> = lang_pages
                .iter()
                .filter(|p| p.date.is_some())
                .copied()
                .collect();
            lang_posts.sort_by_key(|b| std::cmp::Reverse(b.date));

            if !lang_posts.is_empty() {
                let html = generator.generate_archives_page(&lang_posts, lang)?;
                let output_path = if is_default {
                    self.output_dir.join("archives").join("index.html")
                } else {
                    self.output_dir
                        .join(&lang_prefix)
                        .join("archives")
                        .join("index.html")
                };
                if let Some(parent) = output_path.parent() {
                    fs::create_dir_all(parent)?;
                }
                fs::write(&output_path, &html)?;
                count += 1;
                info!(path = %output_path.display(), lang = lang, "generated archives page");
            }

            // 4. Generate section index pages (e.g., /posts/, /{lang}/posts/)
            // Group pages by section within this language
            let mut sections: std::collections::HashMap<String, Vec<&Page>> =
                std::collections::HashMap::new();
            for page in lang_pages.iter().copied() {
                // Extract section from URL (first path segment after lang prefix if any)
                let url = page.url.trim_start_matches('/');
                let section = if is_default {
                    url.split('/').next().unwrap_or("")
                } else {
                    // For non-default lang, URL starts with /{lang}/section/...
                    url.split('/').nth(1).unwrap_or("")
                };

                if !section.is_empty() && section != "index.html" {
                    sections.entry(section.to_string()).or_default().push(page);
                }
            }

            for (section, mut section_pages) in sections {
                // Sort by date (newest first) or by title
                section_pages.sort_by(|a, b| match (&b.date, &a.date) {
                    (Some(b_date), Some(a_date)) => b_date.cmp(a_date),
                    (Some(_), None) => std::cmp::Ordering::Less,
                    (None, Some(_)) => std::cmp::Ordering::Greater,
                    (None, None) => a.title.cmp(&b.title),
                });

                // Generate paginated section index
                let per_page = self.config.taxonomies.tags.paginate;
                let total_pages = section_pages.len().div_ceil(per_page).max(1);

                // Use shorts-specific template for shorts section
                let is_shorts = section == "shorts";
                let author = self.config.site.author.as_deref().unwrap_or("Author");

                for page_num in 1..=total_pages {
                    let (page_items, _) = paginate(&section_pages, page_num, per_page);

                    // Use appropriate item html based on section type
                    let items_html: String = if is_shorts {
                        shorts_with_separators_html(page_items, author)
                    } else {
                        page_items.iter().map(|p| list_item_html(p)).collect()
                    };

                    let base_url = if is_default {
                        format!("/{section}")
                    } else {
                        format!("/{lang}/{section}")
                    };
                    let pagination = pagination_html(page_num, total_pages, &base_url);

                    // Use shorts template for shorts section
                    let html = if is_shorts {
                        generator.generate_shorts_page(
                            &section,
                            None, // description
                            &items_html,
                            pagination.as_deref(),
                            lang,
                        )?
                    } else {
                        generator.generate_section_page(
                            &section,
                            None, // description
                            &items_html,
                            pagination.as_deref(),
                            lang,
                        )?
                    };

                    let output_path = if page_num == 1 {
                        if is_default {
                            self.output_dir.join(&section).join("index.html")
                        } else {
                            self.output_dir
                                .join(&lang_prefix)
                                .join(&section)
                                .join("index.html")
                        }
                    } else if is_default {
                        self.output_dir
                            .join(&section)
                            .join("page")
                            .join(page_num.to_string())
                            .join("index.html")
                    } else {
                        self.output_dir
                            .join(&lang_prefix)
                            .join(&section)
                            .join("page")
                            .join(page_num.to_string())
                            .join("index.html")
                    };

                    if let Some(parent) = output_path.parent() {
                        fs::create_dir_all(parent)?;
                    }
                    fs::write(&output_path, &html)?;
                    count += 1;
                }

                info!(section = %section, lang = %lang, "generated section index page");
            }
        }

        Ok(count)
    }

    /// Generate redirect pages for URL aliases.
    fn generate_redirects(&self, content: &SiteContent) -> Result<usize> {
        let generator = HtmlGenerator::new(&self.config);
        let mut count = 0;

        for page in content.pages.values() {
            for alias in &page.aliases {
                let redirect_url = format!("{}{}", self.config.base_url(), page.url);
                let html = generator.generate_redirect(&redirect_url)?;

                let alias_path = alias.trim_matches('/');
                let output_path = self.output_dir.join(alias_path).join("index.html");

                if let Some(parent) = output_path.parent() {
                    fs::create_dir_all(parent)?;
                }
                fs::write(&output_path, &html)?;
                count += 1;

                debug!(alias = alias, target = %page.url, "generated redirect");
            }
        }

        Ok(count)
    }

    /// Generate RSS feed.
    fn generate_rss(&self, content: &SiteContent) -> Result<()> {
        let generator = RssGenerator::new(&self.config);
        let pages = ContentCollector::pages_by_date(content);

        // Filter to only posts (pages with dates)
        let posts: Vec<_> = pages.into_iter().filter(|p| p.date.is_some()).collect();

        // Generate main RSS feed with all languages
        let xml = generator.generate(&posts)?;
        let output_path = self.output_dir.join("rss.xml");
        fs::write(&output_path, xml)?;
        info!(path = %output_path.display(), "generated RSS feed");

        // Generate language-specific RSS feeds
        let all_languages = self.config.all_languages();
        let default_lang = &self.config.site.default_language;

        for lang in &all_languages {
            // Filter posts by language
            let lang_posts: Vec<_> = posts.iter().filter(|p| p.lang == *lang).copied().collect();

            if lang_posts.is_empty() {
                continue;
            }

            // Generate language-specific feed
            let lang_xml = generator.generate_for_lang(&lang_posts, lang)?;

            // Determine output path
            let lang_output_path = if *lang == default_lang.as_str() {
                self.output_dir.join("rss.xml")
            } else {
                self.output_dir.join(lang).join("rss.xml")
            };

            // Create parent directories if needed
            if let Some(parent) = lang_output_path.parent() {
                fs::create_dir_all(parent)?;
            }

            fs::write(&lang_output_path, lang_xml)?;
            info!(path = %lang_output_path.display(), lang = lang, "generated language-specific RSS feed");
        }

        Ok(())
    }

    /// Generate sitemap.
    fn generate_sitemap(&self, content: &SiteContent) -> Result<()> {
        let generator = SitemapGenerator::new(&self.config);
        let pages: Vec<_> = content.pages.values().collect();

        let xml = generator.generate(&pages)?;
        let output_path = self.output_dir.join("sitemap.xml");
        fs::write(&output_path, xml)?;
        info!(path = %output_path.display(), "generated sitemap");

        // Generate XSLT stylesheet for sitemap
        let xsl = crate::sitemap::generate_sitemap_xsl();
        let xsl_path = self.output_dir.join("sitemap-style.xsl");
        fs::write(&xsl_path, xsl)?;
        info!(path = %xsl_path.display(), "generated sitemap stylesheet");

        Ok(())
    }

    /// Generate robots.txt.
    fn generate_robots(&self) -> Result<()> {
        let generator = RobotsGenerator::new(&self.config);
        generator.generate(&self.output_dir)?;
        Ok(())
    }

    /// Generate search indexes per language.
    ///
    /// Creates a `search-index.json` for default language at root,
    /// and `/{lang}/search-index.json` for non-default languages.
    fn generate_search_indexes(&self, content: &SiteContent) -> Result<()> {
        let all_languages = self.config.all_languages();
        let default_lang = &self.config.site.default_language;

        for lang in &all_languages {
            // Filter pages by language
            let lang_pages: Vec<_> = content.pages.values().filter(|p| p.lang == *lang).collect();

            if lang_pages.is_empty() {
                continue;
            }

            // Build simple search index
            let index = SimpleSearchIndex::from_pages(&lang_pages);

            // Determine output path
            let output_path = if *lang == default_lang.as_str() {
                self.output_dir.join("search-index.json")
            } else {
                self.output_dir.join(lang).join("search-index.json")
            };

            // Create parent directories if needed
            if let Some(parent) = output_path.parent() {
                fs::create_dir_all(parent)?;
            }

            // Write the index
            index
                .write_to_file(&output_path)
                .map_err(|e| BuildError::Config(e.to_string()))?;

            info!(
                path = %output_path.display(),
                lang = lang,
                documents = lang_pages.len(),
                "generated search index"
            );
        }

        Ok(())
    }

    /// Process static assets.
    fn process_assets(&self, static_dir: &Path) -> Result<AssetManifest> {
        let processor = AssetProcessor::new(self.config.build.minify);
        let manifest = processor.process(static_dir, &self.output_dir)?;

        // Write manifest
        let manifest_path = self.output_dir.join("asset-manifest.json");
        fs::write(&manifest_path, manifest.to_json())?;

        Ok(manifest)
    }
}

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

    use tempfile::TempDir;
    use typstify_core::test_fixtures::test_config;

    use super::*;

    #[test]
    fn test_build_empty_site() {
        let content_dir = TempDir::new().unwrap();
        let output_dir = TempDir::new().unwrap();

        let builder = Builder::new(test_config(), content_dir.path(), output_dir.path());

        let stats = builder.build().unwrap();

        assert_eq!(stats.pages, 0);
        assert!(output_dir.path().join("sitemap.xml").exists());
        assert!(output_dir.path().join("rss.xml").exists());
    }

    #[test]
    fn test_build_with_content() {
        let content_dir = TempDir::new().unwrap();
        let output_dir = TempDir::new().unwrap();

        // Create a test markdown file with proper frontmatter
        let post_path = content_dir.path().join("test-post.md");
        fs::write(
            &post_path,
            r#"---
title: "Test Post"
date: 2026-01-14T00:00:00Z
tags:
  - rust
  - web
---

Hello, world!
"#,
        )
        .unwrap();

        // Verify file was created
        assert!(post_path.exists());

        let builder = Builder::new(test_config(), content_dir.path(), output_dir.path());

        let stats = builder.build().unwrap();

        // Check outputs
        let html_path = output_dir.path().join("test-post/index.html");
        let tags_rust = output_dir.path().join("tags/rust/index.html");
        let tags_web = output_dir.path().join("tags/web/index.html");

        // Debug: print what exists
        if html_path.exists() {
            eprintln!("HTML exists at {:?}", html_path);
        } else {
            eprintln!("HTML NOT found at {:?}", html_path);
            // List output dir contents
            if output_dir.path().exists() {
                for entry in std::fs::read_dir(output_dir.path()).unwrap() {
                    eprintln!("  Output contains: {:?}", entry.unwrap().path());
                }
            }
        }

        assert_eq!(stats.pages, 1, "Expected 1 page, got {}", stats.pages);
        assert!(html_path.exists(), "HTML file should exist");
        assert!(tags_rust.exists(), "tags/rust should exist");
        assert!(tags_web.exists(), "tags/web should exist");
    }

    #[test]
    fn test_build_stats() {
        let stats = BuildStats::default();
        assert_eq!(stats.pages, 0);
        assert_eq!(stats.duration_ms, 0);
    }

    #[test]
    fn test_builder_with_static_dir() {
        let content_dir = TempDir::new().unwrap();
        let output_dir = TempDir::new().unwrap();
        let static_dir = TempDir::new().unwrap();

        // Create a static file
        fs::write(static_dir.path().join("style.css"), "body {}").unwrap();

        let builder = Builder::new(test_config(), content_dir.path(), output_dir.path())
            .with_static_dir(static_dir.path());

        let stats = builder.build().unwrap();

        assert_eq!(stats.assets, 1);
        assert!(output_dir.path().join("style.css").exists());
    }

    #[test]
    fn test_rss_feed_paths_default_vs_nondefault() {
        let content_dir = TempDir::new().unwrap();
        let output_dir = TempDir::new().unwrap();

        // Create posts in two languages — lang is detected from filename suffix
        fs::write(
            content_dir.path().join("en-post.md"),
            r#"---
title: "English Post"
date: 2026-01-14T00:00:00Z
---

English content.
"#,
        )
        .unwrap();
        fs::write(
            content_dir.path().join("zh-post.zh.md"),
            r#"---
title: "Chinese Post"
date: 2026-01-14T00:00:00Z
---

Chinese content.
"#,
        )
        .unwrap();

        let mut config = test_config();
        // Register both languages so all_languages() returns both
        config.languages.insert(
            "zh".to_string(),
            typstify_core::config::LanguageConfig {
                name: Some("中文".to_string()),
                title: None,
                description: None,
            },
        );

        let builder = Builder::new(config, content_dir.path(), output_dir.path());
        let stats = builder.build().unwrap();

        // Default language feed at root
        assert!(
            output_dir.path().join("rss.xml").exists(),
            "main RSS feed should exist at root"
        );
        // Non-default language feed in subdirectory
        assert!(
            output_dir.path().join("zh/rss.xml").exists(),
            "zh RSS feed should exist at output_dir/zh/rss.xml"
        );
        assert!(stats.pages >= 2);
    }

    fn multilang_config() -> Config {
        let mut languages = HashMap::new();
        languages.insert(
            "zh".to_string(),
            typstify_core::config::LanguageConfig {
                name: Some("中文".to_string()),
                title: None,
                description: None,
            },
        );
        Config::from_parts(
            typstify_core::config::SiteConfig {
                title: "Test Site".to_string(),
                host: "https://example.com".to_string(),
                base_path: String::new(),
                default_language: "en".to_string(),
                description: None,
                author: None,
            },
            typstify_core::config::BuildConfig::default(),
            typstify_core::config::SearchConfig::default(),
            typstify_core::config::RssConfig::default(),
            typstify_core::config::RobotsConfig::default(),
            typstify_core::config::TaxonomyConfig::default(),
            languages,
        )
    }

    #[test]
    fn test_multilang_page_generation() {
        use chrono::{TimeZone, Utc};

        let config = multilang_config();
        let generator = HtmlGenerator::new(&config);

        // Create English (default language) page
        let en_page = Page {
            url: "/posts/hello-world".to_string(),
            title: "Hello, World!".to_string(),
            description: Some("A test".to_string()),
            date: Some(Utc.with_ymd_and_hms(2024, 1, 15, 10, 0, 0).unwrap()),
            updated: None,
            draft: false,
            lang: "en".to_string(),
            is_default_lang: true,
            canonical_id: "posts/hello-world".to_string(),
            tags: vec![],
            categories: vec![],
            content: "<p>Hello, World!</p>".to_string(),
            summary: None,
            reading_time: None,
            word_count: None,
            toc: vec![],
            custom_js: vec![],
            custom_css: vec![],
            aliases: vec![],
            template: None,
            weight: 0,
            source_path: None,
        };

        // Create Chinese (non-default language) page
        let zh_page = Page {
            url: "/zh/posts/hello-world".to_string(),
            title: "你好世界".to_string(),
            description: Some("一个测试".to_string()),
            date: Some(Utc.with_ymd_and_hms(2024, 1, 15, 10, 0, 0).unwrap()),
            updated: None,
            draft: false,
            lang: "zh".to_string(),
            is_default_lang: false,
            canonical_id: "posts/hello-world".to_string(),
            tags: vec![],
            categories: vec![],
            content: "<p>你好</p>".to_string(),
            summary: None,
            reading_time: None,
            word_count: None,
            toc: vec![],
            custom_js: vec![],
            custom_css: vec![],
            aliases: vec![],
            template: None,
            weight: 0,
            source_path: None,
        };

        // Generate HTML for both pages
        let en_html = generator
            .generate_page(&en_page, &[])
            .expect("English page generation should succeed");
        let zh_html = generator
            .generate_page(&zh_page, &[])
            .expect("Chinese page generation should succeed");

        // English page: default language navigation URLs (no /zh/ prefix on nav links)
        assert!(
            en_html.contains("/posts"),
            "English page should have default language navigation URLs"
        );
        assert!(
            en_html.contains("/archives"),
            "English page should have default language archives URL"
        );
        assert!(
            en_html.contains("/tags"),
            "English page should have default language tags URL"
        );

        // Chinese page: contains Chinese language content
        assert!(
            zh_html.contains("你好"),
            "Chinese page should contain Chinese content"
        );
        assert!(
            zh_html.contains("lang=\"zh\""),
            "Chinese page should have lang='zh' attribute"
        );

        // Chinese page: /zh/ prefix in navigation URLs
        assert!(
            zh_html.contains("/zh/posts"),
            "Chinese page should have /zh/ prefix in navigation URLs"
        );
        assert!(
            zh_html.contains("/zh/archives"),
            "Chinese page should have /zh/ prefix in archives URL"
        );
        assert!(
            zh_html.contains("/zh/tags"),
            "Chinese page should have /zh/ prefix in tags URL"
        );

        // Language switcher: appears on both pages when multiple languages configured
        assert!(
            zh_html.contains("lang-switcher"),
            "Chinese page should contain language switcher"
        );
        assert!(
            zh_html.contains("中文"),
            "Language switcher should show Chinese language name"
        );
        assert!(
            en_html.contains("lang-switcher"),
            "English page should also contain language switcher when multiple languages configured"
        );
        assert!(
            en_html.contains("/zh/posts/hello-world"),
            "English page language switcher should link to Chinese version with /zh/ prefix"
        );
    }

    #[test]
    fn test_page_generation_failed_error() {
        let errors = vec![
            "page1.html".to_string(),
            "page2.html".to_string(),
            "page3.html".to_string(),
        ];
        let err = BuildError::PageGenerationFailed {
            errors: errors.clone(),
        };
        let msg = err.to_string();
        assert!(
            msg.contains("3 errors"),
            "should report error count, got: {msg}"
        );
        assert!(
            msg.contains("page generation failed"),
            "should include prefix, got: {msg}"
        );

        // Verify the inner errors are preserved
        match err {
            BuildError::PageGenerationFailed { errors: inner } => {
                assert_eq!(inner.len(), 3);
                assert_eq!(inner[0], "page1.html");
            }
            _ => panic!("wrong variant"),
        }
    }
}