"""
Code related to text extraction.

Some parts are still in _page.py. In doubt, they will stay there.
"""

import codecs
import math
import re
from collections.abc import Callable, Mapping
from typing import Any, Literal

from .._utils import RTL_CHARACTER_RANGES, is_char_neutral, is_char_rtl
from ..generic import ContentStream, DictionaryObject, TextStringObject, encode_pdfdocencoding
from ..generic._font import Font

CUSTOM_RTL_MIN: str = ""
CUSTOM_RTL_MAX: str = ""
CUSTOM_RTL_SPECIAL_CHARS: str = ""
LAYOUT_NEW_BT_GROUP_SPACE_WIDTHS: int = 5
UNICODE_LOWER_LIMIT = 0
UNICODE_UPPER_LIMIT = 0x10FFFF
RTL_CHARACTER_PATTERN = re.compile("[" + "".join(f"{start}-{end}" for start, end in RTL_CHARACTER_RANGES) + "]")

# The operators that can add text: the text-showing operators (ISO 32000-2:2020,
# 9.4.3, Table 107) and Do, which can paint a form XObject with text (8.8.1, Table 86).
# The bytes may also occur in strings, names or inline image data; that only
# means that the content stream is parsed.
_TEXT_OPERATORS = (b"Tj", b"TJ", b"Do", b"'", b'"')
# Searching for their first bytes and comparing the next byte is faster than
# searching for the alternation Tj|TJ|Do|'|" in content streams with many graphics.
_TEXT_OPERATOR_START = re.compile(rb"[TD'\"]")


class OrientationNotFoundError(Exception):
    pass


def set_custom_rtl(
    _min: str | int | None = "",
    _max: str | int | None = "",
    specials: str | list[int] | None = None,
) -> tuple[str, str, str]:
    """
    Change the Right-To-Left and special characters custom parameters.

    Args:
        _min: The new minimum value for the range of custom characters that
            will be written right to left.
            If set to ``None``, the value will not be changed.
            If set to a valid integer, it will be converted to its corresponding character.
            The default value is "", which sets no additional range to be converted.
        _max: The new maximum value for the range of custom characters that will
            be written right to left.
            If set to ``None``, the value will not be changed.
            If set to a valid integer, it will be converted to its corresponding character.
            The default value is "", which sets no additional range to be converted.
        specials: The new list of special characters to be inserted in the
            current insertion order.
            If set to ``None``, the current value will not be changed.
            If set to a string, it will be converted to a list of ASCII codes.
            The default value is an empty list.

    Returns:
        A tuple containing the new values for ``CUSTOM_RTL_MIN``,
        ``CUSTOM_RTL_MAX``, and ``CUSTOM_RTL_SPECIAL_CHARS``.

    """
    global CUSTOM_RTL_MIN, CUSTOM_RTL_MAX, CUSTOM_RTL_SPECIAL_CHARS
    if isinstance(_min, int):
        CUSTOM_RTL_MIN = chr(_min) if UNICODE_LOWER_LIMIT <= _min <= UNICODE_UPPER_LIMIT else ""
    elif isinstance(_min, str):
        CUSTOM_RTL_MIN = _min
    if isinstance(_max, int):
        CUSTOM_RTL_MAX = chr(_max) if UNICODE_LOWER_LIMIT <= _max <= UNICODE_UPPER_LIMIT else ""
    elif isinstance(_max, str):
        CUSTOM_RTL_MAX = _max
    if isinstance(specials, str):
        CUSTOM_RTL_SPECIAL_CHARS = specials
    elif isinstance(specials, list):
        CUSTOM_RTL_SPECIAL_CHARS = "".join(
            chr(char) for char in specials if UNICODE_LOWER_LIMIT <= char <= UNICODE_UPPER_LIMIT
        )
    return CUSTOM_RTL_MIN, CUSTOM_RTL_MAX, CUSTOM_RTL_SPECIAL_CHARS


def mult(
    m: list[float],
    n: (
        list[float] |
        Mapping[int | Literal["is_text", "is_render"], float | bool]
    ),
) -> list[float]:
    return [
        m[0] * n[0] + m[1] * n[2],
        m[0] * n[1] + m[1] * n[3],
        m[2] * n[0] + m[3] * n[2],
        m[2] * n[1] + m[3] * n[3],
        m[4] * n[0] + m[5] * n[2] + n[4],
        m[4] * n[1] + m[5] * n[3] + n[5],
    ]


def orient(m: list[float]) -> int:
    if m[3] > 1e-6:
        return 0
    if m[3] < -1e-6:
        return 180
    if m[1] > 0:
        return 90
    return 270


