///|
/// Raised when a `# METADATA` comment block contains invalid YAML, an unknown
/// scope, or a malformed standard annotation field.
#derive(Eq, Debug)
pub(all) suberror AnnotationError {
  InvalidYaml(span~ : @syntax.SourceSpan, message~ : String)
  NotAMapping(span~ : @syntax.SourceSpan)
  InvalidScope(span~ : @syntax.SourceSpan, value~ : String)
  InvalidFieldShape(
    span~ : @syntax.SourceSpan,
    field~ : String,
    message~ : String,
  )
}

///|
/// The attachment scope of an OPA `# METADATA` annotation block.
#derive(Eq, Compare, Hash, Debug)
pub(all) enum AnnotationScope {
  Rule
  Document
  Package
  Subpackages
}

///|
pub fn AnnotationScope::parse(
  text : String,
  span : @syntax.SourceSpan,
) -> AnnotationScope raise AnnotationError {
  match text {
    "rule" => Rule
    "document" => Document
    "package" => Package
    "subpackages" => Subpackages
    _ => raise InvalidScope(span~, value=text)
  }
}

///|
pub fn AnnotationScope::to_string(self : AnnotationScope) -> String {
  match self {
    Rule => "rule"
    Document => "document"
    Package => "package"
    Subpackages => "subpackages"
  }
}

///|
/// Deeply immutable value representation for arbitrary `# METADATA` `custom`,
/// `labels`, and schema `definition` payloads.
#derive(Eq, Debug)
pub(all) enum MetadataValue {
  Null
  Bool(Bool)
  Int(Int64)
  Float(Double)
  String(String)
  Seq(ReadOnlyArray[MetadataValue])
  Mapping(ReadOnlyArray[(String, MetadataValue)])
}

///|
fn from_yaml(value : @yaml.Yaml) -> MetadataValue {
  match value {
    Null | BadValue => Null
    Boolean(b) => Bool(b)
    Integer(i) => Int(i)
    Real(f, ..) => Float(f)
    String(s) => String(s)
    Array(items) => {
      let out = []
      for item in items {
        out.push(from_yaml(item))
      }
      Seq(ReadOnlyArray::from_array(out))
    }
    Map(fields) => {
      let pairs : Array[(String, MetadataValue)] = []
      for k, v in fields {
        pairs.push((k, from_yaml(v)))
      }
      pairs.sort_by((a, b) => a.0.compare(b.0))
      Mapping(ReadOnlyArray::from_array(pairs))
    }
  }
}

///|
/// Author entry in `# METADATA` (`authors`).
#derive(Eq, Debug)
struct AuthorAnnotation {
  name : String
  email : String?
}

///|
pub fn AuthorAnnotation::name(self : AuthorAnnotation) -> String {
  self.name
}

///|
pub fn AuthorAnnotation::email(self : AuthorAnnotation) -> String? {
  self.email
}

///|
/// Related resource entry in `# METADATA` (`related_resources`).
#derive(Eq, Debug)
struct RelatedResourceAnnotation {
  ref_uri : String
  description : String?
}

///|
pub fn RelatedResourceAnnotation::ref_uri(
  self : RelatedResourceAnnotation,
) -> String {
  self.ref_uri
}

///|
pub fn RelatedResourceAnnotation::description(
  self : RelatedResourceAnnotation,
) -> String? {
  self.description
}

///|
/// Schema declaration in `# METADATA` (`schemas`).
#derive(Eq, Debug)
struct SchemaAnnotation {
  path : String
  schema : String?
  definition : MetadataValue?
}

///|
pub fn SchemaAnnotation::path(self : SchemaAnnotation) -> String {
  self.path
}

///|
pub fn SchemaAnnotation::schema(self : SchemaAnnotation) -> String? {
  self.schema
}

///|
pub fn SchemaAnnotation::definition(self : SchemaAnnotation) -> MetadataValue? {
  self.definition
}

///|
/// Compile hint entry in `# METADATA` (`compile`).
#derive(Eq, Debug)
struct CompileAnnotation {
  unknowns : ReadOnlyArray[String]
  mask_rule : String?
}

///|
pub fn CompileAnnotation::unknowns(
  self : CompileAnnotation,
) -> ReadOnlyArray[String] {
  self.unknowns
}

///|
pub fn CompileAnnotation::mask_rule(self : CompileAnnotation) -> String? {
  self.mask_rule
}

