///|
fn target_arg(target : @path.Target) -> String {
  match target {
    Js => "js"
    Native => "native"
    Wasm => "wasm"
    WasmGC => "wasm-gc"
  }
}

///|
fn build_arg(build : @path.Build) -> String {
  match build {
    Release => " --release"
    Debug => ""
  }
}

///|
#cfg(not(platform="windows"))
fn shell_quote(s : String) -> String {
  let escaped = s.replace_all(old="'", new="'\"'\"'")
  "'" + escaped + "'"
}

///|
#cfg(platform="windows")
fn shell_quote(s : String) -> String {
  let escaped = s.replace_all(old="\"", new="\"\"")
  "\"" + escaped + "\""
}

///|
#cfg(not(platform="windows"))
fn build_command(
  subcommand : String,
  target : @path.Target,
  build : @path.Build,
  working_dir : @path.SourcePath,
) -> String {
  let cwd = shell_quote("\{working_dir}")
  "cd " +
  cwd +
  " && moon " +
  subcommand +
  " --target " +
  target_arg(target) +
  build_arg(build)
}

///|
#cfg(platform="windows")
fn build_command(
  subcommand : String,
  target : @path.Target,
  build : @path.Build,
  working_dir : @path.SourcePath,
) -> String {
  let cwd = shell_quote("\{working_dir}")
  "cd /d " +
  cwd +
  " && moon " +
  subcommand +
  " --target " +
  target_arg(target) +
  build_arg(build)
}

///|
#borrow(command)
extern "C" fn system(command : Bytes) -> Int = "system"

///|
fn encode_ascii_c_string(s : String) -> Bytes {
  let bytes = []
  for ch in s {
    let code = ch.to_int()
    guard code >= 0 && code <= 0x7F else {
      println("Only ASCII command strings are supported: \{s}")
      panic()
    }
    bytes.push(code.to_byte())
  }
  bytes.push(b'\x00')
  Bytes::from_array(bytes)
}

///|
fn run_command(command : String) -> Int {
  let terminated = encode_ascii_c_string(command)
  system(terminated)
}

///|
fn run_moon_build_watch(
  working_dir : @path.SourcePath,
  target? : @path.Target = Js,
  build? : @path.Build = Debug,
) -> Unit {
  let command = build_command("build", target, build, working_dir) +
    " --watch > /tmp/warren-moon-watch.log 2>&1 < /dev/null &"
  let status = run_command(command)
  guard status == 0 else {
    println("`moon build --watch` failed: \{command}")
    panic()
  }
}

// struct FileWatch {
//   set : Set[String]
// }

// async fn FileWatch::new() -> Unit {
//   { set: Set::new(), }
// }

// ///|
// async fn watch_dir(dir : @path.SourcePath, changed : async () -> Unit) -> Unit {
//   let dir = dir.to_string()
//   let set = Set::from_array([dir])
//   guard @fs.exists(dir) else { abort("Watch dir \{dir} is no exists.") }
//   @async.with_task_group(group => {
//     @fs.walk(dir, (dir, files) => {
//       for file in files {
//         let path = @path.Path::join(dir, file)

//       }
//     }, exclude=s => s == "node_modules")
//   })
// }

///|
enum DevEvent {
  Reload
}

///|
async fn serve_dev_events(
  conn : @http.ServerConnection,
  get_channel : () -> @async.Queue[DevEvent],
) -> Unit {
  conn.send_response(200, "OK", extra_headers={
    "Content-Type": "text/event-stream",
    "Cache-Control": "no-cache",
    "Connection": "keep-alive",
  })
  conn.write(": connected\n\n")
  conn.flush()
  while get_channel().get() is event {
    match event {
      Reload => {
        conn.write("event: reload\n")
        conn.write("data: now\n\n")
        conn.flush()
      }
    }
  }
}

///|
async fn serve(
  dir : @path.SourcePath,
  port? : UInt = 3070,
  get_channel : () -> @async.Queue[DevEvent],
  get_vfs : () -> @vfs.VirtualFileSystem,
) -> Unit {
  let ip = "127.0.0.1"
  let server = @http.Server::new(
    @socket.Addr::parse("\{ip}:\{port}"),
    reuse_addr=true,
  )

  log("info", "Running server on http://\{ip}:\{port}")

  server.run_forever((request, _body, conn) => {
    async fn go(path) {
      match path {
        "/" => go("/index.html")
        "/__warren/events" => serve_dev_events(conn, get_channel)
        other if get_vfs().read(other) is Some(content) => {
          let content_type = match @path.Path::extname(path) {
            ".png" => "image/png"
            ".jpg" | ".jpeg" => "image/jpeg"
            ".html" => "text/html"
            ".css" => "text/css"
            ".js" => "text/javascript"
            ".mp4" => "video/mp4"
            ".mpv" => "video/mpv"
            ".mpeg" => "video/mpeg"
            ".mkv" => "video/x-matroska"
            _ => "application/octet-stream"
          }
          log("info", "200 OK, GET \{path}")
          conn
          ..send_response(200, "OK", extra_headers={
            "Content-Type": content_type,
          })
          ..write(content)
          .end_response()
        }
        _ => {
          log("info", "404 Not Found, GET \{path}")
          conn
          ..send_response(404, "NotFound", extra_headers={
            "Content-Type": "text/plain",
          })
          ..write("\{path} Not Found")
          .end_response()
        }
      }
    }

    let path = request.path
    guard request.meth is Get else { return }
    go(path)
  })
}

///|
async fn copy(src~ : SourcePath, dst~ : SourcePath) -> Unit {
  let src_str = "\{src}"
  let dst_str = "\{dst}"
  println("copy \{src_str} -> \{dst_str}")
  guard @fs.exists(src_str) else { fail("Source path does not exist: \{src}") }
  if @fs.kind(src_str) is Directory {
    println("copy dir \{src_str} -> \{dst_str}")
    @fs.mkdir(dst_str, permission=0o755, recursive=true)
    for entry in @fs.readdir(src_str, sort=true) {
      copy(src=src.join(entry), dst=dst.join(entry))
    }
  } else {
    println("copy file \{src_str} -> \{dst_str}")
    let parent = @path.Path::dirname(dst_str).to_string()
    if parent != "" && parent != "." && !@fs.exists(parent) {
      println("mkdir \{parent}")
      @fs.mkdir(parent, permission=0o755, recursive=true)
    }
    let reader = @fs.open(src_str, mode=ReadOnly)
    defer reader.close()
    let writer = @fs.open(dst_str, mode=WriteOnly, create=0o644, truncate=true)
    defer writer.close()
    writer.write_reader(reader)
  }
}