// Site configuration. `fus.config.yaml` is the canonical format; any registered
// data format works too, and command-line flags override file values.

///|
/// One selectable language of a multi-language site.
///
/// `code` is the directory name under the content root and the URL prefix;
/// `name` is how a language switcher labels it.
pub struct Lang {
  code : String
  name : String
}

///|
/// Normalized site configuration.
///
/// Created by `load_config` from `fus.config.yaml` with command-line overrides.
/// Fields cover content locations (`source`, `dest`, `static_dir`), template
/// locations (`layouts_dir`, `includes_dir`, `data_dir`), URL rules
/// (`permalink`, `paginate_size`), and extension points (`plugins`, `ignore`,
/// `page_exts`). `site_data` and `globals` are exposed to templates as `site`
/// and `config`.
pub struct Config {
  root : String
  source : String
  dest : String
  layouts_dir : String
  includes_dir : String
  data_dir : String
  static_dir : String
  output_dir : String
  ignore : Array[String]
  page_exts : Array[String]
  engine : @engine.EngineKind
  permalink : String
  default_layout : String
  paginate_size : Int32
  plugins : Array[String]
  default_lang : String
  languages : Array[Lang]
  base_path : String
  /// Directory of the theme relative to the site root, or `""` when the site
  /// asked for no theme (`theme: none`).
  theme : String
  /// The theme name as written in the config, trimmed. Distinct from `theme`
  /// because a name resolves to a directory on disk *or* to the built-in theme;
  /// `""` means the site opted out.
  theme_name : String
  site_data : Json
  globals : Json
  raw : Json
}

// Coerce a JSON value into an array of display strings.

///|
fn string_list(value : Json, fallback : Array[String]) -> Array[String] {
  match value {
    Json::Array(items) => {
      let result : Array[String] = []
      for item in items {
        result.push(@core.display(item))
      }
      result
    }
    _ => fallback
  }
}

// Read a string field with a fallback.

///|
fn string_value(value : Json, fallback : String) -> String {
  match value {
    Json::String(s) => s
    Json::Null => fallback
    _ => @core.display(value)
  }
}

// Normalize a deployment prefix: no trailing slash, leading slash, or empty.

///|
fn normalize_base(value : String) -> String {
  let mut text = @core.trim(value)
  if text == "" || text == "/" {
    return ""
  }
  if !text.has_prefix("/") {
    text = "/\{text}"
  }
  while text.length() > 1 && text.has_suffix("/") {
    text = text[:text.length() - 1].to_owned()
  }
  text
}

///|
/// Read the `theme` key.
///
/// A missing key selects the built-in theme, so a site that only has a config
/// file and a content folder still renders inside a document. `none`, `off`,
/// `false` and an empty value opt out; anything else is a name or a path.
fn theme_value(value : Json) -> String {
  match value {
    Json::Null => @theme.name
    Json::True => @theme.name
    Json::False => ""
    Json::String(raw) => {
      let text = @core.trim(raw)
      match text.to_lower() {
        "none" | "off" | "false" | "" => ""
        _ => text
      }
    }
    other => @core.display(other)
  }
}

///|
/// Resolve a theme value to a directory under the site root. Bare names use
/// `themes/`; paths containing a slash or starting with `.` / `/` are
/// taken as written and then resolved against the root, so a theme next door
/// (`../shared/theme`) works too.
fn theme_directory(name : StringView) -> String {
  let text = @core.trim(name)
  if text == "" {
    ""
  } else if text.has_prefix("/") ||
    text.has_prefix(".") ||
    text.find("/") != None {
    @core.normalize_slashes(text)
  } else {
    "themes/\{text}"
  }
}

// Read a theme's optional defaults. A theme may ship `theme.yaml` (or any
// registered config format) with the same keys as `fus.config.yaml`.

///|
async fn theme_config(path : String, formats : @formats.FormatRegistry) -> Json {
  for name in ["theme.yaml", "theme.yml", "theme.json", "fus.config.yaml"] {
    let full = @core.join_path(path, name)
    let text = @core.read_text_or(full, "")
    if text != "" {
      return formats.parse(text, @formats.format_of_path(full))
    }
  }
  Json::object(Map([]))
}

// Read the `i18n` block into (default language, language list).

///|
fn parse_languages(i18n : Json) -> (String, Array[Lang]) {
  let names = @core.get(i18n, "names")
  let result : Array[Lang] = []
  for item in @core.as_array(@core.get(i18n, "languages")) {
    match item {
      Json::String(code) => {
        let name = string_value(
          @core.get(names, code),
          @i18n.display_name(code),
        )
        result.push(Lang::{ code, name, })
      }
      Json::Object(_) => {
        let code = string_value(@core.get(item, "code"), "")
        if code != "" {
          let name = string_value(
            @core.get(item, "name"),
            string_value(@core.get(names, code), @i18n.display_name(code)),
          )
          result.push(Lang::{ code, name, })
        }
      }
      _ => ()
    }
  }
  let mut default_lang = string_value(@core.get(i18n, "default"), "")
  if default_lang == "" && result.length() > 0 {
    default_lang = result[0].code
  }
  if default_lang != "" && !result.any(fn(l) { l.code == default_lang }) {
    result.push(Lang::{
      code: default_lang,
      name: string_value(
        @core.get(names, default_lang),
        @i18n.display_name(default_lang),
      ),
    })
  }
  (default_lang, result)
}

