"""Baseline: multi-char canonicalization + Levenshtein."""

import unicodedata
from rapidfuzz import fuzz
from harness import evaluate

# Single-character equivalence classes
CHAR_MAP = {}
for group in [
    "lI1|!",
    "oO0",
    "sS5",
    "zZ2",
    "bB8",
]:
    canonical = group[0]
    for ch in group:
        CHAR_MAP[ch] = canonical

# Multi-char replacements (applied longest-first)
MULTI_CHAR_RULES = [
    ("rn", "m"),
    ("nn", "m"),
    ("ri", "n"),
    ("cl", "d"),
    ("vv", "w"),
    ("ii", "u"),
]
# Sort by length descending for longest-match-first
MULTI_CHAR_RULES.sort(key=lambda x: len(x[0]), reverse=True)


def canonicalize(text):
    text = unicodedata.normalize("NFKC", text)
    text = text.lower()
    # Apply multi-char rules first (longest-match-first)
    for pattern, replacement in MULTI_CHAR_RULES:
        text = text.replace(pattern, replacement)
    # Then single-char
    text = "".join(CHAR_MAP.get(ch, ch) for ch in text)
    # Collapse whitespace
    text = " ".join(text.split())
    return text


def score(query, candidate):
    q = canonicalize(query)
    c = canonicalize(candidate)
    return fuzz.ratio(q, c) / 100.0


if __name__ == "__main__":
    evaluate(score, name="06 - Multi-char Canonicalization + Levenshtein")
