Abbaye

at 8d154b4

use std::{
    future::Future,
    path::{Path, PathBuf},
    pin::Pin,
};

use chrono::{DateTime, SecondsFormat, Utc};
use indicatif::ProgressStyle;
use miette::{IntoDiagnostic, Result};
use sha2::{Digest, Sha256};
use tera::{Context, Tera};
use tracing::{info, warn};

use crate::{
    changelog::ChangelogExtractor,
    config::{AbbayeConfig, OutputFormat},
    render::{extract_local_refs, render_markdown_gemtext, render_markdown_html},
    utils,
    version_extractors::VersionInfo,
};

pub const TEMPLATE_BASE_HTML: &str = include_str!("templates/base.html.j2");
pub const TEMPLATE_ROOT_INDEX_HTML: &str = include_str!("templates/root_index.html.j2");
pub const TEMPLATE_VERSION_INDEX_HTML: &str = include_str!("templates/version_index.html.j2");
pub const TEMPLATE_ROOT_INDEX_GEMTEXT: &str = include_str!("templates/root_index.gmi.j2");
pub const TEMPLATE_VERSION_INDEX_GEMTEXT: &str = include_str!("templates/version_index.gmi.j2");
pub const SITE_CSS: &str = include_str!("templates/site.css");
const ATOM_FEED_FILENAME: &str = "releases.atom";

pub(crate) const SPINNER_CHARS: &str = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏ ";

/// Create a spinner style matching the rest of the abbaye UI.
/// When `indent` is true the template is prefixed with two spaces (for child spinners).
pub(crate) fn spinner_style(indent: bool) -> ProgressStyle {
    let tmpl = if indent {
        "  {spinner:.bold} {prefix} {msg}"
    } else {
        "{spinner:.bold} {prefix} {msg}"
    };
    ProgressStyle::with_template(tmpl)
        .expect("valid template")
        .tick_chars(SPINNER_CHARS)
}

// ── Types ───────────────────────────────────────────────────────────────────

/// A version entry as passed to Tera templates.
#[derive(serde::Serialize)]
struct VersionEntry {
    /// Version string (e.g. `"1.2.3"`).
    version: String,
    /// ISO-8601 date string (e.g. `"2024-01-15"`) when the release date is known.
    date: Option<String>,
}

impl VersionEntry {
    fn from_info(info: &VersionInfo) -> Self {
        Self {
            version: info.version.clone(),
            date: info.date.map(|dt| dt.format("%Y-%m-%d").to_string()),
        }
    }
}

/// Metadata about a single file-type dist artifact, passed to Tera templates.
#[derive(serde::Serialize, Clone)]
struct DistFileInfo {
    /// File name (relative to `dist/`).
    name: String,
    /// Raw byte size of the file.
    size_bytes: u64,
    /// Human-readable size (e.g. "1.4 MB").
    size_human: String,
    /// Lowercase hex-encoded SHA-256 digest of the file contents.
    sha256: String,
    /// Optional category inherited from the builder that produced this file.
    #[serde(skip_serializing_if = "Option::is_none")]
    category: Option<String>,
    /// Optional display name inherited from the builder entry.
    #[serde(skip_serializing_if = "Option::is_none")]
    group_name: Option<String>,
    /// Optional comment inherited from the builder entry.
    #[serde(skip_serializing_if = "Option::is_none")]
    group_comment: Option<String>,
}

/// A sub-group of dist artifacts sharing the same group name (from the same
/// builder entry).
#[derive(serde::Serialize)]
struct DistSubgroup {
    /// Display name for this group, or `None`.
    #[serde(skip_serializing_if = "Option::is_none")]
    name: Option<String>,
    /// Comment for this group, or `None`.
    #[serde(skip_serializing_if = "Option::is_none")]
    comment: Option<String>,
    /// Files in this sub-group.
    files: Vec<DistFileInfo>,
}

/// A group of dist artifacts sharing the same builder category.
#[derive(serde::Serialize)]
struct DistCategory {
    /// The shared category, or `None` for builders without one.
    category: Option<String>,
    /// Sub-groups within this category, each from a different builder entry.
    groups: Vec<DistSubgroup>,
}

