import re
from binascii import Error as BinasciiError
from binascii import unhexlify
from functools import partial
from hashlib import sha256
from io import BytesIO
from typing import Any, cast

from ._codecs import adobe_glyphs, charset_encoding
from ._utils import logger_error, logger_warning
from .errors import LimitReachedError
from .generic import (
    ArrayObject,
    DecodedStreamObject,
    DictionaryObject,
    PdfObject,
    StreamObject,
    is_null_or_none,
)
from .generic._data_structures import _FontFileEncoding

_predefined_cmap: dict[str, str] = {
    "/Identity-H": "utf-16-be",
    "/Identity-V": "utf-16-be",
    "/GB-EUC-H": "gbk",
    "/GB-EUC-V": "gbk",
    "/GBpc-EUC-H": "gb2312",
    "/GBpc-EUC-V": "gb2312",
    "/GBK-EUC-H": "gbk",
    "/GBK-EUC-V": "gbk",
    "/GBK2K-H": "gb18030",
    "/GBK2K-V": "gb18030",
    "/ETen-B5-H": "cp950",
    "/ETen-B5-V": "cp950",
    "/ETenms-B5-H": "cp950",
    "/ETenms-B5-V": "cp950",
    # Unicode-based CMaps: character codes are UTF-16BE, see
    # ISO 32000-2:2020, 9.7.5.2, Note 1 and Table 116.
    # (UniGB covers the GB18030-2000 character set but is not GB18030-encoded.)
    "/UniCNS-UTF16-H": "utf-16-be",
    "/UniCNS-UTF16-V": "utf-16-be",
    "/UniGB-UTF16-H": "utf-16-be",
    "/UniGB-UTF16-V": "utf-16-be",
    # Japanese CMaps (PDF Reference 1.7, Appendix H)
    "/90ms-RKSJ-H": "cp932",  # Shift-JIS (JIS X 0208-1990), horizontal
    "/90ms-RKSJ-V": "cp932",  # Shift-JIS (JIS X 0208-1990), vertical
    "/UniJIS-UTF16-H": "utf-16-be",  # Unicode UTF-16BE -> JIS, horizontal
    "/UniJIS-UTF16-V": "utf-16-be",  # Unicode UTF-16BE -> JIS, vertical
    # UCS2 in code
}


def get_encoding(
    ft: DictionaryObject
) -> tuple[str | dict[int, str], dict[Any, Any]]:
    encoding = _parse_encoding(ft)
    map_dict, int_entry = _parse_to_unicode(ft)

    # Apply rule from PDF ref 1.7 §5.9.1, 1st bullet:
    #   if cmap not empty encoding should be discarded
    #   (here transformed into identity for those characters)
    # If encoding is a string, it is expected to be an identity translation.
    if isinstance(encoding, dict):
        for x in int_entry:
            if x <= 255:
                encoding[x] = chr(x)

    return encoding, map_dict


