"""Shared helpers of the language pack converters: key normalisation, sharded tables, pack.json.

The pack layout and the file formats are described in README.md next to this file.
"""
import html
import json
import re
import unicodedata
from pathlib import Path

FORMAT = 2
SHARDS = [chr(code) for code in range(ord("a"), ord("z") + 1)] + ["other"]
# Tables of Greek and Cyrillic words are split by letter too (README "Shards"). A key that starts
# with a character of these blocks goes to `u<code point in four lower-case hex digits>.tsv`.
LETTER_SHARD_BLOCKS = ((0x0370, 0x03FF), (0x1F00, 0x1FFF), (0x0400, 0x052F))
LETTER_SHARDS = "letters"
SINGLE_WORD = re.compile(r"[^\W\d_]+(?:['-][^\W\d_]+)*", re.UNICODE)
_KEY_CHARACTERS = str.maketrans({"’": "'", "‐": "-", "‑": "-"})
_FIELD_BREAKS = re.compile(r"[\t\r\n]+")


def normalize(word):
    """The lookup key of a word; must match wordKey() in the app (domain/Services.kt)."""
    return unicodedata.normalize("NFC", word).strip().lower().translate(_KEY_CHARACTERS)


def is_single_word(key):
    return bool(SINGLE_WORD.fullmatch(key))


def shard_of(key, letters=False):
    """The shard file name of a key (without `.tsv`); must match `shardOf` in the app.

    `letters` is the scheme of tables whose keys are mostly Greek or Cyrillic words: those letters
    get shards of their own instead of sharing `other`.
    """
    first = key[0]
    if "a" <= first <= "z":
        return first
    if letters and any(low <= ord(first) <= high for low, high in LETTER_SHARD_BLOCKS):
        return f"u{ord(first):04x}"
    return "other"


def uses_letter_shards(keys):
    """True when more than half of the keys start with a Greek or Cyrillic character."""
    keys = list(keys)
    letter_keys = sum(1 for key in keys if shard_of(key, letters=True) not in SHARDS)
    return letter_keys * 2 > len(keys)


def clean_field(text):
    """Collapses whitespace so a value can never break the tab-separated line it is written to."""
    return " ".join(_FIELD_BREAKS.sub(" ", text).split())


def table_text(rows):
    """Lines `key<TAB>field<TAB>field...`, sorted by the UTF-8 bytes of the key for binary search."""
    lines = []
    for key in sorted(rows, key=lambda item: item.encode("utf-8")):
        fields = [clean_field(field) for field in rows[key]]
        while fields and not fields[-1]:
            fields.pop()
        lines.append("\t".join([key, *fields]) + "\n")
    return "".join(lines)


def write_table(pack_dir, table, rows):
    """Writes one table of a pack as shard files and returns the number of rows.

    `rows` maps a normalised key to the list of fields that follow it on its line. A table of
    mostly Latin keys is written as the 27 files `a.tsv` to `z.tsv` and `other.tsv`, empty ones
    included. A table of mostly Greek or Cyrillic keys gets a file per first letter, only the
    non-empty ones, and its scheme is recorded in pack.json so that the app picks the same file.
    """
    target = Path(pack_dir) / table
    target.mkdir(parents=True, exist_ok=True)
    for stale in target.iterdir():
        stale.unlink()
    letters = uses_letter_shards(rows)
    shards = {} if letters else {shard: {} for shard in SHARDS}
    for key, fields in rows.items():
        if not key or "\t" in key or "\n" in key:
            raise ValueError(f"Invalid table key: {key!r}")
        shards.setdefault(shard_of(key, letters), {})[key] = fields
    for shard, content in shards.items():
        (target / f"{shard}.tsv").write_text(table_text(content), encoding="utf-8")
    _record_shards(pack_dir, table, LETTER_SHARDS if letters else None)
    return len(rows)


def _record_shards(pack_dir, table, scheme):
    """Notes the shard scheme of a table in pack.json; the default scheme leaves no trace."""
    path = Path(pack_dir) / "pack.json"
    manifest = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
    details = manifest.get("tableDetails", {}).get(table)
    if scheme is None and (details is None or "shards" not in details):
        return
    manifest.setdefault("tableDetails", {}).setdefault(table, {})
    if scheme is None:
        del manifest["tableDetails"][table]["shards"]
    else:
        manifest["tableDetails"][table]["shards"] = scheme
    _write_manifest(path, manifest)


def _write_manifest(path, manifest):
    path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
                    encoding="utf-8")


def update_manifest(pack_dir, kind, language, table, rows, source, meaning_language=None):
    """Records one table in the pack's pack.json, keeping the tables other converters wrote.

    `source` describes where the table's data comes from: name, url, licence and snapshot date.
    """
    path = Path(pack_dir) / "pack.json"
    manifest = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
    manifest.update({"format": FORMAT, "kind": kind, "language": language})
    if meaning_language:
        manifest["meaningLanguage"] = meaning_language
    tables = manifest.get("tableDetails", {})
    shards = tables.get(table, {}).get("shards")
    tables[table] = {"rows": rows, "source": source}
    if shards:
        tables[table]["shards"] = shards
    manifest["tableDetails"] = dict(sorted(tables.items()))
    manifest["tables"] = sorted(tables)
    manifest["curated"] = (Path(pack_dir) / "curated.json").exists()
    _write_manifest(path, manifest)


