"""Rich table rendering for JoySpace documents — colSpan/rowSpan, auto-merge, column width inference, HTML table parsing."""

from __future__ import annotations

import html
import re
import secrets
import sys
from html.parser import HTMLParser
from pathlib import Path
from typing import Any

_SCRIPT_DIR = str(Path(__file__).resolve().parent.parent)
if _SCRIPT_DIR not in sys.path:
    sys.path.insert(0, _SCRIPT_DIR)

from utils.column_roles import (
    classify_column,
    display_units,
    estimated_text_width,
    longest_display_units,
)

# ---------------------------------------------------------------------------
# Regex constants
# ---------------------------------------------------------------------------

HTML_BREAK_RE = re.compile(r"<br\s*/?>", re.IGNORECASE)
HTML_TAG_RE = re.compile(r"</?[A-Za-z][A-Za-z0-9:-]*(?:\s+[^<>]*)?>")
SUMMARY_LABEL_RE = re.compile(r"^(?:合计|小计|总计|汇总|全国汇总)(?:[（(].*?[）)])?$")
NUMERIC_VALUE_RE = re.compile(
    r"^[+-]?\s*(?:[¥￥]\s*)?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?\s*(?:%|pp|元|人|名|天|/月)?(?:[）)]?)*$",
    re.IGNORECASE,
)
MONEY_LIKE_RE = re.compile(r"^[+-]?\s*[¥￥]\s*\d")
RIGHT_ALIGN_NUMERIC_HINT_RE = re.compile(r"(?:[¥￥]|,|%|pp|元|人|名|天|/月)", re.IGNORECASE)
PLAIN_NUMERIC_VALUE_RE = re.compile(r"^[+-]?\s*(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?(?:[）)]?)*$", re.IGNORECASE)
RESIDUAL_ITALIC_MARKER_RE = re.compile(r"(?<!\*)\*(?!\*)")
COMPACT_VALUE_RE = re.compile(
    r"^[+-]?\s*(?:[¥￥]\s*)?[\d,]+(?:\.\d+)?\s*(?:%|pp|元|人|名|天|/月)?(?:[）)]?)*$",
    re.IGNORECASE,
)
PROSE_HINT_RE = re.compile(r"[，。；、：]|建议|原因|说明|备注|节省|观察|转后|转按量|转包月|折算|按量|包月|假设|口径|策略")


# ---------------------------------------------------------------------------
# Text helpers
# ---------------------------------------------------------------------------


def cleanup_residual_markdown_markers(text: str) -> str:
    without_bold = str(text or "").replace("**", "")
    return RESIDUAL_ITALIC_MARKER_RE.sub("", without_bold)


def normalize_display_text(text: Any) -> str:
    value = html.unescape("" if text is None else str(text))
    value = HTML_BREAK_RE.sub("\n", value)
    value = HTML_TAG_RE.sub("", value)
    value = cleanup_residual_markdown_markers(value)
    lines = [re.sub(r"[ \t]+", " ", line).strip() for line in value.splitlines()]
    return "\n".join(line for line in lines if line).strip()


# ---------------------------------------------------------------------------
# Slate node builders
# ---------------------------------------------------------------------------


def new_id() -> str:
    return secrets.token_urlsafe(5).replace("-", "_")


def text_leaf(text: str, **attrs: Any) -> dict[str, Any]:
    leaf = {"text": str(text)}
    leaf.update({key: value for key, value in attrs.items() if value is not None})
    return leaf


def p(
    text: str = "",
    *,
    bold: bool = False,
    italic: bool = False,
    font_size: int | None = None,
    font_color: str | None = None,
    align: str | None = None,
    header: int | None = None,
) -> dict[str, Any]:
    attrs: dict[str, Any] = {}
    if bold:
        attrs["bold"] = True
    if italic:
        attrs["italic"] = True
    if font_size:
        attrs["fontSize"] = font_size
    if font_color:
        attrs["fontColor"] = font_color
    node: dict[str, Any] = {"type": "p", "id": new_id(), "children": [text_leaf(text, **attrs)]}
    if align:
        node["align"] = align
    if header:
        node["header"] = header
    return node


def status_light(value: str = "neutral") -> dict[str, Any]:
    mapping = {"good": 0, "watch": 1, "risk": 2, "neutral": 1}
    return {"type": "status-light", "id": new_id(), "value": mapping.get(value, 1), "children": [text_leaf("")]}


def _inline_status_paragraph(
    text: str,
    *,
    bold: bool = False,
    font_color: str | None = None,
    align: str | None = None,
) -> dict[str, Any]:
    attrs: dict[str, Any] = {}
    if bold:
        attrs["bold"] = True
    if font_color:
        attrs["fontColor"] = font_color
    children: list[dict[str, Any]] = []
    parts = re.split(r"([🟢🟡🔴])", str(text))
    status_map = {"🟢": "good", "🟡": "watch", "🔴": "risk"}
    for part in parts:
        if not part:
            continue
        if part in status_map:
            children.append(status_light(status_map[part]))
        else:
            children.append(text_leaf(part, **attrs))
    node: dict[str, Any] = {"type": "p", "id": new_id(), "children": children or [text_leaf("", **attrs)]}
    if align:
        node["align"] = align
    return node


# ---------------------------------------------------------------------------
# Table cell / row builders
# ---------------------------------------------------------------------------


def cell(
    children: list[dict[str, Any]] | None = None,
    *,
    col_span: int | None = None,
    row_span: int | None = None,
    hidden: bool = False,
    bg_color: str | None = None,
    border_color: str | None = None,
    vertical_align: str = "middle",
) -> dict[str, Any]:
    node: dict[str, Any] = {
        "type": "table-cell",
        "id": new_id(),
        "verticalAlign": vertical_align,
        "children": children or [p("")],
    }
    if col_span and col_span > 1:
        node["colSpan"] = col_span
    if row_span and row_span > 1:
        node["rowSpan"] = row_span
    if hidden:
        node["hidden"] = True
    if bg_color:
        node["bgColor"] = bg_color
    if border_color:
        node["borderColor"] = border_color
    return node


