///|
/// 解析规则文件时发现的单行语法问题。
#derive(Eq, Debug)
pub struct ParseIssue {
  source : RuleSource
  error : PatternError
}

///|
/// 规则编译与求值引擎容器。
#derive(Eq, Debug)
pub struct RuleSet {
  rules : Array[CompiledRule]
  parse_issues : Array[ParseIssue]
  options : EvalOptions
}

///|
/// 决策追踪中的单步命中记录。
#derive(Eq, Debug)
pub struct TraceStep {
  rule_id : Int32
  source : RuleSource
  action : RuleAction
  matched_target : String
  superseded : Bool
}

///|
/// 路径裁定原因说明。
#derive(Eq, Debug)
pub(all) enum DecisionReason {
  DefaultIncluded
  MatchedRule(Int32, RuleSource, RuleAction)
  BlockedByIgnoredParent(String, Int32, RuleSource)
}

///|
/// 针对单一路径的完整决策与归因报告。
#derive(Eq, Debug)
pub struct PathDecision {
  path : String
  is_dir : Bool
  verdict : Verdict
  reason : DecisionReason
  trace : Array[TraceStep]
}

///|
/// 按 `\n` 切分规则文本行。
fn split_lines(content : String) -> Array[String] {
  let lines : Array[String] = []
  let buf = StringBuilder()
  for c in content {
    if c == '\n' {
      lines.push(buf.to_string())
      buf.reset()
    } else {
      buf.write_char(c)
    }
  }
  let tail = buf.to_string()
  if !tail.is_empty() || lines.is_empty() {
    lines.push(tail)
  }
  lines
}

///|
/// 从多个不同目录作用域的规则文件编译级联规则集。
/// 规则文件会自动按作用域目录深度升序稳定排序(根目录规则在前,子目录规则在后并拥有更高优先级)。
pub fn RuleSet::from_files(
  files : Array[RuleFileInput],
  options~ : EvalOptions = EvalOptions::default(),
) -> Result[RuleSet, PathError] {
  let normalized_files : Array[(Array[String], Int32, RuleFileInput)] = []
  for idx = 0; idx < files.length(); idx = idx + 1 {
    let f = files[idx]
    match normalize_scope_dir(f.scope_dir) {
      Err(e) => return Err(e)
      Ok(scope_segs) => normalized_files.push((scope_segs, idx, f))
    }
  }
  // 插入排序:按作用域深度升序,同深度保持调用方传入顺序(完全稳定)
  for i = 1; i < normalized_files.length(); i = i + 1 {
    let key = normalized_files[i]
    let mut j = i - 1
    while j >= 0 && normalized_files[j].0.length() > key.0.length() {
      normalized_files[j + 1] = normalized_files[j]
      j = j - 1
    }
    normalized_files[j + 1] = key
  }

  let rules : Array[CompiledRule] = []
  let parse_issues : Array[ParseIssue] = []
  let mut next_id = 1
  for item in normalized_files {
    let (scope_segs, _, file_input) = item
    let canonical_scope = join_segments(scope_segs)
    let lines = split_lines(file_input.content)
    for line_idx = 0; line_idx < lines.length(); line_idx = line_idx + 1 {
      let raw_line = lines[line_idx]
      let src = RuleSource::new(
        file_input.file,
        canonical_scope,
        line_idx + 1,
        raw_line,
      )
      match parse_ignore_line(raw_line, next_id, src, scope_segs) {
        Blank | Comment => ()
        Rule(compiled) => {
          rules.push(compiled)
          next_id = next_id + 1
        }
        Invalid(err_src, err) =>
          parse_issues.push({ source: err_src, error: err, })
      }
    }
  }
  Ok({ rules, parse_issues, options, })
}

///|
/// 从单个规则文件内容构建规则集(默认作用于仓库根目录)。
pub fn RuleSet::from_gitignore(
  content : String,
  file~ : String = ".gitignore",
  scope_dir~ : String = "",
  options~ : EvalOptions = EvalOptions::default(),
) -> Result[RuleSet, PathError] {
  RuleSet::from_files([RuleFileInput::new(file, scope_dir, content)], options~)
}

///|
/// 对单一规范化目标执行规则顺序求值,返回裁定、原因及全部命中轨迹。
fn RuleSet::eval_single_target(
  self : RuleSet,
  target : NormalizedPath,
) -> (Verdict, DecisionReason, Array[TraceStep]) {
  let hits : Array[TraceStep] = []
  let mut verdict = Included
  let mut reason = DefaultIncluded
  for rule in self.rules {
    if rule.matches(target, case_sensitive=self.options.case_sensitive) {
      hits.push({
        rule_id: rule.id,
        source: rule.source,
        action: rule.action,
        matched_target: target.canonical,
        superseded: false,
      })
      verdict = match rule.action {
        Ignore => Ignored
        Include => Included
      }
      reason = MatchedRule(rule.id, rule.source, rule.action)
    }
  }
  if hits.length() > 1 {
    for i = 0; i < hits.length() - 1; i = i + 1 {
      let step = hits[i]
      hits[i] = {
        rule_id: step.rule_id,
        source: step.source,
        action: step.action,
        matched_target: step.matched_target,
        superseded: true,
      }
    }
  }
  (verdict, reason, hits)
}