/// Build the full website into `config.output_dir` (defaults to `public/`).
///
/// # Steps
///
/// 1. Extract the current version via the configured [`crate::version_extractors::AnyVersionExtractor`].
/// 2. Run every configured builder and split the resulting [`crate::builders::ArtifactPath`]s
///    into *dist* (regular files) and *docs* (directories).
/// 3. Copy dist artifacts to `<output>/<version>/dist/`.
/// 4. Copy doc directories to `<output>/<version>/docs/<crate>/` and archive
///    the whole `docs/` tree as `docs.tar.gz`.
/// 5. Render `<output>/<version>/index.html` from the project README and the
///    matching changelog section.
/// 6. Re-render the root `<output>/index.html`, listing all known versions
///    (newest first).
/// 7. Update the `<output>/latest` symlink (Unix) or redirect page (other).
pub async fn build_site(config: AbbayeConfig) -> Result<()> {
    let output_dir = &config.site.output_dir;

    tokio::fs::create_dir_all(output_dir)
        .await
        .into_diagnostic()?;

    // ── 1. Version ────────────────────────────────────────────────────────────
    info!("Extracting version …");
    let version_info = config.version_extractor.extract().await?;
    let version = version_info.version.clone();

    // ── 2. Tera setup ─────────────────────────────────────────────────────────
    info!("Setting up templates …");
    let mut tera = Tera::default();
    let theme_path = PathBuf::from(".abbaye").join("theme");

    // Load templates for each configured format (with theme overrides).
    register_format_templates(
        &mut tera,
        &theme_path,
        &config.site.formats,
        &[
            (
                "root_index",
                TEMPLATE_ROOT_INDEX_HTML,
                TEMPLATE_ROOT_INDEX_GEMTEXT,
            ),
            (
                "version_index",
                TEMPLATE_VERSION_INDEX_HTML,
                TEMPLATE_VERSION_INDEX_GEMTEXT,
            ),
        ],
    )?;
    // Write shared CSS to static/ so the git UI templates can reference it.
    {
        let static_dir = output_dir.join("static");
        tokio::fs::create_dir_all(&static_dir)
            .await
            .into_diagnostic()?;
        tokio::fs::write(static_dir.join("site.css"), SITE_CSS)
            .await
            .into_diagnostic()?;
    }
    // If there's a `static` directory in the theme, copy it over (may overwrite site.css).
    if theme_path.join("static").is_dir() {
        copy_dir_recursive(theme_path.join("static"), output_dir.join("static")).await?;
    }

    // ── 3. Builders (run in parallel, respecting depends_on ordering) ─────────
    info!("Running builders for version {version} …");
    let (dist_artifacts, doc_artifacts) =
        crate::builders::orchestrator::run_builders(&config.builders, &version).await?;

    // ── 4. Lay out dist/ ──────────────────────────────────────────────────────
    info!("Laying out {} dist artifact(s) …", dist_artifacts.len());
    let version_dir = output_dir.join(&version);
    let dist_dir = version_dir.join("dist");
    tokio::fs::create_dir_all(&dist_dir)
        .await
        .into_diagnostic()?;

    // Copy dist artifacts and compute size + SHA-256 in a single pass.
    let mut dist_file_infos: Vec<DistFileInfo> = Vec::new();
    for artifact in &dist_artifacts {
        let bytes = tokio::fs::read(&artifact.path).await.into_diagnostic()?;
        let size_bytes = bytes.len() as u64;
        let sha256 = hex_sha256(&bytes);
        let dest = dist_dir.join(&artifact.name);
        tokio::fs::write(&dest, &bytes).await.into_diagnostic()?;
        dist_file_infos.push(DistFileInfo {
            name: artifact.name.clone(),
            size_bytes,
            size_human: human_size(size_bytes),
            sha256,
            category: artifact.category.clone(),
            group_name: artifact.group_name.clone(),
            group_comment: artifact.group_comment.clone(),
        });
    }

    // Group dist artifacts by category, then by group name within each category.
    let mut category_map: std::collections::BTreeMap<Option<String>, Vec<DistFileInfo>> =
        std::collections::BTreeMap::new();
    for info in dist_file_infos {
        category_map
            .entry(info.category.clone())
            .or_default()
            .push(info);
    }
    let dist_categories: Vec<DistCategory> = category_map
        .into_iter()
        .map(|(category, files)| {
            let mut subgroup_map: std::collections::BTreeMap<
                (Option<String>, Option<String>),
                Vec<DistFileInfo>,
            > = std::collections::BTreeMap::new();
            for f in files {
                subgroup_map
                    .entry((f.group_name.clone(), f.group_comment.clone()))
                    .or_default()
                    .push(f);
            }
            let groups: Vec<DistSubgroup> = subgroup_map
                .into_iter()
                .map(|((name, comment), files)| DistSubgroup {
                    name,
                    comment,
                    files,
                })
                .collect();
            DistCategory { category, groups }
        })
        .collect();
    let has_dist = !dist_categories.is_empty();

    // ── 5. Lay out docs/ ──────────────────────────────────────────────────────
    info!("Laying out {} doc artifact(s) …", doc_artifacts.len());
    let has_docs = !doc_artifacts.is_empty();
    let has_docs_tarball;

    if has_docs {
        let docs_dir = version_dir.join("docs");

        for artifact in &doc_artifacts {
            // Copy the complete target/doc tree - this includes the shared
            // rustdoc CSS, JS, fonts and search indices at the root of the
            // directory in addition to the per-crate HTML subdirectories.
            copy_dir_recursive(artifact.path.clone(), docs_dir.clone()).await?;
        }

        // Rustdoc writes index.html at the root for single-crate projects.
        // For workspaces it may be absent; generate a fallback listing then.
        if !docs_dir.join("index.html").exists() {
            let crate_names = find_doc_crates(&docs_dir).await?;
            write_docs_index(&docs_dir, &crate_names).await?;
        }

        let tarball = version_dir.join("docs.tar.gz");
        let docs_dir_c = docs_dir.clone();
        let tarball_c = tarball.clone();
        tokio::task::spawn_blocking(move || utils::archive_dir(&docs_dir_c, &tarball_c))
            .await
            .into_diagnostic()??;

        has_docs_tarball = true;
    } else {
        has_docs_tarball = false;
    }

    // ── 6. Raw README content ─────────────────────────────────────────────────
    let readme_path = config
        .site
        .readme
        .as_deref()
        .unwrap_or(Path::new("README.md"));

    let readme_md = tokio::fs::read_to_string(readme_path)
        .await
        .unwrap_or_else(|_| {
            warn!("README not found at {}", readme_path.display());
            String::new()
        });

    // Copy any locally-referenced files (e.g. images) from the README's
    // directory into the version directory so they resolve correctly from
    // the generated pages.
    if !readme_md.is_empty() {
        let readme_dir = readme_path.parent().unwrap_or_else(|| Path::new("."));
        for rel in extract_local_refs(&readme_md) {
            let src = readme_dir.join(&rel);
            if src.is_file() {
                let dest = version_dir.join(&rel);
                if let Some(parent) = dest.parent() {
                    tokio::fs::create_dir_all(parent).await.into_diagnostic()?;
                }
                tokio::fs::copy(&src, &dest).await.into_diagnostic()?;
            }
        }
    }

    // ── 7. Raw changelog section ──────────────────────────────────────────────
    let changelog_md = match ChangelogExtractor
        .section(config.changelog.clone(), &version)
        .await
    {
        Ok(section) => section,
        Err(_) => {
            warn!("No changelog entry found for version {version}");
            String::new()
        }
    };

    // ── 8. Version pages (per format) ─────────────────────────────────────────
    info!("Rendering version pages …");

    // Git UI integration: derive the clone URL once and compute the tag name
    // for the current version so the templates can link into the repository UI.
    let git_ui_clone_url: Option<String> = config.git_ui.as_ref().and_then(|cfg| {
        cfg.clone_url.clone().or_else(|| {
            config
                .site
                .base_url
                .as_ref()
                .map(|b| format!("{}/repository.git", b.trim_end_matches('/')))
        })
    });
    let version_tag = config.version_extractor.tag_name(&version);
    let git_ui_path = config
        .git_ui
        .as_ref()
        .map(|cfg| {
            if cfg.prefix.is_empty() {
                String::new()
            } else {
                format!("{}/", cfg.prefix)
            }
        })
        .unwrap_or_default();

    for format in &config.site.formats {
        let suffix = format.extension();
        let tmpl_name = format!("version_index.{suffix}");
        let ext = format.extension();

        let (readme_content, changelog_content): (String, String) = match format {
            OutputFormat::Html => (
                render_markdown_html(&readme_md),
                render_markdown_html(&changelog_md),
            ),
            OutputFormat::Gemtext => (
                render_markdown_gemtext(&readme_md),
                render_markdown_gemtext(&changelog_md),
            ),
        };

        // Pre-render HTML versions (only needed for the HTML template)
        let (readme_html, changelog_html) = match format {
            OutputFormat::Html => (
                render_markdown_html(&readme_md),
                render_markdown_html(&changelog_md),
            ),
            OutputFormat::Gemtext => (String::new(), String::new()),
        };

        let mut ctx = Context::new();
        ctx.insert("config", &config);
        ctx.insert("project_name", &config.site.name);
        ctx.insert("lang", &config.site.lang);
        ctx.insert("repo_url", &config.site.repo_url);
        ctx.insert("version", &version);
        ctx.insert("readme_html", &readme_html);
        ctx.insert("changelog_html", &changelog_html);
        ctx.insert("readme_content", &readme_content);
        ctx.insert("changelog_content", &changelog_content);
        ctx.insert("has_docs", &has_docs);
        ctx.insert("has_docs_tarball", &has_docs_tarball);
        ctx.insert("has_dist", &has_dist);
        ctx.insert("dist_categories", &dist_categories);
        ctx.insert("git_ui_enabled", &config.git_ui.is_some());
        ctx.insert("git_ui_clone_url", &git_ui_clone_url);
        ctx.insert("git_ui_path", &git_ui_path);
        ctx.insert("version_tag", &version_tag);
        ctx.insert("root_path", "../");

        let content = tera.render(&tmpl_name, &ctx).into_diagnostic()?;
        tokio::fs::write(version_dir.join(format!("index.{ext}")), content)
            .await
            .into_diagnostic()?;
    }

    // ── 9. Root index.html + Atom feed ──────────────────────────────────────
    info!("Rendering root index and Atom feed …");
    // Collect every known version from the version extractor, ensure the
    // current version is present (handles untagged builds), then sort newest-first.
    let mut all_versions = config.version_extractor.extract_all().await?;
    if !all_versions.iter().any(|v| v.version == version) {
        all_versions.push(version_info.clone());
    }
    all_versions.sort_by(|a, b| compare_versions(&b.version, &a.version));

    // Build the template-friendly list (version string + optional date string).
    let version_entries: Vec<VersionEntry> =
        all_versions.iter().map(VersionEntry::from_info).collect();

    let base_url = config
        .site
        .base_url
        .as_deref()
        .map(|u| u.trim_end_matches('/'));

    for format in &config.site.formats {
        let suffix = format.extension();
        let tmpl_name = format!("root_index.{suffix}");
        let ext = format.extension();

        let mut ctx = Context::new();
        ctx.insert("config", &config);
        ctx.insert("project_name", &config.site.name);
        ctx.insert("lang", &config.site.lang);
        ctx.insert("repo_url", &config.site.repo_url);
        ctx.insert("versions", &version_entries);
        ctx.insert("atom_feed", ATOM_FEED_FILENAME);
        ctx.insert("git_ui_enabled", &config.git_ui.is_some());
        ctx.insert("git_ui_clone_url", &git_ui_clone_url);
        ctx.insert("git_ui_path", &git_ui_path);
        ctx.insert("root_path", "");

        let content = tera.render(&tmpl_name, &ctx).into_diagnostic()?;
        tokio::fs::write(output_dir.join(format!("index.{ext}")), content)
            .await
            .into_diagnostic()?;
    }

    // ── 10. Atom feed ─────────────────────────────────────────────────────────
    // Load all changelog sections once so we can embed release notes in feed entries.
    let changelog_sections = match ChangelogExtractor
        .all_sections(config.changelog.clone())
        .await
    {
        Ok(map) => map,
        Err(_) => {
            warn!("Could not load changelog for Atom feed; entries will have no content");
            std::collections::HashMap::new()
        }
    };

    let atom_xml = generate_atom_feed(
        &config.site.name,
        &all_versions,
        base_url,
        &changelog_sections,
    );
    tokio::fs::write(output_dir.join(ATOM_FEED_FILENAME), atom_xml)
        .await
        .into_diagnostic()?;

    // ── 11. `latest` symlink ──────────────────────────────────────────────────
    if let Some(latest) = all_versions.first() {
        update_latest_symlink(output_dir, &latest.version)?;
    }

    Ok(())
}

