// Read-only validation of a site: configuration, layouts, includes, URLs and
// drafts. Shares the scanner from `build`, so a change to permalink rules or
// page extensions cannot make `check` disagree with a real build.

///|
/// Severity of one validation finding.
pub enum IssueLevel {
  Error
  Warning
}

///|
/// One finding produced by `check_site`.
///
/// `message` is written for humans and names the offending file, layout or key.
pub struct CheckIssue {
  level : IssueLevel
  message : String
}

///|
/// The severity of an issue as a lowercase word, for consoles and CI logs.
pub fn CheckIssue::level_name(self : CheckIssue) -> String {
  match self.level {
    Error => "error"
    Warning => "warning"
  }
}

///|
/// Result of `check_site`.
///
/// `errors` and `warnings` are counts, `issues` holds every finding in
/// discovery order, and `pages`/`assets` report how much input was scanned.
/// A report with zero errors means a build would very likely succeed.
pub struct CheckReport {
  errors : Int32
  warnings : Int32
  pages : Int32
  assets : Int32
  issues : Array[CheckIssue]
}

///|
/// Whether the site passed validation, i.e. no errors were found.
pub fn CheckReport::is_ok(self : CheckReport) -> Bool {
  self.errors == 0
}

// Append one finding to a report under construction.

///|
fn report_issue(
  issues : Array[CheckIssue],
  level : IssueLevel,
  message : String,
) -> Unit {
  issues.push(CheckIssue::{ level, message, })
}

// Remove `{% raw %}...{% endraw %}` sections before scanning for `include`
// targets: documentation pages quote templates and those examples are not real
// references.

///|
fn without_raw(text : String) -> String {
  let out = StringBuilder(capacity=text.length())
  let mut cursor = 0
  while true {
    let open = match find_at(text, "{% raw", cursor) {
      Some(i) => i
      None => break
    }
    out.write_string(@core.slice(text, cursor, open))
    let close = match find_at(text, "{% endraw", open) {
      Some(i) => i
      None => break
    }
    cursor = close + 9
    while cursor < text.length() && text[cursor] != '}' {
      cursor += 1
    }
    if cursor < text.length() {
      cursor += 1
    }
  }
  if cursor < text.length() {
    out.write_string(@core.slice(text, cursor, text.length()))
  }
  out.to_string()
}

// Drop fenced code blocks. A page that documents `{% include "menu.jinja" %}`
// is showing syntax, not rendering it, and reporting the sample as a missing
// include is the kind of warning that teaches people to ignore warnings.

///|
fn without_fences(text : String) -> String {
  let out = StringBuilder(capacity=text.length())
  let mut cursor = 0
  while true {
    let open = match find_at(text, "```", cursor) {
      Some(i) => i
      None => break
    }
    out.write_string(@core.slice(text, cursor, open))
    // Skip the info string (`yaml`, `jinja`, ...) to the end of its line.
    let mut line_end = open + 3
    while line_end < text.length() && text[line_end] != '\n' {
      line_end = line_end + 1
    }
    let close = match find_at(text, "```", line_end) {
      Some(i) => i
      None => break
    }
    let mut after = close + 3
    while after < text.length() && text[after] != '\n' {
      after = after + 1
    }
    cursor = if after < text.length() { after + 1 } else { after }
  }
  if cursor < text.length() {
    out.write_string(@core.slice(text, cursor, text.length()))
  }
  out.to_string()
}

// Drop inline code spans, so a page that writes `` `{% include "x" %}` `` in a
// sentence is not read as a directive either.

///|
fn without_code_spans(text : String) -> String {
  let out = StringBuilder(capacity=text.length())
  let mut cursor = 0
  while true {
    let open = match find_at(text, "`", cursor) {
      Some(i) => i
      None => break
    }
    out.write_string(@core.slice(text, cursor, open))
    let close = match find_at(text, "`", open + 1) {
      Some(i) => i
      None => break
    }
    // A space keeps `a`b` from being glued into `ab`.
    out.write_string(" ")
    cursor = close + 1
  }
  if cursor < text.length() {
    out.write_string(@core.slice(text, cursor, text.length()))
  }
  out.to_string()
}

