"""Tests for image discovery from Helm templates."""

from __future__ import annotations

from ilum.core.images import ImageRef, parse_images_from_yaml


class TestParseImages:
    def test_parse_single_image(self) -> None:
        yaml_text = """\
apiVersion: apps/v1
kind: Deployment
spec:
  template:
    spec:
      containers:
        - name: core
          image: docker.io/ilum/ilum-core:6.7.0
"""
        images = parse_images_from_yaml(yaml_text)
        assert len(images) == 1
        assert images[0].reference == "docker.io/ilum/ilum-core:6.7.0"

    def test_parse_multiple_images_deduplicates(self) -> None:
        yaml_text = """\
---
apiVersion: apps/v1
kind: Deployment
spec:
  template:
    spec:
      containers:
        - image: docker.io/ilum/ilum-core:6.7.0
        - image: docker.io/ilum/ilum-ui:6.7.0
---
apiVersion: apps/v1
kind: Deployment
spec:
  template:
    spec:
      containers:
        - image: docker.io/ilum/ilum-core:6.7.0
"""
        images = parse_images_from_yaml(yaml_text)
        refs = [i.reference for i in images]
        assert len(refs) == 2
        assert "docker.io/ilum/ilum-core:6.7.0" in refs
        assert "docker.io/ilum/ilum-ui:6.7.0" in refs

    def test_parse_image_with_digest(self) -> None:
        yaml_text = "          image: registry.io/app@sha256:abc123\n"
        images = parse_images_from_yaml(yaml_text)
        assert len(images) == 1
        assert "sha256:abc123" in images[0].reference

    def test_parse_no_images(self) -> None:
        yaml_text = "apiVersion: v1\nkind: ConfigMap\n"
        images = parse_images_from_yaml(yaml_text)
        assert images == []

    def test_parse_init_containers(self) -> None:
        yaml_text = """\
spec:
  template:
    spec:
      initContainers:
        - image: busybox:1.36
      containers:
        - image: ilum/core:6.7.0
"""
        images = parse_images_from_yaml(yaml_text)
        refs = [i.reference for i in images]
        assert "busybox:1.36" in refs
        assert "ilum/core:6.7.0" in refs

    def test_image_ref_sanitized_filename(self) -> None:
        ref = ImageRef(reference="docker.io/ilum/ilum-core:6.7.0")
        assert ref.sanitized_filename() == "docker.io_ilum_ilum-core_6.7.0.tar"

    def test_image_ref_sanitized_filename_with_digest(self) -> None:
        ref = ImageRef(reference="registry.io/app@sha256:abc123def456")
        filename = ref.sanitized_filename()
        assert "/" not in filename
        assert filename.endswith(".tar")
