"""Stage 5B-3C: the executor reads FTP/company settings from the application's .env itself (cron never loads it).

Properties: lazy (idle tick never opens the file), allow-listed keys only, nothing is copied into os.environ / logs /
repr, a missing or broken file means "not set" (config_missing), the process environment still wins, and every one of the
five profiles resolves. The .env used here is a synthetic file shaped like production ("KEY = value", duplicates).
"""
import logging
import os

import pytest

from InvestmentManager.integrator import export_control as control
from InvestmentManager.integrator import export_job_runner as runner
from InvestmentManager.integrator import export_jobs as jobs
from InvestmentManager.integrator import export_transport_config as config
from InvestmentManager.integrator import package_delivery as pd
from tests.investmentmanager import qualification_support as support

SECRET = 'S3cr3t-pass-value-XYZ'
PROFILE_PREFIX = {'no': 'FTP_NO', 'domiporta': 'FTP_DOMIPORTA', 'tabelaofert': 'FTP_TABELAOFERT',
                  'tabelaofert_primary': 'FTP_TABELAOFERT_PRIMARY', 'gruntguru': 'FTP_GRUNTGURU'}


def env_text(skip=(), extra=''):
    lines = ['SECRET_KEY = app-secret-not-for-the-executor', 'FTP_OTODOM_HOST = otodom.example', 'FTP_OTODOM_PASSWORD = otodom-pass']
    for profile, prefix in PROFILE_PREFIX.items():
        for name, value in (('HOST', f'{profile}.example.test'), ('PORT', '2121'), ('USERNAME', f'user-{profile}'),
                            ('PASSWORD', f'{SECRET}-{profile}')):
            if f'{prefix}_{name}' not in skip:
                lines.append(f'{prefix}_{name} = {value}')
    lines += ['GRUNTGURU_ESTICRM_COMPANY_ID = 4242', 'GRUNTGURU_ESTICRM_COMPANY_NAME = Firma Testowa']
    return '\n'.join(lines) + '\n' + extra


@pytest.fixture
def dotenv(tmp_path, monkeypatch):
    path = tmp_path / '.env'
    path.write_text(env_text(), encoding='utf-8')
    monkeypatch.setattr(config, 'ENV_FILE', path)
    for key in config.ALLOWED_KEYS:
        monkeypatch.delenv(key, raising=False)
    return path


@pytest.mark.parametrize('profile', sorted(PROFILE_PREFIX))
def test_every_profile_resolves_from_the_env_file_only(dotenv, profile):
    before = dict(os.environ)
    settings = config.load_profile(profile)
    assert (settings.host, settings.port, settings.username) == (f'{profile}.example.test', 2121, f'user-{profile}')
    assert settings.password == f'{SECRET}-{profile}' and settings.timeout_seconds == config.DEFAULT_TIMEOUT
    assert config.profile_status(profile) == {'profile': profile, 'complete': True, 'missing': []}
    assert dict(os.environ) == before                                              # nothing copied to the global environment


def test_tabelaofert_accounts_never_mix(dotenv):
    assert config.load_profile('tabelaofert').username == 'user-tabelaofert'
    assert config.load_profile('tabelaofert_primary').username == 'user-tabelaofert_primary'
    dotenv.write_text(env_text(skip={'FTP_TABELAOFERT_PRIMARY_HOST'}), encoding='utf-8')   # no fallback to the Polish account
    with pytest.raises(config.ConfigError) as error:
        config.load_profile('tabelaofert_primary')
    assert error.value.code == 'config_missing' and error.value.missing == ('FTP_TABELAOFERT_PRIMARY_HOST',)


def test_duplicate_names_resolve_to_the_last_value_like_flask_app(dotenv):
    dotenv.write_text(env_text() + 'FTP_NO_HOST = later.example.test\n', encoding='utf-8')
    assert config.load_profile('no').host == 'later.example.test'


def test_missing_and_blank_keys_report_names_only(dotenv):
    dotenv.write_text(env_text(skip={'FTP_NO_USERNAME', 'FTP_NO_PASSWORD', 'FTP_NO_HOST'}, extra='FTP_NO_HOST =\n'), encoding='utf-8')
    status = config.profile_status('no')
    assert status['complete'] is False and status['missing'] == ['FTP_NO_HOST', 'FTP_NO_USERNAME', 'FTP_NO_PASSWORD']
    with pytest.raises(config.ConfigError) as error:
        config.load_profile('no')
    assert error.value.code == 'config_missing' and SECRET not in repr(error.value) + str(error.value.missing)


