"""On-demand catalog replays on the CPU workers: wiring contract."""
import pathlib
import unittest

ROOT = pathlib.Path(__file__).resolve().parent
SESSION = (ROOT / "native" / "lab-game-session.sh").read_text()
SWITCH = (ROOT / "native" / "lab-switch-replay.sh").read_text()
SERVICE = (ROOT / "deploy" / "w3cs-live@.service").read_text()
DEPLOY = (ROOT / "deploy" / "deploy-cpu-server.sh").read_text()
REFRESH = (ROOT / "deploy" / "w3cs-catalog-index.sh").read_text()


class OnDemandWiringTests(unittest.TestCase):
    def test_both_launch_paths_materialize_from_the_cdn_without_aws(self):
        for script in (SESSION, SWITCH):
            self.assertIn('( -n "${W3CS_CATALOG_BUCKET:-}" || -n "${W3CS_CATALOG_BASE_URL:-}" )', script)
            self.assertIn('--base-url "$W3CS_CATALOG_BASE_URL"', script)
            self.assertIn('--bucket "$W3CS_CATALOG_BUCKET"', script)

    def test_seats_point_at_the_r2_mirror(self):
        self.assertIn("Environment=W3CS_CATALOG_INDEX=/home/ubuntu/w3cs-lab/catalog-serving.json", SERVICE)
        self.assertIn("Environment=W3CS_CATALOG_BASE_URL=https://cdn.war3replays.com", SERVICE)
        self.assertNotIn("W3CS_CATALOG_BUCKET", SERVICE)

    def test_index_refresh_is_verified_and_atomic(self):
        self.assertIn('catalog/current.json?t=$(date +%s)', REFRESH)
        self.assertIn('"$key" == catalog/serving-index-$sha256.json', REFRESH)
        self.assertIn("sha256sum", REFRESH)
        self.assertIn('mv -f "$tmp" "$TARGET"', REFRESH)
        self.assertIn("w3cs-catalog-index.timer", DEPLOY)
        self.assertIn("/usr/local/sbin/w3cs-catalog-index.sh || echo", DEPLOY)

    def test_index_refresh_rewrites_rerouted_descriptors(self):
        # A new index that moves a replay to another engine profile (the
        # 1.24a/b re-route) must also update the descriptor the seats read,
        # after the atomic swap and without being able to undo it.
        swap = REFRESH.index('mv -f "$tmp" "$TARGET"')
        refresh = REFRESH.index("--refresh-stale")
        self.assertLess(swap, refresh)
        self.assertIn('--index "$TARGET"', REFRESH)
        self.assertIn('runuser -u "$OWNER"', REFRESH)
        self.assertIn("|| echo \"WARN: stale descriptor refresh failed\"", REFRESH)


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