///|
/// The version of this module.
pub fn version() -> String {
  "0.1.0"
}

///|
/// The text of the file at `path`, or the line that says why it cannot be read.
async fn read_text(path : String) -> Result[String, String] noraise {
  Ok(@fs.read_file(path).text()) catch {
    error => Err("\{path}: cannot read the file: \{error}")
  }
}

///|
/// The input that is the same file as `output`, which can have another path.
async fn input_at(inputs : Array[String], output : String) -> String? noraise {
  let real_path = path => Some(@fs.realpath(path)) catch { _ => None }
  guard real_path(output) is Some(file) else { return None }
  for input in inputs {
    if real_path(input) == Some(file) {
      return Some(input)
    }
  }
  None
}

///|
/// Write the code for `inputs` to `output`, or compare them with `check`. The result is what is wrong, one line for each problem.
async fn generate(
  inputs : Array[String],
  output : String,
  check : Bool,
) -> Array[String] noraise {
  let files = []
  let unread = []
  for path in inputs {
    match read_text(path) {
      Ok(text) => files.push((path, text))
      Err(problem) => unread.push(problem)
    }
  }
  match @generator.generate(files) {
    Err(problems) => unread + problems
    Ok(_) if !unread.is_empty() => unread
    Ok(code) if check =>
      match read_text(output) {
        Ok(text) if text.replace_all(old="\r\n", new="\n") == code => []
        Ok(_) => ["\{output}: the code is not up to date with its inputs"]
        Err(problem) => [problem]
      }
    Ok(_) if input_at(inputs, output) is Some(input) =>
      ["\{output}: the output is the input \{input}"]
    Ok(code) =>
      try {
        @fs.write_file(output, code, create_mode=CreateOrTruncate)
        []
      } catch {
        error => ["\{output}: cannot write the file: \{error}"]
      }
  }
}

///|
async fn main {
  match parse_command(@env.args()[1:]) {
    Ok(Help) => @stdio.stdout.write("\{usage}\n")
    Ok(Version) => @stdio.stdout.write("\{version()}\n")
    Ok(Generate(inputs~, output~, check~)) => {
      let problems = generate(inputs, output, check)
      if !problems.is_empty() {
        @stdio.stderr.write("\{problems.join("\n")}\n")
        @env.exit(1)
      }
    }
    Err(problem) => {
      @stdio.stderr.write("\{problem}\n\n\{usage}\n")
      @env.exit(2)
    }
  }
}