"""JSONL (JSON Lines) sink implementation."""

import json
from datetime import datetime
from pathlib import Path
from zoneinfo import ZoneInfo

from quarry.transforms.base import Frame


class JSONLSink:
    """JSONL file sink with timezone-aware timestamp paths."""

    def __init__(self, path_template: str, timezone: str = "America/New_York"):
        self.path_template = path_template
        self.timezone = timezone

    def write(self, df: Frame, job: str) -> str:
        """Write DataFrame to JSONL file."""
        if df.empty:
            raise ValueError("Cannot write empty DataFrame")

        # Expand path template with timezone-aware timestamp
        try:
            tz = ZoneInfo(self.timezone)
        except Exception:
            tz = ZoneInfo("America/New_York")  # Fallback

        now = datetime.now(tz)
        path_str = now.strftime(self.path_template)
        path_str = path_str.replace("{job}", job)

        output_path = Path(path_str)
        output_path.parent.mkdir(parents=True, exist_ok=True)

        # Write JSONL
        with open(output_path, "w", encoding="utf-8") as f:
            for _, row in df.iterrows():
                json.dump(row.to_dict(), f, default=str)
                f.write("\n")

        return str(output_path)
