import type { ApiAlertRule } from "../alerts-service.js"
import { evaluateRule } from "./evaluate-rule.js"
import type { RuleEvalHit, SignalSnapshot } from "./types.js"

export function matchRules(rules: ApiAlertRule[], snap: SignalSnapshot): {
  hitByRule: Map<string, RuleEvalHit | null>
  errors: string[]
} {
  const errors: string[] = []
  const hitByRule = new Map<string, RuleEvalHit | null>()
  for (const rule of rules) {
    try {
      hitByRule.set(rule.id, evaluateRule(rule, snap))
    } catch (e) {
      errors.push(`rule ${rule.id}: ${e instanceof Error ? e.message : String(e)}`)
      hitByRule.set(rule.id, null)
    }
  }
  return { hitByRule, errors }
}
