"""Image discovery from Helm-rendered YAML."""

from __future__ import annotations

import re
from dataclasses import dataclass


@dataclass(frozen=True)
class ImageRef:
    """A container image reference parsed from rendered Helm YAML."""

    reference: str

    def sanitized_filename(self) -> str:
        """Return a filesystem-safe filename for ``docker save`` output."""
        name = self.reference.replace("/", "_").replace(":", "_").replace("@", "_")
        return f"{name}.tar"


# Matches `image: <ref>` lines in rendered YAML (also handles `- image:` list syntax)
_IMAGE_RE = re.compile(r'^\s*-?\s*image:\s*["\']?([^\s"\']+)["\']?\s*$', re.MULTILINE)


def parse_images_from_yaml(yaml_text: str) -> list[ImageRef]:
    """Extract deduplicated container image references from rendered YAML."""
    seen: set[str] = set()
    result: list[ImageRef] = []
    for match in _IMAGE_RE.finditer(yaml_text):
        ref = match.group(1)
        if ref not in seen:
            seen.add(ref)
            result.append(ImageRef(reference=ref))
    return result
