#!/usr/bin/env python3
import hashlib
import json
import os
import subprocess
import tarfile
import tempfile
import unittest
from pathlib import Path


SCRIPT_DIR = Path(__file__).resolve().parent
PLATFORM_ROOT = SCRIPT_DIR.parent.parent
BUILDER = SCRIPT_DIR / "build-external-data-plane-replacement-replay-artifact.mjs"
PATCH_ID = "external-data-plane-replacement-replay-v1-20260721-014"
ENTRY = "platform/services/external-data-plane/src/data-product-delivery.mjs"


class ExternalDataPlaneReplacementReplayArtifactTest(unittest.TestCase):
    def build(self, artifact_dir):
        environment = os.environ.copy()
        environment["NODEDC_DEPLOY_ARTIFACT_DIR"] = str(artifact_dir)
        result = subprocess.run(
            ["node", str(BUILDER), PATCH_ID],
            check=True,
            capture_output=True,
            text=True,
            env=environment,
        )
        return json.loads(result.stdout)

    def test_exact_runtime_slice_is_deterministic(self):
        with tempfile.TemporaryDirectory(prefix="nodedc-edp-replay-artifact-") as directory:
            artifact_dir = Path(directory)
            first = self.build(artifact_dir)
            first_bytes = Path(first["artifact"]).read_bytes()
            second = self.build(artifact_dir)
            second_bytes = Path(second["artifact"]).read_bytes()

            self.assertEqual(first["entries"], [ENTRY])
            self.assertEqual(first["service"], "external-data-plane")
            self.assertEqual(first["database"], "preserved")
            self.assertEqual(first["sha256"], hashlib.sha256(first_bytes).hexdigest())
            self.assertEqual(first["sha256"], second["sha256"])
            self.assertEqual(first_bytes, second_bytes)

            with tarfile.open(first["artifact"], "r:gz") as archive:
                names = archive.getnames()
                manifest = archive.extractfile("manifest.env").read().decode("utf-8")
                files = archive.extractfile("files.txt").read().decode("utf-8")
                payload = archive.extractfile(f"payload/{ENTRY}").read()

            self.assertEqual(manifest, f"id={PATCH_ID}\ncomponent=platform\ntype=app-overlay\n")
            self.assertEqual(files, f"{ENTRY}\n")
            self.assertIn(f"payload/{ENTRY}", names)
            self.assertEqual(
                payload,
                (PLATFORM_ROOT / "services/external-data-plane/src/data-product-delivery.mjs").read_bytes(),
            )
            self.assertFalse(any("/test/" in name or "/node_modules/" in name for name in names))


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