"""Proves the revalidation bypass of legacy tests (tests/conftest.py) does NOT cover the security tests."""
import ast
import inspect
from pathlib import Path

import pytest

from InvestmentManager.middleware import session_guard

HERE = Path(__file__).parent
SECURITY_TEST_FILES = ['test_session_lifecycle.py', 'test_crm_ownership.py', 'test_crm_authorization_policy.py', 'test_csrf_origin_guard.py']
# tests that never log in (pure functions / URL map) and therefore never reach the session guard
NO_SESSION_TESTS = {'test_decision_matrix_for_mutating_requests', 'test_host_comparison_is_case_insensitive_and_port_aware',
                    'test_logout_navigation_rules', 'test_other_get_requests_are_never_blocked_by_the_guard',
                    'test_the_route_map_has_a_realistic_number_of_mutating_routes', 'test_fingerprint_depends_on_the_secret_key_and_the_hash'}


def test_legacy_tests_get_the_bypass(app):
    """No crm_env, no marker: the revalidation is replaced (this is the documented shortcut for hand-planted sessions)."""
    assert session_guard.check_session.__name__ == '<lambda>'


@pytest.mark.crm_session_guard
def test_marker_restores_the_real_guard(app):
    assert inspect.isfunction(session_guard.check_session) and session_guard.check_session.__name__ == 'check_session'


def test_crm_env_restores_the_real_guard(app, crm_env):
    assert session_guard.check_session.__name__ == 'check_session'
    assert session_guard.check_session.__module__ == 'InvestmentManager.middleware.session_guard'


@pytest.mark.parametrize('name', SECURITY_TEST_FILES)
def test_every_session_dependent_security_test_runs_the_real_guard(name):
    tree = ast.parse((HERE / name).read_text(encoding='utf-8'))
    module_marked = any(isinstance(n, ast.Assign) and any(getattr(t, 'id', '') == 'pytestmark' for t in n.targets)
                        and 'crm_session_guard' in ast.dump(n) for n in tree.body)
    offenders = []
    for node in tree.body:
        if isinstance(node, ast.FunctionDef) and node.name.startswith('test_') and node.name not in NO_SESSION_TESTS:
            uses_env = 'crm_env' in {a.arg for a in node.args.args}
            if not (uses_env or module_marked):
                offenders.append(node.name)
    assert not offenders, f'{name}: tests without crm_env / crm_session_guard would silently skip revalidation: {offenders}'