// ── Private helpers ───────────────────────────────────────────────────────────

/// Scan `docs_dir` for subdirectories that contain an `index.html` and return
/// their names. Used to build a fallback listing when rustdoc itself did not
/// generate a root `index.html` (typical for multi-crate workspaces).
async fn find_doc_crates(docs_dir: &Path) -> Result<Vec<String>> {
    let mut names = Vec::new();
    let mut entries = tokio::fs::read_dir(docs_dir).await.into_diagnostic()?;
    while let Some(entry) = entries.next_entry().await.into_diagnostic()? {
        let path = entry.path();
        if path.is_dir() && path.join("index.html").exists() {
            names.push(entry.file_name().to_string_lossy().into_owned());
        }
    }
    Ok(names)
}

/// Write a `docs/index.html` that either redirects straight to the single
/// crate's docs (one crate) or lists all crates (multiple crates).
async fn write_docs_index(docs_dir: &Path, crate_names: &[String]) -> Result<()> {
    let html = if crate_names.len() == 1 {
        format!(
            "<!DOCTYPE html><html><head>\
            <meta http-equiv=\"refresh\" content=\"0;url={}/index.html\">\
            </head></html>",
            crate_names[0]
        )
    } else {
        let items = crate_names
            .iter()
            .map(|n| format!("  <li><a href=\"{n}/index.html\">{n}</a></li>"))
            .collect::<Vec<_>>()
            .join("\n");
        format!(
            "<!DOCTYPE html>\n<html><head><meta charset=\"utf-8\">\
            <title>Documentation</title></head>\
            <body><h1>Documentation</h1><ul>\n{items}\n</ul></body></html>"
        )
    };

    tokio::fs::write(docs_dir.join("index.html"), html)
        .await
        .into_diagnostic()
}

