from __future__ import annotations

import os
import shutil
import subprocess
import unittest
from pathlib import Path

import yaml


DEPLOY_ROOT = Path(__file__).resolve().parents[1]
CHART = DEPLOY_ROOT / "charts" / "trackwalker"
HELM_BINARY = os.environ.get("HELM_BINARY") or shutil.which("helm")


@unittest.skipUnless(HELM_BINARY, "helm is not installed")
class HelmRenderTests(unittest.TestCase):
    def render(self, profile: str) -> list[dict]:
        command = [
            HELM_BINARY or "helm",
            "template",
            "trackwalker",
            str(CHART),
            "--namespace",
            "trackwalker",
            "--values",
            str(CHART / f"values-{profile}.yaml"),
        ]
        completed = subprocess.run(
            command,
            check=True,
            capture_output=True,
            text=True,
            encoding="utf-8",
        )
        return [item for item in yaml.safe_load_all(completed.stdout) if item]

    def test_single_profile_renders_bundled_stateful_services(self):
        documents = self.render("single")
        deployments = {
            item["metadata"]["name"]: item["spec"]["replicas"]
            for item in documents
            if item["kind"] == "Deployment"
        }
        stateful_sets = {
            item["metadata"]["name"]
            for item in documents
            if item["kind"] == "StatefulSet"
        }
        self.assertEqual(1, deployments["backend"])
        self.assertEqual(1, deployments["artifact-installer"])
        self.assertTrue(
            {"postgres", "redis", "kafka", "minio", "prometheus"}.issubset(
                stateful_sets
            )
        )

    def test_ha_profile_excludes_bundled_stateful_services(self):
        documents = self.render("ha")
        self.assertFalse(any(item["kind"] == "StatefulSet" for item in documents))
        deployments = {
            item["metadata"]["name"]: item["spec"]["replicas"]
            for item in documents
            if item["kind"] == "Deployment"
        }
        self.assertEqual(2, deployments["frontend"])
        self.assertEqual(1, deployments["backend"])


if __name__ == "__main__":
    unittest.main()
