"""CSV export utilities."""

from __future__ import annotations

"""CSV exporter module for tabular data."""

import csv  # noqa: E402
from pathlib import Path  # noqa: E402
from typing import Any  # noqa: E402

from sec_interp.logger_config import get_logger  # noqa: E402

from .base_exporter import BaseExporter  # noqa: E402

logger = get_logger(__name__)


class CSVExporter(BaseExporter):
    """Exporter for CSV tabular format."""

    def get_supported_extensions(self) -> list[str]:
        """Get supported CSV extension."""
        return [".csv"]

    def export(
        self, output_path: Path, data: dict[str, Any], layer_name: str | None = None
    ) -> bool:
        """Export tabular data to CSV.

        Args:
            output_path: Output file path.
            data: A dictionary containing 'headers' (list of strings)
                  and 'rows' (list of tuples or lists).
            layer_name: Optional conceptual name for the layer (ignored for CSV).

        Returns:
            True if export successful, False otherwise

        """
        if not data:
            return False

        try:
            headers = data.get("headers")
            rows = data.get("rows")
            if not headers or not rows:
                return False

            with output_path.open("w", newline="", encoding="utf-8") as f:
                writer = csv.writer(f)
                writer.writerow(headers)
                writer.writerows(rows)

        except Exception:
            logger.exception(f"CSV export failed for {output_path}")
            return False
        else:
            return True