// Collect `include "name"` targets from template and page text.

///|
fn scan_includes(text : String, on_name : (String) -> Unit) -> Unit {
  let mut from = 0
  while true {
    let at = match find_at(text, "include", from) {
      Some(i) => i
      None => return
    }
    from = at + 7
    let mut i = from
    while i < text.length() && (text[i] == ' ' || text[i] == '\t') {
      i += 1
    }
    if i >= text.length() {
      return
    }
    let quote = text[i]
    if quote != '"' && quote != '\'' {
      continue
    }
    let mut end = i + 1
    while end < text.length() && text[end] != quote {
      end += 1
    }
    if end >= text.length() {
      return
    }
    on_name(@core.slice(text, i + 1, end))
    from = end + 1
  }
}

// Plugins the build pipeline knows how to run.

///|
fn known_plugin(name : String) -> Bool {
  ["sitemap", "rss", "feed", "robots", "jsonfeed", "llms", "minify"].contains(
    name.to_lower(),
  )
}

// Generator templates and the plugin that renders them. `llms-full` is written
// by `llms` alongside `llms.txt`, and `feed` is the alias of `rss`.

///|
fn generator_templates() -> Array[(String, String)] {
  [
    ("sitemap", "sitemap"),
    ("rss", "rss"),
    ("robots", "robots"),
    ("llms", "llms"),
    ("llms-full", "llms"),
  ]
}

// Whether `plugin` is enabled, accepting `feed` as the other name of `rss`.

///|
fn plugin_enabled(cfg : @config.Config, plugin : String) -> Bool {
  cfg.plugins.contains(plugin) ||
  (plugin == "rss" && cfg.plugins.contains("feed"))
}

// Return the layout that repeats when a chain loops back, or None.

///|
fn layout_cycle(parents : Map[String, String], start : String) -> String? {
  let seen : Array[String] = []
  let mut current = start
  let mut result : String? = None
  let mut done = false
  while !done {
    if seen.contains(current) {
      result = Some(current)
      done = true
    } else {
      seen.push(current)
      match parents.get(current) {
        Some(p) => if p == "" { done = true } else { current = p }
        None => done = true
      }
    }
  }
  result
}

///|
/// Validate a site without writing any output, using the built-in formats.
pub async fn check_site(options : @build.BuildOptions) -> CheckReport {
  check_site_with(
    options,
    @formats.FormatRegistry::builtin(),
    @content.ContentRegistry::builtin(),
  )
}

