///|
#derive(Debug, Eq)
pub(all) suberror ConfigError {
  SyntaxError(line~ : Int32, message~ : String)
  UnknownSection(line~ : Int32, section~ : String)
  KeyOutsideSection(line~ : Int32, key~ : String)
  UnknownKey(line~ : Int32, section~ : String, key~ : String)
  MissingRequiredField(section~ : String, field~ : String)
  InvalidKeyMaterial(line~ : Int32, field~ : String, reason~ : String)
  InvalidPort(line~ : Int32, value~ : String)
  InvalidKeepalive(line~ : Int32, value~ : String)
  InvalidMtu(line~ : Int32, value~ : String)
  InvalidCidr(line~ : Int32, value~ : String)
}

///|
/// Parsed `[Interface]` block of a `wg` / `wg-quick` configuration file.
#derive(Debug, Eq)
pub(all) struct InterfaceConfig {
  private_key : Bytes
  public_key : Bytes
  addresses : Array[String]
  listen_port : Int32?
  mtu : Int32?
  dns : Array[String]
  hooks : Array[(String, String)]
}

///|
/// Parsed `[Peer]` block of a `wg` / `wg-quick` configuration file.
#derive(Debug, Eq)
pub(all) struct PeerConfig {
  public_key : Bytes
  preshared_key : Bytes?
  allowed_ips : Array[@routing.Cidr]
  raw_allowed_ips : Array[(String, Bool)]
  endpoint : String?
  persistent_keepalive : Int32?
}

///|
/// Complete parsed `wg` / `wg-quick` configuration document.
#derive(Debug, Eq)
pub(all) struct WgConfig {
  iface : InterfaceConfig
  peers : Array[PeerConfig]
}

///|
#derive(Debug, Eq)
pub(all) enum AuditSeverity {
  Error
  Warning
  Info
}

///|
#derive(Debug, Eq)
pub(all) struct AuditFinding {
  severity : AuditSeverity
  code : String
  message : String
}

///|
#derive(Debug, Eq)
pub(all) struct AuditReport {
  interface_public_key_b64 : String
  peer_count : Int32
  findings : Array[AuditFinding]
}

///|
pub fn AuditReport::has_errors(self : AuditReport) -> Bool {
  for f in self.findings {
    if f.severity is Error {
      return true
    }
  }
  false
}

///|
pub fn AuditReport::format_text(self : AuditReport) -> String {
  let sb = StringBuilder()
  sb.write_string(
    "Interface PublicKey: \{self.interface_public_key_b64} (peers: \{self.peer_count})\n",
  )
  if self.findings.length() == 0 {
    sb.write_string("Status: OK (0 findings)\n")
  } else {
    for f in self.findings {
      let tag = match f.severity {
        Error => "ERROR"
        Warning => "WARN"
        Info => "INFO"
      }
      sb.write_string("[\{tag}] \{f.code}: \{f.message}\n")
    }
  }
  sb.to_string()
}

///|
fn is_ws(c : UInt16) -> Bool {
  c == ' ' || c == '\t' || c == '\r' || c == 0xfeff
}

///|
fn trim_ws(s : StringView) -> StringView {
  let mut start = 0
  let mut end = s.length()
  while start < end && is_ws(s[start]) {
    start = start + 1
  }
  while end > start && is_ws(s[end - 1]) {
    end = end - 1
  }
  s[start:end]
}

///|
fn strip_comment(line : StringView) -> StringView {
  for i in 0.. String {
  let sb = StringBuilder()
  for i in 0..= 'A' && ch <= 'Z' {
      sb.write_char((ch.to_int() + 32).unsafe_to_char())
    } else {
      sb.write_char(ch.to_int().unsafe_to_char())
    }
  }
  sb.to_string()
}

///|
fn split_csv(s : StringView) -> Array[StringView] {
  let out : Array[StringView] = []
  let mut start = 0
  for i in 0..<=s.length() {
    if i == s.length() || s[i] == ',' {
      let item = trim_ws(s[start:i])
      if item.length() > 0 {
        out.push(item)
      }
      start = i + 1
    }
  }
  out
}

///|
fn parse_uint_range(s : StringView, min_v : Int32, max_v : Int32) -> Int32? {
  if s.length() == 0 || s.length() > 6 {
    None
  } else {
    let mut acc = 0
    for i in 0.. '9' {
        return None
      }
      acc = acc * 10 + (ch.to_int() - '0'.to_int())
    }
    if acc < min_v || acc > max_v {
      None
    } else {
      Some(acc)
    }
  }
}

