"""Architecture contracts K1-K7 and K9 (K8 is in test_k8_route_policy.py). Normative text: docs/CONTRACTS.md.

Ratchet: today's violations are recorded in baseline.json; a NEW violation fails the test, and a violation that disappeared must be
removed from the baseline (``python -m tests.architecture.measure --write-baseline``), so it cannot come back. Deliberate exceptions
live in exceptions.json with a written reason. Set contracts compare exact violation strings; count contracts compare per-file counts.
"""
import ast
import pytest

from tests.architecture import measure, model, scan
from tests.architecture.ratchet import diff

BASELINE = measure.load(measure.BASELINE)
EXCEPTIONS = measure.load(measure.EXCEPTIONS)

DESCRIPTION = {
    'K1': 'layer direction (no upward import) and no import cycles between areas',
    'K2': 'Website <-> CRM imports only through declared ports',
    'K3': 'every table is written only by its declared write interface',
    'K4': 'no direct SQL in the web layer (routes, blueprints, middleware)',
    'K5': 'process environment is read only by the configuration modules',
    'K6': 'no use of _private names of other modules',
    'K7': 'production code does not import compatibility aliases',
}


@pytest.fixture(scope='module')
def observed():
    return measure.measure()


@pytest.fixture(scope='module')
def effective(observed):
    return measure.apply_exceptions(observed, EXCEPTIONS)


@pytest.mark.parametrize('contract', sorted(DESCRIPTION))
def test_ratchet(contract, effective):
    new, stale = diff(effective[contract], BASELINE.get(contract, {} if contract in measure.COUNT_CONTRACTS else []))
    shown = lambda items: (list(items.items()) if isinstance(items, dict) else items)[:25]
    assert not new, (f'{contract} ({DESCRIPTION[contract]}): NEW violations (fix them, or add a justified entry to '
                     f'tests/architecture/exceptions.json): {shown(new)}')
    assert not stale, (f'{contract} ({DESCRIPTION[contract]}): the baseline lists violations that are gone - remove them with '
                       f'`python -m tests.architecture.measure --write-baseline` so they cannot return: {shown(stale)}')


# ------------------------------------------------------------------------------------------------ the ratchet itself
def test_ratchet_diff_set_semantics():
    assert diff({'a', 'b'}, {'a'}) == (['b'], [])
    assert diff({'a'}, {'a', 'b'}) == ([], ['b'])
    assert diff(set(), set()) == ([], [])


def test_ratchet_diff_count_semantics():
    assert diff({'f': 3}, {'f': 2}) == ({'f': (2, 3)}, {})
    assert diff({'f': 1}, {'f': 2}) == ({}, {'f': (2, 1)})
    assert diff({'g': 1}, {}) == ({'g': (0, 1)}, {})
    assert diff({}, {'f': 2}) == ({}, {'f': (2, 0)})
    assert diff({'f': 2}, {'f': 2}) == ({}, {})


def test_exceptions_are_applied_before_comparison():
    raw = {'K5': {'a.py': 5, 'b.py': 2}, 'K7': ['x -> y', 'p -> q']}
    ex = {'exceptions': [{'contract': 'K5', 'key': 'a.py', 'max': 5, 'reason': 'r'}, {'contract': 'K7', 'key': 'p -> q', 'reason': 'r'}]}
    assert measure.apply_exceptions(raw, ex) == {'K5': {'b.py': 2}, 'K7': ['x -> y']}
    ex['exceptions'][0]['max'] = 3
    assert measure.apply_exceptions(raw, ex)['K5'] == {'a.py': 2, 'b.py': 2}


# ------------------------------------------------------------------------------------------------ the scan covers all the code
def test_every_application_file_is_parsed_by_the_scan_including_bom_files():
    """A file the scan cannot read would silently hide violations (stage-0 defect: 7 BOM files were skipped)."""
    parsed = 0
    for path in scan.files():
        assert scan.tree(path) is not None                         # raises AssertionError when a file cannot be parsed
        parsed += 1
    assert parsed == len(scan.files()) > 200
    bom = [p for p in scan.files() if (scan.REPO / p).read_bytes().startswith(b'\xef\xbb\xbf')]
    assert all(len(scan.tree(p).body) > 0 for p in bom), 'a BOM file produced an empty AST'


# ------------------------------------------------------------------------------------------------ the model is complete and honest
def test_every_module_is_mapped_to_a_layer():
    assert measure.unmapped_modules() == [], 'new modules must be assigned a layer in tests/architecture/model.py (LAYERS)'


def test_layer_map_has_no_dead_entries():
    mods = scan.modules()
    dead = [p for p in model.LAYERS if not any(m == p or m.startswith(p + '.') for m in mods)]
    assert not dead, f'LAYERS entries that match no module: {dead}'


def test_declared_ports_are_real_and_documented():
    assert model.PORTS, 'the Website<->CRM ports must be declared'
    for (src, dst), port in model.PORTS.items():
        assert src in scan.modules() and dst in scan.modules(), (src, dst)
        assert measure.family(src) != measure.family(dst), f'{src} -> {dst} is not a Website<->CRM crossing'
        assert len(port['reason']) >= 30, f'port {src} -> {dst} needs a reason'
        if '*' not in port['names']:
            top = {n.name for n in scan.tree(scan.modules()[dst]).body if isinstance(n, (ast.FunctionDef, ast.ClassDef))}
            top |= {t.id for n in scan.tree(scan.modules()[dst]).body if isinstance(n, ast.Assign) for t in n.targets if isinstance(t, ast.Name)}
            assert port['names'] <= top, f'port names {port["names"] - top} do not exist in {dst}'
        used = {(m, name) for m, p in scan.modules().items() if m == src for d, name, _l, _z in scan.imports(p) if d == dst}
        assert used, f'port {src} -> {dst} is declared but no longer used: remove it'


