import { describe, expect, it } from 'vitest'
import { evaluateEvidenceRules, normalizeEvidenceText, scoreEvidenceAnchor } from './evidenceMatching.js'

const barricelliRule = {
  id: 'rule-barricelli',
  name: 'Contemporary Barricelli fire report',
  flagKey: 'barricelli.child-rescue-source',
  minimumAnchorMatches: 1,
  anchors: [{
    id: 'parents',
    phrase: 'den italienske maler og opfinder Barricelli og frue, født Aall',
    minimumSimilarity: 0.72,
  }, {
    id: 'drink',
    phrase: 'Han vækkede nemlig sin mor for at faa noget at drikke',
    minimumSimilarity: 0.72,
  }],
}

describe('evidence text matching', () => {
  it('normalizes historical Norwegian characters and page layout noise', () => {
    expect(normalizeEvidenceText('Født Aall — 2½ aar\n gammel')).toBe('fodt aall 2 1 2 aar gammel')
  })

  it('tolerates plausible OCR substitutions in a distinctive passage', () => {
    const result = scoreEvidenceAnchor(
      normalizeEvidenceText('I kvistleiligheden boede den italienske maler og opfinder Barrioelli og frue, født Aall, med sin lille søn.'),
      barricelliRule.anchors[0].phrase,
    )
    expect(result.similarity).toBeGreaterThan(0.9)
  })

  it('awards the data-defined flag when one configured anchor is present', () => {
    const evaluations = evaluateEvidenceRules('Han vækkede nemlig sin mor for at faa noget at drikke, og da ser hun huset brænder.', [barricelliRule])
    expect(evaluations[0]).toMatchObject({ matched: true, matchedAnchorCount: 1, flagKey: 'barricelli.child-rescue-source' })
  })

  it('does not match generic words from an unrelated fire report', () => {
    const evaluations = evaluateEvidenceRules('A family escaped from a boarding-house fire during the night.', [barricelliRule])
    expect(evaluations[0]).toMatchObject({ matched: false, matchedAnchorCount: 0 })
  })

  it('can require multiple anchors for a stricter level rule', () => {
    const rule = { ...barricelliRule, minimumAnchorMatches: 2 }
    expect(evaluateEvidenceRules(barricelliRule.anchors[0].phrase, [rule])[0].matched).toBe(false)
    expect(evaluateEvidenceRules(barricelliRule.anchors.map(anchor => anchor.phrase).join(' '), [rule])[0].matched).toBe(true)
  })
})
