"""Guard against drift between the code and .env.example (the versioned, canonical list of configuration keys).

Every environment variable the application code reads by a literal name (and every key the export executor may read
from .env) must be listed in .env.example - uncommented or as a commented example. The file must not contain real values
for secrets, and must not list keys the code never reads (except the documented compatibility/test-only ones).
"""
import re
from pathlib import Path

REPO = Path(__file__).resolve().parents[1]
READ = re.compile(r"""(?:environ\.get|getenv|environ\[|_int_env|_bool_env|_optional_positive_int_env)\(?\s*['"]([A-Z][A-Z0-9_]{2,})['"]""")
SKIP_DIRS = {'tests', 'node_modules', '.venv', '.git', '__pycache__', 'static', 'InvestmentEnvironment'}
# Read through other means / outside the app, or documented as optional compatibility keys.
NOT_REQUIRED_IN_EXAMPLE = {'PYTHON_DOTENV_DISABLED'}
DOCUMENTED_BUT_UNREAD = {'MAIL_DEFAULT_SENDER', 'INVESTMENT_LEGACY_STORAGE', 'ESTICRM_COMPANY_ID', 'ESTICRM_COMPANY_NAME'}
SECRETS = ('SECRET_KEY', 'MAIL_PASSWORD', 'DB_SHELL_PASSWORD')


def example_keys():
    text = (REPO / '.env.example').read_text(encoding='utf-8')
    return set(re.findall(r'^\s*#?\s*([A-Z][A-Z0-9_]+)=', text, re.M)), text


def code_keys():
    found = set()
    for path in REPO.rglob('*.py'):
        if SKIP_DIRS & set(path.relative_to(REPO).parts):
            continue
        found |= set(READ.findall(path.read_text(encoding='utf-8', errors='ignore')))
    return found - NOT_REQUIRED_IN_EXAMPLE


def test_every_key_read_by_the_code_is_listed_in_env_example():
    listed, _ = example_keys()
    missing = sorted(code_keys() - listed)
    assert not missing, f'.env.example is missing keys the code reads: {missing}'


def test_every_export_executor_key_is_listed_in_env_example():
    from InvestmentManager.integrator import export_transport_config as config
    listed, _ = example_keys()
    missing = sorted(config.ALLOWED_KEYS - listed - {key for key in config.ALLOWED_KEYS if key.endswith('_TIMEOUT')
                                                    and not key.startswith('FTP_GRUNTGURU')})
    assert not missing, f'.env.example is missing export keys: {missing}'


def test_env_example_lists_no_key_the_code_never_reads():
    from InvestmentManager.integrator import export_transport_config as config
    listed, _ = example_keys()
    known = code_keys() | set(config.ALLOWED_KEYS) | DOCUMENTED_BUT_UNREAD | {'DATA_DIR', 'FLASK_ENV', 'SECRET_KEY'}
    unknown = sorted(listed - known)
    assert not unknown, f'.env.example lists keys nothing reads: {unknown}'


def test_env_example_contains_no_real_looking_secrets():
    _, text = example_keys()
    for key in SECRETS:
        line = re.search(rf'^\s*{key}=(.*)$', text, re.M)
        assert line and line.group(1).strip() == '', f'{key} must be empty in .env.example'
    for line in re.findall(r'^\s*(FTP_[A-Z_]*(?:PASSWORD|USERNAME|HOST)|GRUNTGURU_ESTICRM_[A-Z_]+)=(.*)$', text, re.M):
        assert line[1].strip() == '', f'{line[0]} must be empty in .env.example'
    assert 'FLASK_ENV=development' in text and 'FLASK_ENV=production' not in re.sub(r'#.*', '', text)
