///|
let tool_version : String = "0.1.0"

///|
let generated_marker : String = "// Generated by gaato/mttp_schemagen"

///|
async fn main {
  let args = @env.args()[1:].to_owned()
  let check = args.contains("--check")
  let paths = args.filter(arg => arg != "--check")
  guard paths.length() >= 2 else {
    fail("usage: schemagen [--check] OUTPUT INPUT.mbt [INPUT.mbt ...]")
  }
  let sources = []
  for path in paths[1:] {
    sources.push((path, @fs.read_text(path)))
  }
  let output = formatted(generate(sources, toolchain=toolchain_version()))
  write_output(paths[0], output, check~)
}

///|
async fn toolchain_version() -> String {
  let result = @shell.Cmd("moonc", ["-v"]).output(timeout_ms=30000)
  result.check()
  let version = (result.stdout() + result.stderr()).trim().to_owned()
  guard version.has_prefix("v") && !version.contains("\n") else {
    fail("cannot read moonc version: \{version}")
  }
  version
}

///|
fn owned_source(source : String) -> Bool {
  let line = source.split("\n").next().unwrap_or("")
  line == generated_marker + ". Do not edit." ||
  line.has_prefix(generated_marker + " v")
}

///|
async fn write_output(path : String, output : String, check~ : Bool) -> Unit {
  let exists = @fs.exists(path)
  if exists && !owned_source(@fs.read_text(path)) {
    fail(
      "refusing to overwrite \{path}: generated-file marker required on line 1",
    )
  }
  if check {
    guard exists && @fs.read_text(path) == output else {
      fail("stale generated source: \{path}")
    }
  } else {
    if exists && @fs.read_text(path) == output {
      return
    }
    if !exists {
      @fs.write_text(path, output, create_mode=CreateNew)
    } else {
      let temporary = path + ".schemagen-new"
      if @fs.exists(temporary) {
        guard owned_source(@fs.read_text(temporary)) else {
          fail(
            "refusing to delete \{temporary}: generated-file marker required on line 1",
          )
        }
        @fs.remove(temporary)
      }
      @fs.write_text(temporary, output, create_mode=CreateNew)
      // The newly created file carries the same marker; rename gives readers
      // either complete version, including after an interrupted invocation.
      @fs.rename(temporary, path, replace=true)
    }
  }
}

///|
// Use the active compiler's formatter so generated code uses the pinned
// toolchain's canonical syntax. Stdin keeps --check read-only.
async fn formatted(source : String) -> String {
  let result = @shell.Cmd("moonfmt", ["-"], stdin=Text(source)).output(
    timeout_ms=30000,
    max_output_bytes=16 * 1024 * 1024,
  )
  result.check()
  result.stdout()
}