def _parse_encoding(
    ft: DictionaryObject
) -> str | dict[int, str]:
    encoding: str | list[str] | dict[int, str] = []
    embedded_font_encoding: dict[int, str] = {}

    enc: PdfObject | None = None
    if "/Encoding" in ft:
        enc = ft["/Encoding"]  # Returns one of NameObject, DictionaryObject, or NullObject

    has_no_encoding = is_null_or_none(enc)
    has_no_base_encoding = isinstance(enc, DictionaryObject) and "/BaseEncoding" not in enc

    # For embedded simple fonts, parse the font programme as a basis, but only when encoding is not defined
    # or when base encoding is absent from an encoding dictionary.
    if (
        (has_no_encoding or has_no_base_encoding) and
        ft.get("/Subtype", "") == "/Type1"
    ):
        embedded_font_encoding = _parse_encoding_from_embedded_font(ft)

    # When ft["/Encoding"] is absent or cannot be used, use StandardEncoding as a basis, and add
    # what the embedded font file encoding says, if present. See Table 114, PDF Reference 1.7 / 2.0
    if has_no_encoding or (has_no_base_encoding and "/Differences" not in cast(DictionaryObject, enc)):
        if "/BaseFont" in ft and cast(str, ft["/BaseFont"]) in charset_encoding:
            # This will match Symbol and ZapfDingBats
            encoding = dict(
                zip(range(256), charset_encoding[cast(str, ft["/BaseFont"])])
            )
        else:
            # Set StandardEncoding as fallback option.
            encoding = dict(
                zip(range(256), charset_encoding["/StandardEncoding"])
            )
        # Overwrite the standard encoding with the encoding information from the embedded font file.
        _correct_encoding(embedded_font_encoding, encoding)
        return encoding

    if isinstance(enc, str):
        try:
            # already done : enc = NameObject.unnumber(enc.encode()).decode()
            # for #xx decoding
            if enc in charset_encoding:
                encoding = charset_encoding[enc].copy()
            elif enc in _predefined_cmap:
                encoding = _predefined_cmap[enc]
            elif "-UCS2-" in enc:
                encoding = "utf-16-be"
            else:
                raise KeyError("not found")
        except KeyError:
            encoding = (
                "utf-16-be" if ft.get("/Subtype", "") == "/Type0" else charset_encoding["/StandardEncoding"].copy()
            )
            logger_error(
                "Advanced encoding %(encoding)s not implemented yet, using %(new_encoding)s instead.",
                source=__name__,
                encoding=enc,
                new_encoding=encoding
            )
    elif isinstance(enc, DictionaryObject) and "/BaseEncoding" in enc:
        try:
            encoding = charset_encoding[cast(str, enc["/BaseEncoding"])].copy()
        except KeyError:
            logger_error(
                "Advanced encoding %(encoding)s not implemented yet",
                source=__name__, encoding=encoding
            )
            encoding = charset_encoding["/StandardEncoding"].copy()
    else:
        encoding = charset_encoding["/StandardEncoding"].copy()

    if isinstance(enc, DictionaryObject) and "/Differences" in enc:
        # Overwrite the standard encoding with the encoding information from the embedded font file, if applicable.
        _correct_encoding(embedded_font_encoding, encoding)

        code: int = 0
        differences = enc["/Differences"]
        if not isinstance(differences, ArrayObject):
            logger_warning(
                "Font encoding differences are not an array: %(differences)s",
                source=__name__,
                differences=differences,
            )
            differences = ArrayObject()
        for entry in differences:
            entry = entry.get_object()
            if isinstance(entry, int):
                code = entry
            elif isinstance(entry, str):
                try:
                    if code < len(encoding):
                        encoding[code] = _glyph_name_to_unicode(entry) or entry
                except MemoryError:  # pragma: no cover  # TODO: BLE001
                    raise
                except Exception:
                    encoding[code] = entry
                code += 1
            else:
                # Table 114 of the PDF 2.0 specification only allows character
                # codes and glyph names here. Anything else would end up in the
                # text and break the decoding later on.
                logger_warning(
                    "Ignoring invalid font encoding difference: %(entry)s",
                    source=__name__,
                    entry=entry,
                )
    if isinstance(encoding, list):
        encoding = dict(zip(range(256), encoding))

    return encoding


def _parse_to_unicode(
    ft: DictionaryObject
) -> tuple[dict[Any, Any], list[int]]:
    # We store all character mappings in map_dict. In map_dict[-1] we store the byte length
    # of the character codes (or CIDs) encoded inside the ToUnicode stream.
    map_dict: dict[Any, Any] = {}
    int_entry: list[int] = []

    if "/ToUnicode" not in ft:
        return map_dict, int_entry

    process_rg: bool = False
    process_char: bool = False
    multiline_rg: (
        tuple[int, int] | None
    ) = None  # tuple = (current_char, remaining size) ; cf #1285 for example of file
    cm = prepare_cm(ft)
    for line in cm.split(b"\n"):
        process_rg, process_char, multiline_rg = process_cm_line(
            line.strip(b" \t"),
            process_rg,
            process_char,
            multiline_rg,
            map_dict,
            int_entry,
        )

    map_dict.pop(-1, None)  # Don't pass the -1 key, we only used it to temporarily store encoding length

    return map_dict, int_entry