def crlf_space_check(  # noqa: PLR0913, PLR0917
    text: str,
    cmtm_prev: tuple[list[float], list[float]],
    cmtm_matrix: tuple[list[float], list[float]],
    memo_cmtm: tuple[list[float], list[float]],
    font_resource: DictionaryObject | None,
    orientations: tuple[int, ...],
    output: str,
    font_size: float,
    visitor_text: Callable[[Any, Any, Any, Any, Any], None] | None,
    str_widths: float,
    spacewidth: float,
    str_height: float,
    line_span: tuple[int, float, float] | None,
) -> tuple[str, str, list[float], list[float], tuple[int, float, float] | None]:
    cm_prev = cmtm_prev[0]
    tm_prev = cmtm_prev[1]
    cm_matrix = cmtm_matrix[0]
    tm_matrix = cmtm_matrix[1]
    memo_cm = memo_cmtm[0]
    memo_tm = memo_cmtm[1]

    m_prev = mult(tm_prev, cm_prev)
    m = mult(tm_matrix, cm_matrix)
    orientation = orient(m)
    delta_x = m[4] - m_prev[4]
    delta_y = m[5] - m_prev[5]
    # Table 108 of the 1.7 reference ("Text positioning operators")
    # delta_x/delta_y are expressed in the coordinate system produced by
    # text matrix x current transformation matrix, so the scaling factors
    # they get compared against have to be taken from the same combined
    # matrices instead of the text matrices alone.
    scale_prev_x = math.sqrt(m_prev[0]**2 + m_prev[1]**2)
    scale_prev_y = math.sqrt(m_prev[2]**2 + m_prev[3]**2)
    scale_y = math.sqrt(m[2]**2 + m[3]**2)
    cm_prev = m

    if orientation not in orientations:
        raise OrientationNotFoundError
    if orientation in (0, 180):
        moved_height: float = delta_y
        moved_width: float = delta_x
    elif orientation in (90, 270):
        moved_height = delta_x
        moved_width = delta_y
    # Keep track of the baseline range of the current extracted line. A centered
    # row label can fall between the two baselines of a wrapped cell (#4130), so
    # comparing only with the immediately preceding fragment can incorrectly
    # insert a line break. Use the established baseline range for that case.
    axis_index = 5 if orientation in (0, 180) else 4
    axis = m[axis_index]
    if line_span is None or line_span[0] != axis_index:
        distance = abs(moved_height)
    else:
        lower, upper = line_span[1], line_span[2]
        distance = 0.0 if lower <= axis <= upper else min(abs(axis - lower), abs(axis - upper))
    # The last character of output + text, without copying both strings.
    last = (text or output)[-1:]
    threshold = 0.8 * min(str_height * scale_prev_y, font_size * scale_y)
    if distance > threshold:
        if last not in ("", "\n"):
            output += text + "\n"
            if visitor_text is not None:
                visitor_text(
                    text + "\n",
                    memo_cm,
                    memo_tm,
                    font_resource,
                    font_size,
                )
            text = ""
        line_span = (axis_index, axis, axis)
    else:
        # A fragment kept on this line only by the line span moved to another
        # baseline, so comparing its horizontal gap with the previous fragment
        # would miss the word separation (#4254).
        moved_to_other_baseline = abs(moved_height) > threshold
        if (
            (moved_to_other_baseline or moved_width >= (spacewidth + str_widths) * scale_prev_x)
            and last not in ("", " ")
        ):
            text += " "
        if last in ("", "\n") or line_span is None or line_span[0] != axis_index:
            line_span = (axis_index, axis, axis)
        else:
            line_span = (axis_index, min(line_span[1], axis), max(line_span[2], axis))
    tm_prev = tm_matrix.copy()
    cm_prev = cm_matrix.copy()
    return text, output, cm_prev, tm_prev, line_span


def _count_codes(operand: str | bytes, text: str, font: Font) -> tuple[int, int]:
    """
    Count the character codes of a shown string and the single-byte codes 32 in it.

    Character spacing applies to every character code and word spacing only to
    the single-byte code 32 (Section 9.3.3 of the PDF 2.0 specification).

    Args:
        operand: The string operand as found in the content stream.
        text: The operand decoded with the font encoding.
        font: The font used to show the string.

    Returns:
        The number of character codes and the number of single-byte codes 32.

    """
    if isinstance(operand, str):
        if not isinstance(operand, TextStringObject):
            # The " " that process_tj_offset adds for a gap in a TJ array: no code was shown.
            return 0, 0
        # A content stream that was not parsed as bytes, like one changed by a PdfWriter,
        # has text strings. Count the codes of the bytes they were read from.
        operand = operand.get_original_bytes()
    if isinstance(font.encoding, dict):  # Simple font, one byte per code.
        return len(operand), operand.count(b" ")
    if codecs.lookup(font.encoding).name == "utf-16-be":
        # Two bytes per code. Counting the decoded characters instead would
        # merge two codes forming a surrogate pair into one character.
        return len(operand) // 2, 0
    # Multi-byte encodings like Shift-JIS decode one character per code and
    # keep the ASCII range as single-byte codes.
    return len(text), text.count(" ")


