///|
/// Root of a resolved static import or package reference.
priv enum ImportRoot {
  ImportData
  ImportInput
}

///|
/// A resolved import target inside one module.
priv struct ResolvedImport {
  root : ImportRoot
  path : Array[String]
}

///|
/// Per-module resolution context (package path, import aliases, and package
/// annotations).
priv struct ModuleEnv {
  pkg_path : Array[String]
  imports : Map[String, ResolvedImport]
  pkg_annotations : Array[@ast.Annotation]
}

///|
/// Mutable internal builder for a compiled virtual document node.
priv enum RawNodeKind {
  RawPackage
  RawComplete
  RawPartialSet
  RawVirtualObject
  RawFunction(Int32)
}

///|
priv struct RawClause {
  module_env : ModuleEnv
  rule : @ast.Rule
  param_terms : ReadOnlyArray[@ast.Term]
  dynamic_keys : Array[@ast.Term]
  leaf_kind : DynamicLeafKind
  value_term : @ast.Term?
}

///|
priv struct RawNode {
  mut kind : RawNodeKind
  children : Map[String, RawNode]
  clauses : Array[RawClause]
  mut default_val : @value.Value?
  mut default_term : (ModuleEnv, @ast.Term)?
  doc_annotations : Array[@ast.Annotation]
  span : @syntax.SourceSpan
}

///|
fn RawNode::empty_package(span : @syntax.SourceSpan) -> RawNode {
  {
    kind: RawPackage,
    children: Map([]),
    clauses: [],
    default_val: None,
    default_term: None,
    doc_annotations: [],
    span,
  }
}

///|
fn format_data_path(segs : ArrayView[String]) -> String {
  if segs.is_empty() {
    "data"
  } else {
    let buf = StringBuilder()
    buf.write_string("data")
    for s in segs {
      buf.write_char('.')
      buf.write_string(s)
    }
    buf.to_string()
  }
}

///|
fn extract_package_segments(
  pkg : @ast.PackagePath,
) -> Array[String] raise CompileError {
  let out : Array[String] = []
  for seg in pkg.segments() {
    match seg {
      Dot(k) => out.push(k.to_string())
      Bracket(t) =>
        match t.kind() {
          String(s) => out.push(s)
          _ =>
            raise InvalidRuleHead(
              message="package path bracket segment must be a string literal",
              span=t.span(),
            )
        }
    }
  }
  out
}

///|
fn extract_import_segments(
  r : @ast.Ref,
) -> (String, Array[String]) raise CompileError {
  let base_name = match r.base().kind() {
    Var(id) => id.to_string()
    _ => raise InvalidImport(path="", span=r.base().span())
  }
  let segs : Array[String] = []
  for seg in r.segments() {
    match seg {
      Dot(k) => segs.push(k.to_string())
      Bracket(t) =>
        match t.kind() {
          String(s) => segs.push(s)
          _ => raise InvalidImport(path=base_name, span=t.span())
        }
    }
  }
  (base_name, segs)
}

///|
fn build_module_env(mod : @ast.Module) -> ModuleEnv raise CompileError {
  let pkg_path = extract_package_segments(mod.package_path())
  let imports : Map[String, ResolvedImport] = Map([])
  for imp in mod.imports() {
    let (base_name, segs) = extract_import_segments(imp.path())
    if base_name == "rego" {
      // `import rego.v1` is a valid no-op in strict Rego v1.
      if segs.length() == 1 && segs[0] == "v1" {
        continue
      }
      raise InvalidImport(path="rego." + segs.join("."), span=imp.span())
    }
    if base_name == "future" {
      // `import future.keywords` and `import future.keywords.*` are valid v1 no-ops.
      if !segs.is_empty() && segs[0] == "keywords" {
        continue
      }
      raise InvalidImport(path="future." + segs.join("."), span=imp.span())
    }
    let root : ImportRoot = if base_name == "data" {
      ImportData
    } else if base_name == "input" {
      ImportInput
    } else {
      raise InvalidImport(path=base_name, span=imp.span())
    }
    let alias_name = match imp.alias_name() {
      Some(id) => id.to_string()
      None => if segs.is_empty() { base_name } else { segs[segs.length() - 1] }
    }
    if imports.contains(alias_name) {
      raise DuplicateImportAlias(alias_name~, span=imp.span())
    }
    imports.set(alias_name, { root, path: segs, })
  }
  let pkg_annotations : Array[@ast.Annotation] = []
  for a in mod.package_annotations() {
    pkg_annotations.push(a)
  }
  { pkg_path, imports, pkg_annotations, }
}

