"""
Text formatters for spreadsheet data (LLM-friendly output).
"""

from .spreadsheet import SpreadsheetMetadata, SheetValues


def format_spreadsheet_metadata(metadata: SpreadsheetMetadata) -> str:
    """Format spreadsheet metadata as text."""
    lines = [
        f"Spreadsheet: {metadata.title}",
        f"ID: {metadata.spreadsheet_id}",
        f"Locale: {metadata.locale or 'N/A'}",
        f"Timezone: {metadata.timezone or 'N/A'}",
        "",
        "Sheets:",
    ]

    for sheet in metadata.sheets:
        lines.append(
            f"  [{sheet.index}] {sheet.title} "
            f"({sheet.row_count} rows x {sheet.column_count} cols)"
        )

    return "\n".join(lines)


def format_sheet_values(values: SheetValues, max_rows: int = 100) -> str:
    """
    Format sheet values as text table.

    Args:
        values: Sheet values
        max_rows: Maximum rows to display
    """
    lines = [
        f"Spreadsheet ID: {values.spreadsheet_id}",
        f"Range: {values.range}",
        f"Size: {values.row_count} rows x {values.column_count} cols",
        "",
    ]

    if not values.values:
        lines.append("(empty)")
        return "\n".join(lines)

    # Display up to max_rows
    display_rows = values.values[:max_rows]

    # Calculate column widths (for basic alignment)
    col_widths = [0] * values.column_count
    for row in display_rows:
        for i, cell in enumerate(row):
            col_widths[i] = max(col_widths[i], len(str(cell)))

    # Format rows
    for row_idx, row in enumerate(display_rows):
        cells = []
        for col_idx, cell in enumerate(row):
            width = col_widths[col_idx] if col_idx < len(col_widths) else 0
            cells.append(str(cell).ljust(width))
        # Pad with empty cells if row is shorter
        while len(cells) < values.column_count:
            width = col_widths[len(cells)] if len(cells) < len(col_widths) else 0
            cells.append("".ljust(width))
        lines.append(" | ".join(cells))

    if values.row_count > max_rows:
        lines.append(f"\n... ({values.row_count - max_rows} more rows)")

    return "\n".join(lines)