def row(cells: list[dict[str, Any]]) -> dict[str, Any]:
    return {"type": "table-row", "id": new_id(), "children": cells}


# ---------------------------------------------------------------------------
# Table style presets
# ---------------------------------------------------------------------------

TABLE_STYLE_PRESETS: dict[str, dict[str, Any]] = {
    "plain": {
        "headerBg": "#F5F5F5",
        "headerBorder": "#DEE0E3",
        "bodyBg": None,
        "bodyBorder": "#DEE0E3",
        "headerFontColor": None,
    },
    "executive-red": {
        "headerBg": "#FEF3F3",
        "headerBorder": "#F88E8B",
        "bodyBg": None,
        "bodyBorder": "#DEE0E3",
        "headerFontColor": "#1F2328",
    },
    "success-green": {
        "headerBg": "#F6FFED",
        "headerBorder": "#B7EB8F",
        "bodyBg": None,
        "bodyBorder": "#DEE0E3",
        "headerFontColor": "#1F2328",
    },
    "scorecard-gray": {
        "headerBg": "#F5F5F5",
        "headerBorder": "#BBBFC4",
        "bodyBg": "#F5F5F5",
        "bodyBorder": "#DEE0E3",
        "headerFontColor": "#1F2328",
    },
}


def _style_for_table(table: dict[str, Any]) -> dict[str, Any]:
    style = dict(TABLE_STYLE_PRESETS["plain"])
    preset = str(table.get("stylePreset") or table.get("preset") or "").strip()
    if preset and preset in TABLE_STYLE_PRESETS:
        style.update(TABLE_STYLE_PRESETS[preset])
    raw_style = table.get("style")
    if isinstance(raw_style, dict):
        style.update(raw_style)
    if table.get("colorPolicy"):
        style["colorPolicy"] = table.get("colorPolicy")
    return style


# ---------------------------------------------------------------------------
# Descriptor helpers
# ---------------------------------------------------------------------------


def _column_label(column: Any) -> str:
    if isinstance(column, dict):
        return normalize_display_text(column.get("label") or column.get("name") or column.get("key") or "")
    return normalize_display_text(column)


def _cell_descriptor(value: Any) -> dict[str, Any]:
    if isinstance(value, dict):
        text = value.get("text", value.get("value", value.get("label", "")))
        result = dict(value)
        result["text"] = normalize_display_text(text)
        return result
    return {"text": normalize_display_text(value)}


def _is_numeric_value(text: str) -> bool:
    stripped = normalize_display_text(text).replace(" ", "")
    if not stripped:
        return False
    return bool((MONEY_LIKE_RE.search(stripped) or NUMERIC_VALUE_RE.fullmatch(stripped)) and RIGHT_ALIGN_NUMERIC_HINT_RE.search(stripped))


def _is_plain_numeric_value(text: str) -> bool:
    stripped = normalize_display_text(text).replace(" ", "")
    if not stripped or RIGHT_ALIGN_NUMERIC_HINT_RE.search(stripped):
        return False
    return bool(PLAIN_NUMERIC_VALUE_RE.fullmatch(stripped))


def _should_right_align_value(text: str, role: str) -> bool:
    if _is_numeric_value(text):
        return True
    if role in {"metric", "mixed-value"} and _is_plain_numeric_value(text):
        return True
    return False


def _is_summary_row(values: list[Any]) -> bool:
    texts = [str(_cell_descriptor(value).get("text", "")).strip() for value in values]
    first = next((text for text in texts if text), "")
    return bool(SUMMARY_LABEL_RE.match(first))


def _first_non_empty_index(values: list[Any]) -> int | None:
    for index, value in enumerate(values):
        if str(_cell_descriptor(value).get("text", "")).strip():
            return index
    return None


def _body_alignment(descriptor: dict[str, Any], role: str, *, is_summary: bool, is_summary_label: bool) -> str | None:
    if descriptor.get("align"):
        return str(descriptor["align"])
    # Auto-align based on column role
    if is_summary_label:
        return None
    if is_summary:
        # Summary values: right-align numeric, left-align labels
        return "right" if role in {"metric", "mixed-value"} else None
    if role == "metric":
        return "right"
    if role in {"status", "rank", "date"}:
        return "center"
    if role == "mixed-value":
        return "right"
    # dimension, name, long-text → left (no explicit align needed, left is default)
    return None


# ---------------------------------------------------------------------------
# Cell / row rendering
# ---------------------------------------------------------------------------


def _render_table_cell(value: Any, *, default_style: dict[str, Any], header: bool = False) -> list[dict[str, Any]]:
    descriptor = _cell_descriptor(value)
    text = descriptor.get("text", "")
    if descriptor.get("hidden") is True:
        return [cell([p("")], hidden=True)]

    bg_color = descriptor.get("bgColor") or descriptor.get("backgroundColor")
    border_color = descriptor.get("borderColor")
    font_color = descriptor.get("fontColor")
    if not header and not font_color and default_style.get("colorPolicy") == "red-black-green":
        signed = re.search(r"^[+-]\s*\d+(?:\.\d+)?\s*(?:pp|%)?$", str(text).strip(), flags=re.IGNORECASE)
        if signed:
            font_color = "#2EA121" if str(text).strip().startswith("+") else "#D92D20"
            descriptor["bold"] = True
    if header:
        bg_color = bg_color or default_style.get("headerBg")
        border_color = border_color or default_style.get("headerBorder")
        font_color = font_color or default_style.get("headerFontColor")
    else:
        bg_color = bg_color or default_style.get("bodyBg")
        border_color = border_color or default_style.get("bodyBorder")

    children: list[dict[str, Any]]
    if descriptor.get("status"):
        children = [
            {
                "type": "p",
                "id": new_id(),
                "align": descriptor.get("align") or ("center" if header else None),
                "children": [
                    status_light(str(descriptor.get("status"))),
                    text_leaf(
                        (" " + text) if text else "",
                        bold=bool(descriptor.get("bold") or header),
                        italic=bool(descriptor.get("italic")),
                        fontColor=font_color,
                    ),
                ],
            }
        ]
        if children[0].get("align") is None:
            children[0].pop("align", None)
    else:
        if any(marker in str(text) for marker in ("🟢", "🟡", "🔴")):
            children = [
                _inline_status_paragraph(
                    text,
                    bold=bool(descriptor.get("bold") or header),
                    font_color=font_color,
                    align=descriptor.get("align") or ("center" if header else None),
                )
            ]
        else:
            children = [
                p(
                    text,
                    bold=bool(descriptor.get("bold") or header),
                    italic=bool(descriptor.get("italic")),
                    font_color=font_color,
                    align=descriptor.get("align") or ("center" if header else None),
                )
            ]

    rendered = [
        cell(
            children,
            col_span=int(descriptor.get("colSpan", 1) or 1),
            row_span=int(descriptor.get("rowSpan", 1) or 1),
            bg_color=bg_color,
            border_color=border_color,
            vertical_align=str(descriptor.get("verticalAlign") or "middle"),
        )
    ]
    if descriptor.get("addHiddenPlaceholders", True):
        for _ in range(max(0, int(descriptor.get("colSpan", 1) or 1) - 1)):
            rendered.append(cell([p("")], hidden=True))
    return rendered