///|
/// Splits a rule head `Ref` into its leading static string segments and any
/// remaining dynamic segments starting from the first non-string-literal bracket.
fn split_head_ref(
  r : @ast.Ref,
) -> (Array[String], Array[@ast.Term]) raise CompileError {
  let static_segs : Array[String] = []
  let dynamic_segs : Array[@ast.Term] = []
  match r.base().kind() {
    Var(id) => static_segs.push(id.to_string())
    _ =>
      raise InvalidRuleHead(
        message="rule head must start with an identifier",
        span=r.base().span(),
      )
  }
  let mut in_dynamic = false
  for seg in r.segments() {
    if !in_dynamic {
      match seg {
        Dot(k) => static_segs.push(k.to_string())
        Bracket(t) =>
          match t.kind() {
            String(s) => static_segs.push(s)
            _ => {
              in_dynamic = true
              dynamic_segs.push(t)
            }
          }
      }
    } else {
      match seg {
        Dot(k) =>
          dynamic_segs.push(
            @ast.Term::Term(kind=String(k.to_string()), span=r.span()),
          )
        Bracket(t) => dynamic_segs.push(t)
      }
    }
  }
  (static_segs, dynamic_segs)
}

///|
/// Evaluates a ground term statically (used for `default` rule values).
fn eval_ground_term(term : @ast.Term) -> @value.Value raise CompileError {
  match term.kind() {
    Null => @value.Value::Null
    Bool(b) => @value.Value::Bool(b)
    Number(num) => {
      let dec = @value.Decimal(num.raw()) catch {
        _ => raise InvalidNumber(text=num.raw(), span=term.span())
      }
      @value.Value::Number(dec)
    }
    String(s) => @value.Value::String(s)
    UnaryNeg(inner) =>
      match eval_ground_term(inner) {
        Number(d) => @value.Value::Number(d.neg())
        _ =>
          raise InvalidDefault(
            message="negation in default rule must apply to a number",
            span=term.span(),
          )
      }
    Array(items) => {
      let vals : Array[@value.Value] = []
      for item in items {
        vals.push(eval_ground_term(item))
      }
      @value.Value::array(vals)
    }
    Set(items) => {
      let vals : Array[@value.Value] = []
      for item in items {
        vals.push(eval_ground_term(item))
      }
      @value.Value::set(vals)
    }
    Object(pairs) => {
      let entries : Array[(@value.Value, @value.Value)] = []
      for pair in pairs {
        entries.push((eval_ground_term(pair.0), eval_ground_term(pair.1)))
      }
      @value.Value::object(entries)
    }
    _ =>
      raise InvalidDefault(
        message="default rule value must be a ground constant term",
        span=term.span(),
      )
  }
}

///|
/// Navigates/creates intermediate package/object nodes down to the parent of
/// `full_path` and returns the node at `full_path`.
fn ensure_node_at(
  root : RawNode,
  full_path : Array[String],
  span : @syntax.SourceSpan,
) -> RawNode raise CompileError {
  let mut cur = root
  for i in 0.. ()
      _ =>
        raise ConflictingRuleKind(path=format_data_path(full_path[:i]), span~)
    }
    match cur.children.get(seg) {
      Some(child) => cur = child
      None => {
        let next = RawNode::empty_package(span)
        cur.children.set(seg, next)
        cur = next
      }
    }
  }
  cur
}

///|
fn lookup_raw_node(root : RawNode, path : ArrayView[String]) -> RawNode? {
  let mut cur = root
  for seg in path {
    match cur.kind {
      RawPackage | RawVirtualObject =>
        match cur.children.get(seg) {
          Some(next) => cur = next
          None => return None
        }
      _ => return None
    }
  }
  Some(cur)
}

///|
/// Converts an `@ast.MetadataValue` to a runtime `@value.Value`.
fn metadata_value_to_value(mv : @ast.MetadataValue) -> @value.Value {
  match mv {
    Null => @value.Value::Null
    Bool(b) => @value.Value::Bool(b)
    Int(i) => @value.Value::Number(@value.Decimal::from_int64(i))
    Float(f) => {
      let dec = @value.Decimal::from_double(f) catch {
        _ => @value.Decimal::zero()
      }
      @value.Value::Number(dec)
    }
    String(s) => @value.Value::String(s)
    Seq(items) => {
      let vals : Array[@value.Value] = []
      for item in items {
        vals.push(metadata_value_to_value(item))
      }
      @value.Value::array(vals)
    }
    Mapping(pairs) => {
      let entries : Array[(String, @value.Value)] = []
      for pair in pairs {
        entries.push((pair.0, metadata_value_to_value(pair.1)))
      }
      @value.Value::string_object(entries)
    }
  }
}

