import hashlib
import importlib.machinery
import importlib.util
import io
import json
import os
from pathlib import Path
import subprocess
import tarfile
import tempfile
import unittest
from contextlib import redirect_stdout
from unittest import mock


SCRIPT_DIR = Path(__file__).resolve().parent
RUNNER_PATH = SCRIPT_DIR / "nodedc-deploy"
BUILDER_PATH = SCRIPT_DIR / "build-engine-depttrans-zone-authority-v1-artifact.mjs"
ENGINE_ROOT = SCRIPT_DIR.parent.parent.parent / "NODEDC_ENGINE_INFRA"
PATCH_ID = "engine-depttrans-zone-authority-v1-20991231-999"


def load_runner():
    loader = importlib.machinery.SourceFileLoader(
        "nodedc_engine_depttrans_zone_authority_v1",
        str(RUNNER_PATH),
    )
    spec = importlib.util.spec_from_loader(loader.name, loader)
    module = importlib.util.module_from_spec(spec)
    loader.exec_module(module)
    return module


RUNNER = load_runner()


class EngineDepttransZoneAuthorityV1Test(unittest.TestCase):
    def build(self, artifact_dir):
        current_sha256 = {
            relative_path: hashlib.sha256((ENGINE_ROOT / relative_path).read_bytes()).hexdigest()
            for relative_path in RUNNER.ENGINE_DEPTTRANS_ZONE_AUTHORITY_V1_ARTIFACT_ENTRIES
        }
        if current_sha256 != RUNNER.ENGINE_DEPTTRANS_ZONE_AUTHORITY_V1_TARGET_SHA256:
            self.skipTest("historical Depttrans authority source has advanced to its exact successor")
        environment = os.environ.copy()
        environment["NODEDC_ENGINE_SOURCE_ROOT"] = str(ENGINE_ROOT)
        environment["NODEDC_DEPLOY_ARTIFACT_DIR"] = str(artifact_dir)
        completed = subprocess.run(
            ["node", str(BUILDER_PATH), PATCH_ID],
            check=True,
            capture_output=True,
            text=True,
            env=environment,
        )
        return json.loads(completed.stdout)

    def test_builder_is_deterministic_and_emits_exact_backend_only_slice(self):
        with tempfile.TemporaryDirectory(prefix="nodedc-engine-depttrans-authority-") as directory:
            root = Path(directory)
            first = self.build(root / "first")
            second = self.build(root / "second")
            first_artifact = Path(first["artifact"])
            second_artifact = Path(second["artifact"])
            self.assertEqual(first_artifact.read_bytes(), second_artifact.read_bytes())
            self.assertEqual(first["sha256"], hashlib.sha256(first_artifact.read_bytes()).hexdigest())
            self.assertEqual(first["services"], ["nodedc-backend"])
            self.assertEqual(first["authorityBoundary"], "platform-service")
            self.assertEqual(first["platformService"], "nodedc-map-gateway")
            self.assertEqual(
                tuple(first["entries"]),
                RUNNER.ENGINE_DEPTTRANS_ZONE_AUTHORITY_V1_ARTIFACT_ENTRIES,
            )

            extract = root / "extract"
            with tarfile.open(first_artifact, "r:gz") as archive:
                archive.extractall(extract, filter="data")
            entries = tuple((extract / "files.txt").read_text(encoding="utf-8").splitlines())
            payload = extract / "payload"
            self.assertTrue(RUNNER.is_engine_depttrans_zone_authority_v1_slice("engine", entries))
            self.assertEqual(RUNNER.component_services("engine", entries), ("nodedc-backend",))
            self.assertEqual(
                RUNNER.component_healthchecks("engine", entries, ("nodedc-backend",)),
                ("http://127.0.0.1:3001/health",),
            )
            RUNNER.validate_engine_depttrans_zone_authority_v1_slice(payload, entries)

    def test_preflight_requires_every_exact_live_predecessor(self):
        with tempfile.TemporaryDirectory(prefix="nodedc-engine-depttrans-preflight-") as directory:
            root = Path(directory)
            for relative_path in RUNNER.ENGINE_DEPTTRANS_ZONE_AUTHORITY_V1_PREDECESSOR_SHA256:
                path = root / relative_path
                path.parent.mkdir(parents=True, exist_ok=True)
                path.write_text("predecessor\n", encoding="utf-8")

            def exact_sha(path):
                relative_path = Path(path).relative_to(root).as_posix()
                return RUNNER.ENGINE_DEPTTRANS_ZONE_AUTHORITY_V1_PREDECESSOR_SHA256[relative_path]

            with (
                mock.patch.object(RUNNER, "component_root", return_value=root),
                mock.patch.object(RUNNER, "sha256_file", side_effect=exact_sha),
                mock.patch.object(
                    RUNNER,
                    "preflight_engine_credential_backend_runtime",
                    return_value={"mode": "verified-derived-retry"},
                ),
            ):
                result = RUNNER.preflight_engine_depttrans_zone_authority_v1_predecessor()
            self.assertEqual(result["mode"], "exact-platform-service-authority-v1")
            self.assertEqual(
                result["predecessor_sha256"],
                RUNNER.ENGINE_DEPTTRANS_ZONE_AUTHORITY_V1_PREDECESSOR_SHA256,
            )

            with (
                mock.patch.object(RUNNER, "component_root", return_value=root),
                mock.patch.object(RUNNER, "sha256_file", return_value="0" * 64),
            ):
                with self.assertRaises(RUNNER.DeployError):
                    RUNNER.preflight_engine_depttrans_zone_authority_v1_predecessor()

    def test_plan_renders_new_path_as_absent_predecessor(self):
        preflight = {
            "predecessor_sha256": dict(
                RUNNER.ENGINE_DEPTTRANS_ZONE_AUTHORITY_V1_PREDECESSOR_SHA256
            ),
            "target_sha256": dict(
                RUNNER.ENGINE_DEPTTRANS_ZONE_AUTHORITY_V1_TARGET_SHA256
            ),
            "backend_mode": "verified-derived-retry",
        }
        output = io.StringIO()
        with redirect_stdout(output):
            RUNNER.print_engine_depttrans_zone_authority_v1_plan(preflight)
        rendered = output.getvalue()
        new_path = RUNNER.ENGINE_DEPTTRANS_ZONE_AUTHORITY_V1_NEW_PATHS[0]
        self.assertIn(
            f"engine_depttrans_zone_authority_predecessor_state[{new_path}]=absent",
            rendered,
        )
        self.assertNotIn(
            f"engine_depttrans_zone_authority_predecessor_sha256[{new_path}]",
            rendered,
        )
        for changed_path in RUNNER.ENGINE_DEPTTRANS_ZONE_AUTHORITY_V1_ARTIFACT_ENTRIES:
            self.assertIn(
                f"engine_depttrans_zone_authority_target_sha256[{changed_path}]="
                f"{RUNNER.ENGINE_DEPTTRANS_ZONE_AUTHORITY_V1_TARGET_SHA256[changed_path]}",
                rendered,
            )
        self.assertIn("mcp_nginx=untouched", rendered)

    def test_healthchecks_dispatch_exact_live_acceptance(self):
        entries = RUNNER.ENGINE_DEPTTRANS_ZONE_AUTHORITY_V1_ARTIFACT_ENTRIES
        root = Path("/engine")

        def target_sha(path):
            relative_path = Path(path).relative_to(root).as_posix()
            return RUNNER.ENGINE_DEPTTRANS_ZONE_AUTHORITY_V1_TARGET_SHA256[relative_path]

        with (
            mock.patch.object(RUNNER, "component_root", return_value=root),
            mock.patch.object(RUNNER, "sha256_file", side_effect=target_sha),
            mock.patch.object(Path, "is_file", return_value=True),
            mock.patch.object(Path, "is_symlink", return_value=False),
            mock.patch.object(RUNNER, "healthcheck_compose_service"),
            mock.patch.object(RUNNER, "component_healthchecks", return_value=()),
            mock.patch.object(
                RUNNER,
                "preflight_engine_credential_backend_runtime",
                return_value={"mode": "verified-derived-retry"},
            ),
            mock.patch.object(
                RUNNER,
                "accept_engine_depttrans_zone_authority_v1_runtime",
                return_value={"live": "accepted"},
            ) as acceptance,
            mock.patch.object(RUNNER, "healthcheck_container"),
        ):
            RUNNER.run_healthchecks("engine", entries, ("nodedc-backend",))
        acceptance.assert_called_once_with()

    def test_live_acceptance_probes_platform_service_and_fail_closed_drift(self):
        expected_live = (
            "engine-depttrans-zone-authority:platform-service:"
            "map.zones.current.v2:nodedc-map-gateway"
        )
        with (
            mock.patch.object(RUNNER, "component_root", return_value=ENGINE_ROOT),
            mock.patch.object(RUNNER, "validate_engine_depttrans_zone_authority_v1_slice"),
            mock.patch.object(RUNNER, "engine_backend_container_id", return_value="backend"),
            mock.patch.object(
                RUNNER,
                "run_engine_backend_probe",
                return_value=expected_live,
            ) as backend_probe,
        ):
            result = RUNNER.accept_engine_depttrans_zone_authority_v1_runtime()
        self.assertEqual(result["live"], expected_live)
        self.assertEqual(backend_probe.call_args.args[1], "Engine Depttrans zone authority v1")


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