"""Structural rules applied to every OCR page's Markdown (the OCR prompt asks for them; this guarantees them).

1. A note column holds only note numbers ("4", "12.1", "4.a.1", "5, 6"). Descriptive text found there moves into
   the same row's Particulars cell; the row's values never move.
2. A note's number and title ("42. CONSOLIDATED INCREASE/(DECREASE) OF OTHER ASSETS", printed as a row without
   figures) is the title of its own table: it becomes a "### 42. ..." heading line and the table is split there,
   repeating the header row. On a notes page every such row splits the table; on a primary statement page (balance
   sheet, profit and loss, cash flow, changes in equity) only a title row at the very top of a table is lifted out,
   so numbered sections inside a statement stay in one table.
The text itself is never changed, only where it sits.
"""
import re
from typing import List, Optional

_NOTE_NUM = r"\d{1,3}(?:\.[0-9A-Za-z]{1,3})*\.?"
_NOTE_CELL_RE = re.compile(rf"^(?:{_NOTE_NUM})(?:\s*[,&/]\s*(?:{_NOTE_NUM}))*$")
_NUMBER_ONLY_RE = re.compile(rf"^{_NOTE_NUM}$")
_TITLE_ROW_RE = re.compile(rf"^({_NOTE_NUM})\s+(\S.{{2,}})$")
_TOTAL_RE = re.compile(r"^(total|subtotal|sub-total|grand total)\b", re.I)
_DIVIDER_RE = re.compile(r"^\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$")
_PRIMARY_RE = re.compile(r"balance\s+sheet|statement\s+of\s+financial\s+position|profit\s+(and|&)\s+loss\s+account|"
                         r"income\s+statement|cash\s+flow\s+statement|statement\s+of\s+cash\s+flows|"
                         r"statement\s+of\s+changes\s+in\s+(shareholders'?\s+)?equity", re.I)


def _cells(line: str) -> List[str]:
    s = line.strip()
    if s.startswith("|"):
        s = s[1:]
    if s.endswith("|"):
        s = s[:-1]
    return [c.strip() for c in s.split("|")]


def _row(cells: List[str]) -> str:
    return "| " + " | ".join(cells) + " |"


def _plain(text: str) -> str:
    return re.sub(r"\s+", " ", text.replace("**", "").replace("__", "")).strip()


def _note_col(header: List[str]) -> Optional[int]:
    for i, h in enumerate(header[:3]):
        if _plain(h).lower() in ("note", "notes", "note no.", "note no"):
            return i
    return None


def _normalize_table(block: List[str], primary: bool) -> List[str]:
    if len(block) < 2 or not _DIVIDER_RE.match(block[1]):
        return block
    header, divider = block[0], block[1]
    head = _cells(header)
    note_col = _note_col(head)
    first_value = (note_col + 1) if note_col is not None else 1

    segments: List[dict] = [{"heading": None, "rows": []}]
    for line in block[2:]:
        cells = _cells(line)
        cells += [""] * (len(head) - len(cells))
        changed = False
        has_values = any(_plain(c) for c in cells[first_value:])
        label = _plain(cells[0]) if cells else ""
        title = None

        if note_col is not None and note_col < len(cells):
            note_text = _plain(cells[note_col])
            if note_text and not _NOTE_CELL_RE.match(note_text):
                if not has_values and _NUMBER_ONLY_RE.match(label):
                    title = f"{label} {note_text}"            # | 42. | TITLE | | |
                else:                                          # text in the note column joins the label
                    cells[0] = (cells[0] + " " + cells[note_col]).strip() if cells[0] else cells[note_col]
                    cells[note_col] = ""
                    label = _plain(cells[0])
                    changed = True

        if title is None and not has_values and _TITLE_ROW_RE.match(label):
            rows = segments[-1]["rows"]
            at_top = not any(any(_plain(c) for c in _cells(r)) for r in rows)
            if at_top or not primary:
                title = label

        if title is not None:
            segments.append({"heading": title, "rows": []})
        else:
            segments[-1]["rows"].append(_row(cells) if changed else line)

    if len(segments) == 1 and not any(r is not ln for r, ln in zip(segments[0]["rows"], block[2:])):
        return block
    if len(segments) == 1:
        return [header, divider] + segments[0]["rows"]
    out: List[str] = []
    for seg in segments:
        rows = list(seg["rows"])
        while rows and not any(_plain(c) for c in _cells(rows[-1])):  # blank separator rows
            rows.pop()
        while rows and not any(_plain(c) for c in _cells(rows[0])):
            rows.pop(0)
        if seg["heading"]:
            out += ["", f"### {seg['heading']}", ""]
        if rows:
            out += [header, divider] + rows
    while out and out[0] == "":
        out.pop(0)
    return out


def normalize_note_tables(md: str) -> str:
    """Applies the note rules above to every table of an OCR page."""
    lines = md.split("\n")
    primary = any(_PRIMARY_RE.search(ln) for ln in lines if not ln.lstrip().startswith("|"))
    out: List[str] = []
    i = 0
    while i < len(lines):
        if lines[i].lstrip().startswith("|"):
            j = i
            while j < len(lines) and lines[j].lstrip().startswith("|"):
                j += 1
            out += _normalize_table(lines[i:j], primary)
            i = j
        else:
            out.append(lines[i])
            i += 1
    text = "\n".join(out)
    return re.sub(r"\n{3,}", "\n\n", text)