def test_owner_modules_exist_and_have_reasons_for_transitional_status():
    for table, owner in model.OWNERS.items():
        assert table == table.lower(), f'table names are lower-case: {table}'
        missing = [m for m in owner['modules'] if m not in scan.modules()]
        assert not missing, f'{table}: owner modules do not exist: {missing}'


def test_k3_every_multi_module_write_interface_has_a_coordinator_inside_it():
    multi = {t for t, owner in model.OWNERS.items() if len(owner['modules']) > 1}
    assert multi == set(model.COORDINATORS), f'tables with a multi-module write interface need exactly one coordinator: {sorted(multi ^ set(model.COORDINATORS))}'
    for table, coordinator in model.COORDINATORS.items():
        assert coordinator in model.OWNERS[table]['modules'], f'{table}: coordinator {coordinator} is not part of its write interface'
        assert coordinator in scan.modules(), coordinator


def test_env_readers_exist():
    missing = [m for m in model.ENV_READERS if m not in scan.modules()]
    assert not missing, f'ENV_READERS lists unknown modules: {missing}'


def test_exceptions_are_justified_live_and_not_double_counted(observed):
    for entry in EXCEPTIONS.get('exceptions', []):
        assert entry['contract'] in model.CONTRACT_IDS, entry
        assert len(entry.get('reason', '')) >= 40, f'exception needs a written reason (>= 40 characters): {entry}'
        value = observed[entry['contract']]
        if isinstance(value, dict):
            assert entry['key'] in value and 1 <= entry['max'] <= value[entry['key']], f'exception no longer matches the code, delete it: {entry}'
            assert entry['key'] not in BASELINE.get(entry['contract'], {}) or True
        else:
            assert entry['key'] in value, f'exception no longer matches the code, delete it: {entry}'
            assert entry['key'] not in BASELINE.get(entry['contract'], []), f'{entry["key"]} is both an exception and in the baseline'


# ------------------------------------------------------------------------------------------------ K7: alias registry
def test_k7_every_alias_is_registered_with_owner_reason_and_removal_criterion():
    prefixes = [r['prefix'] for r in model.ALIAS_REGISTRY]
    assert len(prefixes) == len(set(prefixes))
    for entry in model.ALIAS_REGISTRY:
        assert len(entry.get('owner', '')) >= 3 and len(entry.get('canonical', '')) >= 8, f'alias registry entry {entry["prefix"]} needs owner/canonical'
        for field in ('reason', 'removal'):
            assert len(entry.get(field, '')) >= 20, f'alias registry entry {entry["prefix"]} needs a written {field}'
    uncovered = sorted(m for m in measure.aliases() if not any(m == p or m.startswith(p + '.') for p in prefixes))
    assert not uncovered, f'aliases without a registry entry (add one to model.ALIAS_REGISTRY): {uncovered}'
    unused = [p for p in prefixes if not any(m == p or m.startswith(p + '.') for m in scan.modules())]
    assert not unused, f'registry entries without a module: {unused}'


def test_k7_detected_aliases_lie_under_declared_alias_packages():
    outside = sorted(m for m in scan.alias_modules() if not any(m == p or m.startswith(p + '.') for p in model.ALIAS_PREFIXES))
    assert not outside, f'new alias modules must live under a registered alias package: {outside}'


# ------------------------------------------------------------------------------------------------ K9: export subsystem
def test_k9_the_export_engine_imports_nothing_from_the_rest_of_the_project():
    offenders = []
    for module, path in scan.modules().items():
        if module == model.ENGINE_PACKAGE or module.startswith(model.ENGINE_PACKAGE + '.'):
            offenders += [f'{module} -> {dst}' for dst, _n, _l, _z in scan.imports(path)
                          if dst != model.ENGINE_PACKAGE and not dst.startswith(model.ENGINE_PACKAGE + '.')]
    assert not offenders, f'the export engine must stay a pure generator, no project imports outside it: {offenders}'


def test_k9_the_export_engine_has_no_web_or_transport_dependency():
    offenders = []
    for module, path in scan.modules().items():
        if module == model.ENGINE_PACKAGE or module.startswith(model.ENGINE_PACKAGE + '.'):
            bad = scan.third_party_imports(path) & model.ENGINE_FORBIDDEN_THIRD_PARTY
            offenders += [f'{module}: {name}' for name in sorted(bad)]
    assert not offenders, f'forbidden imports in the export engine: {offenders}'


def test_k9_only_the_transport_module_opens_ftp_connections():
    users = {m for m, p in scan.modules().items() if {'ftplib', 'paramiko'} & scan.third_party_imports(p)}
    assert users <= model.FTP_ALLOWED_MODULES, f'FTP/SFTP clients are confined to {model.FTP_ALLOWED_MODULES}, found: {sorted(users)}'


def test_k9_the_existing_export_contract_tests_are_still_there():
    missing = [t for t in model.K9_EXISTING_TESTS if not (scan.REPO / t).is_file()]
    assert not missing, f'export contract tests listed in docs/CONTRACTS.md (K9) are missing: {missing}'
