"""
Row — mirrors pyspark.sql.Row.

Behaves as both a namedtuple (positional access) and a dict (named access).
"""
from __future__ import annotations


class Row(dict):
    """
    A row in a Spark DataFrame — dict with attribute-style access.

    Compatible with pyspark.sql.Row in common usage patterns:
        row = Row(name="Alice", age=30)
        row.name   # "Alice"
        row["age"] # 30
        row[0]     # first value
    """

    def __init__(self, *args, **kwargs):
        if args and not kwargs:
            # Called as Row("Alice", 30) without field names — store positionally
            super().__init__(enumerate(args))
            self._fields = None
        else:
            super().__init__(kwargs)
            self._fields = list(kwargs.keys())

    # ------------------------------------------------------------------
    # Attribute access
    # ------------------------------------------------------------------

    def __getattr__(self, name: str):
        try:
            return self[name]
        except KeyError:
            raise AttributeError(f"Row has no field '{name}'")

    def __setattr__(self, name: str, value):
        if name.startswith("_"):
            object.__setattr__(self, name, value)
        else:
            self[name] = value

    # ------------------------------------------------------------------
    # Positional access (like a namedtuple)
    # ------------------------------------------------------------------

    def __getitem__(self, key):
        if isinstance(key, int):
            values = list(self.values())
            return values[key]
        return super().__getitem__(key)

    # ------------------------------------------------------------------
    # Iteration yields values (like a tuple) for unpacking
    # ------------------------------------------------------------------

    def __iter__(self):
        return iter(self.values())

    def __len__(self):
        return super().__len__()

    # ------------------------------------------------------------------
    # Representation
    # ------------------------------------------------------------------

    def __repr__(self):
        kv = ", ".join(f"{k}={v!r}" for k, v in super().items())
        return f"Row({kv})"

    # ------------------------------------------------------------------
    # Compatibility helpers
    # ------------------------------------------------------------------

    def asDict(self, recursive: bool = False) -> dict:
        return dict(self)

    @property
    def fields(self) -> list[str]:
        return list(self.keys())


def _rows_from_polars(polars_df) -> list[Row]:
    """Convert a Polars DataFrame to a list of Row objects."""
    return [Row(**record) for record in polars_df.to_dicts()]
