from __future__ import annotations

import json
from pathlib import Path
import tempfile
import unittest

from unuforge.runtime.presets import load_preset, preset_profile_names


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


class RuntimePresetTests(unittest.TestCase):
    def test_loads_v1_fixture(self) -> None:
        preset = load_preset(ROOT / "fixtures" / "presets" / "v1-sample.json")
        self.assertEqual(preset["schema_version"], 1)
        self.assertEqual(preset["project"]["name"], "sample")
        self.assertIn("sample.profile", preset["surface_index"])
        self.assertIn("promote", preset["surface_index"])

    def test_loads_v2_fixture(self) -> None:
        preset = load_preset(ROOT / "fixtures" / "presets" / "v2-sample.json")
        self.assertEqual(preset["schema_version"], 2)
        self.assertEqual(preset_profile_names(preset), ["code-quality.workflow", "sample.profile"])

    def test_duplicate_surface_names_fail(self) -> None:
        with tempfile.TemporaryDirectory() as temp_dir:
            path = Path(temp_dir) / "dup.json"
            path.write_text(
                json.dumps(
                    {
                        "schema_version": 2,
                        "project": {"name": "sample", "manifest": "m.json"},
                        "surfaces": [
                            {
                                "name": "duplicate",
                                "type": "profile",
                                "target": "duplicate",
                                "domain": "testing",
                                "visibility": "human-and-machine",
                            },
                            {
                                "name": "duplicate",
                                "type": "action",
                                "impl": "scripts/run.sh",
                                "domain": "deployment",
                                "visibility": "human-and-machine",
                            },
                        ],
                    }
                ),
                encoding="utf-8",
            )

            with self.assertRaises(ValueError):
                load_preset(path)


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