///|
fn usage() -> Unit {
  println("ayatsumugi scan ")
  println("ayatsumugi audit ")
  println("ayatsumugi version")
}

///|
fn decode_input(text : String) -> @core.AuditInput? {
  try {
    let json = @json.parse(text)
    let input : @core.AuditInput = @json.from_json(json)
    input
  } catch {
    _ => None
  } noraise {
    input => Some(input)
  }
}

///|
fn decode_sources(text : String) -> Array[@core.SourceFile]? {
  try {
    let json = @json.parse(text)
    let sources : Array[@core.SourceFile] = @json.from_json(json)
    sources
  } catch {
    _ => None
  } noraise {
    sources => Some(sources)
  }
}

///|
fn empty_vitals() -> @core.WebVitals {
  { fcp_ms: 0.0, lcp_ms: 0.0, cls: 0.0, tbt_ms: 0.0, inp_ms: 0.0, ttfb_ms: 0.0 }
}

///|
fn print_report(input : @core.AuditInput) -> Unit {
  println(@core.audit(input).to_json().stringify(indent=2))
}

///|
fn main {
  let raw = @fsio.args()
  let argv : Array[String] = []
  let start = if raw.length() >= 2 { 2 } else { 0 }
  for index in start.. println("ayatsumugi 0.1.0")
    "audit" => {
      if argv.length() < 2 {
        usage()
        @fsio.set_exit_code(2)
        return
      }
      let text = match @fsio.read_text(argv[1]) {
        Ok(value) => value
        Err(reason) => {
          println("input error: " + reason)
          @fsio.set_exit_code(2)
          return
        }
      }
      match decode_input(text) {
        Some(input) => print_report(input)
        None => {
          println("input error: invalid audit JSON")
          @fsio.set_exit_code(2)
        }
      }
    }
    "scan" => {
      if argv.length() < 2 {
        usage()
        @fsio.set_exit_code(2)
        return
      }
      let encoded = match @fsio.collect_sources_json(argv[1]) {
        Ok(value) => value
        Err(reason) => {
          println("input error: " + reason)
          @fsio.set_exit_code(2)
          return
        }
      }
      match decode_sources(encoded) {
        Some(sources) =>
          print_report({
            sources,
            renders: [],
            vitals: empty_vitals(),
            nodes: [],
            optimization: None,
          })
        None => {
          println("input error: failed to decode scanned sources")
          @fsio.set_exit_code(2)
        }
      }
    }
    _ => {
      usage()
      @fsio.set_exit_code(2)
    }
  }
}