def _render_table_row(values: list[Any], *, default_style: dict[str, Any], header: bool = False) -> dict[str, Any]:
    cells: list[dict[str, Any]] = []
    for value in values:
        cells.extend(_render_table_cell(value, default_style=default_style, header=header))
    return row(cells)


# ---------------------------------------------------------------------------
# Row normalization & span management
# ---------------------------------------------------------------------------


def _declared_row_width(values: list[Any]) -> int:
    width = 0
    for value in values:
        descriptor = _cell_descriptor(value)
        if descriptor.get("hidden") is True:
            continue
        width += max(1, int(descriptor.get("colSpan", 1) or 1))
    return width


def _trim_active(values: list[int]) -> list[int]:
    while values and values[-1] <= 0:
        values.pop()
    return values


def _advance_rowspans(active: list[int], values: list[Any]) -> list[int]:
    old_active = list(active)
    new_active = [max(value - 1, 0) for value in old_active]
    col = 0
    for value in values:
        descriptor = _cell_descriptor(value)
        if descriptor.get("hidden") is True:
            continue
        while col < len(old_active) and old_active[col] > 0:
            col += 1
        col_span = max(1, int(descriptor.get("colSpan", 1) or 1))
        row_span = max(1, int(descriptor.get("rowSpan", 1) or 1))
        needed = col + col_span
        if needed > len(new_active):
            new_active.extend([0] * (needed - len(new_active)))
        if row_span > 1:
            for index in range(col, needed):
                new_active[index] = max(new_active[index], row_span - 1)
        col = needed
    return _trim_active(new_active)


def _normalize_table_rows(rows: list[list[Any]], width: int) -> list[list[Any]]:
    normalized: list[list[Any]] = []
    active: list[int] = []
    for raw_row in rows[:80]:
        active_slots = sum(1 for value in active[:width] if value > 0)
        available_slots = max(0, width - active_slots)
        row_values = _fit_row_to_declared_width(list(raw_row), available_slots)
        normalized.append(row_values)
        active = _advance_rowspans(active, row_values)
    return normalized


def _fit_row_to_declared_width(raw_row: list[Any], width: int) -> list[Any]:
    if width <= 0:
        return []
    fitted: list[Any] = []
    used = 0
    for value in raw_row:
        descriptor = _cell_descriptor(value)
        if descriptor.get("hidden") is True:
            continue
        span = max(1, int(descriptor.get("colSpan", 1) or 1))
        if used >= width:
            break
        remaining = width - used
        if span > remaining:
            clipped = dict(descriptor)
            clipped["colSpan"] = remaining
            value = clipped
            span = remaining
        fitted.append(value)
        used += span
    gap = width - used
    if gap > 0:
        filler: dict[str, Any] = {"text": ""}
        if gap > 1:
            filler["colSpan"] = gap
        fitted.append(filler)
    return fitted


# ---------------------------------------------------------------------------
# Auto-merge blank group cells
# ---------------------------------------------------------------------------


def _descriptor_with_attrs(value: Any, **attrs: Any) -> dict[str, Any]:
    descriptor = _cell_descriptor(value)
    descriptor.update(attrs)
    return descriptor


def _merge_blank_group_cells(rows: list[list[Any]], columns: list[Any], width: int) -> list[list[Any]]:
    if len(rows) < 3 or width <= 1:
        return rows
    labels = [_column_label(column) for column in columns]
    samples_by_column: list[list[str]] = [[] for _ in range(width)]
    for row_values in rows:
        for index, value in enumerate(row_values[:width]):
            text = str(_cell_descriptor(value).get("text", "")).strip()
            if text:
                samples_by_column[index].append(text)

    candidate_columns: list[int] = []
    for index in range(min(width, 3)):
        label = labels[index] if index < len(labels) else ""
        role = classify_column(label, samples_by_column[index], width).role
        if role in {"dimension", "name", "status"}:
            candidate_columns.append(index)

    merged = [list(row_values) for row_values in rows]
    for column_index in candidate_columns:
        row_index = 0
        while row_index < len(merged):
            if _is_summary_row(merged[row_index]):
                row_index += 1
                continue
            text = str(_cell_descriptor(merged[row_index][column_index]).get("text", "")).strip()
            if not text:
                row_index += 1
                continue
            end = row_index + 1
            while end < len(merged):
                if _is_summary_row(merged[end]):
                    break
                next_text = str(_cell_descriptor(merged[end][column_index]).get("text", "")).strip()
                if next_text:
                    break
                end += 1
            span = end - row_index
            if span >= 2:
                merged[row_index][column_index] = _descriptor_with_attrs(merged[row_index][column_index], rowSpan=span)
                for hidden_index in range(row_index + 1, end):
                    merged[hidden_index][column_index] = _descriptor_with_attrs(merged[hidden_index][column_index], hidden=True)
            row_index = end
    return merged


# ---------------------------------------------------------------------------
# Column width inference
# ---------------------------------------------------------------------------


def _display_units_local(text: str) -> int:
    return display_units(text)


def _text_pixel_width(text: str) -> int:
    return max(56, estimated_text_width(text, cap_units=None))


