"""Reading the two shapes a federal news release comes in. Every release in this dataset is a document written for a human being, and every one of them exists in exactly two forms across the period covered: fixed-width text inside a `
` block, and real HTML tables. BLS switched
during 2012, Census and DOL never switched at all, and a parser that knows only
one of them loses years of history.

Both readers produce the same thing: a table addressed by row label and by the
period named in its own column header. Addressing a value by position -- "the
eighth number on the All items line" -- is what breaks when an agency inserts a
column, and it breaks silently, which is worse.
"""

from __future__ import annotations

import html as html_module
import re
from dataclasses import dataclass, field
from html.parser import HTMLParser

# BLS, Census and DOL all pad their text tables with dot leaders. A label is
# everything before the run of dots.
DOT_LEADER = re.compile(r"\.{2,}")
WHITESPACE = re.compile("[\\s\\u00a0]+")
# -1.4, .3, 1,234, (2.1), 1,234.5, -- and N/A all appear in these documents.
NUMBER = re.compile(r"^\(?-?\$?\d{0,3}(?:,\d{3})*(?:\.\d+)?\)?$|^\(?-?\.\d+\)?$")
# A figure the agency flagged as revised or preliminary: `(r)3.4`, `3.4(p)`.
# The marker is information about the figure, not part of it.
FOOTNOTE = re.compile(r"\((?:r|p|c|NA|X|Z)\)", re.IGNORECASE)
TABLE_TITLE_LINE = re.compile(r"^\s*(?:Summary\s+)?[Tt]able\s+[A-Z0-9-]{1,4}\.")


def clean(text: str) -> str:
    return WHITESPACE.sub(" ", html_module.unescape(text)).strip()


# The same flattening the narrative parsers do, for the same reason: a minus
# sign is whichever dash the typesetter reached for.
DASHES = str.maketrans(
    {"\u2010": "-", "\u2011": "-", "\u2012": "-", "\u2013": "-", "\u2212": "-"}
)


def to_number(text: str) -> float | None:
    """A published figure, or None where the agency printed a dash.

    Parentheses mean negative in Census and BEA tables and nothing else; a
    value that is merely absent is left absent rather than turned into zero,
    because a zero that means "not published" is indistinguishable from a real
    zero once it is in a parquet file.
    """

    value = clean(text).translate(DASHES)
    value = value.rstrip("*").strip()
    # Footnote markers ride on the number in some Census tables: "1,234.5 (r)".
    value = FOOTNOTE.sub("", value).strip()
    if not value or value in {"-", "--", "---", "(NA)", "NA", "N/A", "(X)", "(Z)", "...", "."}:
        return None
    negative = value.startswith("(") and value.endswith(")")
    if negative:
        value = value[1:-1].strip()
    if not NUMBER.match(value):
        return None
    value = value.replace(",", "").replace("$", "")
    if value in {"", "-", "."}:
        return None
    try:
        number = float(value)
    except ValueError:
        return None
    return -number if negative else number


