"""Fixed-vocabulary tokenizer mechanics, not pretrained language-model inference.

Requires tokenizers==0.22.2. No training, models, network, offsets, special-token
postprocessor, architecture run, or tokenizer quality benchmark is performed.
"""
from __future__ import annotations

import json
import platform
import unicodedata
import tokenizers
from tokenizers import Tokenizer, models, normalizers, pre_tokenizers


def ascii_word(word: str) -> None:
    if not word or not word.isascii() or not word.isalpha():
        raise ValueError("The readable reference algorithms accept nonempty ASCII letters only")


def ranked_bpe_reference(word: str, ordered_merges: list[tuple[str, str]]):
    """Small deterministic reference, restricted to ASCII and no dropout."""
    ascii_word(word)
    ranks = {pair: rank for rank, pair in enumerate(ordered_merges)}
    pieces = list(word)
    trace = []
    while True:
        candidates = [
            (ranks[(left, right)], pos)
            for pos, (left, right) in enumerate(zip(pieces, pieces[1:]))
            if (left, right) in ranks
        ]
        if not candidates:
            return pieces, trace
        rank, pos = min(candidates)  # Lowest rank first; leftmost on a tie.
        trace.append({"before": pieces[:], "pair": pieces[pos:pos + 2],
                      "rank": rank, "position": pos})
        pieces[pos:pos + 2] = [pieces[pos] + pieces[pos + 1]]
        trace[-1]["after"] = pieces[:]


def longest_prefix_reference(word: str, vocabulary: dict[str, int]):
    """A vocabulary-only contrast; this is deliberately NOT the BPE algorithm."""
    ascii_word(word)
    pieces, start = [], 0
    while start < len(word):
        matches = [token for token in vocabulary if word.startswith(token, start)]
        if not matches:
            raise ValueError("No vocabulary prefix for this contrast case")
        piece = max(matches, key=len)
        pieces.append(piece)
        start += len(piece)
    return pieces


def wordpiece_reference(word: str, vocabulary: dict[str, int]):
    """Longest match with ## on noninitial pieces; whole word UNK on failure."""
    ascii_word(word)
    pieces, trace, start = [], [], 0
    while start < len(word):
        prefix = "" if start == 0 else "##"
        match = next((prefix + word[start:end]
                      for end in range(len(word), start, -1)
                      if prefix + word[start:end] in vocabulary), None)
        if match is None:
            trace.append({"unmatched_suffix": word[start:],
                          "discarded_successful_prefix_pieces": pieces[:]})
            return ["[UNK]"], trace
        trace.append({"position": start, "matched": match})
        pieces.append(match)
        start += len(match) - len(prefix)
    return pieces, trace


def describe_unicode(text: str):
    encoded = text.encode("utf-8", errors="strict")
    return {
        "text": text,
        "unicode_codepoints": [f"U+{ord(char):04X}" for char in text],
        "python_codepoint_count": len(text),
        "utf8_bytes_hex": encoded.hex(" "),
        "utf8_byte_count": len(encoded),
        "utf8_decode_roundtrip": encoded.decode("utf-8") == text,
    }