def _positioned_descriptors(rows: list[list[Any]], width: int):
    active: list[int] = []
    for raw_row in rows[:80]:
        old_active = list(active)
        new_active = [max(value - 1, 0) for value in old_active]
        col = 0
        for value in raw_row:
            descriptor = _cell_descriptor(value)
            if descriptor.get("hidden") is True:
                continue
            while col < len(old_active) and old_active[col] > 0:
                col += 1
            if col >= width:
                break
            col_span = max(1, int(descriptor.get("colSpan", 1) or 1))
            row_span = max(1, int(descriptor.get("rowSpan", 1) or 1))
            col_span = min(col_span, width - col)
            yield col, col_span, descriptor
            needed = col + col_span
            if needed > len(new_active):
                new_active.extend([0] * (needed - len(new_active)))
            if row_span > 1:
                for index in range(col, needed):
                    new_active[index] = max(new_active[index], row_span - 1)
            col = needed
        active = _trim_active(new_active)


def _percentile(values: list[int], ratio: float) -> int:
    cleaned = sorted(int(value) for value in values if int(value) > 0)
    if not cleaned:
        return 0
    if len(cleaned) == 1:
        return cleaned[0]
    ratio = max(0.0, min(1.0, ratio))
    position = (len(cleaned) - 1) * ratio
    lower = int(position)
    upper = min(lower + 1, len(cleaned) - 1)
    if lower == upper:
        return cleaned[lower]
    weight = position - lower
    return int(round(cleaned[lower] * (1 - weight) + cleaned[upper] * weight))


def _ratio(samples: list[str], predicate) -> float:
    non_empty = [sample for sample in samples if str(sample).strip()]
    if not non_empty:
        return 0.0
    return sum(1 for sample in non_empty if predicate(str(sample))) / len(non_empty)


def _has_prose_hint(text: str) -> bool:
    return bool(PROSE_HINT_RE.search(str(text or "")))


def _is_compact_value(text: str) -> bool:
    stripped = normalize_display_text(text).replace(" ", "")
    if not stripped:
        return False
    if any(marker in stripped for marker in ("🟢", "🟡", "🔴", "✔", "✖", "√", "×", "✅", "❌")):
        return display_units(stripped) <= 10
    if COMPACT_VALUE_RE.fullmatch(stripped):
        return True
    return display_units(stripped) <= 8 and not _has_prose_hint(stripped)


def _base_widths(column_count: int) -> tuple[int, int]:
    if column_count >= 14:
        return 48, 62
    if column_count >= 10:
        return 54, 72
    if column_count >= 8:
        return 60, 82
    if column_count >= 5:
        return 68, 94
    return 82, 116


def _preferred_cap(column_count: int, max_units: int, prose_ratio: float, multiline_ratio: float) -> int:
    expandable_text = max_units >= 28 or prose_ratio >= 0.3 or multiline_ratio >= 0.25
    if column_count <= 2:
        return 760 if expandable_text else 480
    if column_count <= 4:
        return 620 if expandable_text else 380
    if column_count <= 7:
        return 360 if expandable_text else 260
    if column_count <= 10:
        return 260 if expandable_text else 190
    if column_count <= 13:
        return 220 if expandable_text else 170
    return 180 if expandable_text else 140


def _maximum_cap(column_count: int, max_units: int, prose_ratio: float, multiline_ratio: float, compact_ratio: float) -> int:
    expandable_text = max_units >= 28 or prose_ratio >= 0.3 or multiline_ratio >= 0.25
    if compact_ratio >= 0.72 and max_units <= 18 and prose_ratio < 0.2:
        if column_count >= 10:
            return 150
        if column_count >= 8:
            return 160
        if column_count >= 5:
            return 180
        return 220
    if column_count <= 2:
        return 920 if expandable_text else 560
    if column_count <= 4:
        return 760 if expandable_text else 460
    if column_count <= 7:
        return 460 if expandable_text else 320
    if column_count <= 10:
        return 320 if expandable_text else 230
    if column_count <= 13:
        return 260 if expandable_text else 190
    return 220 if expandable_text else 160


def _floor_width(
    *,
    base_floor: int,
    header_width: int,
    body_median: int,
    preferred: int,
    max_units: int,
    column_count: int,
    compact_ratio: float,
) -> int:
    floor = max(base_floor, int(round(max(header_width * 0.62, body_median * 0.68))))
    if max_units >= 30 and column_count <= 4:
        floor = max(floor, min(280, int(round(preferred * 0.55))))
    if compact_ratio >= 0.72 and max_units <= 18:
        floor = min(floor, max(base_floor, int(round(preferred * 0.76))))
    return max(base_floor, min(preferred, floor))


def _grow_weight(
    *,
    max_units: int,
    prose_ratio: float,
    multiline_ratio: float,
    compact_ratio: float,
    room: int,
    column_count: int,
) -> float:
    if room <= 0:
        return 0.0
    weight = 0.14
    if max_units >= 18:
        weight += min(1.2, (max_units - 16) / 28)
    weight += prose_ratio * 1.2
    weight += multiline_ratio * 0.6
    if compact_ratio >= 0.72 and max_units <= 18 and prose_ratio < 0.2:
        weight *= 0.22
    if column_count >= 8:
        weight *= 0.82
    if column_count >= 12:
        weight *= 0.58
    return round(max(0.0, min(2.4, weight)), 3)


def _shrink_weight(
    *,
    max_units: int,
    prose_ratio: float,
    multiline_ratio: float,
    compact_ratio: float,
) -> float:
    weight = 0.42 + min(1.05, max_units / 36)
    weight += prose_ratio * 0.8
    weight += multiline_ratio * 0.4
    if compact_ratio >= 0.72 and max_units <= 18 and prose_ratio < 0.2:
        weight *= 0.55
    return round(max(0.2, min(2.2, weight)), 3)


def _target_fill_ratio(column_count: int, grow_weights: list[float]) -> float:
    meaningful = sum(1 for weight in grow_weights if weight >= 0.18)
    if column_count <= 2:
        return 0.76 if meaningful else 0.0
    if column_count <= 4:
        return 0.80 if meaningful else 0.0
    if column_count <= 7:
        return 0.84
    if column_count <= 10:
        return 0.88
    if column_count <= 13:
        return 0.90 if meaningful >= 2 else 0.0
    return 0.0


