import importlib.util
from pathlib import Path
import unittest


SCRIPT = Path(__file__).parents[1] / "scripts" / "compose_preflight.py"
SPEC = importlib.util.spec_from_file_location("compose_preflight", SCRIPT)
assert SPEC and SPEC.loader
MODULE = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(MODULE)


class ComposePreflightTests(unittest.TestCase):
    def test_valid_raw_public_service(self):
        document = {
            "services": {
                "web": {
                    "image": "example/web:1",
                    "networks": ["public"],
                    "labels": {
                        "traefik.enable": "true",
                        "traefik.http.services.web.loadbalancer.server.port": "3000",
                    },
                }
            },
            "networks": {"public": {"name": "coolify", "external": True}},
        }
        self.assertEqual(MODULE.analyze(document, "raw", "coolify", Path.cwd()), [])

    def test_raw_requires_public_network(self):
        findings = MODULE.analyze({"services": {}}, "raw", "coolify", Path.cwd())
        self.assertIn("PUBLIC_NETWORK_MISSING", {item["code"] for item in findings})

    def test_managed_rejects_repository_custom_network(self):
        document = {"services": {}, "networks": {"public": {"name": "coolify"}}}
        findings = MODULE.analyze(document, "managed", "coolify", Path.cwd())
        self.assertIn("MANAGED_CUSTOM_NETWORK", {item["code"] for item in findings})


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