// Command handlers for robots-tool.

///|
fn parse_or_print(o : CliOptions) -> @robots.RobotsFile? {
  match
    @robots.parse_robots_with_limits(input_text(o), resolve_limits(o.limits)) {
    Ok(file) => Some(file)
    Err(e) => {
      println(error_json(e))
      None
    }
  }
}

///|
fn cmd_parse(o : CliOptions) -> Unit {
  match parse_or_print(o) {
    Some(file) => println(parse_json(file))
    None => ()
  }
}

///|
fn cmd_validate(o : CliOptions) -> Unit {
  match
    @robots.parse_robots_with_limits(input_text(o), resolve_limits(o.limits)) {
    Ok(_) => println("{\"ok\":true}")
    Err(e) => println(error_json(e))
  }
}

///|
fn cmd_check(o : CliOptions) -> Unit {
  if o.agent.length() == 0 || o.path.length() == 0 {
    println(
      "{\"ok\":false,\"error\":{\"kind\":\"MissingOption\",\"message\":\"check requires --agent and --path\"}}",
    )
    return
  }
  match parse_or_print(o) {
    None => ()
    Some(file) =>
      match @robots.evaluate(file, o.agent, o.path) {
        Ok(decision) => println(check_json(decision))
        Err(e) => println(error_json(e))
      }
  }
}

///|
fn cmd_format(o : CliOptions) -> Unit {
  match parse_or_print(o) {
    Some(file) => println(@robots.serialize_robots(file))
    None => ()
  }
}

///|
fn cmd_audit(o : CliOptions) -> Unit {
  match parse_or_print(o) {
    Some(file) => println(audit_json(@robots.audit_robots(file)))
    None => ()
  }
}

///|
fn cmd_stats(o : CliOptions) -> Unit {
  match parse_or_print(o) {
    Some(file) => println(stats_json(file))
    None => ()
  }
}