///|
/// One parsed OPA `v1.23.0` `# METADATA` annotation block.
#derive(Eq, Debug)
struct Annotation {
  scope : AnnotationScope
  title : String?
  description : String?
  entrypoint : Bool
  organizations : ReadOnlyArray[String]
  authors : ReadOnlyArray[AuthorAnnotation]
  related_resources : ReadOnlyArray[RelatedResourceAnnotation]
  schemas : ReadOnlyArray[SchemaAnnotation]
  compile : CompileAnnotation?
  custom : MetadataValue?
  labels : MetadataValue?
  span : @syntax.SourceSpan
}

///|
pub fn Annotation::scope(self : Annotation) -> AnnotationScope {
  self.scope
}

///|
pub fn Annotation::title(self : Annotation) -> String? {
  self.title
}

///|
pub fn Annotation::description(self : Annotation) -> String? {
  self.description
}

///|
pub fn Annotation::entrypoint(self : Annotation) -> Bool {
  self.entrypoint
}

///|
pub fn Annotation::organizations(self : Annotation) -> ReadOnlyArray[String] {
  self.organizations
}

///|
pub fn Annotation::authors(
  self : Annotation,
) -> ReadOnlyArray[AuthorAnnotation] {
  self.authors
}

///|
pub fn Annotation::related_resources(
  self : Annotation,
) -> ReadOnlyArray[RelatedResourceAnnotation] {
  self.related_resources
}

///|
pub fn Annotation::schemas(
  self : Annotation,
) -> ReadOnlyArray[SchemaAnnotation] {
  self.schemas
}

///|
pub fn Annotation::compile(self : Annotation) -> CompileAnnotation? {
  self.compile
}

///|
pub fn Annotation::custom(self : Annotation) -> MetadataValue? {
  self.custom
}

///|
pub fn Annotation::labels(self : Annotation) -> MetadataValue? {
  self.labels
}

///|
pub fn Annotation::span(self : Annotation) -> @syntax.SourceSpan {
  self.span
}

///|
fn parse_author_shorthand(text : String) -> AuthorAnnotation {
  let trimmed = text.trim().to_owned()
  match (trimmed.find("<"), trimmed.find(">")) {
    (Some(lt), Some(gt)) if gt > lt => {
      let name = trimmed[:lt].trim().to_owned()
      let email = trimmed[lt + 1:gt].trim().to_owned()
      { name, email: if email.is_empty() { None } else { Some(email) }, }
    }
    _ => { name: trimmed, email: None, }
  }
}

///|
fn parse_authors(
  value : @yaml.Yaml,
  span : @syntax.SourceSpan,
) -> ReadOnlyArray[AuthorAnnotation] raise AnnotationError {
  guard value is Array(items) else {
    raise InvalidFieldShape(
      span~,
      field="authors",
      message="expected a list of authors",
    )
  }
  let out : Array[AuthorAnnotation] = []
  for item in items {
    match item {
      String(s) => out.push(parse_author_shorthand(s))
      Map(m) => {
        let name = match m.get("name") {
          Some(String(s)) => s
          None => ""
          _ =>
            raise InvalidFieldShape(
              span~,
              field="authors",
              message="author `name` must be a string",
            )
        }
        let email = match m.get("email") {
          Some(String(s)) => Some(s)
          None => None
          _ =>
            raise InvalidFieldShape(
              span~,
              field="authors",
              message="author `email` must be a string",
            )
        }
        out.push({ name, email, })
      }
      _ =>
        raise InvalidFieldShape(
          span~,
          field="authors",
          message="each author must be a string or mapping",
        )
    }
  }
  ReadOnlyArray::from_array(out)
}

///|
fn parse_related_resources(
  value : @yaml.Yaml,
  span : @syntax.SourceSpan,
) -> ReadOnlyArray[RelatedResourceAnnotation] raise AnnotationError {
  guard value is Array(items) else {
    raise InvalidFieldShape(
      span~,
      field="related_resources",
      message="expected a list of related resources",
    )
  }
  let out : Array[RelatedResourceAnnotation] = []
  for item in items {
    match item {
      String(s) => out.push({ ref_uri: s, description: None, })
      Map(m) => {
        let ref_uri = match m.get("ref") {
          Some(String(s)) => s
          _ =>
            raise InvalidFieldShape(
              span~,
              field="related_resources",
              message="related resource requires string `ref`",
            )
        }
        let description = match m.get("description") {
          Some(String(s)) => Some(s)
          None => None
          _ =>
            raise InvalidFieldShape(
              span~,
              field="related_resources",
              message="related resource `description` must be a string",
            )
        }
        out.push({ ref_uri, description, })
      }
      _ =>
        raise InvalidFieldShape(
          span~,
          field="related_resources",
          message="each related resource must be a string or mapping",
        )
    }
  }
  ReadOnlyArray::from_array(out)
}

