///|
priv struct FingerprintRule {
  id : String
  name : String
  field : String
  needle : String
}

///|
pub struct RuleSet {
  priv rules : Array[FingerprintRule]
}

///|
/// Parse schema version 1: at most 256 substring rules against bounded service
/// evidence. Matching is ASCII case insensitive; no scripts or regex are executed.
///
/// ```mbt check
/// test {
///   let rules = @mscan.RuleSet::parse("{\"version\":1,\"rules\":[]}")
///   assert_eq(@mscan.Detector::id(rules), "fingerprints.v1")
/// }
/// ```
pub fn RuleSet::parse(text : String) -> RuleSet raise InputError {
  guard text.length() <= 1048576 else {
    raise InputError("rule file exceeds 1 MiB of text")
  }
  let json = @json.parse(text, reject_duplicate_keys=true) catch {
    _ => raise InputError("invalid rule JSON")
  }
  guard json is { "version": Number(1, ..), "rules": Array(entries), .. } else {
    raise InputError("expected rule schema version 1 and rules array")
  }
  guard entries.length() <= 256 else {
    raise InputError("at most 256 fingerprint rules")
  }
  let rules = []
  let identifiers : Set[String] = Set([])
  for entry in entries {
    guard entry
      is {
        "id": String(id),
        "name": String(name),
        "field": String(field),
        "contains": String(needle),
        ..
      } else {
      raise InputError("each rule needs id, name, field and contains strings")
    }
    guard !id.is_empty() &&
      id.length() <= 128 &&
      id
      .iter()
      .all(c => c is ('a'..<='z' | 'A'..<='Z' | '0'..<='9' | '.' | '_' | '-')) &&
      !identifiers.contains(id) else {
      raise InputError("invalid or duplicate rule id: \{id}")
    }
    guard !name.is_empty() &&
      name.length() <= 256 &&
      !needle.is_empty() &&
      needle.length() <= 256 else {
      raise InputError("rule names and needles must be in 1..256 characters")
    }
    guard field
      is ("protocol"
      | "banner"
      | "server"
      | "title"
      | "location"
      | "http_status") else {
      raise InputError("unknown evidence field: \{field}")
    }
    identifiers.insert(id) |> ignore
    rules.push({ id, name, field, needle: ascii_lower(needle), })
  }
  { rules, }
}

///|
pub impl Detector for RuleSet with fn id(_) {
  "fingerprints.v1"
}

///|
pub impl Detector for RuleSet with fn inspect(self, result) {
  let findings = []
  if result.service is Some(info) {
    for rule in self.rules {
      @async.pause()
      let value = match rule.field {
        "protocol" => Some(info.protocol)
        "banner" => info.banner
        "server" => info.server
        "title" => info.title
        "location" => info.location
        "http_status" => info.http_status.map(code => code.to_string())
        _ => None
      }
      if value is Some(value) && ascii_lower(value).contains(rule.needle) {
        findings.push({
          id: rule.id,
          name: rule.name,
          evidence: value[:1024].to_owned(),
        })
      }
    }
  }
  findings
}