"""Loader + matcher for the Header → Standard Field synonym dictionary.

The actual synonym data lives next to this file in `header_synonyms.json`
so it can be edited without touching Python code.
"""

import json
import os


_HERE = os.path.dirname(__file__)
_JSON_PATH = os.path.join(_HERE, "header_synonyms.json")


def _load_synonyms():
	with open(_JSON_PATH, encoding="utf-8") as f:
		data = json.load(f)
	# Drop the leading "_comment" key (used as inline documentation in the JSON).
	return {k: tuple(v) for k, v in data.items() if not k.startswith("_") and isinstance(v, list)}


HEADER_SYNONYMS = _load_synonyms()


_AZERI_TO_LATIN = str.maketrans({
	"ə": "e", "Ə": "e", "ı": "i", "İ": "i", "ö": "o", "Ö": "o",
	"ü": "u", "Ü": "u", "ş": "s", "Ş": "s", "ç": "c", "Ç": "c",
	"ğ": "g", "Ğ": "g",
})


def _norm(s):
	if s is None:
		return ""
	s = str(s).strip().lower().translate(_AZERI_TO_LATIN)
	return " ".join(s.split())


def guess_standard_field(header):
	"""Return a Standard Field label for the given header text, or None.

	Two-pass: exact normalised match first, then substring fallback (catches
	headers like "Payment Reference No." against the synonym "reference"). The
	substring pass requires a minimum length of 4 to avoid noise from very
	short synonyms.
	"""
	h = _norm(header)
	if not h:
		return None
	for field, synonyms in HEADER_SYNONYMS.items():
		for syn in synonyms:
			if h == _norm(syn):
				return field
	for field, synonyms in HEADER_SYNONYMS.items():
		for syn in synonyms:
			syn_n = _norm(syn)
			if syn_n and len(syn_n) >= 4 and syn_n in h:
				return field
	return None
