"""K8: the access policy of every route is frozen in route_policy.json (derived from the real application).

The snapshot reproduces the CURRENT policy exactly; it changes nothing. A route that is added/removed, or whose decorators, access-level
literals, guard calls or blueprint gate change, fails this test until the new policy has been reviewed and the snapshot is rewritten
deliberately:  ARCH_WRITE_ROUTE_POLICY=1 python -m pytest tests/architecture/test_k8_route_policy.py -s
(the new snapshot is printed between <<<ROUTE_POLICY_SNAPSHOT ... ROUTE_POLICY_SNAPSHOT>>>; review it and save it as route_policy.json).
"""
import json
import os
from pathlib import Path

import pytest

from tests.architecture import route_policy

SNAPSHOT = Path(__file__).with_name('route_policy.json')


@pytest.fixture
def current(app):
    return route_policy.snapshot(app)


def test_route_policy_snapshot_matches_the_application(current):
    if os.environ.get('ARCH_WRITE_ROUTE_POLICY') == '1':
        # Tests may not write into the checkout: the new snapshot is printed (run with -s) between markers for review and copying.
        print('<<<ROUTE_POLICY_SNAPSHOT\n' + json.dumps(current, indent=1, sort_keys=True) + '\nROUTE_POLICY_SNAPSHOT>>>')
        pytest.skip('new snapshot printed on stdout (run with -s): review it, then save it as tests/architecture/route_policy.json')
    assert SNAPSHOT.is_file(), 'route_policy.json is missing (create it with ARCH_WRITE_ROUTE_POLICY=1)'
    stored = json.loads(SNAPSHOT.read_text(encoding='utf-8'))
    problems = route_policy.compare(current, stored)
    assert not problems, 'K8 route policy drift:\n  ' + '\n  '.join(problems[:20])


def test_every_crm_route_is_covered_by_the_login_gate(current):
    gate = [name for key, names in current['gates'].items() if key == 'before_request:investmentmanager' for name in names]
    assert any('require_crm_session' in name for name in gate), 'the CRM blueprint lost its login gate (before_request)'
    crm = [key for key, entry in current['routes'].items() if entry['endpoint'].startswith('investmentmanager.')]
    assert len(crm) > 100, 'unexpectedly few CRM routes in the snapshot'
