"""Alternative text serializations for TableData — for embedding-optimized RAG."""

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from .schema import TableData


def to_markdown(table: TableData) -> str:
    """Return existing markdown representation (default)."""
    return table.markdown or ""


def to_nl_rows(table: TableData) -> str:
    """Serialize each row as natural language: 'Row 1: Col=Val, Col=Val'."""
    if not table.structured:
        return table.markdown or ""
    headers = table.structured.headers or []
    rows = table.structured.rows or []
    lines: list[str] = []
    for i, row in enumerate(rows, 1):
        if headers:
            pairs = ", ".join(
                f"{h}={v}" for h, v in zip(headers, row, strict=False) if v and str(v).strip()
            )
            lines.append(f"Row {i}: {pairs}" if pairs else f"Row {i}: (empty)")
        else:
            vals = ", ".join(str(v) for v in row if v and str(v).strip())
            lines.append(f"Row {i}: {vals}" if vals else f"Row {i}: (empty)")
    return "\n".join(lines)


def to_nl_columns(table: TableData) -> str:
    """Serialize column-by-column: 'ColName: v1, v2, v3'."""
    if not table.structured:
        return table.markdown or ""
    headers = table.structured.headers or []
    rows = table.structured.rows or []
    if not rows:
        return table.markdown or ""
    lines: list[str] = []
    n_cols = max(len(r) for r in rows) if rows else 0
    for col_idx in range(n_cols):
        header = headers[col_idx] if col_idx < len(headers) else f"Column {col_idx + 1}"
        values = [
            str(row[col_idx])
            for row in rows
            if col_idx < len(row) and row[col_idx] and str(row[col_idx]).strip()
        ]
        if values:
            lines.append(f"{header}: {', '.join(values)}")
    return "\n".join(lines)


def to_hybrid(table: TableData) -> str:
    """NL rows followed by markdown table."""
    nl = to_nl_rows(table)
    md = to_markdown(table)
    if nl and md:
        return f"{nl}\n\n{md}"
    return nl or md


def serialize(table: TableData, mode: str) -> str:
    """Dispatch to the appropriate serializer."""
    if mode == "nl-rows":
        return to_nl_rows(table)
    elif mode == "nl-columns":
        return to_nl_columns(table)
    elif mode == "hybrid":
        return to_hybrid(table)
    return to_markdown(table)  # default: markdown