@pytest.mark.parametrize('line', ['FTP_NO_PORT = abc', 'FTP_NO_PORT = 0', 'FTP_NO_PORT = 70000', 'FTP_NO_TIMEOUT = x',
                                  'FTP_NO_TIMEOUT = 0', 'FTP_NO_TIMEOUT = 9999'])
def test_invalid_port_or_timeout_is_config_invalid(dotenv, line):
    text = env_text(skip={'FTP_NO_PORT'}) if 'PORT' in line else env_text()
    dotenv.write_text(text + line + '\n', encoding='utf-8')
    with pytest.raises(config.ConfigError) as error:
        config.load_profile('no')
    assert error.value.code == 'config_invalid'


def test_timeout_and_default_port_come_from_the_file(dotenv):
    dotenv.write_text(env_text(skip={'FTP_NO_PORT'}, extra='FTP_NO_TIMEOUT = 7.5\n'), encoding='utf-8')
    settings = config.load_profile('no')
    assert (settings.port, settings.timeout_seconds) == (config.DEFAULT_PORT, 7.5)


def test_only_allowed_keys_are_ever_returned(dotenv, monkeypatch):
    for key in ('SECRET_KEY', 'FTP_OTODOM_HOST', 'NOT_IN_FILE'):
        monkeypatch.delenv(key, raising=False)                                     # only the FILE is under test here
    assert config.environment_getter('SECRET_KEY') is None and config.environment_getter('FTP_OTODOM_HOST') is None
    assert config.environment_getter('FTP_NO_HOST') == 'no.example.test'
    assert config.environment_getter('NOT_IN_FILE') is None
    assert set(config.ALLOWED_KEYS) == {f'{p}_{n}' for p, _, _ in config.PROFILES.values()
                                        for n in ('HOST', 'PORT', 'USERNAME', 'PASSWORD', 'TIMEOUT')} | set(config.COMPANY_KEYS) | set(config.FOREIGN_PACKAGE_KEYS)


def test_process_environment_wins_over_the_file(dotenv, monkeypatch):
    monkeypatch.setenv('FTP_NO_HOST', 'from-env.example.test')
    assert config.load_profile('no').host == 'from-env.example.test'
    monkeypatch.setenv('FTP_NO_HOST', '')                                          # empty variable does not hide the file
    assert config.load_profile('no').host == 'no.example.test'


def _absent(path):
    return None


def _directory(path):
    path.mkdir()


def _binary(path):
    path.write_bytes(b'\xff\xfe\x00\x01 = \x00\n\x80')


def _unterminated(path):
    path.write_text('FTP_NO_HOST "unterminated\n', encoding='utf-8')


@pytest.mark.parametrize('make', [_absent, _directory, _binary, _unterminated])
def test_missing_directory_or_broken_file_means_not_set(tmp_path, monkeypatch, make):
    path = tmp_path / 'absent.env'
    make(path)
    monkeypatch.setattr(config, 'ENV_FILE', path)
    for key in config.ALLOWED_KEYS:
        monkeypatch.delenv(key, raising=False)
    assert config.environment_getter('FTP_NO_HOST') is None
    with pytest.raises(config.ConfigError) as error:
        config.load_profile('no')
    assert error.value.code == 'config_missing'


def test_without_python_dotenv_the_file_is_not_set(dotenv, monkeypatch):
    import builtins
    real = builtins.__import__

    def deny(name, *args, **kwargs):
        if name == 'dotenv':
            raise ImportError(name)
        return real(name, *args, **kwargs)
    monkeypatch.setattr(builtins, '__import__', deny)
    assert config.environment_getter('FTP_NO_HOST') is None


def test_no_secret_in_logs_repr_or_stdout(dotenv, caplog, capsys):
    with caplog.at_level(logging.DEBUG):
        settings = config.load_profile('no')
        status = config.profile_status('no')
        config.company_settings()
    out = capsys.readouterr()
    haystack = caplog.text + out.out + out.err + repr(settings) + str(status)
    assert SECRET not in haystack and 'user-no' not in haystack and 'no.example.test' not in haystack


def test_getter_keeps_nothing_between_calls(dotenv):
    assert config.environment_getter('FTP_NO_HOST') == 'no.example.test'
    dotenv.write_text(env_text().replace('no.example.test', 'changed.example.test'), encoding='utf-8')
    assert config.environment_getter('FTP_NO_HOST') == 'changed.example.test'      # no cache, no stale secret


