from typing import List, Any
import csv
import os
from ..core.base import Sink


class CsvSink(Sink):
    def __init__(self, path: str, overwrite: bool = True) -> None:
        self.path = path
        self.overwrite = overwrite
        self._initialized = False
        self._fieldnames: List[str] | None = None

    def _ensure_dir(self) -> None:
        d = os.path.dirname(self.path)
        if d and not os.path.exists(d):
            os.makedirs(d, exist_ok=True)

    def write_batch(self, batch: List[Any]) -> None:
        if not batch:
            return
        self._ensure_dir()
        mode = "w" if self.overwrite and not self._initialized else "a"
        with open(self.path, mode, newline="", encoding="utf-8") as f:
            if isinstance(batch[0], dict):
                if not self._fieldnames:
                    self._fieldnames = list(batch[0].keys())
                writer = csv.DictWriter(f, fieldnames=self._fieldnames)
                if not self._initialized:
                    writer.writeheader()
                    self._initialized = True
                for item in batch:
                    writer.writerow(item)
            else:
                writer = csv.writer(f)
                for item in batch:
                    writer.writerow([item])

    def close(self) -> None:
        pass