///|
/// Converts an `@ast.Annotation` to the OPA `rego.metadata.rule()` object shape.
fn annotation_to_value(ann : @ast.Annotation) -> @value.Value {
  let entries : Array[(String, @value.Value)] = [
    ("scope", @value.Value::String(ann.scope().to_string())),
  ]
  if ann.title() is Some(t) {
    entries.push(("title", @value.Value::String(t)))
  }
  if ann.description() is Some(d) {
    entries.push(("description", @value.Value::String(d)))
  }
  if !ann.organizations().is_empty() {
    let orgs : Array[@value.Value] = []
    for o in ann.organizations() {
      orgs.push(@value.Value::String(o))
    }
    entries.push(("organizations", @value.Value::array(orgs)))
  }
  if !ann.authors().is_empty() {
    let authors : Array[@value.Value] = []
    for a in ann.authors() {
      let a_entries : Array[(String, @value.Value)] = [
        ("name", @value.Value::String(a.name())),
      ]
      if a.email() is Some(e) {
        a_entries.push(("email", @value.Value::String(e)))
      }
      authors.push(@value.Value::string_object(a_entries))
    }
    entries.push(("authors", @value.Value::array(authors)))
  }
  if !ann.related_resources().is_empty() {
    let res : Array[@value.Value] = []
    for r in ann.related_resources() {
      let r_entries : Array[(String, @value.Value)] = [
        ("ref", @value.Value::String(r.ref_uri())),
      ]
      if r.description() is Some(d) {
        r_entries.push(("description", @value.Value::String(d)))
      }
      res.push(@value.Value::string_object(r_entries))
    }
    entries.push(("related_resources", @value.Value::array(res)))
  }
  if ann.entrypoint() {
    entries.push(("entrypoint", @value.Value::Bool(true)))
  }
  if ann.custom() is Some(c) {
    entries.push(("custom", metadata_value_to_value(c)))
  }
  if ann.labels() is Some(l) {
    entries.push(("labels", metadata_value_to_value(l)))
  }
  @value.Value::string_object(entries)
}

