from __future__ import annotations

import subprocess
import sys
import tempfile
import unittest
from pathlib import Path

import yaml


DEPLOY_ROOT = Path(__file__).resolve().parents[1]


class RenderValuesTests(unittest.TestCase):
    def test_derives_site_values_and_injects_locked_image_digest(self):
        versions = yaml.safe_load(
            (DEPLOY_ROOT / "versions.lock.yaml").read_text(encoding="utf-8")
        )
        digest = "sha256:" + ("a" * 64)
        versions["images"]["frontend"]["digest"] = digest

        with tempfile.TemporaryDirectory() as directory:
            temp_root = Path(directory)
            versions_path = temp_root / "versions.yaml"
            output_path = temp_root / "values.yaml"
            versions_path.write_text(
                yaml.safe_dump(versions, sort_keys=False),
                encoding="utf-8",
            )
            subprocess.run(
                [
                    sys.executable,
                    str(DEPLOY_ROOT / "scripts/render_helm_values.py"),
                    "--site",
                    str(DEPLOY_ROOT / "config/site.example.yaml"),
                    "--versions",
                    str(versions_path),
                    "--output",
                    str(output_path),
                ],
                check=True,
            )
            values = yaml.safe_load(output_path.read_text(encoding="utf-8"))

        self.assertEqual("cpu-local", values["global"]["runtimeProfile"])
        self.assertEqual("local-path", values["global"]["storageClass"])
        self.assertEqual("100Gi", values["modelStorage"]["capacity"])
        self.assertEqual(digest, values["images"]["frontend"]["digest"])
        self.assertNotIn("digest", values["images"].get("backend", {}))


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