// Theme resolution: where a site's layouts, data and assets come from.
//
// A theme name can mean two different things. If `themes/` exists on disk
// it wins, because that is a theme the site owns and can edit. Otherwise a name
// that matches the theme compiled into the binary selects the built-in one, so a
// site with only a config file and a content folder still gets a document shell.
//
// Both the build and the validator resolve the theme through this file. When the
// two disagreed, `check` reported layouts the build had quietly found elsewhere.

///|
/// Where a site's theme comes from.
#derive(Eq)
pub(all) enum ThemeSource {
  /// `theme: none`, or a name that resolves to neither a directory nor the
  /// built-in theme.
  NoTheme
  /// A directory addressed from the site root (`themes/`, `./shared`).
  DiskTheme(String)
  /// The theme compiled into the binary.
  BuiltinTheme
}

///|
/// Pick the theme for a loaded configuration.
///
/// A directory on disk always wins over the built-in theme of the same name, so
/// `theme: fus` keeps working for a site that vendored and edited that theme.
pub async fn resolve_theme(cfg : @config.Config) -> ThemeSource {
  let path = cfg.theme_path()
  // `exists` raises on a path the platform cannot even represent (`D:/x`
  // joined onto a site root on Windows). That is a configuration mistake the
  // caller reports, not a reason to abort the build.
  let on_disk = if path == "" {
    false
  } else {
    @fs.exists(path) catch {
      _ => false
    }
  }
  if on_disk {
    DiskTheme(path)
  } else if @theme.has(cfg.theme_name) {
    BuiltinTheme
  } else {
    NoTheme
  }
}

///|
/// The theme's absolute directory, or `""` when there is no directory to read.
pub fn theme_path(source : ThemeSource) -> String {
  match source {
    DiskTheme(path) => path
    _ => ""
  }
}

///|
/// Static assets of the built-in theme, as `(file name, contents)`.
pub fn builtin_assets() -> Array[(String, String)] {
  @theme.assets()
}

///|
/// Revision of the compiled theme, for the build cache key.
pub fn theme_signature() -> String {
  @theme.signature()
}

///|
/// Whether the built-in theme provides `layout`, compiled.
///
/// The build and `check` both answer "does this layout exist" through one
/// function, so a name the build can render is never reported as missing.
pub fn builtin_layout(layout : StringView) -> Bool {
  @theme.has_layout(layout)
}

///|
/// Render a compiled layout, returning its HTML and the layout that wraps it.
///
/// `None` means the name is not compiled and the caller should look for a file
/// in `_layouts` instead. `base` returns `""` as its parent: it is the shell.
///
/// `slot` resolves one fragment of the shell (`head`, `header`, `menu`,
/// `footer`, `pagination`): a file in the site wins, the compiled fragment is
/// the fallback, and an empty string means "nothing here".
pub fn render_builtin(
  layout : StringView,
  page : Json,
  body : String,
  slot : (StringView) -> String,
) -> (String, String)? {
  let site = @core.get(page, "site")
  let page_title = str_field(page, "title", "")
  let site_title = str_field(site, "title", "")
  let lang = match str_field(page, "lang", "") {
    "" => "en"
    value => value
  }
  let base = str_field(page, "base", "")
  let root = str_field(page, "root", "")
  match layout {
    "base" => {
      let title = if page_title != "" {
        if site_title != "" {
          "\{page_title} · \{site_title}"
        } else {
          page_title
        }
      } else if site_title != "" {
        site_title
      } else {
        "Home"
      }
      let url = @core.strip_trailing_slash(str_field(site, "url", ""))
      let page_url = str_field(page, "url", "")
      let canonical = if url == "" { "" } else { "\{url}\{page_url}" }
      let description = str_field(page, "description", "")
      let home = page_url == "\{base}/"
      let dated = str_field(page, "date", "") != ""
      let html = @theme.render_shell(
        @theme.ThemeMeta::{
          lang,
          title,
          description,
          canonical,
          site_title: if site_title == "" {
            "Home"
          } else {
            site_title
          },
          base,
          root,
          alternates: theme_alternates(page, url),
          og_type: if dated && !home {
            "article"
          } else {
            "website"
          },
          og_title: if page_title != "" {
            page_title
          } else if site_title != "" {
            site_title
          } else {
            "Home"
          },
          og_locale: og_locale(lang),
          json_ld: structured_data(
            page,
            if page_title != "" {
              page_title
            } else {
              title
            },
            description,
            canonical,
            lang,
          ),
        },
        footer_note(page),
        slot("head"),
        slot("header"),
        slot("footer"),
        if is_paginated(page) && pagination_links(page) {
          slot("pagination")
        } else {
          ""
        },
        body,
      )
      Some((html, ""))
    }
    "post" => {
      let date = str_field(page, "date", "")
      // The built-in theme is English-only, like its other fixed strings.
      let date_text = if date == "" {
        ""
      } else {
        @core.format_date(date, "en")
      }
      Some(
        (
          @theme.render_article(
            str_field(page, "title", ""),
            date,
            date_text,
            body,
          ),
          "base",
        ),
      )
    }
    _ => None
  }
}

///|
/// Resolve one shell slot, preferring the site over the compiled fragment.
///
/// `head` has no compiled default: it is the injection point for extra ``,
/// fonts or analytics, and renders nothing until the site provides it.
pub fn theme_slot(
  name : StringView,
  page : Json,
  env : @engine.TemplateEnv,
) -> String {
  match env.sources.get(name.to_owned()) {
    Some(_) => @core.trim_end(@engine.render_template(name, page, env))
    None => compiled_slot(name, page, env)
  }
}

// A compiled slot, trimmed the same way as a site one so the layout supplies
// the newline.

///|
fn compiled_slot(
  name : StringView,
  page : Json,
  env : @engine.TemplateEnv,
) -> String {
  let site = @core.get(page, "site")
  let base = str_field(page, "base", "")
  let root = str_field(page, "root", "")
  match name {
    "header" =>
      @core.trim_end(
        @theme.render_header(
          base,
          root,
          match str_field(site, "title", "") {
            "" => "Home"
            value => value
          },
          theme_slot("menu", page, env),
        ),
      )
    "menu" => @core.trim_end(@theme.render_menu(base, root, has_blog(page)))
    "footer" => @core.trim_end(@theme.render_footer(footer_note(page)))
    "pagination" => {
      let pagination = @core.get(page, "pagination")
      let prev = json_str(pagination, "prev")
      let next = json_str(pagination, "next")
      // A listing with a single page carries a `pagination` object with no
      // links; rendering it would leave an empty `