// Output plugins: extra files generated from the finished page set.
//
// Plugins are named in `plugins: [sitemap, rss, robots]` and run after every page
// and asset has been written. Unknown names are ignored by the pipeline and
// reported as warnings by `check`.
//
// Each plugin has a built-in default and an override: a template named after the
// plugin (`_includes/sitemap.jinja`, `_includes/rss.liquid`, ...) replaces the
// whole file, rendered with the same data the default was built from. The
// override model is "one file per output", not "one fragment per item": a feed
// has an order, a header and an escape rule, and splitting those apart produces
// more configuration than it saves.

///|
/// Execute one built-in output plugin.
///
/// Returns the output-relative files it wrote, so the caller can record them in
/// the manifest and delete them again when the plugin is removed from the
/// configuration. Unknown names write nothing.
pub async fn run_plugin(
  plugin : StringView,
  cfg : @config.Config,
  pages : Array[Page],
  site_data : Json,
  env : @engine.TemplateEnv,
) -> Array[String] {
  let root = cfg.output_path()
  let written : Array[String] = []
  match plugin.to_owned().to_lower() {
    "sitemap" => {
      let base = site_base(site_data)
      let entries : Array[Json] = []
      for page in pages {
        if page.paginated {
          continue
        }
        entries.push(generator_page(page, base, false))
      }
      let ctx = generator_ctx(site_data, base, entries, [])
      let text = match plugin_override("sitemap", ctx, env) {
        Some(rendered) => rendered
        None => {
          let buf = StringBuilder(capacity=512)
          buf.write_string(
            "\n\n",
          )
          for page in pages {
            if page.paginated {
              continue
            }
            buf.write_string(
              "\{@core.html_escape("\{base}\{page.url}")}",
            )
            let date = str_field(page.data, "date", "")
            if date != "" {
              buf.write_string("\{date}")
            }
            buf.write_string("\n")
          }
          buf.write_string("\n")
          buf.to_string()
        }
      }
      @core.write_if_changed(@core.join_path(root, "sitemap.xml"), text)
      |> ignore
      written.push("sitemap.xml")
    }
    "rss" | "feed" => {
      let base = site_base(site_data)
      let title = str_field(site_data, "title", cfg.root)
      let items : Array[Json] = []
      for page in pages {
        if is_listing(page) {
          continue
        }
        items.push(generator_page(page, base, false))
      }
      let ctx = generator_ctx(site_data, base, items, [])
      let text = match plugin_override("rss", ctx, env) {
        Some(rendered) => rendered
        None => {
          let buf = StringBuilder(capacity=512)
          buf.write_string(
            "\n\n",
          )
          buf.write_string(
            "\{@core.html_escape(title)}\n\{@core.html_escape(base)}\n",
          )
          for page in pages {
            if is_listing(page) {
              continue
            }
            buf.write_string(
              "\{@core.html_escape(str_field(page.data, "title", page.url))}",
            )
            buf.write_string(
              "\{@core.html_escape("\{base}\{page.url}")}",
            )
            buf.write_string(
              "\{@core.html_escape(str_field(page.data, "description", ""))}",
            )
            buf.write_string("\n")
          }
          buf.write_string("\n")
          buf.to_string()
        }
      }
      @core.write_if_changed(@core.join_path(root, "feed.xml"), text) |> ignore
      written.push("feed.xml")
    }
    "llms" => {
      // A two-file, plain-text view of the site for LLM retrieval: a short
      // index (`llms.txt`) and the raw page bodies (`llms-full.txt`).
      //
      // Both are plain text, while Jinja escapes for HTML, so an override marks
      // its values safe (`{{ page.link | safe }}`).
      let base = site_base(site_data)
      let title = str_field(site_data, "title", cfg.root)
      let description = str_field(site_data, "description", "")
      let docs : Array[Json] = []
      let blog : Array[Json] = []
      let other : Array[Json] = []
      let full : Array[Json] = []
      for page in pages {
        if page.paginated || page.skip {
          continue
        }
        let entry = generator_page(page, base, false)
        if str_field(page.data, "doc", "") != "" {
          docs.push(entry)
        } else if str_field(page.data, "nav", "") == "blog" {
          blog.push(entry)
        } else {
          other.push(entry)
        }
        full.push(generator_page(page, base, true))
      }
      let ctx = generator_ctx(site_data, base, other, [
        ("docs", @core.jarr(docs)),
        ("blog", @core.jarr(blog)),
        ("entries", @core.jarr(full)),
      ])
      let index = match plugin_override("llms", ctx, env) {
        Some(rendered) => rendered
        None => {
          let index = StringBuilder(capacity=1024)
          index.write_string("# \{title}\n\n> \{description}\n\n")
          index.write_string("## Documentation\n\n")
          for page in pages {
            if page.paginated || page.skip {
              continue
            }
            if str_field(page.data, "doc", "") != "" {
              llms_link(index, page, base)
            }
          }
          index.write_string("\n## Blog\n\n")
          for page in pages {
            if page.paginated || page.skip {
              continue
            }
            if str_field(page.data, "nav", "") == "blog" &&
              str_field(page.data, "doc", "") == "" {
              llms_link(index, page, base)
            }
          }
          index.write_string("\n## Pages\n\n")
          for page in pages {
            if page.paginated || page.skip {
              continue
            }
            if str_field(page.data, "doc", "") == "" &&
              str_field(page.data, "nav", "") != "blog" {
              llms_link(index, page, base)
            }
          }
          index.to_string()
        }
      }
      let bodies = match plugin_override("llms-full", ctx, env) {
        Some(rendered) => rendered
        None => {
          let full_text = StringBuilder(capacity=4096)
          full_text.write_string("# \{title}\n\n> \{description}\n\n")
          for page in pages {
            if page.paginated || page.skip {
              continue
            }
            let title = str_field(page.data, "title", page.url)
            let description = str_field(page.data, "description", "")
            full_text.write_string(
              "\n## \{title}\n\nURL: \{base}\{page.url}\n\n",
            )
            if description != "" {
              full_text.write_string("\{description}\n\n")
            }
            full_text.write_string(@core.trim(page.body))
            full_text.write_string("\n")
          }
          full_text.to_string()
        }
      }
      @core.write_if_changed(@core.join_path(root, "llms.txt"), index) |> ignore
      @core.write_if_changed(@core.join_path(root, "llms-full.txt"), bodies)
      |> ignore
      written.push("llms.txt")
      written.push("llms-full.txt")
    }
    "robots" => {
      let base = site_base(site_data)
      // Only point at a sitemap this build actually writes; a dangling
      // `Sitemap:` line sends crawlers to a 404.
      let sitemap = if cfg.plugins.contains("sitemap") {
        "\{base}/sitemap.xml"
      } else {
        ""
      }
      let ctx = generator_ctx(site_data, base, [], [
        ("sitemap", @core.jstr(sitemap)),
      ])
      let text = match plugin_override("robots", ctx, env) {
        Some(rendered) => rendered
        None => {
          let line = if sitemap == "" { "" } else { "Sitemap: \{sitemap}\n" }
          "User-agent: *\nAllow: /\n\{line}"
        }
      }
      @core.write_if_changed(@core.join_path(root, "robots.txt"), text)
      |> ignore
      written.push("robots.txt")
    }
    "jsonfeed" => {
      let base = site_base(site_data)
      let feed = @core.jobj([
        ("version", @core.jstr("https://jsonfeed.org/version/1.1")),
        ("title", @core.jstr(str_field(site_data, "title", cfg.root))),
        ("home_page_url", @core.jstr(base)),
        (
          "items",
          @core.jarr(
            pages
            .filter(fn(p) { !is_listing(p) })
            .map(fn(p) {
              @core.jobj([
                ("id", @core.jstr("\{base}\{p.url}")),
                ("url", @core.jstr("\{base}\{p.url}")),
                ("title", @core.jstr(str_field(p.data, "title", p.url))),
                ("summary", @core.jstr(str_field(p.data, "description", ""))),
              ])
            }),
          ),
        ),
      ])
      @core.write_if_changed(
        @core.join_path(root, "feed.json"),
        feed.stringify(indent=2),
      )
      |> ignore
      written.push("feed.json")
    }
    _ => ()
  }
  written
}