@dataclass(slots=True)
class Table:
    """A table with its header rows expanded so every column has its own labels."""

    caption: str
    header: list[list[str]]
    rows: list[list[str]]
    identifier: str | None = None

    def column_labels(self) -> list[str]:
        """One label per column: the header cells above it, joined.

        The join is what makes `Jul.2026-Aug.2026` under `Seasonally adjusted
        percent change` distinguishable from the identically named column under
        `Unadjusted percent change`.
        """

        width = max(
            [len(row) for row in self.rows] + [len(row) for row in self.header] or [0],
            default=0,
        )
        labels = []
        for index in range(width):
            parts: list[str] = []
            for row in self.header:
                cell = row[index] if index < len(row) else ""
                if cell and cell not in parts:
                    parts.append(cell)
            labels.append(" | ".join(parts))
        return labels

    def find_column(
        self,
        *,
        contains: str,
        group: str | None = None,
        excluding: str | None = None,
    ) -> int | None:
        """The index of the one column whose header says this, or None.

        `excluding` is not a convenience. In a text-era CPI release the
        seasonally adjusted column for August and the unadjusted 12-month
        column ending in August are both labelled with August, and only the
        second says `12-mos.`; without a way to rule one out, both match and
        neither can be used.
        """

        wanted = normalise_period(contains)
        banned = normalise_period(excluding) if excluding else None
        found = None
        for index, label in enumerate(self.column_labels()):
            normalised = normalise_period(label)
            if wanted not in normalised:
                continue
            if group is not None and normalise_period(group) not in normalised:
                continue
            if banned is not None and banned in normalised:
                continue
            if found is not None:
                # Two columns matching one description is not a column: the
                # caller has under-specified, and picking the first would put a
                # plausible wrong number into the dataset.
                return None
            found = index
        return found

    def headings(self) -> list[tuple[list[str], list[str]]]:
        """Every data row paired with the headings it sits under.

        A statistical table is not flat. The Employment Situation's summary
        table B carries `Total nonfarm` twice -- once as the over-the-month
        change and once as a three-month average -- and `Total private` three
        times. Addressing a row by its label alone picks one of them at random,
        so a row is addressed by its label *and* the headings above it.

        A heading here is a row with a label and no figures, which is how all
        four agencies mark one.
        """

        stack: list[str] = []
        previous_was_heading = False
        paired: list[tuple[list[str], list[str]]] = []
        for row in self.rows:
            if not row or not row[0]:
                previous_was_heading = False
                continue
            if not any(cell for cell in row[1:]):
                # Headings written one after another nest: `HOURS AND
                # EARNINGS` then `Total private`. A heading that follows data
                # is the next section, not a child of the last one.
                stack = [*stack, row[0]] if previous_was_heading else [row[0]]
                previous_was_heading = True
                continue
            previous_was_heading = False
            paired.append((row, list(stack)))
        return paired

    def find_row(
        self, label: str, *, section: str | None = None, exact: bool = True
    ) -> list[str] | None:
        target = row_key(label)
        wanted = row_key(section) if section else None
        matches = [
            row
            for row, headings in self.headings()
            if (row_key(row[0]) == target or (not exact and target in row_key(row[0])))
            and (wanted is None or any(wanted in row_key(heading) for heading in headings))
        ]
        if len(matches) != 1:
            # None and many are the same answer: this table does not have one
            # row by that description, and guessing which was meant is how a
            # plausible wrong number gets published.
            return None
        return matches[0]

    def value(self, label: str, column: int | None, *, section: str | None = None) -> float | None:
        if column is None:
            return None
        row = self.find_row(label, section=section)
        if row is None or column >= len(row):
            return None
        return to_number(row[column])


def row_key(label: str) -> str:
    """Compare row labels without the typography the agencies vary freely."""

    text = clean(label).lower()
    text = DOT_LEADER.sub(" ", text)
    text = re.sub(r"\(\d+\)", " ", text)          # footnote markers
    text = re.sub(r"[^a-z0-9]+", " ", text)
    return " ".join(text.split())


def normalise_period(label: str) -> str:
    """`Jul.2026-Aug.2026` and `July 2026 - Aug. 2026` compare equal."""

    text = clean(label).lower()
    text = re.sub(r"\(\d+\)", " ", text)
    text = text.replace("\u2013", "-").replace("\u2212", "-")
    text = re.sub(r"(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\.?", r"\1", text)
    text = re.sub(r"[^a-z0-9-]+", " ", text)
    return " ".join(text.split())