///|
/// 在关闭父目录剪枝(类似 `.dockerignore` 扁平语义)时对目标及其祖先统一按规则顺序求值。
fn RuleSet::eval_flat_mode(
  self : RuleSet,
  target : NormalizedPath,
) -> PathDecision {
  let ancestors = target.ancestors()
  let hits : Array[TraceStep] = []
  let mut verdict = Included
  let mut reason = DefaultIncluded
  for rule in self.rules {
    let mut matched_on : String? = None
    if rule.matches(target, case_sensitive=self.options.case_sensitive) {
      matched_on = Some(target.canonical)
    } else if rule.action == Ignore {
      // 扁平模式下,忽略父目录的规则同样会使子路径进入忽略态,但后续显式 `!` 规则仍可重新放行
      for anc in ancestors {
        if rule.matches(anc, case_sensitive=self.options.case_sensitive) {
          matched_on = Some(anc.canonical)
          break
        }
      }
    }
    match matched_on {
      None => ()
      Some(m_target) => {
        hits.push({
          rule_id: rule.id,
          source: rule.source,
          action: rule.action,
          matched_target: m_target,
          superseded: false,
        })
        verdict = match rule.action {
          Ignore => Ignored
          Include => Included
        }
        reason = MatchedRule(rule.id, rule.source, rule.action)
      }
    }
  }
  if hits.length() > 1 {
    for i = 0; i < hits.length() - 1; i = i + 1 {
      let step = hits[i]
      hits[i] = {
        rule_id: step.rule_id,
        source: step.source,
        action: step.action,
        matched_target: step.matched_target,
        superseded: true,
      }
    }
  }
  {
    path: target.canonical,
    is_dir: target.is_dir,
    verdict,
    reason,
    trace: hits,
  }
}

///|
/// 对已规范化的路径执行完整求值并产出带归因链的 `PathDecision`。
pub fn RuleSet::evaluate_normalized(
  self : RuleSet,
  target : NormalizedPath,
) -> PathDecision {
  if !self.options.prune_ignored_dirs {
    return self.eval_flat_mode(target)
  }
  let ancestors = target.ancestors()
  for anc in ancestors {
    let (anc_verdict, anc_reason, anc_trace) = self.eval_single_target(anc)
    if anc_verdict == Ignored {
      let blocked_reason = match anc_reason {
        MatchedRule(rid, rsrc, _) =>
          BlockedByIgnoredParent(anc.canonical, rid, rsrc)
        _ => anc_reason
      }
      return {
        path: target.canonical,
        is_dir: target.is_dir,
        verdict: Ignored,
        reason: blocked_reason,
        trace: anc_trace,
      }
    }
  }
  let (verdict, reason, trace) = self.eval_single_target(target)
  { path: target.canonical, is_dir: target.is_dir, verdict, reason, trace, }
}

///|
/// 判断给定路径是否被当前规则集忽略。
pub fn RuleSet::is_ignored(
  self : RuleSet,
  path : String,
  is_dir~ : Bool = false,
) -> Result[Bool, PathError] {
  match normalize_path(path, is_dir~) {
    Err(e) => Err(e)
    Ok(norm) => Ok(self.evaluate_normalized(norm).verdict == Ignored)
  }
}

///|
/// 检查目录遍历器是否应进入给定目录(用于扫描器剪枝加速)。
/// 在父目录剪枝模式下,一旦目录被忽略即可安全跳过整棵子树;
/// 在扁平模式下,若后续存在任何否定规则,则仍需继续进入目录检查子文件。
pub fn RuleSet::should_enter_dir(
  self : RuleSet,
  dir_path : String,
) -> Result[Bool, PathError] {
  let norm = match normalize_path(dir_path, is_dir=true) {
    Err(e) => return Err(e)
    Ok(p) => p
  }
  let decision = self.evaluate_normalized(norm)
  if decision.verdict == Included {
    return Ok(true)
  }
  if self.options.prune_ignored_dirs {
    return Ok(false)
  }
  // 扁平模式下,仅当规则集中完全没有否定规则时才能整棵剪枝
  for rule in self.rules {
    if rule.action == Include {
      return Ok(true)
    }
  }
  Ok(false)
}