///|
/// Path of the configuration file a build would read.
///
/// `config_path` wins when given. Otherwise the first existing file of
/// `fus.config.yaml`, `.yml`, `.json`, `.toml`, `.ini` is used, and finally the
/// YAML path so that callers always have something to create or report.
pub async fn resolve_config_path(
  root : String,
  config_path : String?,
) -> String {
  match config_path {
    Some(p) => p
    None => {
      let default = @core.join_path(root, "fus.config.yaml")
      let candidates = [
        "fus.config.yaml", "fus.config.yml", "fus.config.json", "fus.config.toml",
        "fus.config.ini",
      ]
      for name in candidates {
        let path = @core.join_path(root, name)
        if @fs.exists(path) {
          return path
        }
      }
      default
    }
  }
}

///|
/// Load and normalize a site configuration with the built-in registries.
///
/// `root` is the site directory. `config_path` overrides the default file,
/// `dest_override` overrides the configured output directory and `force`
/// disables reading the cache manifest. Formats follow the file extension.
pub async fn load_config(
  root : String,
  config_path : String?,
  dest_override : String?,
  force : Bool,
) -> Config {
  load_config_with(
    root,
    config_path,
    dest_override,
    force,
    @formats.FormatRegistry::builtin(),
    @content.ContentRegistry::builtin(),
  )
}

///|
/// Load configuration with explicit registries.
///
/// Use this to add data formats or page formats: the configuration file is
/// parsed by `formats`, and the default `pageExtensions` come from `contents`.
pub async fn load_config_with(
  root : String,
  config_path : String?,
  dest_override : String?,
  force : Bool,
  formats : @formats.FormatRegistry,
  contents : @content.ContentRegistry,
) -> Config {
  let path = resolve_config_path(root, config_path)
  let text = @core.read_text_or(path, "")
  if text != "" && !@formats.parse_ok(text, @formats.format_of_path(path)) {
    println("warning: could not parse \{path}; falling back to defaults")
  }
  let site_raw = if text == "" {
    Json::object(Map([]))
  } else {
    formats.parse(text, @formats.format_of_path(path))
  }
  // Theme values are defaults: the site's own config always wins, key by key.
  // No `theme` key means the built-in theme, so a site with nothing but a config
  // file and a content folder still gets a document shell. `theme: none` opts
  // out and keeps the old "render the body only" behaviour.
  let theme_name = theme_value(@core.get(site_raw, "theme"))
  let theme_dir = theme_directory(theme_name)
  let theme_path = if theme_dir == "" {
    ""
  } else {
    @core.join_path(root, theme_dir)
  }
  let theme_raw = if theme_path == "" {
    Json::object(Map([]))
  } else {
    theme_config(theme_path, formats)
  }
  let raw = @core.merge(theme_raw, site_raw)
  let source = string_value(@core.get(raw, "srcDir"), ".")
  let dest = match dest_override {
    Some(d) => d
    None => string_value(@core.get(raw, "dest"), "_site")
  }
  let ignore_default = [
    "_site", ".git", ".fus-cache", "_build", "node_modules", ".DS_Store",
  ]
  let ignore = string_list(@core.get(raw, "ignore"), ignore_default)
  // The output directory is ignored only where it actually sits inside the
  // scanned tree. Matching its base name hid unrelated content folders: with
  // `srcDir: content` and `dest: public`, `content/public/` disappeared from
  // the site even though the output goes to `/public`.
  let source_norm = @core.collapse_dots(source)
  let dest_norm = @core.collapse_dots(dest)
  if source_norm == "" {
    ignore.push(dest_norm)
  } else if dest_norm.has_prefix("\{source_norm}/") {
    ignore.push(
      @core.slice(dest_norm, source_norm.length() + 1, dest_norm.length()),
    )
  }
  ignore.push(@core.basename(string_value(@core.get(raw, "dataDir"), "_data")))
  // The configuration file is not content, even when `srcDir` is the site root.
  ignore.push(@core.basename(path))
  if theme_dir != "" {
    ignore.push(@core.normalize_slashes(theme_dir))
  }
  let (default_lang, languages) = parse_languages(@core.get(raw, "i18n"))
  let base_path = normalize_base(string_value(@core.get(raw, "assetBase"), ""))
  // `site` always has a `url` key, even when the config omits it. `title`,
  // `description` and `url` are also read from the top level, so the smallest
  // possible config — one file, no `site:` block — still names the site. The
  // `site:` block always wins.
  let site_data = match @core.get(raw, "site") {
    Json::Object(map) => {
      let copy : Map[String, Json] = Map([])
      for key, value in map {
        copy.set(key, value)
      }
      for key in ["title", "description", "url"] {
        if copy.get(key) == None {
          match @core.get(raw, key) {
            Json::Null => ()
            value => copy.set(key, value)
          }
        }
      }
      if copy.get("url") == None {
        copy.set("url", Json::string(""))
      }
      Json::object(copy)
    }
    _ => {
      let copy : Map[String, Json] = Map([])
      for key in ["title", "description", "url"] {
        match @core.get(raw, key) {
          Json::Null => ()
          value => copy.set(key, value)
        }
      }
      if copy.get("url") == None {
        copy.set("url", Json::string(""))
      }
      Json::object(copy)
    }
  }
  {
    let config_map = match raw {
      Json::Object(m) => m
      _ => Map([])
    }
    config_map.set("force", Json::boolean(force))
  }
  // `globals.config` points back at the configuration, and the configuration
  // contains `globals`: building that view from copies is what keeps the tree
  // acyclic. Sharing the map here used to make `raw.stringify()` recurse until
  // the stack died, so a site with a `globals:` block crashed the build.
  let globals = match @core.get(raw, "globals") {
    Json::Object(map) => {
      let inner : Map[String, Json] = Map([])
      for key, value in map {
        inner.set(key, value)
      }
      let config_view = @core.set(raw, "globals", Json::object(inner))
      let exposed : Map[String, Json] = Map([])
      for key, value in inner {
        exposed.set(key, value)
      }
      exposed.set("config", config_view)
      Json::object(exposed)
    }
    _ => @core.jobj([("config", raw)])
  }
  Config::{
    root,
    source,
    dest,
    layouts_dir: string_value(@core.get(raw, "layouts"), "_layouts"),
    includes_dir: string_value(@core.get(raw, "includes"), "_includes"),
    data_dir: string_value(@core.get(raw, "dataDir"), "_data"),
    static_dir: string_value(@core.get(raw, "static"), "static"),
    output_dir: ".fus-cache",
    ignore,
    // The registry decides the default page extensions, so registering a new
    // content format makes its extension a page by default.
    page_exts: string_list(
      @core.get(raw, "pageExtensions"),
      contents.extensions(),
    ),
    engine: @engine.engine_kind(
      string_value(@core.get(raw, "templateEngine"), "minijinja"),
    ),
    permalink: string_value(@core.get(raw, "permalink"), "/:path/"),
    default_layout: string_value(@core.get(raw, "layout"), ""),
    paginate_size: @core.as_int(@core.get(raw, "paginate")),
    plugins: string_list(@core.get(raw, "plugins"), []),
    default_lang,
    languages,
    base_path,
    theme: theme_dir,
    theme_name,
    site_data,
    globals,
    raw,
  }
}

