import { type ComputedRef } from 'vue'
import type { OcrConfidenceMap } from '../types'

/** Design-doc §14: 95–100% high, 80–94% medium, <80% low */
export type OcrConfidenceLevel = 'high' | 'medium' | 'low'

export const OCR_HIGH_THRESHOLD = 0.95
export const OCR_MEDIUM_THRESHOLD = 0.8

export function confidenceToLevel(confidence: number): OcrConfidenceLevel {
  if (confidence >= OCR_HIGH_THRESHOLD) return 'high'
  if (confidence >= OCR_MEDIUM_THRESHOLD) return 'medium'
  return 'low'
}

export function formatOcrBadgeLabel(confidence: number): string {
  const pct = Math.round(confidence * 100)
  return `OCR ${pct}%`
}

export function useOcrFieldConfidence(
  ocrConfidence: ComputedRef<OcrConfidenceMap | null | undefined>,
) {
  function getFieldConfidence(fieldPath: string): number | undefined {
    if (!ocrConfidence.value) return undefined
    return ocrConfidence.value.fieldConfidences[fieldPath]
  }

  function fieldConfidenceLevel(fieldPath: string): OcrConfidenceLevel | null {
    const confidence = getFieldConfidence(fieldPath)
    if (confidence === undefined) return null
    return confidenceToLevel(confidence)
  }

  function fieldConfidenceLabel(fieldPath: string): string | null {
    const confidence = getFieldConfidence(fieldPath)
    if (confidence === undefined) return null
    return formatOcrBadgeLabel(confidence)
  }

  function fieldConfidenceClass(fieldPath: string): string {
    const level = fieldConfidenceLevel(fieldPath)
    if (!level) return ''
    if (level === 'high') return 'ocr-high'
    if (level === 'medium') return 'ocr-medium'
    return 'ocr-low'
  }

  return {
    getFieldConfidence,
    fieldConfidenceLevel,
    fieldConfidenceLabel,
    fieldConfidenceClass,
  }
}
