//! Create documentation pages for each rule. Pages are printed as Markdown and
//! get added to the website.

use oxc_linter::{table::RuleTableRow, RuleFixMeta};
use std::fmt::{self, Write};

use crate::linter::rules::html::HtmlWriter;

pub fn render_rule_docs_page(rule: &RuleTableRow) -> Result<String, fmt::Error> {
    const APPROX_FIX_CATEGORY_AND_PLUGIN_LEN: usize = 512;
    let RuleTableRow { name, documentation, plugin, turned_on_by_default, autofix, .. } = rule;

    let mut page = HtmlWriter::with_capacity(
        documentation.map_or(0, str::len) + name.len() + APPROX_FIX_CATEGORY_AND_PLUGIN_LEN,
    );

    writeln!(
        page,
        "<!-- This file is auto-generated by {}. Do not edit it manually. -->\n",
        file!()
    )?;
    writeln!(page, "# {plugin}/{name}\n")?;

    // rule metadata
    page.div(r#"class="rule-meta""#, |p| {
        if *turned_on_by_default {
            p.span(r#"class="default-on""#, |p| {
                p.writeln("✅ This rule is turned on by default.")
            })?;
        }

        if let Some(emoji) = fix_emoji(*autofix) {
            p.span(r#"class="fix""#, |p| {
                p.writeln(format!("{} {}", emoji, autofix.description()))
            })?;
        }

        Ok(())
    })?;

    // rule documentation
    if let Some(docs) = documentation {
        writeln!(page, "\n{}", *docs)?;
    }

    // TODO: link to rule source

    Ok(page.into())
}

fn fix_emoji(fix: RuleFixMeta) -> Option<&'static str> {
    match fix {
        RuleFixMeta::None => None,
        RuleFixMeta::FixPending => Some("🚧"),
        RuleFixMeta::Conditional(_) | RuleFixMeta::Fixable(_) => Some("🛠️"),
    }
}