// `site.url` without its trailing slash. Every page URL starts with one, and
// `https://example.com/` + `/about/` would otherwise produce `//about/` in the
// sitemap, the feeds and the generator context templates read as `base`.

///|
fn site_base(site_data : Json) -> String {
  @core.strip_trailing_slash(str_field(site_data, "url", ""))
}

///|
/// Render a site's override for one generator, if it wrote one.
///
/// The template is looked up by the plugin's name, so `_includes/sitemap.jinja`
/// and `_templates/robots.liquid` both work and the extension picks the engine.
pub fn plugin_override(
  name : StringView,
  ctx : Json,
  env : @engine.TemplateEnv,
) -> String? {
  match env.sources.get(name.to_owned()) {
    Some(_) => Some(@engine.render_template(name, ctx, env))
    None => None
  }
}

// One page as a generator template sees it: relative url, absolute link, and
// the front-matter fields generators quote. `with_body` adds the raw Markdown,
// which only `llms-full` needs.

///|
fn generator_page(page : Page, base : String, with_body : Bool) -> Json {
  let fields : Array[(String, Json)] = [
    ("url", @core.jstr(page.url)),
    ("link", @core.jstr("\{base}\{page.url}")),
    ("title", @core.jstr(str_field(page.data, "title", page.url))),
    ("date", @core.jstr(str_field(page.data, "date", ""))),
    ("description", @core.jstr(str_field(page.data, "description", ""))),
  ]
  if with_body {
    fields.push(("body", @core.jstr(@core.trim(page.body))))
  }
  @core.jobj(fields)
}

