"""Markdown pipe-table primitives — the single reference point for every
producer/consumer of final-report (and schedule) tables.

GFM treats every unescaped ``|`` inside a cell as a column boundary — even
inside inline-code spans — and renders ``\\|`` back as a literal ``|``. A row
is also line-terminated, so a newline inside a value truncates the row at that
point and drops every column after it. Producers therefore normalise cell text
with ``to_cell_text`` (exposed as the ``mdcell`` Jinja filter in
``render_final_report``), and consumers split rows with ``split_pipe_row``,
which honours the same ``\\|`` convention.
"""
from __future__ import annotations

import re
from typing import Any

# A `|` not preceded by a backslash: a real column boundary.
UNESCAPED_PIPE_RE = re.compile(r"(?<!\\)\|")

_SEPARATOR_CELL_RE = re.compile(r"\s*:?-+:?\s*")

_NEWLINE_RE = re.compile(r"\r\n|\r|\n")


def to_cell_text(value: Any) -> str:
    """Render a value as one markdown table cell: no newlines, no bare ``|``.

    Newlines fold to ``<br>`` (a blank line becomes ``<br><br>``, keeping the
    paragraph break visible) and literal ``|`` is escaped as ``\\|``.

    Idempotent: pipes that are already escaped are left alone and the folded
    ``<br>`` carries no newline, so re-rendering (Phase 7) never stacks
    backslashes or breaks. ``None`` renders as the empty string — the same
    contract as the template's ``or ''`` fallbacks.
    """
    if value is None:
        return ""
    folded = _NEWLINE_RE.sub("<br>", str(value).strip())
    return UNESCAPED_PIPE_RE.sub(r"\\|", folded)


def split_pipe_row(line: str) -> list[str]:
    """Split a markdown pipe-table row into whitespace-stripped cell texts.

    Outer pipes are dropped; ``\\|`` is an escaped literal pipe — it never
    splits a cell and is unescaped to ``|`` in the returned cell text.
    """
    stripped = line.strip()
    if stripped.startswith("|"):
        stripped = stripped[1:]
    if stripped.endswith("|") and not stripped.endswith("\\|"):
        stripped = stripped[:-1]
    return [
        cell.replace("\\|", "|").strip()
        for cell in UNESCAPED_PIPE_RE.split(stripped)
    ]


def is_separator_row(line: str) -> bool:
    """Detect ``|---|:---:|`` divider lines that separate header from body."""
    stripped = line.strip()
    if not stripped.startswith("|"):
        return False
    inner = stripped.strip("|").strip()
    return all(_SEPARATOR_CELL_RE.fullmatch(cell) for cell in inner.split("|"))
