"""SVG exporter module for vector graphics."""

from pathlib import Path

from qgis.core import QgsMapRendererCustomPainterJob
from qgis.PyQt.QtCore import QRectF, QSize
from qgis.PyQt.QtGui import QPainter
from qgis.PyQt.QtSvg import QSvgGenerator

from sec_interp.logger_config import get_logger

from .base_exporter import BaseExporter


logger = get_logger(__name__)


class SVGExporter(BaseExporter):
    """Exporter for SVG vector format."""

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

    def export(self, output_path: Path, map_settings) -> bool:
        """Export map to SVG.

        Args:
            output_path: Output file path
            map_settings: QgsMapSettings instance configured for rendering

        Returns:
            True if export successful, False otherwise

        """
        try:
            width = self.get_setting("width", 800)
            height = self.get_setting("height", 600)
            title = self.get_setting("title", "Section Interpretation Preview")
            description = self.get_setting("description", "Generated by SecInterp QGIS Plugin")

            # Setup SVG generator
            generator = QSvgGenerator()
            generator.setFileName(str(output_path))
            generator.setSize(QSize(width, height))
            generator.setViewBox(QRectF(0, 0, width, height))
            generator.setTitle(title)
            generator.setDescription(description)

            # Setup painter
            painter = QPainter()
            if not painter.begin(generator):
                return False

            try:
                painter.setRenderHint(QPainter.Antialiasing)

                # Render map
                job = QgsMapRendererCustomPainterJob(map_settings, painter)
                job.start()
                job.waitForFinished()

                # Draw legend if available
                legend_renderer = self.get_setting("legend_renderer")
                if legend_renderer:
                    legend_renderer.draw_legend(painter, QRectF(0, 0, width, height))

                return True

            finally:
                painter.end()

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