class _TableReader(HTMLParser):
    """Just enough HTML to read a statistical table correctly.

    `rowspan` and `colspan` are not decoration in these documents: the CPI
    release's Table 1 puts three sub-columns under `Seasonally adjusted percent
    change` and one of them is the headline number. Ignoring the spans shifts
    every column label by two, and the shift is invisible in the output.

    So the table is built as a grid. A cell with `colspan=3` occupies three
    columns; a cell with `rowspan=2` occupies its column in the next row as
    well. Every row then has one entry per column and column *n* means the same
    thing in the header as it does in the body.
    """

    def __init__(self) -> None:
        super().__init__(convert_charrefs=True)
        self.tables: list[Table] = []
        self._stack: list[_Grid] = []
        self._cell: list[str] | None = None
        self._caption_depth = 0

    def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
        attributes = {key: (value or "") for key, value in attrs}
        if tag == "table":
            self._stack.append(_Grid(identifier=attributes.get("id")))
        elif not self._stack:
            return
        elif tag == "caption":
            self._caption_depth += 1
        elif tag in {"thead", "tbody", "tfoot"}:
            self._stack[-1].in_head = tag == "thead"
        elif tag == "tr":
            self._stack[-1].start_row()
        elif tag in {"td", "th"}:
            self._cell = []
            self._stack[-1].pending = (
                _span(attributes.get("colspan")),
                _span(attributes.get("rowspan")),
                tag == "th",
            )

    def handle_endtag(self, tag: str) -> None:
        if not self._stack:
            return
        grid = self._stack[-1]
        if tag == "caption":
            self._caption_depth = max(0, self._caption_depth - 1)
        elif tag in {"td", "th"} and self._cell is not None:
            grid.add_cell(clean("".join(self._cell)))
            self._cell = None
        elif tag == "thead":
            grid.end_row()
            grid.in_head = False
        elif tag == "tr":
            grid.end_row()
        elif tag == "table":
            self.tables.append(self._stack.pop().finish())

    def handle_data(self, data: str) -> None:
        if self._caption_depth and self._stack:
            self._stack[-1].caption.append(data)
        elif self._cell is not None:
            self._cell.append(data)


@dataclass(slots=True)
class _Grid:
    """A table under construction, one row at a time, spans resolved."""

    identifier: str | None = None
    caption: list[str] = field(default_factory=list)
    rows: list[list[str]] = field(default_factory=list)
    is_header: list[bool] = field(default_factory=list)
    # `` is the table's own answer to which rows are headings, and it
    # beats the shape of the cells. December 2019's projections table opens its
    # header with a `` spacer and closes its body with an all-`` memo
    # row; read by cell tag alone, that table loses `Median`, `Central
    # Tendency` and `Range` from its labels and gains a memo line instead.
    in_head: bool = False
    saw_head: bool = False
    pending: tuple[int, int, bool] = (1, 1, False)
    _row: list[str] | None = None
    _row_all_header: bool = True
    _row_has_cell: bool = False
    # column -> (text, rows still to fill)
    _carry: dict[int, tuple[str, int]] = field(default_factory=dict)

    def start_row(self) -> None:
        self.end_row()
        self._row = []
        self._row_all_header = True
        self._row_has_cell = False
        self._fill_carried()

    def _fill_carried(self) -> None:
        if self._row is None:
            return
        while len(self._row) in self._carry:
            text, left = self._carry[len(self._row)]
            self._row.append(text)
            if left <= 1:
                del self._carry[len(self._row) - 1]
            else:
                self._carry[len(self._row) - 1] = (text, left - 1)

    def add_cell(self, text: str) -> None:
        if self._row is None:
            self.start_row()
        assert self._row is not None
        colspan, rowspan, header = self.pending
        self.pending = (1, 1, False)
        self._row_has_cell = True
        if not header:
            self._row_all_header = False
        for _ in range(colspan):
            self._fill_carried()
            column = len(self._row)
            self._row.append(text)
            if rowspan > 1:
                self._carry[column] = (text, rowspan - 1)
        self._fill_carried()

    def end_row(self) -> None:
        if self._row is None:
            return
        if self._row_has_cell:
            self.rows.append(self._row)
            self.is_header.append(self.in_head or (self._row_all_header and not self.saw_head))
            self.saw_head = self.saw_head or self.in_head
        self._row = None

    def finish(self) -> Table:
        self.end_row()
        header = [row for row, flag in zip(self.rows, self.is_header, strict=True) if flag]
        body = [row for row, flag in zip(self.rows, self.is_header, strict=True) if not flag]
        # A table that marks nothing as a header still has one: its first row.
        # Census writes tables this way and the column labels are in it.
        if not header and self.rows:
            header, body = self.rows[:1], self.rows[1:]
        return Table(
            caption=clean("".join(self.caption)),
            header=header,
            rows=body,
            identifier=self.identifier,
        )


