export def _ansi [
  arg: string
] {
  if (is-terminal --stdout) {
    $"(ansi $arg)"
  } else {
    ""
  }
}

export def log_debug [
    msg: string
] {
    use std
    std log debug $msg
}

export def format_out [
  data: string
  src?: string
  mode?: string
] {
  let msg = match $src {
    "json" => ($data | from json),
    _ => $data,
  }
  match $mode {
    "table" => {
      ($msg | table -i false)
    },
    _ => { $msg }
  }
}
export def _print [
  data: string
  src?: string
  context?: string
  mode?: string
] {
  if ($env.PROVISIONING_OUT | is-empty)  {
    print (format_out $data $src $mode)
  } else {
    match $env.PROVISIONING_OUT {
       "json" => {
          if $context != "result" { return }
          if $src == "json" {
            print ($data)
          } else {
            print ($data | to json)
          }
       },
       "yaml" | "yml" => {
          if $context != "result" { return }
          if $src == "json" {
            print ($data | from json | to yaml)
          } else {
            print ($data | to yaml)
          }
       },
       "text" | "txt" => {
          if $context != "result" { return }
          print (format_out $data $src $mode)
       },
       _ => {
        if ($env.PROVISIONING_OUT | str ends-with ".json" ) {
          if $context != "result" { return }
          (if $src == "json" {
            ($data)
          } else {
            ($data | to json)
          } |  save --force $env.PROVISIONING_OUT)
        } else if ($env.PROVISIONING_OUT | str ends-with ".yaml" ) {
          if $context != "result" { return }
          (if $src == "json" {
            ($data | from json | to yaml)
          } else {
            ($data | to yaml)
          } | save --force $env.PROVISIONING_OUT)
        } else if ($env.PROVISIONING_OUT | str ends-with ".text" ) or ($env.PROVISIONING_OUT | str ends-with ".txt" ) {
          if $context != "result" { return }
          format_out $data $src $mode | save --force $env.PROVISIONING_OUT
        } else {
          format_out $data $src $mode | save --append $env.PROVISIONING_OUT
        }
      }
    }
  }
}