def main() -> None:
    bpe_vocab = {"[UNK]": 0, "a": 1, "b": 2, "c": 3, "ab": 4, "bc": 5}
    orders = [[("b", "c"), ("a", "b")], [("a", "b"), ("b", "c")]]
    bpe_cases = []
    for merges in orders:
        tokenizer = Tokenizer(models.BPE(
            vocab=bpe_vocab, merges=merges, unk_token="[UNK]",
            dropout=None, ignore_merges=False, byte_fallback=False,
        ))
        # No normalizer or pre-tokenizer: this single ASCII word is unchanged.
        observed = tokenizer.encode("abc", add_special_tokens=False)
        expected, trace = ranked_bpe_reference("abc", merges)
        assert observed.tokens == expected
        assert observed.ids == [bpe_vocab[token] for token in expected]
        bpe_cases.append({"ordered_merges_rank_zero_first": merges,
                          "input": "abc", "tokens": observed.tokens,
                          "ids": observed.ids, "reference_trace": trace})
    contrast = longest_prefix_reference("abc", bpe_vocab)
    assert bpe_cases[0]["tokens"] == ["a", "bc"]
    assert bpe_cases[1]["tokens"] == contrast == ["ab", "c"]

    wp_vocab = {"[UNK]": 0, "ab": 1, "a": 2, "##bc": 3, "##c": 4, "b": 5}
    wp = Tokenizer(models.WordPiece(
        vocab=wp_vocab, unk_token="[UNK]", continuing_subword_prefix="##",
        max_input_chars_per_word=100,
    ))
    wp.pre_tokenizer = pre_tokenizers.WhitespaceSplit()
    wp_cases = []
    for text in ["abc", "bc", "c", "abx", "abc bc"]:
        words = text.split()  # These fixed samples contain only ASCII spaces.
        references = [wordpiece_reference(word, wp_vocab) for word in words]
        expected = [piece for pieces, _ in references for piece in pieces]
        observed = wp.encode(text, add_special_tokens=False)
        assert observed.tokens == expected
        assert observed.ids == [wp_vocab[token] for token in expected]
        wp_cases.append({"input": text, "whitespace_pretokens": words,
                         "tokens": observed.tokens, "ids": observed.ids,
                         "per_word_reference_traces": [trace for _, trace in references]})
    assert wp_cases[0]["tokens"] == ["ab", "##c"]
    assert wp_cases[2]["tokens"] == wp_cases[3]["tokens"] == ["[UNK]"]

    unicode_cases = [describe_unicode(text) for text in ["A", "中", "é", "e\u0301"]]
    # These are separate demonstrations, not a hidden part of either tokenizer.
    normalizer = normalizers.Sequence([
        normalizers.NFD(), normalizers.Lowercase(), normalizers.StripAccents(),
    ])
    normalization = []
    for text in ["É", "E\u0301", "e"]:
        normalized = normalizer.normalize_str(text)
        # Independent standard-library check for these Latin samples only.
        reference = "".join(c for c in unicodedata.normalize("NFD", text).lower()
                            if unicodedata.category(c) != "Mn")
        assert normalized == reference == "e"
        normalization.append({"input": describe_unicode(text),
                              "normalized": describe_unicode(normalized),
                              "input_equals_normalized": text == normalized})
    compatible_input = "Ａ①"
    compatible_output = normalizers.NFKC().normalize_str(compatible_input)
    assert compatible_output == unicodedata.normalize("NFKC", compatible_input) == "A1"

    result = {
        "scope": "Tiny fixed vocabularies/merges; BPE and WordPiece inference only, plus independent Unicode normalization examples. No tokenizer training, downloaded vocabulary/model, Transformers/SentencePiece run, architecture inference, quality benchmark or offsets.",
        "environment": {"python": platform.python_version(),
                        "tokenizers": tokenizers.__version__,
                        "python_unicodedata_version": unicodedata.unidata_version,
                        "execution": "CPU host; no GPU or neural model"},
        "bpe": {"vocabulary_ids_hand_assigned": bpe_vocab,
                "options": {"dropout": None, "ignore_merges": False,
                            "byte_fallback": False, "normalizer": None,
                            "pre_tokenizer": None, "special_token_postprocessor": None},
                "same_vocabulary_two_merge_orders": bpe_cases,
                "vocabulary_only_longest_prefix_contrast": contrast,
                "meaning": "The same vocabulary permits a|bc or ab|c. Ranked merges, not vocabulary longest-prefix alone, determine these deterministic BPE results. This is not byte-level BPE and has no all-Unicode coverage claim."},
        "wordpiece": {"vocabulary_ids_hand_assigned": wp_vocab,
                      "options": {"continuation_prefix": "##", "normalizer": None,
                                  "pre_tokenizer": "WhitespaceSplit",
                                  "max_input_chars_per_word": 100,
                                  "special_token_postprocessor": None},
                      "cases": wp_cases,
                      "meaning": "##c is legal as a continuation but no plain c token exists at word start. For abx the matched ab prefix is discarded: one entire pretokenized word becomes [UNK]. No claim about original Google WordPiece training or trainer scoring."},
        "unicode_codepoints_and_utf8": unicode_cases,
        "normalization_separate_from_tokenizers": {
            "pipeline": ["NFD", "Lowercase", "StripAccents"],
            "cases": normalization,
            "distinct_originals_collide": len({row["input"]["text"] for row in normalization}) == 3 and len({row["normalized"]["text"] for row in normalization}) == 1,
            "separate_NFKC_compatibility_case": {"input": describe_unicode(compatible_input),
                                                 "normalized": describe_unicode(compatible_output)},
            "meaning": "UTF-8 encode/decode is exact for these valid strings. Normalization maps different originals to the same output, so the normalized string alone cannot recover original case, accent or composition. NFKC additionally folds the shown compatibility forms. Codepoint count is not a general visible-grapheme count. No token offsets or decoder roundtrip is tested."},
    }
    print(json.dumps(result, ensure_ascii=False, indent=2, allow_nan=False))


if __name__ == "__main__":
    main()
