"""The parent composite freezes helper paths before a nested action changes its context."""
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest

import yaml

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


class ManifestPathScopeTests(unittest.TestCase):
    def test_real_transport_step_captures_parent_paths_without_exporting_a_job_hook(self):
        action = yaml.safe_load((ROOT / "android-action/flutter-setup/action.yml").read_text())
        guard = action["runs"]["steps"][0]
        with tempfile.TemporaryDirectory(prefix="manifest parent ") as directory:
            root = Path(directory)
            parent = root / "parent/flutter-setup"
            scripts = parent.parent / "scripts"
            parent.mkdir(parents=True); scripts.mkdir()
            names = ("flutter_manifest.py", "flutter_download.py", "flutter_manifest_env.sh")
            for name in names:
                shutil.copyfile(ROOT / "android-action/scripts" / name, scripts / name)
            env_file, output = root / "env", root / "output"
            env = {**os.environ, "GITHUB_ACTION_PATH": str(parent), "GITHUB_ENV": str(env_file),
                   "GITHUB_OUTPUT": str(output), "RUNNER_TEMP": str(root)}
            result = subprocess.run(["bash", "-e", "-o", "pipefail", "-c", guard["run"]], env=env,
                                    capture_output=True, text=True, timeout=10)
            self.assertEqual((result.returncode, result.stdout, result.stderr), (0, "", ""))
            paths = dict(line.split("=", 1) for line in output.read_text().splitlines())
            self.assertEqual(Path(paths["manifest_env"]).resolve(), (scripts / "flutter_manifest_env.sh").resolve())
            self.assertEqual(Path(paths["manifest_helper"]).resolve(), (scripts / "flutter_manifest.py").resolve())
            # The step publishes helper paths on its own outputs only. It must add nothing
            # to the job environment, so $GITHUB_ENV stays empty — or absent entirely.
            exported = env_file.read_text() if env_file.exists() else ""
            self.assertNotIn("BASH_ENV", exported)
            self.assertNotIn("GOWALK_FLUTTER_MANIFEST_HELPER", exported)
            self.assertNotIn("PROXY", exported.upper())


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