from __future__ import annotations

import re
from typing import Any

from .render import render_page


WORD_RE = re.compile(r"[^\W_]+(?:['’][^\W_]+)?", re.UNICODE)


def _reading_words(page: dict[str, Any]) -> list[str]:
    return [
        word.casefold().replace("’", "'")
        for word in WORD_RE.findall(render_page(page, diplomatic=False))
    ]


def detect_cross_page_duplicates(
    pages: dict[int, dict[str, Any]], *, minimum_words: int = 8, maximum_words: int = 80
) -> list[dict[str, Any]]:
    """Report exact reading-text suffix/prefix overlap without changing pages.

    The conservative threshold avoids flagging ordinary short repeated phrases.
    Findings are review warnings, not automatic transcription failures.
    """

    findings: list[dict[str, Any]] = []
    for left_number in sorted(pages):
        right_number = left_number + 1
        if right_number not in pages:
            continue
        left_words = _reading_words(pages[left_number])
        right_words = _reading_words(pages[right_number])
        upper = min(maximum_words, len(left_words), len(right_words))
        overlap = 0
        for count in range(upper, minimum_words - 1, -1):
            if left_words[-count:] == right_words[:count]:
                overlap = count
                break
        if overlap:
            findings.append(
                {
                    "left_page": left_number,
                    "right_page": right_number,
                    "word_count": overlap,
                    "normalized_text": " ".join(right_words[:overlap]),
                }
            )
    return findings