/// Recursively copy the contents of `src` into `dst`.
///
/// Uses explicit boxing to satisfy the compiler for the async recursive call.
fn copy_dir_recursive(
    src: PathBuf,
    dst: PathBuf,
) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
    Box::pin(async move {
        tokio::fs::create_dir_all(&dst).await.into_diagnostic()?;
        let mut entries = tokio::fs::read_dir(&src).await.into_diagnostic()?;
        while let Some(entry) = entries.next_entry().await.into_diagnostic()? {
            let src_path = entry.path();
            let dst_path = dst.join(entry.file_name());
            if src_path.is_dir() {
                copy_dir_recursive(src_path, dst_path).await?;
            } else {
                tokio::fs::copy(&src_path, &dst_path)
                    .await
                    .into_diagnostic()?;
            }
        }
        Ok(())
    })
}

/// Compare two version strings, preferring semver ordering and falling back
/// to lexicographic comparison for non-semver strings (e.g. git describe output).
fn strip_v(s: &str) -> &str {
    s.strip_prefix('v').unwrap_or(s)
}

fn compare_versions(a: &str, b: &str) -> std::cmp::Ordering {
    match (
        semver::Version::parse(strip_v(a)),
        semver::Version::parse(strip_v(b)),
    ) {
        (Ok(va), Ok(vb)) => va.cmp(&vb),
        _ => a.cmp(b),
    }
}