def _dynamic_width_target(
    widths: list[int],
    table_budget: int,
    max_widths: list[int],
    grow_weights: list[float],
) -> int:
    preferred_total = sum(widths)
    if preferred_total >= table_budget:
        return table_budget
    max_total = sum(max_widths)
    fill_ratio = _target_fill_ratio(len(widths), grow_weights)
    target = preferred_total
    if fill_ratio > 0:
        target = max(target, int(round(table_budget * fill_ratio)))
    return min(table_budget, max_total, target)


def _scale_widths_to_budget(
    widths: list[int],
    budget: int,
    floors: list[int] | None = None,
    shrink_weights: list[float] | None = None,
) -> list[int]:
    if not widths or sum(widths) <= budget:
        return widths
    floors = list(floors or [])
    floors.extend([0] * (len(widths) - len(floors)))
    minimums = [max(44, min(widths[index], floors[index])) for index in range(len(widths))]
    min_total = sum(minimums)
    if min_total >= budget:
        return minimums
    shrink_weights = list(shrink_weights or [])
    shrink_weights.extend([1.0] * (len(widths) - len(shrink_weights)))
    overflow = sum(widths) - budget
    weighted_total = sum(
        max(0, width - minimum) * max(0.01, shrink_weights[index])
        for index, (width, minimum) in enumerate(zip(widths, minimums))
    )
    if weighted_total <= 0:
        return widths
    scaled = []
    for index, (width, minimum) in enumerate(zip(widths, minimums)):
        flex = max(0, width - minimum)
        reduction = overflow * (flex * max(0.01, shrink_weights[index]) / weighted_total)
        scaled.append(max(minimum, int(round(width - reduction))))
    overflow = sum(scaled) - budget
    while overflow > 0:
        candidates = [
            (index, value - minimums[index])
            for index, value in enumerate(scaled)
            if value > minimums[index]
        ]
        if not candidates:
            break
        index = max(candidates, key=lambda item: item[1])[0]
        scaled[index] -= 1
        overflow -= 1
    return scaled


def _expand_widths_to_target(
    widths: list[int],
    target: int,
    max_widths: list[int],
    grow_weights: list[float] | None = None,
) -> list[int]:
    if not widths or sum(widths) >= target:
        return widths
    grow_weights = list(grow_weights or [])
    grow_weights.extend([0.1] * (len(widths) - len(grow_weights)))
    expanded = list(widths)
    remaining = target - sum(expanded)
    while remaining > 0:
        candidates = [
            (index, max_widths[index] - expanded[index], max(0.0, grow_weights[index]))
            for index in range(len(expanded))
            if index < len(max_widths) and expanded[index] < max_widths[index] and grow_weights[index] > 0
        ]
        if not candidates:
            break
        weighted_total = sum(room * weight for _index, room, weight in candidates)
        if weighted_total <= 0:
            break
        changed = 0
        for index, room, weight in candidates:
            addition = max(1, int(round(remaining * (room * weight / weighted_total))))
            addition = min(addition, room, remaining - changed)
            if addition <= 0:
                continue
            expanded[index] += addition
            changed += addition
            if changed >= remaining:
                break
        if changed <= 0:
            break
        remaining -= changed
    return expanded