///|
fn decode_key32(
  line : Int32,
  field : String,
  val : StringView,
) -> Bytes raise ConfigError {
  let raw = @crypto.from_base64(val) catch {
    _ =>
      raise ConfigError::InvalidKeyMaterial(
        line~,
        field~,
        reason="invalid Base64 encoding",
      )
  }
  if raw.length() != 32 {
    raise ConfigError::InvalidKeyMaterial(
      line~,
      field~,
      reason="expected 32-byte key, got \{raw.length()} bytes",
    )
  }
  raw
}

///|
/// Parse a `wg` or `wg-quick` INI configuration text into a typed `WgConfig`.
pub fn parse_wg_config(content : StringView) -> WgConfig raise ConfigError {
  let mut section = ""
  let mut has_iface = false
  let mut iface_priv : Bytes? = None
  let iface_addrs : Array[String] = []
  let mut iface_port : Int32? = None
  let mut iface_mtu : Int32? = None
  let iface_dns : Array[String] = []
  let iface_hooks : Array[(String, String)] = []

  let peers : Array[PeerConfig] = []
  let mut in_peer = false
  let mut peer_pub : Bytes? = None
  let mut peer_psk : Bytes? = None
  let mut peer_allowed : Array[@routing.Cidr] = []
  let mut peer_raw_allowed : Array[(String, Bool)] = []
  let mut peer_endpoint : String? = None
  let mut peer_keepalive : Int32? = None

  let mut line_no = 0
  let mut pos = 0
  let total = content.length()
  while pos <= total {
    let mut nl = pos
    while nl < total && content[nl] != '\n' {
      nl = nl + 1
    }
    line_no = line_no + 1
    let raw_line = content[pos:nl]
    let cleaned = trim_ws(strip_comment(raw_line))
    if cleaned.length() > 0 {
      if cleaned[0] == '[' {
        if cleaned[cleaned.length() - 1] != ']' {
          raise ConfigError::SyntaxError(
            line=line_no,
            message="unclosed section header",
          )
        }
        if in_peer {
          guard peer_pub is Some(pk) else {
            raise ConfigError::MissingRequiredField(
              section="Peer",
              field="PublicKey",
            )
          }
          peers.push({
            public_key: pk,
            preshared_key: peer_psk,
            allowed_ips: peer_allowed,
            raw_allowed_ips: peer_raw_allowed,
            endpoint: peer_endpoint,
            persistent_keepalive: peer_keepalive,
          })
          in_peer = false
        }
        let sec_name = ascii_lower(trim_ws(cleaned[1:cleaned.length() - 1]))
        if sec_name == "interface" {
          section = "interface"
          has_iface = true
        } else if sec_name == "peer" {
          section = "peer"
          in_peer = true
          peer_pub = None
          peer_psk = None
          peer_allowed = []
          peer_raw_allowed = []
          peer_endpoint = None
          peer_keepalive = None
        } else {
          raise ConfigError::UnknownSection(line=line_no, section=sec_name)
        }
      } else {
        if section == "" {
          raise ConfigError::KeyOutsideSection(
            line=line_no,
            key=cleaned.to_owned(),
          )
        }
        let mut eq_idx = -1
        for i in 0..
        findings.push({
          severity: Error,
          code: "EXACT_ROUTE_CONFLICT",
          message: "\{ov.wider_peer} and \{ov.narrower_peer} both claim identical AllowedIPs prefix \{ov.wider_cidr}; earlier route is overwritten.",
        })
      RedundantSelfSubset =>
        findings.push({
          severity: Warning,
          code: "REDUNDANT_SELF_SUBNET",
          message: "\{ov.wider_peer} lists \{ov.narrower_cidr} which is already covered by its own \{ov.wider_cidr}.",
        })
      CrossPeerSubnetCarve =>
        findings.push({
          severity: Warning,
          code: "CROSS_PEER_SUBNET_SHADOW",
          message: "\{ov.narrower_peer} prefix \{ov.narrower_cidr} is a more-specific subset inside \{ov.wider_peer} prefix \{ov.wider_cidr} (LPM carves traffic to \{ov.narrower_peer}).",
        })
    }
  }

  {
    interface_public_key_b64: iface_pub_b64,
    peer_count: cfg.peers.length(),
    findings,
  }
}