///|
priv struct JobCursor {
  hosts : Iter[String]
  ports : Array[Int32]
  mut host : String?
  mut port_index : Int32
}

///|
fn JobCursor::next(self : JobCursor) -> (String, Int32)? {
  if self.host is None || self.port_index == self.ports.length() {
    self.host = self.hosts.next()
    self.port_index = 0
  }
  match self.host {
    None => None
    Some(host) => {
      let port = self.ports[self.port_index]
      self.port_index += 1
      Some((host, port))
    }
  }
}

///|
priv struct RateGate {
  lock : @async.Mutex
  interval : Int64
  mut next_start : Int64
}

///|
async fn RateGate::wait(self : RateGate) -> Unit {
  if self.interval == 0 {
    return
  }
  self.lock.acquire()
  defer self.lock.release()
  let remaining = self.next_start - @async.now()
  if remaining > 0 {
    @async.sleep(remaining.to_int())
  }
  self.next_start = @async.now() + self.interval
}

///|
/// Winsock reports a refused TCP connect as `WSAECONNREFUSED` and an OS-level
/// connect timeout as `WSAETIMEDOUT`. The current MoonBit core errno table only
/// maps the Win32 `ERROR_CONNECTION_REFUSED` form, so recognize the Winsock
/// codes directly. Neither value can collide with a Unix errno.
const WSAECONNREFUSED : Int32 = 10061

///|
const WSAETIMEDOUT : Int32 = 10060

///|
fn classify(error : Error) -> PortState {
  match error {
    @async.TimeoutError => TimedOut
    @os_error.OsError(ConnectionRefused, ..) => Closed
    @os_error.OsError(_, raw_code~, ..) if raw_code == WSAECONNREFUSED => Closed
    @os_error.OsError(_, raw_code~, ..) if raw_code == WSAETIMEDOUT => TimedOut
    _ => Failed
  }
}

///|
async fn connect_result(
  target : String,
  address : @socket.Addr,
  timeout : Int32,
  mode : ProbeMode,
  probe_timeout_ms : Int32,
  max_probe_bytes : Int32,
  cert_verify : Bool,
  cert_ca_file : String?,
  openssl : String,
) -> ScanResult {
  let start = @async.now()
  let mut error = None
  let mut service = None
  let mut probe_error = None
  let state = try {
    let socket = @async.with_timeout(timeout, () => {
      @socket.Tcp::connect(address)
    })
    defer socket.close()
    if mode != Disabled {
      let (info, failure) = probe_connection(
        socket, target, address, mode, probe_timeout_ms, max_probe_bytes, cert_verify,
        cert_ca_file, openssl,
      )
      service = info
      probe_error = failure
    }
    Open
  } catch {
    err => {
      error = Some(err.to_string())
      classify(err)
    }
  }
  {
    target,
    address: address.ip.to_string(),
    port: address.port.to_int(),
    state,
    elapsed_ms: @async.now() - start,
    error,
    service,
    probe_error,
    attempts: 1,
    detection: None,
  }
}