def read_table(pack_dir, table):
    """Reads a table back as {key: [fields]}; used by the measuring script and the tests."""
    rows = {}
    folder = Path(pack_dir) / table
    for path in sorted(folder.glob("*.tsv")) if folder.is_dir() else []:
        if path.name.startswith("._"):
            continue
        for line in path.read_text(encoding="utf-8").splitlines():
            key, *fields = line.split("\t")
            rows[key] = fields
    return rows


# --- Cleaning of meanings -------------------------------------------------------------------------
_WIKI_LINK = re.compile(r"\[\[([^\[\]|]*)(?:\|([^\[\]]*))?\]\]")
_WIKI_TEMPLATE = re.compile(r"\{\{[^{}]*\}\}")
_ENTITY = re.compile(r"&#?[A-Za-z0-9]+;")
# A truncated entity (`é&l`, `jidi&`): an ampersand glued to a letter and cut off, never "R&D" or "A & B".
_BROKEN_AMPERSAND = re.compile(r"(?<=[^\W\d_])&[a-z]?$|&action=")
# UTF-8 text read as Latin-1 / Windows-1252: a lead byte (2, 3 or 4 byte sequence) followed by exactly as
# many continuation bytes. Two byte sequences are limited to the leads of Latin, Greek and Cyrillic
# (Â Ã Ä Å Î Ï Ð Ñ): a Czech capital followed by a letter ("Óš", "Úž") is not mojibake.
_CONTINUATION = ("[\u0080-\u00bf\u0152\u0153\u0160\u0161\u0178\u017d\u017e\u0192\u02c6\u02dc\u2013\u2014"
                 "\u2018-\u201e\u2020-\u2022\u2026\u2030\u2039\u203a\u20ac\u2122]")
_MOJIBAKE = re.compile(f"[\u00c2-\u00c5\u00ce\u00cf\u00d0\u00d1]{_CONTINUATION}|[\u00e0-\u00ef]{_CONTINUATION}{{2}}|[\u00f0-\u00f4]{_CONTINUATION}{{3}}")
_MARKUP_LEFTOVER = re.compile(r"\[\[|\]\]|\{\{|\}\}|''")
_REPLACEMENT = "\ufffd"


def _repair_sequence(match):
    """The character a mojibake sequence stands for; raises ValueError when it is not valid UTF-8."""
    raw = bytearray()
    for character in match.group():
        code = ord(character)
        raw.extend([code] if code < 0x100 else character.encode("cp1252"))
    return bytes(raw).decode("utf-8")


def _repair_mojibake(text):
    """The text with every mojibake sequence read as UTF-8 again, or None when one does not decode."""
    try:
        return _MOJIBAKE.sub(_repair_sequence, text)
    except (UnicodeEncodeError, UnicodeDecodeError):
        return None


def clean_meaning(text):
    """The meaning without wiki markup, HTML entities and mojibake, or None when nothing usable is left.

    `[[target|label]]` becomes the label, `[[target]]` the target; stray `[[`, `]]`, `{{...}}` and
    `''` go. Entities are decoded, and a meaning that still holds one is dropped. Mojibake is repaired
    when the repaired text is valid and has no replacement character, otherwise the meaning is dropped.
    Correct text (diacritics, curly quotes, dashes, parentheses) is never changed.
    """
    if text is None:
        return None
    while True:
        stripped = _WIKI_TEMPLATE.sub("", text)
        if stripped == text:
            break
        text = stripped
    text = _WIKI_LINK.sub(lambda match: match.group(2) if match.group(2) is not None else match.group(1), text)
    text = _MARKUP_LEFTOVER.sub("", text)
    if _BROKEN_AMPERSAND.search(text.strip()):
        return None
    text = html.unescape(text)
    if _ENTITY.search(text):
        return None
    if _MOJIBAKE.search(text):
        text = _repair_mojibake(text)
        if text is None:
            return None
    if _REPLACEMENT in text:
        return None
    return clean_field(text) or None


def has_markup_or_damage(text):
    """True when a hand-written meaning holds what clean_meaning removes (wiki markup, entity, mojibake)."""
    return (bool(_MARKUP_LEFTOVER.search(text) or _ENTITY.search(text) or _MOJIBAKE.search(text)
                 or _BROKEN_AMPERSAND.search(text.strip()) or _REPLACEMENT in text))


def check_curated(meanings_by_word, name="curated list"):
    """Fails loudly when a hand-written list holds wiki markup, an entity or mojibake."""
    bad = [(word, meaning) for word, meanings in meanings_by_word.items()
           for meaning in meanings if has_markup_or_damage(meaning)]
    if bad:
        listed = "; ".join(f"{word}: {meaning!r}" for word, meaning in bad[:10])
        raise SystemExit(f"The {name} has {len(bad)} damaged meanings (markup, entity or mojibake): {listed}")


def clean_meanings(meanings):
    """Cleans a list of meanings: drops the unusable and the duplicates, keeps the order."""
    cleaned = []
    for meaning in meanings:
        result = clean_meaning(meaning)
        if result and result not in cleaned:
            cleaned.append(result)
    return cleaned