///|
fn parse_schemas(
  value : @yaml.Yaml,
  span : @syntax.SourceSpan,
) -> ReadOnlyArray[SchemaAnnotation] raise AnnotationError {
  guard value is Array(items) else {
    raise InvalidFieldShape(
      span~,
      field="schemas",
      message="expected a list of schema entries",
    )
  }
  let out : Array[SchemaAnnotation] = []
  for item in items {
    guard item is Map(m) else {
      raise InvalidFieldShape(
        span~,
        field="schemas",
        message="each schema entry must be a mapping",
      )
    }
    // OPA supports both `{ path: ..., schema: ... }` and `{ input: schema.foo }` shorthand.
    if m.get("path") is Some(String(path)) {
      let schema = match m.get("schema") {
        Some(String(s)) => Some(s)
        None => None
        _ =>
          raise InvalidFieldShape(
            span~,
            field="schemas",
            message="schema `schema` field must be a string",
          )
      }
      let definition = m.get("definition").map(from_yaml)
      out.push({ path, schema, definition, })
    } else if m.length() == 1 {
      for k, v in m {
        match v {
          String(s) => out.push({ path: k, schema: Some(s), definition: None, })
          _ =>
            out.push({ path: k, schema: None, definition: Some(from_yaml(v)), })
        }
      }
    } else {
      raise InvalidFieldShape(
        span~,
        field="schemas",
        message="schema entry must specify `path` or a single path-to-schema mapping",
      )
    }
  }
  ReadOnlyArray::from_array(out)
}

///|
fn parse_compile(
  value : @yaml.Yaml,
  span : @syntax.SourceSpan,
) -> CompileAnnotation raise AnnotationError {
  guard value is Map(m) else {
    raise InvalidFieldShape(
      span~,
      field="compile",
      message="expected a mapping for `compile`",
    )
  }
  let unknowns : Array[String] = []
  if m.get("unknowns") is Some(u) {
    guard u is Array(items) else {
      raise InvalidFieldShape(
        span~,
        field="compile",
        message="`compile.unknowns` must be a list of strings",
      )
    }
    for item in items {
      guard item is String(s) else {
        raise InvalidFieldShape(
          span~,
          field="compile",
          message="each entry in `compile.unknowns` must be a string",
        )
      }
      unknowns.push(s)
    }
  }
  let mask_rule = match m.get("mask_rule") {
    Some(String(s)) => Some(s)
    None => None
    _ =>
      raise InvalidFieldShape(
        span~,
        field="compile",
        message="`compile.mask_rule` must be a string",
      )
  }
  { unknowns: ReadOnlyArray::from_array(unknowns), mask_rule, }
}

