#!/usr/bin/env python3
from __future__ import annotations

import importlib.util
import json
import tempfile
import unittest
from pathlib import Path

HERE = Path(__file__).resolve().parent
SCRIPT = HERE.parent / "remote/phase2-server.py"
spec = importlib.util.spec_from_file_location("phase2_server", SCRIPT)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)


class ServerHelperTests(unittest.TestCase):
    def make_root(self, root: Path) -> None:
        base = root / "etc/rancher/k3s/overdeck"
        base.mkdir(parents=True)
        control = {
            "schema_version": 2,
            "api": {"endpoint": "https://100.101.104.41:6443", "cacerts_sha256": "1" * 64},
        }
        lock = {
            "schema_version": 2,
            "version": "v1.36.3+k3s1",
            "launcher": {"invocation_path": "/usr/local/bin/k3s", "sha256": "2" * 64},
        }
        (base / "control-plane.json").write_text(json.dumps(control))
        (base / "version-lock.json").write_text(json.dumps(lock))

    def test_fixture_contract_inspection(self):
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp)
            self.make_root(root)
            payload = module.inspect(root)
            self.assertEqual(payload["status"], "ok")
            self.assertTrue(payload["launcher_digest_verified"])
            self.assertEqual(payload["mutation_surface"], "none")

    def test_contract_symlink_is_rejected(self):
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp)
            self.make_root(root)
            target = root / "etc/rancher/k3s/overdeck/control-plane.json"
            target.unlink()
            target.symlink_to("version-lock.json")
            with self.assertRaises(module.InspectError):
                module.inspect(root)

    def test_cli_has_no_mutation_command(self):
        with self.assertRaises(SystemExit):
            module.parser().parse_args(["create-token"])


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