"""
ResultSet — lightweight wrapper around API response data.

Provides .to_pandas(), .to_polars(), .to_parquet(), .to_csv(), .to_json()
without forcing any dependency. Raw data always accessible via .data
"""

from typing import Any, Dict, List, Optional


class ResultSet:
    """
    A collection of result rows from the GrandJury API.

    Usage:
        results = gj.results(model="my-model")
        print(results)              # ResultSet(12 rows)
        print(len(results))         # 12
        print(results[0])           # first row as dict
        for row in results:         # iterate
            print(row)

        df = results.to_pandas()
        df_pl = results.to_polars()
        results.to_parquet("output.parquet")
        results.to_csv("output.csv")
        results.to_json("output.json")
    """

    def __init__(self, data: List[Dict[str, Any]]):
        self.data = data

    def __len__(self) -> int:
        return len(self.data)

    def __repr__(self) -> str:
        return f"ResultSet({len(self.data)} rows)"

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

    def __getitem__(self, idx):
        return self.data[idx]

    def __bool__(self) -> bool:
        return len(self.data) > 0

    def to_pandas(self):
        """Convert to pandas DataFrame. Requires: pip install pandas"""
        try:
            import pandas as pd
        except ImportError:
            raise ImportError("pandas is required: pip install grandjury[pandas]")
        return pd.DataFrame(self.data)

    def to_polars(self):
        """Convert to polars DataFrame. Requires: pip install polars"""
        try:
            import polars as pl
        except ImportError:
            raise ImportError("polars is required: pip install grandjury[polars]")
        return pl.DataFrame(self.data)

    def to_parquet(self, path: str) -> None:
        """Export to Parquet file. Requires: pip install pyarrow or pandas"""
        try:
            import pyarrow as pa
            import pyarrow.parquet as pq
            table = pa.Table.from_pylist(self.data)
            pq.write_table(table, path)
            return
        except ImportError:
            pass
        try:
            self.to_pandas().to_parquet(path, index=False)
            return
        except ImportError:
            raise ImportError("pyarrow or pandas required: pip install grandjury[parquet]")

    def to_csv(self, path: str) -> None:
        """Export to CSV file. Requires: pip install pandas (or uses csv stdlib)."""
        try:
            self.to_pandas().to_csv(path, index=False)
            return
        except ImportError:
            pass
        # Fallback: stdlib csv
        import csv
        if not self.data:
            return
        with open(path, "w", newline="") as f:
            writer = csv.DictWriter(f, fieldnames=self.data[0].keys())
            writer.writeheader()
            writer.writerows(self.data)

    def to_json(self, path: Optional[str] = None) -> Optional[str]:
        """Export to JSON. If path given, writes file. Otherwise returns string."""
        import json
        out = json.dumps(self.data, indent=2, default=str)
        if path:
            with open(path, "w") as f:
                f.write(out)
            return None
        return out
