"""SVG export utilities."""

from __future__ import annotations

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

from pathlib import Path  # noqa: E402

from qgis.core import QgsMapRendererCustomPainterJob  # noqa: E402
from qgis.PyQt.QtCore import QCoreApplication, QRectF, QSize  # noqa: E402
from qgis.PyQt.QtGui import QPainter  # noqa: E402
from qgis.PyQt.QtSvg import QSvgGenerator  # noqa: E402

from sec_interp.logger_config import get_logger  # noqa: E402

from .base_exporter import BaseExporter  # noqa: E402

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",
                QCoreApplication.translate("SVGExporter", "Section Interpretation Preview"),
            )
            description = self.get_setting(
                "description",
                QCoreApplication.translate("SVGExporter", "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
                show_legend = self.get_setting("show_legend", True)
                legend_renderer = self.get_setting("legend_renderer")
                if legend_renderer and show_legend:
                    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