///|
/// Parses a stripped `# METADATA` YAML body into a typed `Annotation`.
pub fn parse_metadata_yaml(
  yaml_text : String,
  default_scope~ : AnnotationScope,
  span~ : @syntax.SourceSpan,
) -> Annotation raise AnnotationError {
  let docs = @yaml.Yaml::load_from_string(yaml_text[:]) catch {
    @yaml.YamlError(info~, ..) => raise InvalidYaml(span~, message=info)
  }
  let fields = match docs {
    [] => Map([])
    [Map(m)] => m
    [_] => raise NotAMapping(span~)
    _ =>
      raise InvalidYaml(
        span~,
        message="METADATA block must contain a single YAML mapping",
      )
  }
  let scope = match fields.get("scope") {
    Some(String(s)) => AnnotationScope::parse(s, span)
    None => default_scope
    _ =>
      raise InvalidFieldShape(
        span~,
        field="scope",
        message="`scope` must be a string",
      )
  }
  let title = match fields.get("title") {
    Some(String(s)) => Some(s)
    None => None
    _ =>
      raise InvalidFieldShape(
        span~,
        field="title",
        message="`title` must be a string",
      )
  }
  let description = match fields.get("description") {
    Some(String(s)) => Some(s)
    None => None
    _ =>
      raise InvalidFieldShape(
        span~,
        field="description",
        message="`description` must be a string",
      )
  }
  let entrypoint = match fields.get("entrypoint") {
    Some(Boolean(b)) => b
    None => false
    _ =>
      raise InvalidFieldShape(
        span~,
        field="entrypoint",
        message="`entrypoint` must be a boolean",
      )
  }
  let organizations : Array[String] = []
  if fields.get("organizations") is Some(v) {
    guard v is Array(items) else {
      raise InvalidFieldShape(
        span~,
        field="organizations",
        message="`organizations` must be a list of strings",
      )
    }
    for item in items {
      guard item is String(s) else {
        raise InvalidFieldShape(
          span~,
          field="organizations",
          message="each organization must be a string",
        )
      }
      organizations.push(s)
    }
  }
  let authors = match fields.get("authors") {
    Some(v) => parse_authors(v, span)
    None => ReadOnlyArray::from_array([])
  }
  let related_resources = match fields.get("related_resources") {
    Some(v) => parse_related_resources(v, span)
    None => ReadOnlyArray::from_array([])
  }
  let schemas = match fields.get("schemas") {
    Some(v) => parse_schemas(v, span)
    None => ReadOnlyArray::from_array([])
  }
  let compile = match fields.get("compile") {
    Some(v) => Some(parse_compile(v, span))
    None => None
  }
  let custom = fields.get("custom").map(from_yaml)
  let labels = fields.get("labels").map(from_yaml)
  {
    scope,
    title,
    description,
    entrypoint,
    organizations: ReadOnlyArray::from_array(organizations),
    authors,
    related_resources,
    schemas,
    compile,
    custom,
    labels,
    span,
  }
}

///|
/// Strips the leading `#` and one optional space/tab from a comment line inside
/// a `# METADATA` block.
fn strip_comment_prefix(comment_text : String) -> String {
  if !comment_text.has_prefix("#") {
    return comment_text
  }
  let rest = comment_text[1:]
  if rest.has_prefix(" ") || rest.has_prefix("\t") {
    rest[1:].to_owned()
  } else {
    rest.to_owned()
  }
}

///|
/// Scans trivia tokens in `elements` between `from_idx` and `target_idx` (exclusive)
/// and extracts any OPA `# METADATA` comment blocks attached to the target node.
fn extract_attached_annotations(
  elements : ReadOnlyArray[@syntax.SyntaxElement],
  from_idx : Int32,
  target_idx : Int32,
  default_scope : AnnotationScope,
) -> Array[Annotation] raise AnnotationError {
  // Collect comment blocks separated by blank lines (>= 2 newlines without a comment).
  let blocks : Array[Array[@syntax.SyntaxToken]] = []
  let mut cur_block : Array[@syntax.SyntaxToken] = []
  let mut newlines_since_comment = 0
  for i in from_idx..
        match tok.kind() {
          Comment => {
            if newlines_since_comment >= 2 && !cur_block.is_empty() {
              blocks.push(cur_block)
              cur_block = []
            }
            cur_block.push(tok)
            newlines_since_comment = 0
          }
          Newline => newlines_since_comment += 1
          Whitespace => ()
          _ => {
            if !cur_block.is_empty() {
              blocks.push(cur_block)
              cur_block = []
            }
            newlines_since_comment = 0
          }
        }
      Node(_) => {
        if !cur_block.is_empty() {
          blocks.push(cur_block)
          cur_block = []
        }
        newlines_since_comment = 0
      }
    }
  }
  if !cur_block.is_empty() {
    blocks.push(cur_block)
  }
  let out : Array[Annotation] = []
  for block in blocks {
    // A single contiguous comment run can contain one or more `# METADATA` headers.
    let mut i = 0
    while i < block.length() {
      let header = strip_comment_prefix(block[i].text()).trim().to_owned()
      if header == "METADATA" {
        let mut span = block[i].span()
        let lines : Array[String] = []
        i += 1
        while i < block.length() {
          let candidate = strip_comment_prefix(block[i].text())
            .trim()
            .to_owned()
          if candidate == "METADATA" {
            break
          }
          span = span.cover(block[i].span())
          lines.push(strip_comment_prefix(block[i].text()))
          i += 1
        }
        let yaml_text = lines.join("\n")
        out.push(parse_metadata_yaml(yaml_text, default_scope~, span~))
      } else {
        i += 1
      }
    }
  }
  out
}