///|
/// Prepares internal app creation state from an already parsed manifest.
fn prepare_app(
  manifest : @manifest.AppManifest,
  registry : ExtensionRegistry,
  base_dir? : String? = None,
) -> Result[PreparedApp, String] {
  match validate_manifest_windows(manifest) {
    Err(error) => return Err(error)
    Ok(_) => ()
  }
  match plan_extensions(manifest, registry) {
    Err(error) => Err(error)
    Ok(extensions) =>
      Ok(
        PreparedApp::new(
          runtime_config_from_manifest(manifest),
          extensions,
          base_dir~,
        ),
      )
  }
}

///|
/// Validates secondary window ids before runtime app construction can abort.
fn validate_manifest_windows(
  manifest : @manifest.AppManifest,
) -> Result[Unit, String] {
  let ids : Map[String, Bool] = {}
  for window in manifest.windows {
    let id = window.id
    guard id.trim().to_owned() != "" else {
      return Err("window id must not be empty")
    }
    guard id != "main" else {
      return Err("window id \"main\" is reserved for the primary window")
    }
    guard ids.get(id) is None else { return Err("duplicate window id: " + id) }
    ids.set(id, true)
  }
  Ok(())
}

///|
/// Creates a runtime app from an already parsed manifest and extension registry.
/// This resolves declarative extensions, prepares the runtime config, and then
/// builds the final `@wvrt.App` in one step.
pub fn create_app(
  manifest : @manifest.AppManifest,
  registry : ExtensionRegistry,
  base_dir? : String? = None,
) -> Result[@wvrt.App, String] {
  match prepare_app(manifest, registry, base_dir~) {
    Err(error) => Err(error)
    Ok(prepared) => build_prepared_app(prepared)
  }
}

///|
/// Loads a manifest document from disk and creates a runtime app.
/// Relative file entries and extension base directories are resolved from the
/// manifest file's parent directory before the runtime app is constructed.
pub fn create_app_from_file(
  path : String,
  registry : ExtensionRegistry,
) -> Result[@wvrt.App, String] {
  match @bootstrap.load_config_manifest_from_file(path) {
    Err(error) => Err(error)
    Ok(loaded) =>
      create_app(loaded.manifest(), registry, base_dir=loaded.base_dir())
  }
}