def _infer_col_widths(table: dict[str, Any], columns: list[Any], header_rows: list[list[Any]], rows: list[list[Any]], width: int) -> list[int] | None:
    if table.get("autoColWidths") is False or table.get("widthMode") == "none":
        return None
    explicit_widths = table.get("width") if isinstance(table.get("width"), list) else table.get("colWidths")
    raw_widths: list[int] = []
    if isinstance(explicit_widths, list):
        for value in explicit_widths:
            try:
                raw_widths.append(int(float(value)))
            except (TypeError, ValueError):
                continue
        if raw_widths:
            raw_widths = raw_widths[:width]
            raw_widths.extend([96] * (width - len(raw_widths)))
        if raw_widths and (table.get("preserveWidths") is True or table.get("widthMode") == "fixed"):
            return raw_widths

    column_labels = [_column_label(column) for column in columns]
    header_for_widths = list(header_rows)
    if columns:
        header_for_widths.append(columns)

    labels_by_column: list[list[str]] = [[] for _ in range(width)]
    header_candidates: list[list[int]] = [[] for _ in range(width)]
    body_candidates: list[list[int]] = [[] for _ in range(width)]
    samples_by_column: list[list[str]] = [[] for _ in range(width)]
    body_samples_by_column: list[list[str]] = [[] for _ in range(width)]
    for start, span, descriptor in _positioned_descriptors(header_for_widths, width):
        text = str(descriptor.get("text", ""))
        if text:
            share = max(56, int(_text_pixel_width(text) / max(1, span)))
            for index in range(start, start + span):
                labels_by_column[index].append(text)
                header_candidates[index].append(share)
                samples_by_column[index].append(text)

    for start, span, descriptor in _positioned_descriptors(rows, width):
        text = str(descriptor.get("text", ""))
        if not text:
            continue
        share = int(_text_pixel_width(text) / max(1, span))
        if descriptor.get("status"):
            share += 22
        for index in range(start, start + span):
            body_candidates[index].append(share)
            samples_by_column[index].append(text)
            body_samples_by_column[index].append(text)

    widths: list[int] = []
    floor_widths: list[int] = []
    header_widths: list[int] = []
    body_p90_widths: list[int] = []
    max_widths: list[int] = []
    grow_weights: list[float] = []
    shrink_weights: list[float] = []
    diagnostics: list[dict[str, Any]] = []
    for index in range(width):
        label = column_labels[index] if index < len(column_labels) else ""
        header_width = max([_text_pixel_width(label), *header_candidates[index]]) if label or header_candidates[index] else 0
        body_widths = body_candidates[index]
        all_candidates = [candidate for candidate in [header_width, *header_candidates[index], *body_widths] if candidate > 0]
        body_median = _percentile(body_widths, 0.5)
        body_p90 = _percentile(body_widths, 0.9)
        body_max = max(body_widths or [0])
        max_units = max((longest_display_units(sample) for sample in samples_by_column[index]), default=0)
        body_sample_count = len(body_samples_by_column[index])
        compact_ratio = _ratio(body_samples_by_column[index], _is_compact_value)
        prose_ratio = _ratio(body_samples_by_column[index], _has_prose_hint)
        multiline_ratio = _ratio(samples_by_column[index], lambda value: "\n" in value or "\r" in value)
        base_floor, base_default = _base_widths(width)
        preferred_cap = _preferred_cap(width, max_units, prose_ratio, multiline_ratio)
        maximum_cap = _maximum_cap(width, max_units, prose_ratio, multiline_ratio, compact_ratio)
        content_p90 = _percentile(all_candidates, 0.9)
        content_max = max(all_candidates or [base_default])
        preferred_seed = max(base_default, header_width, body_p90, content_p90)
        if body_sample_count <= 3 and body_max:
            preferred_seed = max(preferred_seed, min(body_max, content_p90 + 32))
        preferred = max(base_floor, min(preferred_cap, preferred_seed))
        if raw_widths and index < len(raw_widths):
            preferred = max(preferred, min(maximum_cap, raw_widths[index]))
        maximum = max(preferred, min(maximum_cap, max(content_max, preferred + 36)))
        floor = _floor_width(
            base_floor=base_floor,
            header_width=header_width,
            body_median=body_median,
            preferred=preferred,
            max_units=max_units,
            column_count=width,
            compact_ratio=compact_ratio,
        )
        grow_weight = _grow_weight(
            max_units=max_units,
            prose_ratio=prose_ratio,
            multiline_ratio=multiline_ratio,
            compact_ratio=compact_ratio,
            room=maximum - preferred,
            column_count=width,
        )
        shrink_weight = _shrink_weight(
            max_units=max_units,
            prose_ratio=prose_ratio,
            multiline_ratio=multiline_ratio,
            compact_ratio=compact_ratio,
        )
        widths.append(preferred)
        floor_widths.append(min(preferred, floor))
        header_widths.append(header_width)
        body_p90_widths.append(body_p90)
        max_widths.append(max(maximum, preferred, floor))
        grow_weights.append(grow_weight)
        shrink_weights.append(shrink_weight)

    default_budget = 2060 if width >= 14 else 1600 if width >= 8 else 960
    budget = int(table.get("widthBudget") or table.get("targetWidth") or default_budget)
    if raw_widths:
        budget = max(budget, sum(raw_widths))

    preferred_widths = list(widths)
    target = _dynamic_width_target(widths, budget, max_widths, grow_weights)
    widths = _scale_widths_to_budget(
        widths,
        target,
        floors=floor_widths,
        shrink_weights=shrink_weights,
    )
    widths = _expand_widths_to_target(
        widths,
        target,
        max_widths,
        grow_weights=grow_weights,
    )

    # Adaptive fill: stretch columns proportionally to fill page width
    fill_page = table.get("fillPageWidth") or table.get("adaptiveLayout")
    # Page width: 标宽页面=960, 超宽页面=1360(扣除目录和留白), 或由 table.pageWidth 显式指定
    if table.get("pageWidth"):
        page_width = int(table["pageWidth"])
    elif str(table.get("adaptiveLayout")) == "0":
        page_width = 960  # 标宽页面
    elif width >= 14:
        page_width = 1800
    elif width >= 8:
        page_width = 1360  # 超宽页面(扣除目录~220px和留白)
    else:
        page_width = 960   # 标宽页面
    # Width strategy: content-driven — tables use only the width they need.
    # - Too wide → shrink proportionally to fit page
    # - Reasonably wide (>60% of page) → stretch to fill
    # - Small tables → keep natural content-based widths
    min_col_w = 56
    current_total = sum(widths)

    if current_total > page_width:
        # Table too wide — proportionally shrink to fit
        scale = page_width / current_total
        widths = [max(min_col_w, int(round(w * scale))) for w in widths]
        diff = page_width - sum(widths)
        if diff != 0:
            sorted_indices = sorted(range(len(widths)), key=lambda i: widths[i], reverse=True)
            for i in range(abs(diff)):
                idx = sorted_indices[i % len(sorted_indices)]
                widths[idx] += 1 if diff > 0 else -1
                if widths[idx] < min_col_w:
                    widths[idx] = min_col_w
    elif fill_page is not False and current_total > page_width * 0.6:
        # Table is reasonably wide (>60% of page) — stretch to fill
        scale = page_width / current_total
        filled = [max(min_col_w, int(round(w * scale))) for w in widths]
        diff = page_width - sum(filled)
        if diff != 0:
            sorted_indices = sorted(range(len(filled)), key=lambda i: filled[i], reverse=True)
            for i in range(abs(diff)):
                idx = sorted_indices[i % len(sorted_indices)]
                filled[idx] += 1 if diff > 0 else -1
                if filled[idx] < min_col_w:
                    filled[idx] = min_col_w
        widths = filled
    # else: keep natural content-based widths (small tables stay small)

    for index, final_width in enumerate(widths):
        diagnostics.append(
            {
                "column": index,
                "label": column_labels[index] if index < len(column_labels) else "",
                "floor": floor_widths[index],
                "preferred": preferred_widths[index],
                "max": max_widths[index],
                "final": final_width,
                "headerWidth": header_widths[index],
                "bodyP90": body_p90_widths[index],
                "maxUnits": max((longest_display_units(sample) for sample in samples_by_column[index]), default=0),
                "compactRatio": round(_ratio(body_samples_by_column[index], _is_compact_value), 3),
                "proseRatio": round(_ratio(body_samples_by_column[index], _has_prose_hint), 3),
                "growWeight": grow_weights[index],
                "shrinkWeight": shrink_weights[index],
                "sampleCount": len(samples_by_column[index]) if index < len(samples_by_column) else 0,
                "compressionRatio": round(final_width / max(1, preferred_widths[index]), 3),
            }
        )
    table["_widthDiagnostics"] = {
        "budget": budget,
        "target": target,
        "preferredTotal": sum(preferred_widths),
        "finalTotal": sum(widths),
        "columns": diagnostics,
    }
    return widths