/// Compute a lowercase hex-encoded SHA-256 digest of `data`.
fn hex_sha256(data: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(data);
    hasher
        .finalize()
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect()
}

/// Format a byte count as a human-readable string (e.g. "1.4 MB").
fn human_size(bytes: u64) -> String {
    const KIB: u64 = 1024;
    const MIB: u64 = KIB * 1024;
    const GIB: u64 = MIB * 1024;
    if bytes >= GIB {
        format!("{:.1} GB", bytes as f64 / GIB as f64)
    } else if bytes >= MIB {
        format!("{:.1} MB", bytes as f64 / MIB as f64)
    } else if bytes >= KIB {
        format!("{:.1} KB", bytes as f64 / KIB as f64)
    } else {
        format!("{bytes} B")
    }
}

/// Escape the five XML predefined characters in a string.
fn xml_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&apos;")
}

/// Generate an Atom 1.0 feed listing all known releases.
///
/// - `base_url`: when provided (already stripped of trailing `/`), used to
///   build `<link>` and `<id>` elements with absolute URLs.  When absent,
///   a `urn:` based ID is used and no `<link>` elements are emitted.
/// - `changelog_sections`: map from version string to Markdown release-note
///   body.  When a matching entry is found it is rendered to HTML and included
///   as a `<content type="html">` element in the Atom entry.
fn generate_atom_feed(
    project_name: &str,
    versions: &[VersionInfo],
    base_url: Option<&str>,
    changelog_sections: &std::collections::HashMap<String, String>,
) -> String {
    let now: DateTime<Utc> = Utc::now();

    // The feed's <updated> is the most-recent entry date, or now as fallback.
    let feed_updated = versions.iter().filter_map(|v| v.date).max().unwrap_or(now);

    let feed_updated_str = feed_updated.to_rfc3339_opts(SecondsFormat::Secs, true);

    // Feed-level <id> and self-link.
    let feed_id = match base_url {
        Some(base) => format!("{base}/{ATOM_FEED_FILENAME}"),
        None => format!("urn:abbaye:feed:{}", xml_escape(project_name)),
    };

    let self_link = match base_url {
        Some(base) => format!(
            "  <link rel=\"self\" href=\"{}/{ATOM_FEED_FILENAME}\"/>\n",
            xml_escape(base)
        ),
        None => String::new(),
    };
    let alt_link = match base_url {
        Some(base) => format!("  <link href=\"{}\"/>\n", xml_escape(base)),
        None => String::new(),
    };

    let entries: String = versions
        .iter()
        .map(|vi| {
            let entry_date = vi.date.unwrap_or(now);
            let entry_date_str = entry_date.to_rfc3339_opts(SecondsFormat::Secs, true);
            let v_escaped = xml_escape(&vi.version);

            let entry_id = match base_url {
                Some(base) => format!("{base}/{v_escaped}/"),
                None => format!(
                    "urn:abbaye:release:{}:{v_escaped}",
                    xml_escape(project_name)
                ),
            };

            let entry_link = match base_url {
                Some(base) => format!("    <link href=\"{base}/{v_escaped}/\"/>\n"),
                None => String::new(),
            };

            // Render the changelog section (if any) to HTML, then XML-escape
            // it for embedding inside <content type="html">.
            let content_element = match changelog_sections.get(&vi.version) {
                Some(md) if !md.is_empty() => {
                    let html = render_markdown_html(md);
                    format!(
                        "    <content type=\"html\">{}</content>\n",
                        xml_escape(&html)
                    )
                }
                _ => String::new(),
            };

            format!(
                "  <entry>\n\
                 \x20   <title>{v_escaped}</title>\n\
                 \x20   <id>{entry_id}</id>\n\
                 \x20   <updated>{entry_date_str}</updated>\n\
                 {entry_link}\
                 {content_element}\
                 \x20 </entry>"
            )
        })
        .collect::<Vec<_>>()
        .join("\n");

    format!(
        "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\
         <feed xmlns=\"http://www.w3.org/2005/Atom\">\n\
         \x20 <title>{name} Releases</title>\n\
         {self_link}\
         {alt_link}\
         \x20 <updated>{feed_updated_str}</updated>\n\
         \x20 <id>{feed_id}</id>\n\
         {entries}\n\
         </feed>\n",
        name = xml_escape(project_name),
    )
}