def _span(value: str | None) -> int:
    try:
        return max(1, min(int(value or 1), 64))
    except ValueError:
        return 1


def html_tables(document: str) -> list[Table]:
    reader = _TableReader()
    reader.feed(document)
    reader.close()
    return reader.tables


PRE_BLOCK = re.compile(r"(?is)]*>(.*?)
") TAG = re.compile(r"(?s)<[^>]+>") def pre_text(document: str) -> str: """The plain-text body of a release, as the agency laid it out. Line breaks and column positions are meaningful here -- they are the table -- so nothing is collapsed. """ blocks = PRE_BLOCK.findall(document) if not blocks: return "" return "\n".join(html_module.unescape(TAG.sub("", block)) for block in blocks) def pdf_text(content: bytes) -> str: """The text of a PDF release. Census, DOL and BEA publish their news releases as PDF and have done throughout the period covered, so there is no HTML alternative to fall back to. What comes out has the spacing a PDF extractor invents rather than the spacing the author typed, which is why the parsers that read these documents match against text with the gaps removed. """ from io import BytesIO from pypdf import PdfReader reader = PdfReader(BytesIO(content)) return "\n".join(page.extract_text() or "" for page in reader.pages) def is_pdf(content: bytes) -> bool: return content[:4] == b"%PDF" def is_html(document: str) -> bool: return "` block holding less than this is a heading, not a release. Some ETA # pages from 2012 put "News Release" in a `
` and the report itself in
# ordinary markup; trusting the block because it exists returns two words.
MIN_PRE_CHARS = 400


def text_body(document: str) -> str:
    """The release text, whether it arrived as HTML or as a plain .txt file."""

    if not is_html(document):
        return document
    body = pre_text(document)
    if len(body.strip()) >= MIN_PRE_CHARS:
        return body
    # Releases with no `
` at all: strip tags and keep the line structure.
    stripped = re.sub(r"(?is)<(script|style)[^>]*>.*?", " ", document)
    stripped = re.sub(r"(?is)", "\n", stripped)
    stripped = re.sub(r"(?is)", "\n", stripped)
    return html_module.unescape(TAG.sub(" ", stripped))


# ---------------------------------------------------------------------------
# The other shape: a table drawn with spaces.


def _spans(text: str, offset: int = 0) -> list[tuple[int, int, str]]:
    return [
        (match.start() + offset, match.end() + offset, match.group(0))
        for match in re.finditer(r"\S+", text)
    ]


def _columns(rows: list[list[tuple[int, int, str]]]) -> list[tuple[int, int]]:
    """Column ranges inferred from where the numbers actually sit.

    The header of a fixed-width table is drawn across as many lines as the
    labels need -- `Un-` / `adjusted` / `12-mos.` / `ended` / `Aug.` / `2010`
    is one column over six lines -- so the columns cannot be read from it. The
    data rows are regular, and every one of them has its figures in the same
    places, so they define the grid and the header is fitted to it afterwards.
    """

    groups: list[list[tuple[int, int]]] = []
    for row in rows:
        for start, end, _ in row:
            for group in groups:
                if any(start < g_end and end > g_start for g_start, g_end in group):
                    group.append((start, end))
                    break
            else:
                groups.append([(start, end)])
    ranges = sorted((min(s for s, _ in g), max(e for _, e in g)) for g in groups)
    # Two groups that grew into each other are one column.
    merged: list[tuple[int, int]] = []
    for start, end in ranges:
        if merged and start < merged[-1][1]:
            merged[-1] = (merged[-1][0], max(merged[-1][1], end))
        else:
            merged.append((start, end))
    return merged


def _place(spans: list[tuple[int, int, str]], columns: list[tuple[int, int]]) -> list[str]:
    cells = [""] * (len(columns) + 1)
    for start, end, text in spans:
        overlaps = [
            (min(end, c_end) - max(start, c_start), index)
            for index, (c_start, c_end) in enumerate(columns)
            if start < c_end and end > c_start
        ]
        if not overlaps:
            continue
        _, index = max(overlaps)
        cells[index + 1] = f"{cells[index + 1]} {text}".strip()
    return cells


def fixed_width_table(block: str, *, caption: str = "") -> Table:
    """Read a table drawn with spaces and dot leaders.

    Rows are recognised by their dot leader, which every agency that publishes
    this way uses, and a label that wrapped onto the line above is joined back
    on -- `All items less food and` / `energy...........` is one row, and
    dropping the first half would leave the core CPI unfindable.
    """

    lines = block.split("\n")
    data_indices = [index for index, line in enumerate(lines) if DOT_LEADER.search(line)]
    if not data_indices:
        return Table(caption=caption, header=[], rows=[])

    rows: list[tuple[str, list[tuple[int, int, str]]]] = []
    consumed: set[int] = set()
    for index in data_indices:
        line = lines[index]
        leader = DOT_LEADER.search(line)
        assert leader is not None
        label = line[: leader.start()].strip()
        # A label too long for its column wraps upward, onto lines that carry
        # no figures of their own.
        above = index - 1
        prefix: list[str] = []
        while (
            above >= 0
            and above not in consumed
            and above not in data_indices
            and lines[above].strip()
            and not re.search(r"\d", lines[above])
        ):
            prefix.insert(0, lines[above].strip())
            consumed.add(above)
            above -= 1
        if prefix:
            label = " ".join([*prefix, label]).strip()
        rows.append((label, _spans(line[leader.end():], offset=leader.end())))

    columns = _columns([spans for _, spans in rows])
    # The title line is not a column header. Everything else above the data is
    # kept, including the line that carries the row-label heading and the month
    # names together -- dropping that line by its indentation also dropped the
    # months, and left a JOLTS table whose columns were labelled only by year.
    header_lines = [
        line
        for index, line in enumerate(lines[: data_indices[0]])
        if index not in consumed and line.strip() and not TABLE_TITLE_LINE.match(line)
    ]
    header = [_place(_spans(line), columns) for line in header_lines]
    header = [row for row in header if any(cell for cell in row[1:])]
    body = [[label, *_place(spans, columns)[1:]] for label, spans in rows]
    return Table(caption=caption, header=header, rows=body)


def sections(text: str, pattern: str) -> list[tuple[str, str]]:
    """Split release text into (heading, body) at every line matching `pattern`.

    Tables in a text release are separated by their own titles and nothing
    else, so the title line is the only reliable boundary.
    """

    compiled = re.compile(pattern)
    lines = text.split("\n")
    starts = [index for index, line in enumerate(lines) if compiled.search(line)]
    found = []
    for position, start in enumerate(starts):
        end = starts[position + 1] if position + 1 < len(starts) else len(lines)
        found.append((lines[start].strip(), "\n".join(lines[start:end])))
    return found


__all__ = [
    "Table",
    "clean",
    "fixed_width_table",
    "html_tables",
    "is_html",
    "is_pdf",
    "normalise_period",
    "pdf_text",
    "pre_text",
    "row_key",
    "sections",
    "text_body",
    "to_number",
]