"""Plain-text cleanup for personal noticing surfaces (You pane, journal, proposals)."""

from __future__ import annotations

import re

_LATEX_ARROW_REPLACEMENTS = (
    (r"\$\\leftrightarrow\$", " ↔ "),
    (r"\\leftrightarrow", "↔"),
    (r"\$\\rightarrow\$", " → "),
    (r"\\rightarrow", "→"),
    (r"\$\\leftarrow\$", " ← "),
    (r"\\leftarrow", "←"),
)

_PREFIX_STRIP_RES = (
    re.compile(r"^Consolidation\s*[—–-]\s*Connections\s*&\s*Links\s*:\s*", re.I),
    re.compile(r"^Cross-thread link:\s*", re.I),
    re.compile(r"^Cross-thread recall detected:\s*", re.I),
    re.compile(r"^Vault project discuss:\s*", re.I),
    re.compile(r"^Vault discuss:\s*", re.I),
)

# Strip filesystem paths from human-facing noticing text (You pane, API summaries).
_KNOWN_ABSOLUTE_PATH_RE = re.compile(
    r"(?:/Users/|/home/|/var/|/private/|/tmp/|C:\\|D:\\)[^\s`\"']+",
    re.IGNORECASE,
)
_UNIX_MULTI_SEGMENT_PATH_RE = re.compile(
    r"(?<![\w:])(?:/(?:[a-zA-Z0-9_.-]+)){2,}(?![\w/.])",
)


def _redact_noticing_paths(text: str) -> str:
    s = _KNOWN_ABSOLUTE_PATH_RE.sub("[path]", text)
    return _UNIX_MULTI_SEGMENT_PATH_RE.sub("[path]", s)


def sanitize_noticing_plaintext(text: str, *, max_len: int = 400) -> str:
    """Strip markdown/LaTeX noise from consolidation or journal lines for human UI."""
    s = str(text or "").strip()
    if not s:
        return ""
    for pattern, repl in _LATEX_ARROW_REPLACEMENTS:
        s = re.sub(pattern, repl, s)
    # Inline code / bold / italic (non-greedy, single-line friendly)
    s = re.sub(r"\*\*(.+?)\*\*", r"\1", s)
    s = re.sub(r"\*(.+?)\*", r"\1", s)
    s = re.sub(r"`([^`]+)`", r"\1", s)
    for prefix_re in _PREFIX_STRIP_RES:
        s = prefix_re.sub("", s)
    s = _redact_noticing_paths(s)
    s = re.sub(r"\s+", " ", s).strip()
    if len(s) > max_len:
        cut = s[:max_len].rsplit(" ", 1)[0] if " " in s[:max_len] else s[:max_len]
        s = cut.rstrip(".,;:") + "…"
    return s


def extract_journal_bullet_lines(journal_tail: str, *, max_lines: int = 3) -> list[str]:
    """Return the most recent journal bullets as sanitized plain lines."""
    lines: list[str] = []
    for raw in (journal_tail or "").splitlines():
        trimmed = raw.strip()
        if trimmed.startswith("- "):
            cleaned = sanitize_noticing_plaintext(trimmed[2:])
            if len(cleaned) >= 14:
                lines.append(cleaned)
    if not lines:
        fallback = sanitize_noticing_plaintext(journal_tail, max_len=220)
        if fallback:
            lines.append(fallback)
    return lines[-max_lines:]
