"""SVG exporter for vector output.

Note: This exports the LAST frame as a static SVG, not an animation.
For animated SVG, consider using CSS animations or SMIL.
"""
from pathlib import Path
import base64
from io import BytesIO

from .base import BaseExporter, register_exporter
from ..config import TapeConfig


@register_exporter
class SVGExporter(BaseExporter):
    """Export the last frame as SVG.

    Embeds the rasterized frame as a base64 data URI within an SVG.
    This provides vector scaling at the container level while
    preserving the terminal rendering.

    For true vector SVG with text elements, consider using a
    specialized terminal-to-SVG tool.
    """

    format_name = "SVG"
    extensions = ["svg"]
    requires_ffmpeg = False

    def export(self, output_path: Path) -> Path:
        """Export last frame as SVG with embedded image."""
        self.validate()

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

        # Get the last frame
        frame = self.frames[-1]
        if frame.mode != "RGB":
            frame = frame.convert("RGB")

        width, height = frame.size

        # Convert to base64 PNG
        buffer = BytesIO()
        frame.save(buffer, format="PNG", optimize=True)
        b64_data = base64.b64encode(buffer.getvalue()).decode("utf-8")

        # Create SVG with embedded image
        svg_content = f'''<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     width="{width}" height="{height}"
     viewBox="0 0 {width} {height}">
  <title>{self.config.title}</title>
  <desc>Generated by termgif</desc>
  <image width="{width}" height="{height}"
         xlink:href="data:image/png;base64,{b64_data}"/>
</svg>
'''

        output_path.write_text(svg_content)
        return output_path