def prepare_cm(ft: DictionaryObject) -> bytes:
    tu = ft["/ToUnicode"]
    cm: bytes
    if isinstance(tu, StreamObject):
        cm = cast(DecodedStreamObject, ft["/ToUnicode"]).get_data()
    else:  # if (tu is None) or cast(str, tu).startswith("/Identity"):
        # the full range 0000-FFFF will be processed
        cm = b"beginbfrange\n<0000> <0001> <0000>\nendbfrange"
    if isinstance(cm, str):
        cm = cm.encode()
    # we need to prepare cm before due to missing return line in pdf printed
    # to pdf from word
    cm = (
        cm.strip()
        .replace(b"beginbfchar", b"\nbeginbfchar\n")
        .replace(b"endbfchar", b"\nendbfchar\n")
        .replace(b"beginbfrange", b"\nbeginbfrange\n")
        .replace(b"endbfrange", b"\nendbfrange\n")
        .replace(b"<<", b"\n{\n")  # text between << and >> not used but
        .replace(b">>", b"\n}\n")  # some solution to find it back
    )
    ll = cm.split(b"<")
    for i in range(len(ll)):
        j = ll[i].find(b">")
        if j >= 0:
            if j == 0:
                # string is empty: stash a placeholder here (see below)
                # see https://github.com/py-pdf/pypdf/issues/1111
                content = b"."
            else:
                content = ll[i][:j].replace(b" ", b"")
            ll[i] = content + b" " + ll[i][j + 1 :]
    cm = (
        (b" ".join(ll))
        .replace(b"[", b" [ ")
        .replace(b"]", b" ]\n ")
        .replace(b"\r", b"\n")
    )
    return cm


def process_cm_line(
    line: bytes,
    process_rg: bool,
    process_char: bool,
    multiline_rg: tuple[int, int] | None,
    map_dict: dict[Any, Any],
    int_entry: list[int],
) -> tuple[bool, bool, tuple[int, int] | None]:
    if line == b"" or line[0] == 37:  # 37 = %
        return process_rg, process_char, multiline_rg
    line = line.replace(b"\t", b" ")
    if b"beginbfrange" in line:
        process_rg = True
    elif b"endbfrange" in line:
        process_rg = False
    elif b"beginbfchar" in line:
        process_char = True
    elif b"endbfchar" in line:
        process_char = False
    elif process_rg:
        try:
            multiline_rg = parse_bfrange(line, map_dict, int_entry, multiline_rg)
        except (ValueError, IndexError) as error:
            logger_warning("Skipping broken line %(line)r: %(error)s", source=__name__, line=line, error=error)
    elif process_char:
        try:
            parse_bfchar(line, map_dict, int_entry)
        except ValueError as error:
            logger_warning("Skipping broken line %(line)r: %(error)s", source=__name__, line=line, error=error)
    return process_rg, process_char, multiline_rg


# Usual values should be up to 65_536.
MAPPING_DICTIONARY_SIZE_LIMIT = 100_000

# Typical /ToUnicode CMaps use 1-4 byte source codes.
# This is intentionally generous.
# The actual limit is doubled, as each byte is represented by two hex characters.
MAX_CMAP_CODE_BYTES = 8
MAX_CMAP_STRING_BYTES = 512
MAX_CMAP_CODE_BYTES_LIMIT = MAX_CMAP_CODE_BYTES * 2
MAX_CMAP_STRING_BYTES_LIMIT = MAX_CMAP_STRING_BYTES * 2