///|
/// Absolute or root-relative path to the content source directory.
pub fn Config::source_path(self : Config) -> String {
  @core.join_path(self.root, self.source)
}

///|
/// Absolute or root-relative path to the generated site directory.
pub fn Config::output_path(self : Config) -> String {
  @core.join_path(self.root, self.dest)
}

///|
/// Path to the incremental cache manifest inside the site root.
pub fn Config::cache_path(self : Config) -> String {
  @core.join_path(self.root, self.output_dir)
}

///|
/// Whether a relative path matches any configured ignore prefix.
pub fn Config::is_ignored(self : Config, relative : StringView) -> Bool {
  for pattern in self.ignore {
    let p = @core.normalize_slashes(pattern)
    if relative == p ||
      relative.has_prefix("\{p}/") ||
      (
        relative.has_prefix("\{p}") &&
        !p.has_suffix("/") &&
        @core.basename(relative) == p
      ) {
      return true
    }
  }
  false
}

///|
/// Whether the site declares more than one language.
pub fn Config::is_multilingual(self : Config) -> Bool {
  self.languages.length() > 0 && self.default_lang != ""
}

///|
/// Whether `code` is a configured language.
pub fn Config::has_lang(self : Config, code : StringView) -> Bool {
  for lang in self.languages {
    if lang.code == code.to_owned() {
      return true
    }
  }
  false
}

///|
/// How a language is labelled in a switcher, or the uppercase code.
pub fn Config::lang_name(self : Config, code : StringView) -> String {
  for lang in self.languages {
    if lang.code == code.to_owned() {
      return lang.name
    }
  }
  code.to_upper().to_owned()
}

///|
/// The URL prefix of a language, empty for the default one.
pub fn Config::lang_prefix(self : Config, code : StringView) -> String {
  if code == "" || code == self.default_lang {
    ""
  } else {
    "/\{code}"
  }
}

///|
/// Path to the configured theme directory, or an empty string when no theme is
/// used. The site root is always searched after the theme, so site files win.
pub fn Config::theme_path(self : Config) -> String {
  if self.theme == "" {
    ""
  } else {
    @core.join_path(self.root, self.theme)
  }
}