"""docs/CONTRACTS.md and docs/ARCHITECTURE.md must describe the model that the tests enforce (no silent drift between text and code)."""
import re

from tests.architecture import model, scan

CONTRACTS = (scan.REPO / 'docs' / 'CONTRACTS.md').read_text(encoding='utf-8')
ARCHITECTURE = (scan.REPO / 'docs' / 'ARCHITECTURE.md').read_text(encoding='utf-8')


def test_every_contract_has_a_section():
    for contract in model.CONTRACT_IDS:
        assert re.search(rf'^### {contract}\.', CONTRACTS, re.M), f'docs/CONTRACTS.md has no section for {contract}'


def test_every_layer_is_described():
    for layer in ('L0', 'L1', 'L2', 'L3', 'L4'):
        assert f'**{layer} ' in CONTRACTS, f'layer {layer} is not described in docs/CONTRACTS.md'


def test_every_port_is_documented():
    for (src, dst), port in model.PORTS.items():
        assert src.split('InvestmentManager.')[-1].split('InvestmentWebsite.')[-1] in CONTRACTS and dst.rsplit('.', 1)[-1] in CONTRACTS, (src, dst)


def test_every_table_owner_is_documented():
    missing = [t for t in model.OWNERS if f'`{t}`' not in CONTRACTS]
    assert not missing, f'tables with an owner but absent from the K3 table in docs/CONTRACTS.md: {missing}'


def test_every_coordinator_and_the_transaction_rules_are_documented():
    assert 'Spójność i transakcje' in CONTRACTS
    for table, coordinator in model.COORDINATORS.items():
        assert f'`{table}`' in CONTRACTS and coordinator.split('InvestmentManager.')[-1] in CONTRACTS, (table, coordinator)


def test_the_unprotected_crm_routes_are_scheduled_for_the_authorization_review():
    assert '39 tras CRM' in CONTRACTS and 'audycie części 2' in CONTRACTS


def test_every_alias_package_is_documented():
    missing = [r['prefix'] for r in model.ALIAS_REGISTRY if r['prefix'].split('.', 1)[-1] not in CONTRACTS]
    assert not missing, f'alias prefixes missing in the K7 table of docs/CONTRACTS.md: {missing}'


def test_every_env_reader_and_k9_test_is_documented():
    for module in model.ENV_READERS:
        assert module.rsplit('.', 1)[-1] in CONTRACTS, f'{module} (K5) is not described in docs/CONTRACTS.md'
    for path in model.K9_EXISTING_TESTS:
        assert path.rsplit('/', 1)[-1].replace('.py', '') in CONTRACTS, f'{path} (K9) is not listed in docs/CONTRACTS.md'


def test_architecture_doc_points_to_the_contracts_and_names_the_crm_as_the_only_export_operator():
    assert 'CONTRACTS.md' in ARCHITECTURE
    assert 'jedynym operatorem eksportów' in ARCHITECTURE
    assert 'wykonuje ręczny transport' not in ARCHITECTURE, 'ARCHITECTURE.md still says that IDBManager performs transport'
    assert 'IDBManager jest osobną aplikacją operatora' not in ARCHITECTURE