// The shared context of every generator override, plus plugin-specific keys.

///|
fn generator_ctx(
  site_data : Json,
  base : String,
  pages : Array[Json],
  extra : Array[(String, Json)],
) -> Json {
  let fields : Array[(String, Json)] = [
    ("site", site_data),
    ("base", @core.jstr(base)),
    ("pages", @core.jarr(pages)),
  ]
  for entry in extra {
    fields.push(entry)
  }
  @core.jobj(fields)
}

///|
/// Remove redundant whitespace from generated HTML.
///
/// Scans for `<` and copies whole runs instead of walking character by
/// character: page text is UTF-16, so per-character scanning both costs a
/// transition per character and can split a surrogate pair.
pub fn minify_html(input : StringView) -> String {
  let s = input.to_owned()
  let n = s.length()
  let result = StringBuilder(capacity=n)
  let mut i = 0
  while i < n {
    let next_tag = match find_at(s, "<", i) {
      Some(at) => at
      None => n
    }
    if next_tag > i {
      result.write_string(flatten_text(@core.slice(s, i, next_tag)))
    }
    if next_tag >= n {
      break
    }
    let end = match find_at(s, ">", next_tag + 1) {
      Some(at) => at
      None => {
        result.write_string(flatten_text(@core.slice(s, next_tag, n)))
        break
      }
    }
    let tag = @core.slice(s, next_tag, end + 1)
    let lower = tag.to_lower()
    let closing = if lower.has_prefix("")
    } else if lower.has_prefix("")
    } else if lower.has_prefix("")
    } else if lower.has_prefix("")
    } else {
      None
    }
    match closing {
      Some(close) =>
        match find_at(s, close, end + 1) {
          Some(close_at) => {
            // `pre`, `textarea`, `script` and `style` keep their bytes intact:
            // whitespace is significant there and `` may sit inside a
            // string literal.
            result.write_string(
              @core.slice(s, next_tag, close_at + close.length()),
            )
            i = close_at + close.length()
            continue
          }
          None => ()
        }
      None => ()
    }
    result.write_string(flatten_text(tag))
    i = end + 1
  }
  @core.trim(result.to_string()) + "\n"
}

// Collapse newlines and tabs to single spaces, leaving everything else alone.

///|
fn flatten_text(text : StringView) -> String {
  text.replace_all(old="\n", new=" ").replace_all(old="\t", new=" ").to_owned()
}

// Find a substring from an index without checking boundaries.

///|
fn find_at(s : StringView, needle : StringView, from : Int32) -> Int32? {
  if from >= s.length() {
    return None
  }
  match s[from:s.length()].find(needle) {
    Some(i) => Some(from + i)
    None => None
  }
}

// Whether a page is a listing rather than an article: the home page and every
// archive are files named `index`, and a page URL always ends in `/`, so the
// source name is the only reliable signal. Feed readers want the articles.

///|
fn is_listing(page : Page) -> Bool {
  page.paginated ||
  @core.strip_ext(@core.basename(page.src)).to_lower() == "index"
}

// Append one llms.txt link, using the page description as its note.

///|
fn llms_link(buf : StringBuilder, page : Page, base : String) -> Unit {
  let title = str_field(page.data, "title", page.url)
  let description = str_field(page.data, "description", "")
  let suffix = if description == "" { "" } else { ": \{description}" }
  buf.write_string("- [\{title}](\{base}\{page.url})\{suffix}\n")
}