def _check_mapping_size(size: int) -> None:
    if size > MAPPING_DICTIONARY_SIZE_LIMIT:
        raise LimitReachedError(f"Maximum /ToUnicode size limit reached: {size} > {MAPPING_DICTIONARY_SIZE_LIMIT}.")


def _check_token_length(token: bytes, limit: int) -> None:
    token_length = len(token)
    if token_length > limit:
        description = {
            MAX_CMAP_CODE_BYTES_LIMIT: "code",
            MAX_CMAP_STRING_BYTES_LIMIT: "string",
        }.get(limit, "token")

        raise LimitReachedError(
            f"Maximum /ToUnicode {description} length exceeded: {token_length} > {limit}."
        )


def __parse_bfrange__decode(map_dict: dict[Any, Any], code: int) -> str:
    # `map_dict[-1]` is the number of bytes each source code occupies. Building
    # the bytes directly with `int.to_bytes` avoids the hex round-trip of
    # `unhexlify(b"%%0%dX" % (map_dict[-1] * 2) % code)` (format to hex, parse
    # the hex back to bytes), which is measurably cheaper for large maps.
    return code.to_bytes(map_dict[-1], "big").decode(
        "charmap" if map_dict[-1] == 1 else "utf-16-be",
        "surrogatepass",
    )


def parse_bfrange(
    line: bytes,
    map_dict: dict[Any, Any],
    int_entry: list[int],
    multiline_rg: tuple[int, int] | None,
) -> tuple[int, int] | None:
    entry_count = len(int_entry)
    _check_mapping_size(entry_count)

    # Bound tokenization to the range header, the remaining allowed
    # destinations, and one extra token to detect a mapping-limit violation.
    allowed_length = MAPPING_DICTIONARY_SIZE_LIMIT - entry_count
    max_splits = 3 + max(allowed_length, 0) + 1
    lst = line.split(maxsplit=max_splits)

    closure_found = False
    decode_utf16 = partial(bytes.decode, encoding="utf-16-be", errors="surrogatepass")
    if multiline_rg is not None:
        a = multiline_rg[0]  # a, b not in the current line
        b = multiline_rg[1]
        for sq in lst:
            if sq == b"]":
                closure_found = True
                break
            _check_token_length(sq, limit=MAX_CMAP_STRING_BYTES_LIMIT)
            entry_count += 1
            _check_mapping_size(entry_count)
            map_dict[
                __parse_bfrange__decode(map_dict=map_dict, code=a)
            ] = decode_utf16(unhexlify(sq))
            int_entry.append(a)
            a += 1
    else:
        _check_token_length(lst[0], limit=MAX_CMAP_CODE_BYTES_LIMIT)
        _check_token_length(lst[1], limit=MAX_CMAP_CODE_BYTES_LIMIT)
        a = int(lst[0], 16)
        b = int(lst[1], 16)
        if a < 0 or b < 0:
            # int(token, 16) accepts a leading "-"; negative range bounds
            # would leak an OverflowError from the to_bytes encoding below.
            raise ValueError(f"Negative bfrange source range: {lst[0]!r} {lst[1]!r}")
        nbi = max(len(lst[0]), len(lst[1]))
        map_dict[-1] = (nbi + 1) // 2
        if lst[2] == b"[":
            for sq in lst[3:]:
                if sq == b"]":
                    closure_found = True
                    break
                _check_token_length(sq, limit=MAX_CMAP_STRING_BYTES_LIMIT)
                entry_count += 1
                _check_mapping_size(entry_count)
                map_dict[
                    __parse_bfrange__decode(map_dict=map_dict, code=a)
                ] = decode_utf16(unhexlify(sq))
                int_entry.append(a)
                a += 1
        else:  # case without list
            _check_token_length(lst[2], limit=MAX_CMAP_STRING_BYTES_LIMIT)
            c = int(lst[2], 16)
            fmt2 = b"%%0%dX" % max(4, len(lst[2]))
            closure_found = True
            range_size = max(0, b - a + 1)
            _check_mapping_size(entry_count + range_size)  # This can be checked beforehand.
            while a <= b:
                destination = unhexlify(fmt2 % c)
                _check_token_length(destination, limit=MAX_CMAP_CODE_BYTES_LIMIT)
                map_dict[
                    __parse_bfrange__decode(map_dict=map_dict, code=a)
                ] = decode_utf16(destination)
                int_entry.append(a)
                a += 1
                c += 1
    return None if closure_found else (a, b)


