"""CSV/JSON file-based post source for testing and offline runs."""

from __future__ import annotations

import csv
import json
import logging
from collections.abc import Iterator
from pathlib import Path

from agent_samochodowy.ingestor.base import PostSource
from agent_samochodowy.models import Post

logger = logging.getLogger(__name__)


class CsvSource(PostSource):
    """Read posts from a CSV or JSON file."""

    def __init__(self, file_path: str) -> None:
        self.path = Path(file_path)
        if not self.path.exists():
            raise FileNotFoundError(f"Source file not found: {file_path}")

    def fetch_posts(self) -> Iterator[Post]:
        suffix = self.path.suffix.lower()
        if suffix == ".json":
            yield from self._read_json()
        elif suffix in (".csv", ".tsv"):
            yield from self._read_csv()
        else:
            raise ValueError(f"Unsupported file format: {suffix}")

    def _read_json(self) -> Iterator[Post]:
        with self.path.open(encoding="utf-8") as f:
            data = json.load(f)
        items = data if isinstance(data, list) else data.get("posts", data.get("data", []))
        for item in items:
            try:
                yield Post(**item)
            except Exception as e:
                logger.warning("Skipping invalid JSON entry: %s", e)

    def _read_csv(self) -> Iterator[Post]:
        with self.path.open(encoding="utf-8") as f:
            reader = csv.DictReader(f)
            for row in reader:
                try:
                    yield Post(**row)
                except Exception as e:
                    logger.warning("Skipping invalid CSV row: %s", e)
