"""Rule-based Natural Language Conversion for Excel Table Records.

Converts structured Excel table records (JSON format) into natural language
text using simple "key is value" formatting. No LLM calls required.
"""

from typing import List, Dict, Any

import structlog

logger = structlog.get_logger(__name__)


class RecordToNaturalLanguage:
    """Converts Excel table records to natural language using rule-based formatting.

    Formats each key-value pair as "key is value", one per line,
    prefixed with sheet and row context.

    Example:
        >>> converter = RecordToNaturalLanguage()
        >>> records = [{"Name": "Alice", "Age": "30"}]
        >>> sheets = ["Employees"]
        >>> rows = [5]
        >>> texts = converter.convert_batch(records, sheets, rows)
        >>> print(texts[0])
        In Employees (row 5):
        Name is Alice
        Age is 30
    """

    def __init__(self):
        self.logger = structlog.get_logger(__name__)

    def _convert_single(
        self,
        record: Dict[str, Any],
        sheet: str,
        row: int,
    ) -> str:
        """Convert a single record to natural language.

        Args:
            record: Record content dictionary
            sheet: Sheet name
            row: Row number

        Returns:
            Natural language string
        """
        if not record or all(v is None or v == "" for v in record.values()):
            return ""

        lines = [f"In {sheet} (row {row}):"]
        for key, value in record.items():
            if key.startswith("_"):
                continue
            if value is None or value == "":
                continue
            lines.append(f"{key} is {value}")

        return "\n".join(lines)

    def convert_batch(
        self,
        records: List[Dict[str, Any]],
        sheet_names: List[str],
        row_numbers: List[int],
        batch_size: int = 10,
    ) -> List[str]:
        """Convert a batch of Excel records to natural language.

        Args:
            records: List of record content dictionaries
            sheet_names: Corresponding sheet names for each record
            row_numbers: Corresponding row numbers for each record
            batch_size: Unused (kept for backward compatibility)

        Returns:
            List of natural language strings, one per record, in same order as input

        Raises:
            ValueError: If input lists have mismatched lengths
        """
        if not (len(records) == len(sheet_names) == len(row_numbers)):
            raise ValueError(
                f"Input length mismatch: {len(records)} records, "
                f"{len(sheet_names)} sheets, {len(row_numbers)} rows"
            )

        if not records:
            return []

        results = [
            self._convert_single(record, sheet, row)
            for record, sheet, row in zip(records, sheet_names, row_numbers)
        ]

        self.logger.info(
            "rule_based_conversion_complete",
            total_records=len(records),
            non_empty=sum(1 for r in results if r),
        )

        return results
