"""Metadata cache selectors cannot freeze moving requests or cross platforms/origins."""
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest

SCRIPT = Path(__file__).with_name("flutter_release_cache.py")


class CacheSelectionTests(unittest.TestCase):
    def prepare(self, root, **changes):
        output = root / "outputs"
        output.write_text("")
        env = {**os.environ, "GITHUB_OUTPUT": str(output), "RUNNER_TEMP": str(root), "RUNNER_OS": "Linux",
               "GOWALK_FLUTTER_VERSION": "3.44.0", "GOWALK_FLUTTER_VERSION_FILE": "",
               "GOWALK_FLUTTER_CHANNEL": "stable", "GOWALK_FLUTTER_ARCHITECTURE": "X64",
               "FLUTTER_STORAGE_BASE_URL": "https://storage.googleapis.com", **changes}
        result = subprocess.run([sys.executable, str(SCRIPT)], env=env, capture_output=True, timeout=10)
        self.assertEqual((result.returncode, result.stdout, result.stderr), (0, b"", b""))
        return dict(line.split("=", 1) for line in output.read_text().splitlines())

    def test_exact_identity_is_stable_and_other_selections_have_separate_keys(self):
        with tempfile.TemporaryDirectory() as directory:
            root = Path(directory)
            first = self.prepare(root)
            self.assertEqual(first, self.prepare(root))
            self.assertEqual(first["enabled"], "true")
            self.assertEqual(json.loads(first["pin"])["architecture"], "x64")
            for change in [{"RUNNER_OS": "macOS"}, {"GOWALK_FLUTTER_ARCHITECTURE": "ARM64"},
                           {"GOWALK_FLUTTER_CHANNEL": "beta"}, {"GOWALK_FLUTTER_VERSION": "3.44.1"},
                           {"FLUTTER_STORAGE_BASE_URL": "https://another.fixture.invalid"}]:
                with self.subTest(change=change):
                    self.assertNotEqual(first["key"], self.prepare(root, **change)["key"])

    def test_moving_or_file_resolved_versions_do_not_enable_metadata_reuse(self):
        with tempfile.TemporaryDirectory() as directory:
            root = Path(directory)
            for change in [{"GOWALK_FLUTTER_VERSION": ""}, {"GOWALK_FLUTTER_VERSION": "3.x"},
                           {"GOWALK_FLUTTER_CHANNEL": "master"},
                           {"GOWALK_FLUTTER_VERSION_FILE": "pubspec.yaml"}]:
                with self.subTest(change=change):
                    self.assertEqual(self.prepare(root, **change), {"enabled": "false"})


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