/// Create or replace the `latest` symlink in `output_dir`, pointing to
/// `version_dir_name`.
///
/// On non-Unix platforms a meta-refresh redirect page is written instead.
fn update_latest_symlink(output_dir: &Path, version_dir_name: &str) -> Result<()> {
    let link = output_dir.join("latest");

    #[cfg(unix)]
    {
        // Remove any stale symlink or file before (re-)creating it.
        if link.exists() || link.is_symlink() {
            std::fs::remove_file(&link).into_diagnostic()?;
        }
        std::os::unix::fs::symlink(version_dir_name, &link).into_diagnostic()?;
    }

    #[cfg(not(unix))]
    {
        std::fs::create_dir_all(&link).into_diagnostic()?;
        std::fs::write(
            link.join("index.html"),
            format!(
                "<!DOCTYPE html><html><head>\
                <meta http-equiv=\"refresh\" content=\"0;url=../{version_dir_name}/\">\
                </head></html>"
            ),
        )
        .into_diagnostic()?;
    }

    Ok(())
}

/// Register templates for each configured output format, supporting theme overrides.
///
/// For each `format` in `formats` and each `(base_name, html_builtin, gmi_builtin)`
/// tuple in `templates`, registers a Tera template named `"{base_name}.{ext}"` —
/// first checking for a user override at `theme_path / "{base_name}.{ext}.j2"`,
/// otherwise falling back to the corresponding builtin constant.
///
/// After registering the format-specific templates, also loads any extra `.j2`
/// files from the theme directory that weren't explicitly registered (see
/// [`load_extra_theme_templates`]).
pub(crate) fn register_format_templates(
    tera: &mut Tera,
    theme_path: &Path,
    formats: &[OutputFormat],
    templates: &[(&str, &str, &str)],
) -> Result<()> {
    // Register the shared HTML base template so child templates can
    // {% extends "base.html" %}.  A theme override at
    // theme/base.html.j2 takes precedence when present.
    let base_theme = theme_path.join("base.html.j2");
    if base_theme.is_file() {
        tera.add_template_file(&base_theme, Some("base.html"))
            .into_diagnostic()?;
    } else {
        tera.add_raw_template("base.html", TEMPLATE_BASE_HTML)
            .into_diagnostic()?;
    }

    for format in formats {
        let ext = format.extension();
        for (template_base, builtin_html, builtin_gmi) in templates {
            let name = format!("{template_base}.{ext}");
            let builtin = match format {
                OutputFormat::Html => builtin_html,
                OutputFormat::Gemtext => builtin_gmi,
            };
            let theme_file = theme_path.join(format!("{template_base}.{ext}.j2"));
            if theme_file.is_file() {
                tera.add_template_file(&theme_file, Some(&name))
                    .into_diagnostic()?;
            } else {
                tera.add_raw_template(&name, builtin).into_diagnostic()?;
            }
        }
    }

    let skip_names: Vec<String> = formats
        .iter()
        .flat_map(|fmt| {
            let ext = fmt.extension();
            templates
                .iter()
                .map(move |(base, _, _)| format!("{base}.{ext}"))
        })
        .collect();
    let skip_refs: Vec<&str> = skip_names.iter().map(|s| s.as_str()).collect();
    load_extra_theme_templates(tera, theme_path, &skip_refs)?;
    Ok(())
}

/// Scans `theme_path` for any `*.j2` files whose stem (the name without the
/// `.j2` suffix, e.g. `"base.html"`) is **not** already listed in `skip`, and
/// loads each one into `tera` under that stem name.
///
/// This makes user-supplied helper or base templates - e.g. a `base.html.j2`
/// referenced by `{% extends "base.html" %}` in a customised main template -
/// available at render time without the caller needing to enumerate them.
pub(crate) fn load_extra_theme_templates(
    tera: &mut tera::Tera,
    theme_path: &std::path::Path,
    skip: &[&str],
) -> miette::Result<()> {
    let entries = match std::fs::read_dir(theme_path) {
        Ok(e) => e,
        Err(_) => return Ok(()), // theme dir absent - nothing to do
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("j2") {
            continue;
        }
        let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
            continue;
        };
        if skip.contains(&stem) {
            continue;
        }
        tera.add_template_file(&path, Some(stem)).map_err(|e| {
            miette::miette!("failed to load theme template {}: {e}", path.display())
        })?;
    }
    Ok(())
}