import logging
from collections.abc import Sequence
from pathlib import Path

from opentelemetry.sdk.trace import ReadableSpan
from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult

logger = logging.getLogger(__name__)


class FileSpanExporter(SpanExporter):
    """Span exporter that writes each span to its own JSON file in a folder."""

    def __init__(self, folder_path: str):
        self.folder_path = Path(folder_path)
        self.folder_path.mkdir(parents=True, exist_ok=True)

    def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
        """Export each span to its own file."""
        try:
            for span in spans:
                trace_id = format(span.context.trace_id, "032x")
                span_id = format(span.context.span_id, "016x")
                filename = f"{trace_id}_{span_id}.json"
                file_path = self.folder_path / filename

                with open(file_path, "w", encoding="utf-8") as f:
                    f.write(span.to_json())

            return SpanExportResult.SUCCESS
        except Exception:
            return SpanExportResult.FAILURE

    def shutdown(self) -> None:
        """Shutdown the exporter."""
