///|
/// Atomic element inside a compiled flat GBNF alternative.
#derive(Debug, Eq)
pub(all) enum IrElement {
  /// Matches any single Unicode code point in these normalized positive ranges.
  CharRanges(Array[CharRange])
  /// Calls another compiled rule by integer ID.
  RuleRef(Int32)
}

///|
/// A compiled rule consisting of one or more flat alternatives.
/// An empty alternative `[]` represents epsilon (matches zero characters).
#derive(Debug, Eq)
pub(all) struct IrRule {
  name : String
  alts : Array[Array[IrElement]]
}

///|
/// Flat, validated, indexed representation ready for incremental decoding.
#derive(Debug, Eq)
pub(all) struct CompiledGrammar {
  root_id : Int32
  rules : Array[IrRule]
  rule_index : Map[String, Int32]
}

///|
/// Errors returned during full compilation (`parse` + `validate` + `lower`).
#derive(Debug, Eq)
pub(all) enum CompileError {
  ParseFailed(ParseError)
  ValidationFailed(Array[ValidationIssue])
}

///|
/// Format compile errors (parse or static validation failures).
pub impl Show for CompileError with fn output(self, logger) {
  match self {
    ParseFailed(e) => logger.write_string("parse error: \{e}")
    ValidationFailed(issues) => {
      logger.write_string("validation failed (\{issues.length()} error(s)): ")
      for i = 0; i < issues.length(); i = i + 1 {
        if i > 0 {
          logger.write_string("; ")
        }
        logger.write_string("\{issues[i]}")
      }
    }
  }
}

///|
priv struct Lowerer {
  rules : Array[IrRule]
  rule_index : Map[String, Int32]
  mut synth_counter : Int32
}

///|
fn Lowerer::alloc_synth_rule(
  self : Lowerer,
  prefix : String,
  alts : Array[Array[IrElement]],
) -> Int32 {
  let id = self.rules.length()
  let name = "\{prefix}#\{self.synth_counter}"
  self.synth_counter += 1
  self.rules.push({ name, alts, })
  self.rule_index[name] = id
  id
}

///|
fn Lowerer::reserve_synth_rule(self : Lowerer, prefix : String) -> Int32 {
  let id = self.rules.length()
  let name = "\{prefix}#\{self.synth_counter}"
  self.synth_counter += 1
  self.rules.push({ name, alts: [], })
  self.rule_index[name] = id
  id
}

///|
/// Lower an expression into a single `IrElement`, synthesizing a helper rule if needed.
fn Lowerer::lower_to_single_elem(
  self : Lowerer,
  expr : Expr,
  owner : String,
) -> IrElement {
  match expr {
    Literal(codes) if codes.length() == 1 =>
      CharRanges([{ start: codes[0], end: codes[0], }])
    CharClass(ranges, neg) => CharRanges(resolve_char_class(ranges, neg))
    AnyChar => CharRanges(all_unicode_ranges())
    RuleRef(name) => RuleRef(self.rule_index.get(name).unwrap_or(0))
    _ => {
      let alts = self.lower_alts(expr, owner)
      let id = self.alloc_synth_rule(owner, alts)
      RuleRef(id)
    }
  }
}

///|
/// Append lowered elements for `expr` into an existing sequence `seq`.
fn Lowerer::lower_into_seq(
  self : Lowerer,
  expr : Expr,
  owner : String,
  seq : Array[IrElement],
) -> Unit {
  match expr {
    Literal(codes) =>
      for cp in codes {
        seq.push(CharRanges([{ start: cp, end: cp, }]))
      }
    CharClass(ranges, neg) =>
      seq.push(CharRanges(resolve_char_class(ranges, neg)))
    AnyChar => seq.push(CharRanges(all_unicode_ranges()))
    RuleRef(name) => seq.push(RuleRef(self.rule_index.get(name).unwrap_or(0)))
    Seq(items) =>
      for item in items {
        self.lower_into_seq(item, owner, seq)
      }
    Alt(_) => {
      let alts = self.lower_alts(expr, owner)
      let id = self.alloc_synth_rule(owner, alts)
      seq.push(RuleRef(id))
    }
    Repeat(inner, min_v, max_v) => {
      let elem = self.lower_to_single_elem(inner, owner)
      for i = 0; i < min_v; i = i + 1 {
        seq.push(elem)
      }
      match max_v {
        None => {
          // Right-recursive repetition tail: tail ::= elem tail | ε
          let tail_id = self.reserve_synth_rule("\{owner}_rep")
          let alts : Array[Array[IrElement]] = [[elem, RuleRef(tail_id)], []]
          self.rules[tail_id] = { name: self.rules[tail_id].name, alts, }
          seq.push(RuleRef(tail_id))
        }
        Some(max_n) => {
          let extra = max_n - min_v
          if extra > 0 {
            // Linear optional chain: opt_1 ::= elem | ε; opt_k ::= elem opt_{k-1} | ε
            let mut next_opt : Int32? = None
            for k = 0; k < extra; k = k + 1 {
              let branch : Array[IrElement] = match next_opt {
                None => [elem]
                Some(prev_id) => [elem, RuleRef(prev_id)]
              }
              let opt_id = self.alloc_synth_rule("\{owner}_opt", [branch, []])
              next_opt = Some(opt_id)
            }
            match next_opt {
              Some(entry_id) => seq.push(RuleRef(entry_id))
              None => ()
            }
          }
        }
      }
    }
  }
}

///|
/// Lower a top-level or grouped expression into a list of flat alternatives.
fn Lowerer::lower_alts(
  self : Lowerer,
  expr : Expr,
  owner : String,
) -> Array[Array[IrElement]] {
  match expr {
    Alt(branches) => {
      let alts : Array[Array[IrElement]] = []
      for b in branches {
        let seq : Array[IrElement] = []
        self.lower_into_seq(b, owner, seq)
        alts.push(seq)
      }
      alts
    }
    _ => {
      let seq : Array[IrElement] = []
      self.lower_into_seq(expr, owner, seq)
      [seq]
    }
  }
}

///|
/// Validate and lower a parsed `Grammar` into a `CompiledGrammar`.
pub fn Grammar::compile(
  self : Grammar,
) -> Result[CompiledGrammar, CompileError] {
  let report = self.validate()
  if !report.is_valid() {
    return Err(ValidationFailed(report.errors()))
  }
  let rules : Array[IrRule] = []
  let rule_index : Map[String, Int32] = Map([])
  for rule in self.rules {
    let id = rules.length()
    rule_index[rule.name] = id
    rules.push({ name: rule.name, alts: [], })
  }
  let lowerer : Lowerer = { rules, rule_index, synth_counter: 0, }
  for i = 0; i < self.rules.length(); i = i + 1 {
    let r = self.rules[i]
    let alts = lowerer.lower_alts(r.expr, r.name)
    lowerer.rules[i] = { name: r.name, alts, }
  }
  let root_id = lowerer.rule_index.get("root").unwrap_or(0)
  Ok({ root_id, rules: lowerer.rules, rule_index: lowerer.rule_index, })
}

///|
/// Parse, validate, and compile GBNF source text in one call.
pub fn compile(src : String) -> Result[CompiledGrammar, CompileError] {
  match parse(src) {
    Err(e) => Err(ParseFailed(e))
    Ok(g) => g.compile()
  }
}