"""Exercise the access checks embedded in the deploy script without connecting to a server."""
from __future__ import annotations

from contextlib import redirect_stdout
import io
import itertools
import json
import os
from pathlib import Path
import re
import shlex
import sys
from types import ModuleType
import unittest
from unittest.mock import patch


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


class DeployAccessProfileTests(unittest.TestCase):
    @classmethod
    def setUpClass(cls) -> None:
        cls.script = (ROOT / "scripts/deploy-release.ps1").read_text(encoding="utf-8")
        staging = re.search(
            r'"\$venv_release/bin/python" - "\$access_profile" <<\'PY\'\n(.*?)\nPY\n',
            cls.script, re.DOTALL,
        )
        if staging is None:
            raise AssertionError("The staged access-profile check is missing")
        cls.staging_code = compile(staging.group(1), "deploy-staged-access", "exec")
        public_checks = [
            match.group(1)
            for match in re.finditer(r"^\s*'([^'\n]+)'\s*\\$", cls.script, re.MULTILINE)
            if 'data.get("revision")' in match.group(1)
        ]
        if len(public_checks) != 1:
            raise AssertionError("Expected one public revision/access-profile check")
        cls.public_code = compile(public_checks[0], "deploy-public-access", "exec")

    def run_staging(self, profile, auth, public, docs) -> None:
        app = ModuleType("app")
        app.__path__ = []
        main = ModuleType("app.main")
        main.AUTH_REQUIRED, main.DOCS_ENABLED = auth, docs
        routes = ModuleType("app.calculation_routes")
        routes.PUBLIC_CALCULATION_JOBS_ENABLED = public
        environment = dict(os.environ)
        with (
            patch.dict(sys.modules, {"app": app, "app.main": main, "app.calculation_routes": routes}),
            patch.object(sys, "argv", ["-", profile]),
            redirect_stdout(io.StringIO()) as output,
        ):
            try:
                exec(self.staging_code, {"__name__": "__main__"})
            finally:
                self.assertEqual(dict(os.environ), environment)
        self.assertIn("staged access policy ok", output.getvalue())

    def public_exit_code(self, profile, payload, revision="R2.28"):
        with (
            patch.object(sys, "argv", ["-c", revision, profile]),
            patch.object(sys, "stdin", io.StringIO(json.dumps(payload))),
            self.assertRaises(SystemExit) as stopped,
        ):
            exec(self.public_code, {"__name__": "__main__"})
        return stopped.exception.code

    def test_production_is_the_validated_default_profile(self) -> None:
        self.assertRegex(
            self.script,
            r'\[ValidateSet\("Production", "Development"\)\]\s*'
            r'\[string\]\$AccessProfile = "Production"',
        )
        self.assertRegex(
            self.script,
            r'case "\$access_profile" in\s*Production\|Development\) ;;\s*'
            r'\*\).*?exit 1 ;;\s*esac',
        )

    def test_staging_accepts_only_the_exact_boolean_policy_for_each_profile(self) -> None:
        for profile in ("Production", "Development"):
            expected = (profile == "Production", profile != "Production", False)
            for values in itertools.product((False, True), repeat=3):
                with self.subTest(profile=profile, values=values):
                    if values == expected:
                        self.run_staging(profile, *values)
                    else:
                        with self.assertRaises(RuntimeError):
                            self.run_staging(profile, *values)

    def test_staging_rejects_non_boolean_policy_values(self) -> None:
        for profile in ("Production", "Development"):
            for position, invalid in itertools.product(range(3), (None, 0, 1, "false", "true")):
                values = [profile == "Production", profile != "Production", False]
                values[position] = invalid
                with self.subTest(profile=profile, position=position, invalid=invalid):
                    with self.assertRaises(RuntimeError):
                        self.run_staging(profile, *values)

    def test_remote_environment_is_copied_to_staging_and_not_swapped(self) -> None:
        environment_installs = [
            shlex.split(line)
            for line in self.script.splitlines()
            if line.startswith("install ") and ".env" in line
        ]
        self.assertEqual(environment_installs, [["install", "-m", "600", ".env", "$stage/.env"]])
        deploy_items = re.search(r"deploy_items=\(\n(.*?)\n\)", self.script, re.DOTALL)
        self.assertIsNotNone(deploy_items)
        self.assertNotIn(".env", shlex.split(deploy_items.group(1)))
        self.assertNotRegex(self.script, r"(?m)^\s*(?:sed|tee|cp|mv|rm)\b[^\n]*[\s\"/]\.env(?:[\s\"]|$)")

    def test_public_check_requires_matching_revision_and_exact_boolean_policy(self) -> None:
        for profile in ("Production", "Development"):
            expected = (profile == "Production", profile != "Production", False)
            for values in itertools.product((False, True), repeat=3):
                payload = dict(zip(("auth_required", "public_calculation_jobs_enabled", "docs_enabled"), values))
                payload["revision"] = "R2.28"
                with self.subTest(profile=profile, values=values):
                    self.assertEqual(self.public_exit_code(profile, payload), 0 if values == expected else 1)
            payload.update(zip(("auth_required", "public_calculation_jobs_enabled", "docs_enabled"), expected))
            with self.subTest(profile=profile, stale_revision=True):
                self.assertEqual(self.public_exit_code(profile, payload, revision="R2.29"), 1)

    def test_public_check_rejects_missing_or_non_boolean_fields(self) -> None:
        keys = ("auth_required", "public_calculation_jobs_enabled", "docs_enabled")
        for profile in ("Production", "Development"):
            for key in keys:
                payload = dict(zip(keys, (profile == "Production", profile != "Production", False)))
                payload["revision"] = "R2.28"
                for invalid in (None, 0, 1, "false", "true"):
                    payload[key] = invalid
                    with self.subTest(profile=profile, field=key, invalid=invalid):
                        self.assertEqual(self.public_exit_code(profile, payload), 1)
                payload.pop(key)
                with self.subTest(profile=profile, missing=key):
                    self.assertEqual(self.public_exit_code(profile, payload), 1)


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