# ---------------------------------------------------------------------------
# Column role classification
# ---------------------------------------------------------------------------


def _column_alignment_labels(columns: list[Any], header_rows: list[list[Any]], width: int) -> list[str]:
    labels_by_column: list[list[str]] = [[] for _ in range(width)]
    for start, span, descriptor in _positioned_descriptors([*header_rows, columns], width):
        text = str(descriptor.get("text", "")).strip()
        if not text:
            continue
        for index in range(start, min(width, start + span)):
            labels_by_column[index].append(text)
    labels: list[str] = []
    for index, labels_for_column in enumerate(labels_by_column):
        deduped = list(dict.fromkeys(labels_for_column))
        fallback = _column_label(columns[index]) if index < len(columns) else ""
        labels.append(" ".join(deduped) or fallback)
    return labels


def _column_roles_for_body(columns: list[Any], header_rows: list[list[Any]], rows: list[list[Any]], width: int) -> list[str]:
    labels = _column_alignment_labels(columns, header_rows, width)
    samples_by_column: list[list[str]] = [[] for _ in range(width)]
    for start, span, descriptor in _positioned_descriptors(rows, width):
        text = str(descriptor.get("text", "")).strip()
        if not text:
            continue
        for index in range(start, min(width, start + span)):
            samples_by_column[index].append(text)
    return [
        classify_column(labels[index] if index < len(labels) else "", samples_by_column[index], width).role
        for index in range(width)
    ]


# ---------------------------------------------------------------------------
# Main table_block entry point
# ---------------------------------------------------------------------------


def table_block(columns: list[Any], rows: list[list[Any]], title: str = "", table: dict[str, Any] | None = None) -> list[dict[str, Any]]:
    """Build a complete Slate table block array with header groups, auto-merge, column width inference."""
    if not columns:
        return []
    table = table or {}
    table_style = _style_for_table(table)
    header_rows = [
        header_row
        for header_row in (table.get("headerRows") or table.get("headerGroups") or [])
        if isinstance(header_row, list)
    ]
    header_width = max((_declared_row_width(header_row) for header_row in header_rows), default=0)
    body_width = max(
        len(columns),
        header_width,
        *(_declared_row_width(raw_row) for raw_row in rows if isinstance(raw_row, list)),
        0,
    )
    normalized_rows = _normalize_table_rows(rows, body_width)
    if table.get("autoMergeGroupCells") is not False:
        normalized_rows = _merge_blank_group_cells(normalized_rows, columns, body_width)
    column_roles = _column_roles_for_body(columns, header_rows, normalized_rows, body_width)

    table_rows = []
    for header_row in header_rows:
        table_rows.append(_render_table_row(header_row, default_style=table_style, header=True))

    column_styles = table.get("columnStyles") if isinstance(table.get("columnStyles"), list) else []
    header_cells: list[Any] = []
    header_cell_count = len(columns) if header_rows else body_width
    for index in range(header_cell_count):
        col = columns[index] if index < len(columns) else f"字段{index + 1}"
        descriptor = _cell_descriptor(col)
        if index < len(column_styles) and isinstance(column_styles[index], dict):
            descriptor = {**column_styles[index], **descriptor}
        header_cells.append(descriptor)
    if not table.get("suppressColumnHeader"):
        table_rows.append(_render_table_row(header_cells, default_style=table_style, header=True))

    row_styles = table.get("rowStyles") if isinstance(table.get("rowStyles"), list) else []
    for data_row_index, row_values in enumerate(normalized_rows):
        styled_values: list[Any] = []
        is_summary = _is_summary_row(row_values)
        summary_label_index = _first_non_empty_index(row_values) if is_summary else None
        for col_index, value in enumerate(row_values):
            descriptor = _cell_descriptor(value)
            if col_index < len(column_styles) and isinstance(column_styles[col_index], dict):
                descriptor = {**column_styles[col_index], **descriptor}
            if data_row_index < len(row_styles) and isinstance(row_styles[data_row_index], dict):
                descriptor = {**row_styles[data_row_index], **descriptor}
            if is_summary:
                descriptor.setdefault("bold", True)
                descriptor.setdefault("bgColor", "#F8FAFC")
                descriptor.setdefault("borderColor", "#D7DEE8")
            role = column_roles[col_index] if col_index < len(column_roles) else "dimension"
            alignment = _body_alignment(
                descriptor,
                role,
                is_summary=is_summary,
                is_summary_label=summary_label_index == col_index,
            )
            if alignment:
                descriptor["align"] = alignment
            styled_values.append(descriptor)
        table_rows.append(_render_table_row(styled_values, default_style=table_style, header=False))

    blocks: list[dict[str, Any]] = []
    if title:
        blocks.append(p(title, bold=True, font_size=18))
    table_node: dict[str, Any] = {"type": "table", "id": new_id(), "children": table_rows}
    col_widths = _infer_col_widths(table, columns, header_rows, normalized_rows, body_width)
    if col_widths:
        table_node["colWidths"] = col_widths
        table_node["width"] = col_widths
        if isinstance(table.get("_widthDiagnostics"), dict):
            table_node["widthDiagnostics"] = table["_widthDiagnostics"]
    blocks.append(table_node)
    return blocks


# ---------------------------------------------------------------------------
# HTML table parser
# ---------------------------------------------------------------------------