///|
/// Scan targets with a fixed worker pool. The callback is serialized and backpressures
/// workers. Callback errors cancel the scan; ordinary connection errors are results.
/// Rate limits count connection attempts, not DNS lookups. DNS selects one address
/// per hostname, cached for this scan; numeric IPv4/IPv6 targets bypass DNS.
pub async fn scan(
  targets : TargetPlan,
  ports : ArrayView[Int32],
  concurrency~ : Int32 = 32,
  timeout_ms~ : Int32 = 1000,
  rate~ : Int32 = 100,
  probe~ : ProbeMode = Disabled,
  probe_timeout_ms~ : Int32 = 1500,
  max_probe_bytes~ : Int32 = 16384,
  retries~ : Int32 = 0,
  retry_delay_ms~ : Int32 = 100,
  scope~ : Scope = Scope::loopback(),
  max_hosts~ : Int32 = 256,
  max_attempts~ : Int32 = 65536,
  deadline_ms~ : Int32 = 60000,
  cert_verify~ : Bool = false,
  cert_ca_file? : String,
  openssl~ : String = "openssl",
  on_result~ : async (ScanResult) -> Unit,
) -> ScanSummary {
  guard concurrency > 0 && concurrency <= 1024 else {
    raise InputError("concurrency must be in 1..1024")
  }
  guard timeout_ms > 0 else { raise InputError("timeout must be positive") }
  guard retries >= 0 &&
    retries <= 10 &&
    retry_delay_ms >= 0 &&
    retry_delay_ms <= 60000 else {
    raise InputError("retries must be in 0..10; retry delay in 0..60000")
  }
  guard probe_timeout_ms > 0 &&
    max_probe_bytes > 0 &&
    max_probe_bytes <= 1048576 else {
    raise InputError(
      "probe timeout must be positive; response limit must be in 1..1048576",
    )
  }
  guard rate >= 1 && rate <= 1000 else {
    raise InputError("rate must be in 1..1000")
  }
  guard !ports.is_empty() && ports.all(p => p > 0 && p <= 65535) else {
    raise InputError("provide ports in 1..65535")
  }
  guard max_hosts > 0 && max_attempts > 0 && deadline_ms > 0 else {
    raise InputError("host, attempt and time budgets must be positive")
  }
  targets.validate_limits(
    scope,
    ports.length(),
    retries,
    max_hosts,
    max_attempts,
  )
  let cursor : JobCursor = {
    hosts: targets.hosts(),
    ports: ports.to_owned(),
    host: None,
    port_index: 0,
  }
  let gate : RateGate = {
    lock: @async.Mutex(),
    interval: ((1000 + rate - 1) / rate).to_int64(),
    next_start: 0,
  }
  let report_lock = @async.Mutex()
  let resolved : Map[String, @async.Lazy[Result[@socket.IpAddr, Error]]] = Map([])
  let summary = ScanSummary::new()
  @async.with_timeout(deadline_ms, () => {
    @async.with_task_group(group => {
      for _ in 0.. {
          while cursor.next() is Some((host, port)) {
            let start = @async.now()
            let ip = @socket.IpAddr::parse(host) catch {
              _ => {
                let lookup = match resolved.get(host) {
                  Some(cached) => cached
                  None => {
                    let cached = @async.Lazy(() => {
                      Ok(
                        @async.with_timeout(timeout_ms, () => {
                          @socket.Addr::resolve(host, port=0).ip
                        }),
                      ) catch {
                        err => Err(err)
                      }
                    })
                    resolved[host] = cached
                    cached
                  }
                }
                match lookup.wait() {
                  Ok(ip) => ip
                  Err(err) => {
                    let result : ScanResult = {
                      target: host,
                      address: "",
                      port,
                      state: Failed,
                      elapsed_ms: @async.now() - start,
                      error: Some(err.to_string()),
                      service: None,
                      probe_error: None,
                      attempts: 0,
                      detection: None,
                    }
                    report_lock.acquire()
                    summary.record(result.state)
                    {
                      defer report_lock.release()
                      on_result(result)
                    }
                    continue
                  }
                }
              }
            }
            if targets.excludes(ip) {
              continue
            }
            // Pin the checked numeric address: connect never resolves the name again.
            guard scope.allows(ip) else {
              raise InputError(
                "resolved target is outside scope: \{host} => \{ip}",
              )
            }
            let result = retry_connection(retries, retry_delay_ms, () => {
              gate.wait()
              connect_result(
                host,
                @socket.Addr(ip, port.to_uint16()),
                timeout_ms,
                probe,
                probe_timeout_ms,
                max_probe_bytes,
                cert_verify,
                cert_ca_file,
                openssl,
              )
            })
            report_lock.acquire()
            summary.record(result.state)
            defer report_lock.release()
            on_result(result)
          }
        })
      }
    })
  })
  summary
}

///|
async fn retry_connection(
  retries : Int32,
  delay_ms : Int32,
  attempt : async () -> ScanResult,
) -> ScanResult {
  let start = @async.now()
  for count = 1; ; count = count + 1 {
    let result = attempt()
    if count > retries || result.state is (Open | Closed) {
      return { ..result, attempts: count, elapsed_ms: @async.now() - start, }
    }
    @async.sleep(delay_ms)
  }
}