///|
/// Validate a site with an explicit format registry.
///
/// Checks the configuration file, the content and layout directories, front
/// matter delimiters, layout chains, `include` targets, duplicate permalinks,
/// unknown plugins and skipped drafts. Only reads files: `_site` and
/// `.fus-cache` are never modified, so this is safe to run in CI.
pub async fn check_site_with(
  options : @build.BuildOptions,
  formats : @formats.FormatRegistry,
  contents : @content.ContentRegistry,
) -> CheckReport {
  let issues : Array[CheckIssue] = []
  let config_path = @config.resolve_config_path(options.root, options.config)
  let config_text = @core.read_text_or(config_path, "")
  if @core.trim(config_text) == "" {
    report_issue(
      issues,
      Warning,
      "no configuration at \{config_path}; defaults are used",
    )
  } else {
    let parsed = formats.parse(
      config_text,
      @formats.format_of_path(config_path),
    )
    if @core.keys(parsed).length() == 0 {
      report_issue(
        issues,
        Error,
        "cannot parse \{config_path}; check indentation and quoting",
      )
    }
  }
  let cfg = @config.load_config_with(
    options.root,
    options.config,
    options.dest,
    options.force,
    formats,
    contents,
  )
  for plugin in cfg.plugins {
    if !known_plugin(plugin) {
      report_issue(
        issues,
        Warning,
        "unknown plugin \"\{plugin}\"; it is ignored",
      )
    }
  }
  let theme = @build.resolve_theme(cfg)
  let theme_root = @build.theme_path(theme)
  match theme {
    @build.NoTheme =>
      if cfg.theme != "" {
        report_issue(
          issues,
          Error,
          "theme directory \{cfg.theme_path()} does not exist, and no built-in theme has that name",
        )
      }
    _ => ()
  }
  let source_root = cfg.source_path()
  if !@fs.exists(source_root) {
    report_issue(
      issues,
      Error,
      "content directory \{source_root} does not exist",
    )
  }
  // Layouts and includes: theme files are defaults, site files override them.
  let layout_root = @core.join_path(cfg.root, cfg.layouts_dir)
  let include_root = @core.join_path(cfg.root, cfg.includes_dir)
  let layout_texts : Map[String, String] = Map([])
  let include_names : Map[String, Bool] = Map([])
  let include_texts : Map[String, String] = Map([])
  let layout_roots : Array[String] = []
  let include_roots : Array[String] = []
  // The built-in theme is the lowest-priority source, exactly as in the build:
  // a theme on disk and the site both override it. Its layouts are compiled, so
  // they contribute a name and a known parent instead of a text to parse; an
  // empty text marks the compiled placeholder.
  let compiled_parents : Map[String, String] = Map([])
  if theme == @build.BuiltinTheme {
    for name in @theme.layout_names() {
      compiled_parents.set(name, if name == "post" { "base" } else { "" })
      layout_texts.set(name, "")
    }
  }
  if theme_root != "" {
    layout_roots.push(@core.join_path(theme_root, cfg.layouts_dir))
    include_roots.push(@core.join_path(theme_root, cfg.includes_dir))
  }
  layout_roots.push(layout_root)
  include_roots.push(include_root)
  for root in layout_roots {
    if @fs.exists(root) {
      for rel in @core.collect_files(root, fn(_) { false }) {
        if !@build.is_page_file(rel, cfg) {
          continue
        }
        let name = @core.strip_ext(rel)
        layout_texts.set(
          name,
          @core.read_text_or(@core.join_path(root, rel), ""),
        )
      }
    }
  }
  for root in include_roots {
    if @fs.exists(root) {
      for rel in @core.collect_files(root, fn(_) { false }) {
        if !@build.is_page_file(rel, cfg) {
          continue
        }
        let name = @core.strip_ext(rel)
        include_names.set(name, true)
        include_names.set(rel, true)
        // The bare name is enough: scanning both spellings would report every
        // missing target twice.
        include_texts.set(
          name,
          @core.read_text_or(@core.join_path(root, rel), ""),
        )
      }
    }
  }
  // A generator template only runs when its plugin does. Saying nothing here
  // makes a forgotten `plugins:` entry look like a broken override. The lookup
  // accepts `_layouts` as well as `_includes`, exactly like the build.
  let layout_names : Array[String] = []
  let layout_parents : Map[String, String] = Map([])
  for name, text in layout_texts {
    layout_names.push(name)
    let parent = if text == "" {
      match compiled_parents.get(name) {
        Some(p) => p
        None => ""
      }
    } else {
      let (meta, _) = @formats.split_front_matter_with(text, formats)
      @build.str_field(meta, "layout", "")
    }
    if parent != "" {
      layout_parents.set(name, parent)
    }
  }
  for entry in generator_templates() {
    let (template, plugin) = entry
    let present = include_names.get(template).unwrap_or(false) ||
      layout_names.contains(template)
    if present && !plugin_enabled(cfg, plugin) {
      report_issue(
        issues,
        Warning,
        "template \"\{template}\" has no effect: add \"\{plugin}\" to plugins",
      )
    }
  }
  if layout_names.length() == 0 && cfg.default_layout != "" {
    report_issue(
      issues,
      Error,
      "no layouts found in \{cfg.layouts_dir} or the theme",
    )
  }
  let includes_ready = include_names.length() > 0
  let reported_cycles : Array[String] = []
  for name in layout_names {
    let parent = match layout_parents.get(name) {
      Some(p) => p
      None => ""
    }
    if parent != "" &&
      !layout_names.contains(parent) &&
      !layout_names.contains(@core.strip_ext(parent)) {
      report_issue(
        issues,
        Error,
        "layout \"\{name}\" extends missing layout \"\{parent}\"",
      )
    }
    match layout_cycle(layout_parents, name) {
      Some(loop_name) =>
        if !reported_cycles.contains(loop_name) {
          reported_cycles.push(loop_name)
          report_issue(
            issues,
            Error,
            "layout \"\{name}\" is in a cycle through \"\{loop_name}\"",
          )
        }
      None => ()
    }
    match layout_texts.get(name) {
      Some(text) =>
        scan_includes(without_fences(without_raw(text)), fn(target) {
          if includes_ready && !include_names.contains(target) {
            report_issue(
              issues,
              Warning,
              "layout \"\{name}\" includes missing \"\{target}\"",
            )
          }
        })
      None => ()
    }
  }
  // Includes include too. A layout that pulls in `header.jinja`, which in turn
  // pulls in a renamed `menu.jinja`, otherwise failed silently at render time —
  // the engine writes `` into the page.
  for name, text in include_texts {
    scan_includes(without_fences(without_raw(text)), fn(target) {
      if includes_ready && !include_names.contains(target) {
        report_issue(
          issues,
          Warning,
          "include \"\{name}\" includes missing \"\{target}\"",
        )
      }
    })
  }
  // Pages: front matter, layouts, permalinks and duplicates.
  let prefixes = @build.content_prefixes(cfg)
  let permalinks : Map[String, String] = Map([])
  let mut pages = 0
  let mut assets = 0
  if @fs.exists(source_root) {
    for
      rel in @core.collect_files(source_root, fn(p) {
        @build.is_excluded(p, cfg, prefixes)
      }) {
      if rel == "" {
        continue
      }
      if !@build.is_page_file(rel, cfg) {
        assets += 1
        continue
      }
      let text = @core.read_text_or(@core.join_path(source_root, rel), "")
      if @formats.has_unclosed_front_matter(text) {
        report_issue(
          issues,
          Error,
          "\{rel}: front matter opens but never closes",
        )
      }
      let (front, body) = @formats.split_front_matter_with(text, formats)
      match
        @build.page_shell(
          body,
          front,
          cfg,
          fn(name) {
            layout_names.contains(name.to_owned()) ||
            layout_names.contains(@core.strip_ext(name))
          },
          theme != @build.NoTheme,
        ) {
        @build.Missing(layout) =>
          report_issue(
            issues,
            Error,
            "\{rel}: layout \"\{layout}\" not found in \{cfg.layouts_dir}",
          )
        @build.NoLayout =>
          report_issue(
            issues,
            Warning,
            "\{rel}: no layout applied, so the page is written as an HTML fragment; add `layout:` or a _layouts/base.jinja",
          )
        _ => ()
      }
      let url = @build.page_url(cfg, front, rel)
      if url == "" {
        report_issue(
          issues,
          Warning,
          "\{rel}: permalink produced an empty URL, page is skipped",
        )
      } else {
        let dest = @build.url_to_dest(url)
        match permalinks.get(dest) {
          Some(other) =>
            report_issue(
              issues,
              Error,
              "\{rel}: output \{dest} collides with \{other}",
            )
          None => permalinks.set(dest, rel)
        }
      }
      if @build.str_field(front, "title", "") == "" {
        report_issue(issues, Warning, "\{rel}: no title in front matter")
      }
      if @build.bool_field(front, "draft") && !options.drafts {
        report_issue(
          issues,
          Warning,
          "\{rel}: draft, excluded unless --drafts is passed",
        )
      }
      scan_includes(without_code_spans(without_fences(without_raw(body))), fn(
        target,
      ) {
        if includes_ready && !include_names.contains(target) {
          report_issue(
            issues,
            Warning,
            "\{rel}: includes missing \"\{target}\"",
          )
        }
      })
      pages += 1
    }
  }
  // Static assets copied verbatim on every build.
  let static_root = @core.join_path(cfg.root, cfg.static_dir)
  if @fs.exists(static_root) {
    for _ in @core.collect_files(static_root, fn(_) { false }) {
      assets += 1
    }
  }
  let mut errors = 0
  let mut warnings = 0
  for issue in issues {
    match issue.level {
      Error => errors += 1
      Warning => warnings += 1
    }
  }
  CheckReport::{ errors, warnings, pages, assets, issues, }
}

// 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
  }
}