///|
/// Inserts all modules and rules into the raw `data.*` virtual document tree,
/// checking import aliases, rule kind compatibility, and default constraints.
fn build_raw_tree(
  modules : ArrayView[@ast.Module],
) -> (
  RawNode,
  Array[ModuleEnv],
  Map[String, Array[@ast.Annotation]],
  Map[String, Array[@ast.Annotation]],
) raise CompileError {
  let empty_span = @syntax.SourceSpan::empty_at_start()
  let root = RawNode::empty_package(empty_span)
  let envs : Array[ModuleEnv] = []
  let pkg_ann_map : Map[String, Array[@ast.Annotation]] = Map([])
  let subpkg_ann_map : Map[String, Array[@ast.Annotation]] = Map([])

  for mod in modules {
    let env = build_module_env(mod)
    envs.push(env)
    let pkg_key = env.pkg_path.join(".")
    for ann in env.pkg_annotations {
      match ann.scope() {
        Package => {
          let list = match pkg_ann_map.get(pkg_key) {
            Some(existing) => existing
            None => {
              let fresh : Array[@ast.Annotation] = []
              pkg_ann_map.set(pkg_key, fresh)
              fresh
            }
          }
          list.push(ann)
        }
        Subpackages => {
          let list = match subpkg_ann_map.get(pkg_key) {
            Some(existing) => existing
            None => {
              let fresh : Array[@ast.Annotation] = []
              subpkg_ann_map.set(pkg_key, fresh)
              fresh
            }
          }
          list.push(ann)
        }
        _ => ()
      }
    }
    // Ensure package node exists in tree even for empty modules.
    let _ = ensure_node_at(root, env.pkg_path, mod.span())

    for rule in mod.rules() {
      match rule.head() {
        Default(ref_head~, args~, assigned~) => {
          let (static_head, dynamic_head) = split_head_ref(ref_head)
          if !dynamic_head.is_empty() {
            raise InvalidDefault(
              message="default rule head cannot contain dynamic bracket keys",
              span=rule.span(),
            )
          }
          let full_path = env.pkg_path.copy()
          for s in static_head {
            full_path.push(s)
          }
          let node = ensure_node_at(root, full_path, rule.span())
          if node.default_val is Some(_) || node.default_term is Some(_) {
            raise DuplicateDefault(
              path=format_data_path(full_path),
              span=rule.span(),
            )
          }
          let is_comp_default = match assigned.value().kind() {
            ArrayComprehension(..)
            | SetComprehension(..)
            | ObjectComprehension(..) => true
            _ => false
          }
          let ground_opt : @value.Value? = if is_comp_default && args.is_empty() {
            None
          } else {
            Some(eval_ground_term(assigned.value()))
          }
          if args.is_empty() {
            match node.kind {
              RawPackage =>
                if !node.children.is_empty() {
                  raise InvalidDefault(
                    message="default rule conflicts with child rules at `\{format_data_path(full_path)}`",
                    span=rule.span(),
                  )
                } else {
                  node.kind = RawComplete
                }
              RawComplete => ()
              _ =>
                raise InvalidDefault(
                  message="default rule incompatible with existing rule at `\{format_data_path(full_path)}`",
                  span=rule.span(),
                )
            }
          } else {
            let arity = args.length()
            match node.kind {
              RawPackage =>
                if !node.children.is_empty() {
                  raise ConflictingRuleKind(
                    path=format_data_path(full_path),
                    span=rule.span(),
                  )
                } else {
                  node.kind = RawFunction(arity)
                }
              RawFunction(existing) if existing == arity => ()
              _ =>
                raise ConflictingRuleKind(
                  path=format_data_path(full_path),
                  span=rule.span(),
                )
            }
          }
          match ground_opt {
            Some(g) => node.default_val = Some(g)
            None => node.default_term = Some((env, assigned.value()))
          }
          for ann in rule.annotations() {
            if ann.scope() is Document {
              node.doc_annotations.push(ann)
            }
          }
        }
        Function(ref_head~, args~, assigned~) => {
          let (static_head, dynamic_head) = split_head_ref(ref_head)
          if !dynamic_head.is_empty() {
            raise InvalidRuleHead(
              message="function name cannot contain dynamic bracket segments",
              span=rule.span(),
            )
          }
          let full_path = env.pkg_path.copy()
          for s in static_head {
            full_path.push(s)
          }
          let node = ensure_node_at(root, full_path, rule.span())
          let arity = args.length()
          match node.kind {
            RawPackage =>
              if !node.children.is_empty() {
                raise ConflictingRuleKind(
                  path=format_data_path(full_path),
                  span=rule.span(),
                )
              } else {
                node.kind = RawFunction(arity)
              }
            RawFunction(existing) if existing == arity => ()
            _ =>
              raise ConflictingRuleKind(
                path=format_data_path(full_path),
                span=rule.span(),
              )
          }
          let val_term = match assigned {
            Some(av) => Some(av.value())
            None => None
          }
          node.clauses.push({
            module_env: env,
            rule,
            param_terms: args,
            dynamic_keys: [],
            leaf_kind: DynamicValue,
            value_term: val_term,
          })
          for ann in rule.annotations() {
            if ann.scope() is Document {
              node.doc_annotations.push(ann)
            }
          }
        }
        Complete(ref_head~, assigned~) => {
          let (static_head, dynamic_head) = split_head_ref(ref_head)
          let full_path = env.pkg_path.copy()
          for s in static_head {
            full_path.push(s)
          }
          let val_term = match assigned {
            Some(av) => Some(av.value())
            None => None
          }
          if dynamic_head.is_empty() {
            let node = ensure_node_at(root, full_path, rule.span())
            match node.kind {
              RawPackage =>
                if !node.children.is_empty() {
                  raise ConflictingRuleKind(
                    path=format_data_path(full_path),
                    span=rule.span(),
                  )
                } else {
                  node.kind = RawComplete
                }
              RawComplete => ()
              _ =>
                raise ConflictingRuleKind(
                  path=format_data_path(full_path),
                  span=rule.span(),
                )
            }
            node.clauses.push({
              module_env: env,
              rule,
              param_terms: ReadOnlyArray::from_array([]),
              dynamic_keys: [],
              leaf_kind: DynamicValue,
              value_term: val_term,
            })
            for ann in rule.annotations() {
              if ann.scope() is Document {
                node.doc_annotations.push(ann)
              }
            }
          } else {
            if !rule.else_branches().is_empty() {
              raise InvalidRuleHead(
                message="`else` is not allowed on dynamic ref-head partial rules",
                span=rule.span(),
              )
            }
            let node = ensure_node_at(root, full_path, rule.span())
            match node.kind {
              RawPackage => node.kind = RawVirtualObject
              RawVirtualObject => ()
              _ =>
                raise ConflictingRuleKind(
                  path=format_data_path(full_path),
                  span=rule.span(),
                )
            }
            node.clauses.push({
              module_env: env,
              rule,
              param_terms: ReadOnlyArray::from_array([]),
              dynamic_keys: dynamic_head,
              leaf_kind: DynamicValue,
              value_term: val_term,
            })
          }
        }
        PartialSet(ref_head~, key~) => {
          if !rule.else_branches().is_empty() {
            raise InvalidRuleHead(
              message="`else` is not allowed on partial set rules",
              span=rule.span(),
            )
          }
          let (static_head, dynamic_head) = split_head_ref(ref_head)
          let full_path = env.pkg_path.copy()
          for s in static_head {
            full_path.push(s)
          }
          if dynamic_head.is_empty() {
            let node = ensure_node_at(root, full_path, rule.span())
            if node.default_val is Some(_) {
              raise InvalidDefault(
                message="default rule cannot coexist with partial set rule",
                span=rule.span(),
              )
            }
            match node.kind {
              RawPackage =>
                if !node.children.is_empty() {
                  raise ConflictingRuleKind(
                    path=format_data_path(full_path),
                    span=rule.span(),
                  )
                } else {
                  node.kind = RawPartialSet
                }
              RawPartialSet => ()
              _ =>
                raise ConflictingRuleKind(
                  path=format_data_path(full_path),
                  span=rule.span(),
                )
            }
            node.clauses.push({
              module_env: env,
              rule,
              param_terms: ReadOnlyArray::from_array([]),
              dynamic_keys: [],
              leaf_kind: DynamicSetElem,
              value_term: Some(key),
            })
            for ann in rule.annotations() {
              if ann.scope() is Document {
                node.doc_annotations.push(ann)
              }
            }
          } else {
            let node = ensure_node_at(root, full_path, rule.span())
            match node.kind {
              RawPackage => node.kind = RawVirtualObject
              RawVirtualObject => ()
              _ =>
                raise ConflictingRuleKind(
                  path=format_data_path(full_path),
                  span=rule.span(),
                )
            }
            node.clauses.push({
              module_env: env,
              rule,
              param_terms: ReadOnlyArray::from_array([]),
              dynamic_keys: dynamic_head,
              leaf_kind: DynamicSetElem,
              value_term: Some(key),
            })
          }
        }
        PartialObject(ref_head~, key~, assigned~) => {
          let (static_head, dynamic_head) = split_head_ref(ref_head)
          // If the key is a string literal and there are no dynamic prefix segments,
          // OPA treats `p["k"] := v` identically to `p.k := v` (complete rule at p.k)!
          match (dynamic_head.is_empty(), key.kind()) {
            (true, String(k_str)) => {
              let full_path = env.pkg_path.copy()
              for s in static_head {
                full_path.push(s)
              }
              full_path.push(k_str)
              let node = ensure_node_at(root, full_path, rule.span())
              match node.kind {
                RawPackage =>
                  if !node.children.is_empty() {
                    raise ConflictingRuleKind(
                      path=format_data_path(full_path),
                      span=rule.span(),
                    )
                  } else {
                    node.kind = RawComplete
                  }
                RawComplete => ()
                _ =>
                  raise ConflictingRuleKind(
                    path=format_data_path(full_path),
                    span=rule.span(),
                  )
              }
              node.clauses.push({
                module_env: env,
                rule,
                param_terms: ReadOnlyArray::from_array([]),
                dynamic_keys: [],
                leaf_kind: DynamicValue,
                value_term: Some(assigned.value()),
              })
              for ann in rule.annotations() {
                if ann.scope() is Document {
                  node.doc_annotations.push(ann)
                }
              }
            }
            _ => {
              if !rule.else_branches().is_empty() {
                raise InvalidRuleHead(
                  message="`else` is not allowed on partial object rules",
                  span=rule.span(),
                )
              }
              let full_path = env.pkg_path.copy()
              for s in static_head {
                full_path.push(s)
              }
              let node = ensure_node_at(root, full_path, rule.span())
              if node.default_val is Some(_) {
                raise InvalidDefault(
                  message="default rule cannot coexist with partial object rule",
                  span=rule.span(),
                )
              }
              match node.kind {
                RawPackage => node.kind = RawVirtualObject
                RawVirtualObject => ()
                _ =>
                  raise ConflictingRuleKind(
                    path=format_data_path(full_path),
                    span=rule.span(),
                  )
              }
              let dyn_keys = dynamic_head.copy()
              dyn_keys.push(key)
              node.clauses.push({
                module_env: env,
                rule,
                param_terms: ReadOnlyArray::from_array([]),
                dynamic_keys: dyn_keys,
                leaf_kind: DynamicValue,
                value_term: Some(assigned.value()),
              })
            }
          }
        }
      }
    }
  }
  (root, envs, pkg_ann_map, subpkg_ann_map)
}