def get_text_operands(
    operands: list[str | TextStringObject],
    cm_matrix: list[float],
    tm_matrix: list[float],
    font: Font,
    orientations: tuple[int, ...]
) -> tuple[str, bool, float, int, int]:
    text: str = ""
    is_str_operands = False
    widths: float = 0.0
    glyph_count = 0
    space_count = 0
    width_cache: dict[str, float] = {}
    m = mult(tm_matrix, cm_matrix)
    orientation = orient(m)
    raw_characters: str = ""
    if orientation in orientations and len(operands) > 0:
        if isinstance(operands[0], str):
            text = operands[0]
            is_str_operands = True
        else:
            text = ""
            tt: bytes = (
                encode_pdfdocencoding(operands[0])
                if isinstance(operands[0], str)
                else operands[0]
            )
            if isinstance(font.encoding, str):  # Apply named encoding
                try:
                    text = tt.decode(font.encoding, "surrogatepass")
                except UnicodeDecodeError:
                    # Fallback for odd byte counts or unmapped 16-bit GIDs/CIDs
                    text = tt.decode(font.encoding, "replace")
            else:  # Apply dict encoding
                text = "".join(font.encoding.get(x, chr(x)) for x in tt)
                raw_characters = "".join(chr(byte) for byte in tt)
        glyph_count, space_count = _count_codes(operands[0], text, font)
        for char in (raw_characters or text):
            if char == font.space_char:
                widths += font.space_width
            else:
                if char not in width_cache:
                    width_cache[char] = font.get_text_width(char)
                widths += width_cache[char]

    width_cache.clear()
    return (text, is_str_operands, widths, glyph_count, space_count)


def get_display_str(
    text: str,
    cm_matrix: list[float],
    tm_matrix: list[float],
    font_resource: DictionaryObject | None,
    font: Font,
    text_operands: str,
    font_size: float,
    rtl_dir: bool,
    visitor_text: Callable[[Any, Any, Any, Any, Any], None] | None
) -> tuple[str, bool, str]:
    """
    Add the characters of ``text_operands`` to ``text`` in display order.

    Returns:
        A tuple containing the current text run, its direction, and any text runs completed
        because of a direction change. The completed runs precede the current run in display order.

    """
    # "\u0590 - \u08FF \uFB50 - \uFDFF"
    characters = [font.character_map.get(raw_character, raw_character) for raw_character in text_operands]
    if not rtl_dir and not (CUSTOM_RTL_MIN and CUSTOM_RTL_MAX):
        # Without a right-to-left character, all characters are appended in order.
        appended_text = "".join(characters)
        if RTL_CHARACTER_PATTERN.search(appended_text) is None:
            return text + appended_text, rtl_dir, ""

    completed_text: list[str] = []
    neutral_cache: dict[str, bool] = {}
    rtl_cache: dict[str, bool] = {}
    # Characters are only ever prepended in a right-to-left run and appended in a
    # left-to-right run. Collect them and join once, as building the string one
    # prepended character at a time takes quadratic time.
    run_parts = [text]

    def clear_character_caches() -> None:
        neutral_cache.clear()
        rtl_cache.clear()

    def get_run_text() -> str:
        return "".join(reversed(run_parts)) if rtl_dir else "".join(run_parts)

    for x in characters:
        # Test whether x is a sequence of bytes; ex: habibi.pdf
        if len(x) == 1:
            if x not in neutral_cache:
                neutral_cache[x] = is_char_neutral(x, CUSTOM_RTL_SPECIAL_CHARS)
            if neutral_cache[x]:
                # Cases where the current inserting order is kept
                run_parts.append(x)
            else:
                if x not in rtl_cache:
                    rtl_cache[x] = is_char_rtl(x, CUSTOM_RTL_MIN, CUSTOM_RTL_MAX)
                if rtl_cache[x] != rtl_dir:
                    # The direction changes: right-to-left or left-to-right characters
                    text = get_run_text()
                    rtl_dir = rtl_cache[x]
                    if visitor_text is not None:
                        visitor_text(text, cm_matrix, tm_matrix, font_resource, font_size)
                        clear_character_caches()
                    completed_text.append(text)
                    run_parts = []
                run_parts.append(x)
        else:
            # Treat a sequence of bytes as a neutral character.
            run_parts.append(x)
    return get_run_text(), rtl_dir, "".join(completed_text)


def _has_text_operator(data: bytes) -> bool:
    """Return whether the bytes contain an operator that can add text."""
    for match in _TEXT_OPERATOR_START.finditer(data):
        start = match.start()
        if data[start : start + 2] in _TEXT_OPERATORS or match[0] in _TEXT_OPERATORS:
            return True
    return False


def _get_content_stream_for_text(
    obj: DictionaryObject, pdf: Any, content_key: str | None, *, has_visitor: bool
) -> ContentStream | None:
    """
    Return the content stream to extract text from, or None if it cannot give any text.

    Content without text, e.g. a figure, gives no text either. It is only parsed if
    a visitor has to see its operators.
    """
    try:
        content = obj[content_key].get_object() if isinstance(content_key, str) else obj
        if not isinstance(content, ContentStream):
            content = ContentStream(content, pdf, "bytes")
    except (AttributeError, KeyError):  # no content can be extracted (certainly empty page)
        return None
    if not has_visitor and not _has_text_operator(content.get_data()):
        return None
    return content