# Match non-empty tokens using the same separator as the `parse_bfchar` split call.
_NON_SPACE_RUN = re.compile(rb"[^ ]+")


def parse_bfchar(line: bytes, map_dict: dict[Any, Any], int_entry: list[int]) -> None:
    # Estimate the number of mappings using the number of separators.
    # Only count tokens exactly when the estimate indicates that the mapping
    # size limit might be exceeded. This avoids regex scanning for normal CMaps.
    if len(int_entry) + (line.count(b" ") + 1) // 2 > MAPPING_DICTIONARY_SIZE_LIMIT:
        token_count = sum(1 for _ in _NON_SPACE_RUN.finditer(line))
        _check_mapping_size(len(int_entry) + token_count // 2)

    lst = [x for x in line.split(b" ") if x]
    lst_length = len(lst)
    if lst_length == 0:
        logger_warning("Skipping broken line %(line)r: Line is empty.", source=__name__, line=line)
        return
    if lst_length % 2:
        logger_warning("Ignoring final token of odd-length line %(line)r.", source=__name__, line=line)

    map_dict[-1] = len(lst[0]) // 2

    for index in range(0, lst_length - 1, 2):
        source = lst[index]
        destination = lst[index + 1]

        _check_token_length(source, limit=MAX_CMAP_CODE_BYTES_LIMIT)

        map_to = ""
        # placeholder (see above) means empty string
        if destination != b".":
            _check_token_length(destination, limit=MAX_CMAP_STRING_BYTES_LIMIT)
            try:
                map_to = unhexlify(destination).decode(
                    "charmap" if len(destination) < 4 else "utf-16-be", "surrogatepass"
                )  # join is here as some cases where the code was split
            except BinasciiError as exception:
                logger_warning(
                    "Got invalid hex string: %(exception)s (%(destination)r)",
                    source=__name__,
                    exception=exception,
                    destination=destination,
                )
        map_dict[
            unhexlify(source).decode(
                "charmap" if map_dict[-1] == 1 else "utf-16-be", "surrogatepass"
            )
        ] = map_to
        int_entry.append(int(source, 16))


def _correct_encoding(
    embedded_font_encoding: dict[int, str] | None,
    encoding: dict[int, str] | list[str]
) -> None:
    if not embedded_font_encoding:
        return

    for character_code, unicode_code_point in embedded_font_encoding.items():
        encoding[character_code] = unicode_code_point


def _parse_encoding_from_embedded_font(font_dictionary: DictionaryObject) -> dict[int, str]:
    """
    Derive the encoding from an embedded font program, caching the result on its stream. See Table 126
    about embedded font file organization in the PDF specification 1.7 for details

    The encoding depends only on the decoded font data, and the same font program is reached from every
    font dictionary, resource name and page referencing its stream. Parsing a font program with fontTools is
    expensive, so each stream is parsed once and reused until its data changes, which a digest of the data
    detects (a writer may replace the font program). See #4156.
    """
    if (
        "/FontDescriptor" not in font_dictionary or
        not isinstance(font_descriptor := font_dictionary["/FontDescriptor"], DictionaryObject)
    ):
        return {}

    if not any(
        (font_file := target) in font_descriptor
        and isinstance(font_file_dict := cast(StreamObject, font_descriptor[font_file]), StreamObject)
        for target in ("/FontFile", "/FontFile3")
    ):
        return {}

    font_file_handlers = {
        # A normal Type1 font file, can be part of a Type1 or MMType1 font dictionary.
        "/FontFile": _derive_encoding_from_type1_font_file,
        # A CFF Type1 font file, as part of a Type1 or MMType1 font dictionary.
        "/FontFile3": _derive_encoding_from_cff_type1_font_file,
    }
    font_file_processor = font_file_handlers[font_file]

    from .generic._font import HAS_FONTTOOLS  # noqa: PLC0415
    if font_file == "/FontFile3" and not HAS_FONTTOOLS:
        logger_warning(
            (
                "fontTools is required to fully parse the encoding of a CFF Type1 font in font "
                "dictionary %(font_dictionary)s, but is not installed. Consider installing "
                "fontTools if you encounter encoding problems."
            ),
            source=__name__,
            font_dictionary=font_dictionary,
        )
        return {}

    if not (font_file_data := font_file_dict.get_data()):
        return {}

    digest = sha256(font_file_data).digest()
    cached = font_file_dict._font_file_encoding
    if cached is None or cached.digest != digest:
        cached_encoding = font_file_processor(font_file_data)
        cached = _FontFileEncoding(digest, cached_encoding)
        font_file_dict._font_file_encoding = cached
    return cached.embedded_font_encoding


def _glyph_name_to_unicode(glyph_name: str) -> str | None:
    try:
        return adobe_glyphs[glyph_name]
    except KeyError:
        if glyph_name.startswith("/uni"):
            code_point = glyph_name[4:]
        elif glyph_name.startswith("/u"):
            code_point = glyph_name[2:]
        else:
            return None
        try:
            return chr(int(code_point, 16))
        except ValueError:  # pragma: no cover
            return None


def _derive_encoding_from_cff_type1_font_file(font_data: bytes) -> dict[int, str]:
    embedded_font_encoding: dict[int, str] = {}
    try:
        from fontTools.cffLib import CFFFontSet  # noqa: PLC0415
        cff_set = CFFFontSet()
        cff_set.decompile(BytesIO(font_data), None)
        cff_font = cff_set.topDictIndex[0]
        cff_encoding = cff_font.Encoding
        # Encoding can fall back to literal strings "StandardEncoding" or "ExpertEncoding", which we do not parse.
        if isinstance(cff_encoding, str):
            return embedded_font_encoding
        for i in range(min(len(cff_encoding), 256)):
            glyph_name = cff_encoding[i]
            if not glyph_name or glyph_name == ".notdef":
                continue
            if unipoint := _glyph_name_to_unicode(f"/{glyph_name}"):
                embedded_font_encoding[i] = unipoint
    except MemoryError:  # pragma: no cover  # TODO: BLE001
        raise
    except Exception:
        return embedded_font_encoding
    else:
        return embedded_font_encoding


def _derive_encoding_from_type1_font_file(font_data: bytes) -> dict[int, str]:
    embedded_font_encoding: dict[int, str] = {}
    txt = font_data.split(b"eexec\n")[0]  # Only the clear part
    encoding_part = txt.split(b"/Encoding")
    if len(encoding_part) < 2:
        return embedded_font_encoding
    txt = encoding_part[1]  # To get the encoding part
    lines = txt.replace(b"\r", b"\n").split(b"\n")
    for li in lines:
        # A line should be of format 'dup 63 /question put'
        if li.startswith(b"dup"):
            words = li.replace(b"/", b" /").split()
            # We require four elements to parse a line:
            # 1. "dup" (words[0]), which starts the code definition;
            # 2. the character code (words[1]);
            # 3. the glyph name (words[2]); and
            # 4. "put" (words[3]), which ends the code definition.
            if len(words) < 4 or words[3] != b"put":
                continue
            try:
                i = int(words[1])
            except ValueError:
                continue
            # Ensure the character code stays strictly within the 8-bit limit (0-255)
            if 0 <= i <= 255 and (unipoint := _glyph_name_to_unicode(words[2].decode())):
                embedded_font_encoding[i] = unipoint

    return embedded_font_encoding
