"""REQ-FD-007: Dual-path delivery dedup for pending_media vs message-tool sent paths."""

from __future__ import annotations

import re
from pathlib import Path

MIN_TEXT_LENGTH_FOR_DEDUPE = 10


def normalize_media_path(path: str) -> str | None:
    """Normalize a media path for dedup comparison."""
    if not path or not path.strip():
        return None
    stripped = path.strip()
    if stripped.lower().startswith(("http://", "https://")):
        return stripped.lower()
    try:
        return str(Path(stripped).expanduser().resolve())
    except Exception:
        return None


def dedupe_pending_media(
    pending_media: list[str],
    sent_media_paths: set[str],
) -> list[str]:
    """Remove paths from *pending_media* that were already sent via the message tool."""
    if not sent_media_paths:
        return list(pending_media)

    normalized_sent = {normalize_media_path(p) for p in sent_media_paths} - {None}
    result: list[str] = []
    for p in pending_media:
        norm = normalize_media_path(p)
        if norm and norm in normalized_sent:
            continue
        result.append(p)
    return result


def normalize_text(text: str) -> str:
    """Normalize whitespace and case for text comparison."""
    return re.sub(r"\s+", " ", text.strip().lower()).strip()


def is_text_duplicate(text: str, sent_texts: list[str]) -> bool:
    """
    Check if *text* is substantially the same as any already-sent text.

    Short texts (< MIN_TEXT_LENGTH_FOR_DEDUPE) are never considered duplicates.
    """
    if not sent_texts:
        return False
    normalized = normalize_text(text)
    if len(normalized) < MIN_TEXT_LENGTH_FOR_DEDUPE:
        return False
    for sent in sent_texts:
        n_sent = normalize_text(sent)
        if len(n_sent) < MIN_TEXT_LENGTH_FOR_DEDUPE:
            continue
        if normalized in n_sent or n_sent in normalized:
            return True
    return False