def test_company_settings_for_package_preparation(dotenv):
    from InvestmentManager.integrator import domestic_packages
    assert config.COMPANY_KEYS == domestic_packages.COMPANY_KEYS
    assert config.company_settings() == {'GRUNTGURU_ESTICRM_COMPANY_ID': '4242', 'GRUNTGURU_ESTICRM_COMPANY_NAME': 'Firma Testowa',
                                         'ESTICRM_COMPANY_ID': None, 'ESTICRM_COMPANY_NAME': None}
    env = pd.default_env()
    assert env.secret_getter('FTP_NO_USERNAME') == 'user-no'
    assert env.settings('foreign') == {'FOREIGN_MEDIA_HOST_PINS': None}


def test_foreign_worker_reads_the_same_allowlisted_media_pins_as_wsgi(dotenv, monkeypatch):
    pins = '{"media.example.invalid":["93.184.216.34"]}'
    dotenv.write_text(env_text() + f'FOREIGN_MEDIA_HOST_PINS={pins}\n', encoding='utf-8')
    monkeypatch.delenv('FOREIGN_MEDIA_HOST_PINS', raising=False)
    assert pd._settings(pd.default_env(), type('ForeignClaim', (), {'domain': 'foreign', 'portal': 'tabelaofert'})()) == {
        'FOREIGN_MEDIA_HOST_PINS': {'media.example.invalid': ['93.184.216.34']}}
    assert config._file_value('SECRET_KEY') is None


class Claim:
    domain = 'domestic'

    def __init__(self, portal):
        self.portal = portal


def test_only_a_gruntguru_job_falls_back_to_the_env_file_for_company_keys(dotenv, monkeypatch):
    env = pd.default_env()
    opened = []
    import dotenv as dotenv_module
    real = dotenv_module.dotenv_values
    monkeypatch.setattr(dotenv_module, 'dotenv_values', lambda *a, **k: opened.append(a) or real(*a, **k))
    for portal in ('no', 'domiporta', 'tabelaofert'):
        settings = pd._settings(env, Claim(portal))
        assert all(value is None for value in settings.values()) and opened == []        # file never opened for them
    settings = pd._settings(env, Claim('gruntguru'))
    assert settings['GRUNTGURU_ESTICRM_COMPANY_ID'] == '4242' and settings['ESTICRM_COMPANY_ID'] is None and opened
    monkeypatch.setenv('GRUNTGURU_ESTICRM_COMPANY_ID', '7')                              # process environment still wins
    assert pd._settings(env, Claim('gruntguru'))['GRUNTGURU_ESTICRM_COMPANY_ID'] == '7'
    custom = pd.Env(settings=lambda domain: {'X': 'y'})                                  # test doubles are untouched
    assert pd._settings(custom, Claim('gruntguru')) == {'X': 'y'}


def test_executor_env_reports_config_missing_without_a_file(tmp_path, monkeypatch):
    monkeypatch.setattr(config, 'ENV_FILE', tmp_path / 'nope.env')
    for key in config.ALLOWED_KEYS:
        monkeypatch.delenv(key, raising=False)
    assert config.missing_keys('tabelaofert', pd.default_env().secret_getter) == [
        'FTP_TABELAOFERT_HOST', 'FTP_TABELAOFERT_USERNAME', 'FTP_TABELAOFERT_PASSWORD']


def test_idle_tick_never_opens_the_env_file(dotenv, tmp_path, monkeypatch):
    root = tmp_path / 'InvestmentData'
    root.mkdir()
    monkeypatch.setenv('DATA_DIR', str(root))
    support.init_root(root)
    opened = []
    import dotenv as dotenv_module
    real = dotenv_module.dotenv_values
    monkeypatch.setattr(dotenv_module, 'dotenv_values', lambda *a, **k: opened.append(a) or real(*a, **k))
    assert runner.tick_one() is None                                              # no schema
    jobs.init_schema(backup=False)
    assert runner.tick_one()['outcome'] == 'idle'                                 # schema, dispatch missing
    control.set_dispatch(True, changed_by='test')
    assert runner.tick_one()['outcome'] == 'idle'                                 # dispatch on, nothing queued, automation off
    control.set_dispatch(False, changed_by='test')
    assert opened == []
    assert config.environment_getter('FTP_NO_HOST') == 'no.example.test' and len(opened) == 1   # proves the probe would notice