class _HTMLTableParser(HTMLParser):
    """SAX-style parser that extracts table structure with colspan/rowspan."""

    def __init__(self):
        super().__init__()
        self.rows: list[list[dict]] = []
        self._current_row: list[dict] | None = None
        self._current_cell: dict | None = None
        self._cell_text_parts: list[str] = []
        self._in_table = False
        self._table_depth = 0
        self._in_thead = False

    def handle_starttag(self, tag, attrs):
        tag_lower = tag.lower()
        attr_dict = dict(attrs)

        if tag_lower == "table":
            self._table_depth += 1
            if self._table_depth == 1:
                self._in_table = True
            return

        if not self._in_table:
            return

        if tag_lower == "thead":
            self._in_thead = True
        elif tag_lower == "tr":
            self._current_row = []
        elif tag_lower in ("td", "th"):
            if self._current_row is None:
                self._current_row = []
            cell: dict[str, Any] = {
                "text": "",
                "header": tag_lower == "th" or self._in_thead,
            }
            colspan = attr_dict.get("colspan")
            if colspan:
                try:
                    cell["colSpan"] = int(colspan)
                except (ValueError, TypeError):
                    pass
            rowspan = attr_dict.get("rowspan")
            if rowspan:
                try:
                    cell["rowSpan"] = int(rowspan)
                except (ValueError, TypeError):
                    pass
            style = attr_dict.get("style", "")
            bg_match = re.search(r"background-color:\s*([^;]+)", style, re.I)
            if bg_match:
                cell["bgColor"] = bg_match.group(1).strip()
            align_match = re.search(r"text-align:\s*([^;]+)", style, re.I)
            if align_match:
                cell["align"] = align_match.group(1).strip()
            bold_attr = attr_dict.get("bold")
            if bold_attr and bold_attr.lower() in ("true", "1"):
                cell["bold"] = True
            self._current_cell = cell
            self._cell_text_parts = []

    def handle_endtag(self, tag):
        tag_lower = tag.lower()

        if tag_lower == "table":
            self._table_depth -= 1
            if self._table_depth == 0:
                self._in_table = False
            return

        if not self._in_table:
            return

        if tag_lower == "thead":
            self._in_thead = False
        elif tag_lower == "tr":
            if self._current_row is not None:
                self.rows.append(self._current_row)
            self._current_row = None
        elif tag_lower in ("td", "th"):
            if self._current_cell is not None:
                self._current_cell["text"] = "".join(self._cell_text_parts).strip()
                self._current_row.append(self._current_cell)
            self._current_cell = None
            self._cell_text_parts = []

    def handle_data(self, data):
        if self._current_cell is not None:
            self._cell_text_parts.append(data)

    def handle_entityref(self, name):
        if self._current_cell is not None:
            self._cell_text_parts.append(html.unescape(f"&{name};"))

    def handle_charref(self, name):
        if self._current_cell is not None:
            self._cell_text_parts.append(html.unescape(f"&#{name};"))


def parse_html_table(html_text: str) -> list[list[dict]]:
    """Parse an HTML <table> string into a structured grid with colSpan/rowSpan descriptors.

    Returns a list of rows, where each row is a list of cell dicts with keys:
    'text', 'colSpan', 'rowSpan', 'header' (bool if <th>), 'bgColor', 'align', etc.
    """
    parser = _HTMLTableParser()
    parser.feed(html_text)
    return parser.rows


def html_table_to_slate(
    html_text: str,
    *,
    style_preset: str = "plain",
    color_policy: str = "neutral",
    auto_col_widths: bool = True,
    auto_merge: bool = False,
    style_overrides: dict[str, Any] | None = None,
) -> list[dict]:
    """Convert an HTML <table> string directly to a Slate table block array.

    Convenience function combining parse_html_table() + table_block().

    Args:
        style_overrides: dict to override table style attributes (applied on top
            of the preset). Supported keys: headerBg, headerBorder, bodyBg,
            bodyBorder, headerFontColor. Example:
            {"headerBg": "#F5F5F5", "headerBorder": "#DEE0E3"}
    """
    rows = parse_html_table(html_text)
    if not rows:
        return []

    # Separate header rows from body rows
    header_rows_raw: list[list[dict]] = []
    body_rows: list[list[dict]] = []
    for row_cells in rows:
        if any(cell.get("header") for cell in row_cells):
            header_rows_raw.append(row_cells)
        else:
            body_rows.append(row_cells)

    # If no explicit body rows, treat all rows as body
    if not body_rows and header_rows_raw:
        body_rows = header_rows_raw
        header_rows_raw = []

    # Build columns from first header row or first body row
    # When multiple header rows exist, all go into headerRows (with colSpan/rowSpan),
    # and columns are derived from the widest row for column count.
    if header_rows_raw:
        widest_row = max(header_rows_raw, key=lambda r: sum(c.get("colSpan", 1) for c in r))
        columns = [cell.get("text", f"字段{i + 1}") for i, cell in enumerate(widest_row)]
    else:
        columns = [cell.get("text", f"字段{i + 1}") for i, cell in enumerate(body_rows[0])]

    def _cell_to_descriptor(cell_info: dict, *, is_header: bool = False) -> dict[str, Any]:
        desc: dict[str, Any] = {"text": cell_info.get("text", "")}
        if is_header:
            desc["header"] = True
        if cell_info.get("colSpan") and cell_info["colSpan"] > 1:
            desc["colSpan"] = cell_info["colSpan"]
        if cell_info.get("rowSpan") and cell_info["rowSpan"] > 1:
            desc["rowSpan"] = cell_info["rowSpan"]
        if cell_info.get("bgColor"):
            desc["bgColor"] = cell_info["bgColor"]
        if cell_info.get("align"):
            desc["align"] = cell_info["align"]
        if cell_info.get("bold"):
            desc["bold"] = True
        return desc

    # Convert body row cells to descriptors
    body_descriptors = []
    for row_cells in body_rows:
        body_descriptors.append([_cell_to_descriptor(cell) for cell in row_cells])

    # Convert all header rows to headerGroups descriptors (preserving colSpan/rowSpan)
    header_groups: list[list[dict]] = []
    for header_row in header_rows_raw:
        header_groups.append([_cell_to_descriptor(cell, is_header=True) for cell in header_row])

    table_meta: dict[str, Any] = {
        "stylePreset": style_preset,
        "colorPolicy": color_policy,
        "autoColWidths": auto_col_widths,
        "autoMergeGroupCells": auto_merge,
    }
    if style_overrides:
        table_meta["style"] = dict(style_overrides)
    if header_groups:
        table_meta["headerRows"] = header_groups
        # Suppress the default column header row when HTML headers are present
        table_meta["suppressColumnHeader"] = True

    return table_block(columns, body_descriptors, table=table_meta)
