///|
/// Numeric allowlist checked against the actual destination before connecting.
/// Hostnames are deliberately not permitted as scope entries.
pub struct Scope {
  priv ranges : Array[IpRange]
  priv ipv6 : Set[@socket.IpAddr]
}

///|
fn canonical_ip(ip : @socket.IpAddr) -> @socket.IpAddr {
  match ip {
    Ipv6(bytes, ..) if bytes[:10].iter().all(b => b == 0) &&
      bytes[10] == 0xff &&
      bytes[11] == 0xff => {
      let value = (bytes[12].to_uint() << 24) |
        (bytes[13].to_uint() << 16) |
        (bytes[14].to_uint() << 8) |
        bytes[15].to_uint()
      @socket.IpAddr::v4(value)
    }
    _ => ip
  }
}

///|
/// Create scope from IPv4/CIDR or individual IPv6 addresses.
///
/// ```mbt check
/// test {
///   let scope = @mscan.Scope::parse(["192.0.2.0/24", "::1"])
///   assert_true(scope.contains("192.0.2.10"))
///   assert_false(scope.contains("198.51.100.1"))
/// }
/// ```
pub fn Scope::parse(entries : ArrayView[String]) -> Scope raise InputError {
  let ranges = []
  let ipv6 : Set[@socket.IpAddr] = Set([])
  for entry in entries {
    let value = entry.trim()
    match range_of(value) {
      Some(range) => ranges.push(range)
      None => {
        let ip = @socket.IpAddr::parse(value) catch {
          _ =>
            raise InputError("scope requires numeric IP/CIDR entries: \{entry}")
        }
        match canonical_ip(ip) {
          Ipv4(value) =>
            ranges.push({ first: value.to_int64(), last: value.to_int64(), })
          ip => ipv6.insert(ip) |> ignore
        }
      }
    }
  }
  { ranges: normalize(ranges), ipv6, }
}

///|
pub fn Scope::loopback() -> Scope {
  // These numeric constants cannot fail parsing.
  try! Scope::parse(["127.0.0.0/8", "::1"])
}

///|
fn Scope::allows(self : Scope, ip : @socket.IpAddr) -> Bool {
  match canonical_ip(ip) {
    Ipv4(value) =>
      self.ranges.any(r => {
        r.first <= value.to_int64() && value.to_int64() <= r.last
      })
    ip => self.ipv6.contains(ip)
  }
}

///|
pub fn Scope::contains(self : Scope, address : String) -> Bool raise InputError {
  let ip = @socket.IpAddr::parse(address) catch {
    _ => raise InputError("expected numeric address: \{address}")
  }
  self.allows(ip)
}

///|
fn TargetPlan::validate_limits(
  self : TargetPlan,
  scope : Scope,
  port_count : Int32,
  retries : Int32,
  max_hosts : Int32,
  max_attempts : Int32,
) -> Unit raise InputError {
  let mut hosts = self.hosts.length().to_int64()
  for range in self.ranges {
    hosts += range.last - range.first + 1
    guard scope.ranges.any(allowed => {
      allowed.first <= range.first && range.last <= allowed.last
    }) else {
      raise InputError(
        "target range is outside scope; provide an authorized numeric scope file",
      )
    }
  }
  for host in self.hosts {
    try @socket.IpAddr::parse(host) catch {
      _ => ()
    } noraise {
      ip =>
        if !scope.allows(ip) {
          raise InputError("target is outside scope: \{host}")
        }
    }
  }
  guard hosts <= max_hosts.to_int64() else {
    raise InputError("target count exceeds max-hosts=\{max_hosts}")
  }
  // Division prevents overflow even for an IPv4 /0 and a large retry count.
  let per_host = port_count.to_int64() * (retries + 1).to_int64()
  guard hosts <= max_attempts.to_int64() / per_host else {
    raise InputError(
      "planned TCP attempts exceed max-attempts=\{max_attempts} (including retries)",
    )
  }
}