// The data model shared by the build pipeline and the validator.

///|
/// One content page in the build pipeline.
///
/// `src` is the source-relative path, `dest` the output-relative path and
/// `url` the public URL. `data` holds merged front matter, `body` the raw body
/// and `html` the rendered markup. `paginated` marks generated archive pages
/// and `skip` excludes drafts.
pub struct Page {
  src : String
  dest : String
  url : String
  data : Json
  body : String
  html : String
  output : String
  paginated : Bool
  skip : Bool
}

///|
/// Inputs to a build invocation.
///
/// Construct with `make_options` or `default_options`.
pub struct BuildOptions {
  root : String
  config : String?
  dest : String?
  force : Bool
  drafts : Bool
  quiet : Bool
}

///|
/// Statistics returned by `build_site`.
///
/// `pages` counts source pages plus generated pages, `generated` counts
/// pagination pages, `assets` counts copied static files, `skipped` counts
/// cache hits, `writes` counts files actually written and `elapsed_ms` is
/// the total build time.
pub struct BuildResult {
  pages : Int32
  generated : Int32
  assets : Int32
  skipped : Int32
  writes : Int32
  /// Problems that did not stop the build, in the order they were found.
  /// `fus build` prints them after the summary; `check` reports the same
  /// conditions with a file name per page.
  warnings : Array[String]
  elapsed_ms : Int64
}

///|
/// Create build options from explicit values.
///
/// Use this when embedding Fus in another tool. `config` and `dest` are optional
/// overrides; `force` bypasses the incremental cache, `drafts` includes draft
/// pages and `quiet` suppresses the build summary.
pub fn make_options(
  root : String,
  config : String?,
  dest : String?,
  force : Bool,
  drafts : Bool,
  quiet : Bool,
) -> BuildOptions {
  BuildOptions::{ root, config, dest, force, drafts, quiet, }
}

///|
/// Return options for building the current directory with defaults.
///
/// The defaults are: root `.`, no config/dest override, cache enabled, drafts
/// excluded and summary printed.
pub fn default_options() -> BuildOptions {
  BuildOptions::{
    root: ".",
    config: None,
    dest: None,
    force: false,
    drafts: false,
    quiet: false,
  }
}

// Print a build stage only when FUS_DEBUG=1.

///|
fn debug_step(label : String) -> Unit {
  if @env.get_env_var("FUS_DEBUG") == Some("1") {
    println("[fus] \{label}")
  }
}

///|
/// Set a string field on a JSON object.
pub fn set_str(value : Json, key : String, s : StringView) -> Json {
  @core.set(value, key, Json::string(s.to_owned()))
}

///|
/// Read a string field with a fallback.
pub fn str_field(value : Json, key : StringView, fallback : String) -> String {
  let v = @core.get(value, key)
  match v {
    Json::String(s) => s
    Json::Null => fallback
    _ => @core.display(v)
  }
}

///|
/// Read a boolean field, defaulting to false.
pub fn bool_field(value : Json, key : StringView) -> Bool {
  @core.truthy(@core.get(value, key))
}

///|
/// Read an array-of-strings field, defaulting to empty.
pub fn list_field(value : Json, key : StringView) -> Array[String] {
  let result : Array[String] = []
  for item in @core.as_array(@core.get(value, key)) {
    result.push(@core.display(item))
  }
  result
}

///|
/// Assign a value at a slash-separated path, creating objects along the way.
///
/// Data files use this so `_data/nav/links.yaml` lands at `data.nav.links`.
pub fn set_path(root : Json, path : StringView, value : Json) -> Unit {
  let parts = path.split("/")
  let arr : Array[String] = []
  for part in parts {
    let name = @core.trim(part)
    if name != "" {
      arr.push(name)
    }
  }
  if arr.length() == 0 {
    return
  }
  put_path(root, arr, 0, value)
}

// Walk one segment of a data path, mutating the fresh `_data` tree in place.
// `@core.set` returns a copy, so it cannot be used here: the copy would drop
// everything assigned to the parent object.

///|
fn put_path(
  node : Json,
  parts : Array[String],
  index : Int32,
  value : Json,
) -> Unit {
  match node {
    Json::Object(map) =>
      if index == parts.length() - 1 {
        map.set(parts[index], value)
      } else {
        let child = match map.get(parts[index]) {
          Some(Json::Object(_) as existing) => existing
          _ => {
            let created = Json::object(Map([]))
            map.set(parts[index], created)
            created
          }
        }
        put_path(child, parts, index + 1, value)
      }
    _ => ()
  }
}