"""2B.3: profiles, single-shot uploader, FTPS verification, redaction. Fakes replace only the network."""
import datetime
import ftplib
import socket
import ssl

import pytest

from InvestmentManager.integrator import export_arm
from InvestmentManager.integrator import export_transport_config as config
from InvestmentManager.integrator import portal_transport as transport

@pytest.fixture(autouse=True)
def armed(monkeypatch):
    """These tests exercise the uploader's own behaviour with fake ftp objects; the arm itself is tested in test_export_arm.py."""
    monkeypatch.setattr(export_arm, 'check', lambda profile, **kw: {'allowed': True, 'code': 'armed'})


ZIP = b'PK-synthetic-zip-bytes' * 50
NAME = 'no_17_20261111120000.zip'
SECRET = 'S3cr3t-Pa55word'
HOST = 'ftp.secret-host.example'
USER = 'secret-user'


def getter_for(prefix, extra=None):
    values = {f'{prefix}_HOST': HOST, f'{prefix}_USERNAME': USER, f'{prefix}_PASSWORD': SECRET}
    values.update(extra or {})
    return lambda key: values.get(key)


class FakeFTP:
    """Scriptable ftplib double. Records every command; `fail` maps a step to an exception."""
    instances = []

    def __init__(self, fail=None, replies=None):
        self.fail, self.calls, self.sock = fail or {}, [], object()
        self.replies = {'stor': '226 Transfer complete', 'rename': '250 RNTO command successful'} | (replies or {})
        FakeFTP.instances.append(self)

    def _step(self, name, *args):
        self.calls.append((name,) + args)
        if name in self.fail:
            raise self.fail[name]

    def connect(self, host=None, port=None, timeout=None):
        self._step('connect', host, port, timeout)

    def login(self, user=None, passwd=None):
        self._step('login', user, passwd)

    def prot_p(self):
        self._step('prot_p')

    def set_pasv(self, flag):
        self._step('set_pasv', flag)

    def storbinary(self, command, stream, callback=None):
        self._step('storbinary', command)
        data = stream.read()
        if callback:
            for index in range(0, len(data), 100):
                callback(data[index:index + 100])
        if 'stor_after_send' in self.fail:
            raise self.fail['stor_after_send']
        return self.replies['stor']

    def rename(self, source, target):
        self._step('rename', source, target)
        return self.replies['rename']

    def quit(self):
        self._step('quit')
        self.sock = None

    def close(self):
        self.calls.append(('close',))
        if 'close' in self.fail:
            raise self.fail['close']
        self.sock = None


def upload(profile='no', fail=None, name=NAME, body=ZIP, getter=None, replies=None, **kwargs):
    fake = FakeFTP(fail, replies)
    prefix = config.PROFILES[profile][0] if profile in config.PROFILES else 'X'
    result = transport.upload_portal_zip(profile, name, body, secret_getter=getter or getter_for(prefix),
                                         ftp_factory=lambda settings: fake, **kwargs)
    return result, fake


def names(fake):
    return [call[0] for call in fake.calls]


# ----------------------------------------------------------------- outcomes
@pytest.mark.parametrize('profile', ['no', 'tabelaofert', 'tabelaofert_primary', 'gruntguru'])
def test_plain_success_is_confirmed_with_one_stor_and_no_rename(profile):
    result, fake = upload(profile)
    assert (result.outcome, result.error_code, result.stor_reply_code, result.bytes_complete) == ('confirmed', None, 226, True)
    assert result.rename_reply_code is None and result.bytes_sent == len(ZIP)
    assert names(fake) == ['connect', 'login', 'set_pasv', 'storbinary', 'quit']
    assert ('storbinary', 'STOR ' + NAME) in fake.calls and ('set_pasv', True) in fake.calls
    assert not {'rename', 'retr', 'dele', 'nlst'} & set(names(fake))


def test_domiporta_is_confirmed_only_after_stor_then_rename_to_ok_prefix():
    result, fake = upload('domiporta')
    order = [call[0] for call in fake.calls]
    assert result.outcome == 'confirmed' and result.rename_reply_code == 250
    assert order.index('storbinary') < order.index('rename')
    assert ('rename', NAME, 'ok-' + NAME) in fake.calls
    assert not any(call[0] == 'storbinary' and call[1].startswith('STOR ok-') for call in fake.calls)


@pytest.mark.parametrize('step,error', [
    ('connect', OSError('refused')), ('connect', socket.timeout('t')), ('login', ftplib.error_perm('530 no')),
    ('login', EOFError())])
def test_failures_before_stor_are_certain_not_sent(step, error):
    result, fake = upload(fail={step: error})
    assert result.outcome == 'not_sent' and 'storbinary' not in names(fake)
    assert result.error_code == ('timeout' if isinstance(error, socket.timeout) else f'{step}_failed')


@pytest.mark.parametrize('error,code', [
    (EOFError('lost'), 'stor_failed'), (OSError('data channel'), 'stor_failed'), (socket.timeout('x'), 'timeout'),
    (ftplib.error_temp('425 cannot open data connection'), 'stor_failed')])
def test_any_failure_once_stor_is_attempted_is_unknown(error, code):
    result, fake = upload(fail={'storbinary': error})
    assert result.outcome == 'unknown' and result.error_code == code and names(fake).count('storbinary') == 1
    assert 'rename' not in names(fake)


def test_failure_after_bytes_were_sent_is_unknown_and_counts_bytes():
    result, fake = upload(fail={'stor_after_send': EOFError('no 226')})
    assert result.outcome == 'unknown' and result.bytes_sent == len(ZIP) and not result.timings['stor']['complete']


@pytest.mark.parametrize('error', [EOFError('rename reply lost'), ftplib.error_perm('550 no'), OSError('x')])
def test_domiporta_rename_failure_is_never_not_sent(error):
    result, fake = upload('domiporta', fail={'rename': error})
    assert result.outcome == 'unknown' and result.error_code == 'rename_failed' and result.stor_reply_code == 226
    assert names(fake).count('storbinary') == 1


@pytest.mark.parametrize('fail', [{'quit': EOFError()}, {'quit': ftplib.error_temp('421')}, {'close': OSError()}])
def test_close_errors_after_confirmation_do_not_undo_it(fail):
    result, _ = upload(fail=fail)
    assert result.outcome == 'confirmed' and result.error_code is None


def test_stage_timings_are_complete_for_executed_stages_only():
    result, _ = upload('domiporta')
    assert set(result.timings) == {'connect', 'login', 'stor', 'rename'} and all(t['complete'] for t in result.timings.values())
    result, _ = upload(fail={'login': EOFError()})
    assert set(result.timings) == {'connect'}


# ------------------------------------------------------- input validation
@pytest.mark.parametrize('name', ['', 'a/b.zip', 'a\\b.zip', 'x\r\n.zip', 'x\x00.zip', '../x.zip', 'x.txt', 'a b.zip', 'x' * 130 + '.zip', None, 5])
def test_invalid_filename_never_reaches_the_network(name):
    result, fake = upload(name=name)
    assert (result.outcome, result.error_code) == ('not_sent', 'config_invalid') and fake.calls == []


@pytest.mark.parametrize('body', [b'', None, 'text'])
def test_invalid_payload_never_reaches_the_network(body):
    result, fake = upload(body=body)
    assert result.outcome == 'not_sent' and fake.calls == []


def test_missing_or_invalid_configuration_is_not_sent_without_connecting():
    result, fake = upload('no', getter=lambda key: None)
    assert (result.outcome, result.error_code) == ('not_sent', 'config_missing') and fake.calls == []
    result, fake = upload('no', getter=getter_for('FTP_NO', {'FTP_NO_PORT': 'abc'}))
    assert result.error_code == 'config_invalid' and fake.calls == []
    result, fake = upload('otodom')
    assert result.error_code == 'config_invalid' and fake.calls == []


# ------------------------------------------------------------- profiles
@pytest.mark.parametrize('domain,portal,profile', [
    ('domestic', 'no', 'no'), ('domestic', 'domiporta', 'domiporta'), ('domestic', 'tabelaofert', 'tabelaofert'),
    ('domestic', 'gruntguru', 'gruntguru'), ('foreign', 'domiporta', 'domiporta'), ('foreign', 'tabelaofert', 'tabelaofert_primary')])
def test_five_profiles_map_to_the_existing_key_names(domain, portal, profile):
    assert config.profile_for(domain, portal) == profile
    prefix = config.PROFILES[profile][0]
    seen = []
    settings = config.load_profile(profile, lambda key: seen.append(key) or {'HOST': 'h', 'USERNAME': 'u', 'PASSWORD': 'p'}.get(key.rsplit('_', 1)[1]))
    assert set(seen) == {f'{prefix}_{n}' for n in ('HOST', 'PORT', 'USERNAME', 'PASSWORD', 'TIMEOUT')}
    assert (settings.port, settings.timeout_seconds, settings.use_tls) == (21, 20.0, False)
    assert settings.ready_prefix == ('ok-' if profile == 'domiporta' else '')


def test_primary_profile_never_falls_back_to_the_polish_account():
    requested = []
    values = {'FTP_TABELAOFERT_HOST': 'pl', 'FTP_TABELAOFERT_USERNAME': 'pl', 'FTP_TABELAOFERT_PASSWORD': 'pl'}

    def getter(key):
        requested.append(key)
        return values.get(key)
    with pytest.raises(config.ConfigError) as error:
        config.load_profile('tabelaofert_primary', getter)
    assert error.value.code == 'config_missing' and all(key.startswith('FTP_TABELAOFERT_PRIMARY_') for key in requested)
    assert set(error.value.missing) == {'FTP_TABELAOFERT_PRIMARY_HOST', 'FTP_TABELAOFERT_PRIMARY_USERNAME', 'FTP_TABELAOFERT_PRIMARY_PASSWORD'}
    assert config.profile_status('tabelaofert_primary', getter)['complete'] is False


def test_overrides_and_foreign_binding_agreement():
    got = config.load_profile('no', getter_for('FTP_NO', {'FTP_NO_PORT': ' 2121 ', 'FTP_NO_TIMEOUT': '7.5'}))
    assert (got.port, got.timeout_seconds) == (2121, 7.5)
    assert config.profile_for('foreign', 'tabelaofert', {'transport_profile': 'tabelaofert_primary'}) == 'tabelaofert_primary'
    for bad in ({'transport_profile': 'tabelaofert'}, {}):
        with pytest.raises(config.ConfigError):
            config.profile_for('foreign', 'tabelaofert', bad)
    for domain, portal in (('domestic', 'otodom'), ('foreign', 'no'), ('foreign', 'gruntguru')):
        with pytest.raises(config.ConfigError):
            config.profile_for(domain, portal)
    assert 'otodom' not in config.PROFILES and set(config.PROFILES) == {'no', 'domiporta', 'tabelaofert', 'tabelaofert_primary', 'gruntguru'}


# -------------------------------------------------------------- redaction
LEAKS = [OSError(f'cannot reach {HOST} as {USER} password {SECRET} at C:\\private\\path'),
         ftplib.error_perm(f'530 login {USER}/{SECRET} refused by {HOST}'), EOFError(f'{SECRET}'),
         ssl.SSLError(f'handshake with {HOST} failed {SECRET}'), RuntimeError(f'{USER}@{HOST}:{SECRET}'),
         socket.timeout(f'{HOST}'), ValueError(SECRET), ftplib.error_temp(f'425 {HOST}'), OSError(HOST), KeyError(SECRET)]


@pytest.mark.parametrize('step', ['connect', 'login', 'storbinary'])
@pytest.mark.parametrize('leak', LEAKS, ids=lambda e: type(e).__name__)
def test_results_never_contain_exception_text_hosts_or_credentials(step, leak):
    result, _ = upload(fail={step: leak})
    dump = repr(result) + repr(result.__dict__)
    for secret in (SECRET, HOST, USER, 'private'):
        assert secret not in dump
    assert result.error_code in transport.ERROR_CODES


def test_domiporta_rename_error_text_is_not_exposed_either():
    result, _ = upload('domiporta', fail={'rename': OSError(f'{HOST} {SECRET}')})
    assert SECRET not in repr(result) and HOST not in repr(result)


def test_config_repr_hides_credentials():
    settings = config.load_profile('no', getter_for('FTP_NO'))
    assert SECRET not in repr(settings) and USER not in repr(settings) and HOST not in repr(settings)


# ---------------------------------------------------------------- FTPS
def make_certificates(tmp_path):
    from cryptography import x509
    from cryptography.hazmat.primitives import hashes, serialization
    from cryptography.hazmat.primitives.asymmetric import rsa
    from cryptography.x509.oid import NameOID
    now = datetime.datetime.now(datetime.timezone.utc)

    def key():
        return rsa.generate_private_key(public_exponent=65537, key_size=2048)

    def name(value):
        return x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, value)])
    ca_key, leaf_key = key(), key()
    ca = (x509.CertificateBuilder().subject_name(name('test-ca')).issuer_name(name('test-ca')).public_key(ca_key.public_key())
          .serial_number(1).not_valid_before(now - datetime.timedelta(days=1)).not_valid_after(now + datetime.timedelta(days=2))
          .add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True)
          .add_extension(x509.SubjectKeyIdentifier.from_public_key(ca_key.public_key()), critical=False)
          .add_extension(x509.KeyUsage(digital_signature=True, content_commitment=False, key_encipherment=False, data_encipherment=False, key_agreement=False, key_cert_sign=True, crl_sign=True, encipher_only=False, decipher_only=False), critical=True)
          .sign(ca_key, hashes.SHA256()))
    leaf = (x509.CertificateBuilder().subject_name(name('ftp.test.invalid')).issuer_name(ca.subject)
            .public_key(leaf_key.public_key()).serial_number(2).not_valid_before(now - datetime.timedelta(days=1))
            .not_valid_after(now + datetime.timedelta(days=2))
            .add_extension(x509.SubjectAlternativeName([x509.DNSName('ftp.test.invalid')]), critical=False)
            .add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_key.public_key()), critical=False)
            .add_extension(x509.SubjectKeyIdentifier.from_public_key(leaf_key.public_key()), critical=False)
            .sign(ca_key, hashes.SHA256()))
    pem = serialization.Encoding.PEM
    (tmp_path / 'leaf.pem').write_bytes(leaf.public_bytes(pem))
    (tmp_path / 'leaf.key').write_bytes(leaf_key.private_bytes(pem, serialization.PrivateFormat.TraditionalOpenSSL,
                                                                serialization.NoEncryption()))
    return ca.public_bytes(pem).decode(), tmp_path / 'leaf.pem', tmp_path / 'leaf.key'


def handshake(client_context, server_context, hostname):
    """TLS handshake through memory BIOs (no sockets). Raises the client's verification error."""
    c_in, c_out, s_in, s_out = ssl.MemoryBIO(), ssl.MemoryBIO(), ssl.MemoryBIO(), ssl.MemoryBIO()
    client = client_context.wrap_bio(c_in, c_out, server_hostname=hostname)
    server = server_context.wrap_bio(s_in, s_out, server_side=True)
    done = [False, False]
    for _ in range(50):
        for index, side in enumerate((client, server)):
            if done[index]:
                continue
            try:
                side.do_handshake()
                done[index] = True
            except ssl.SSLWantReadError:
                pass
            except ssl.SSLError as exc:
                if side is client:
                    raise
                done[index] = True
                _ = exc
        s_in.write(c_out.read())
        c_in.write(s_out.read())
        if all(done):
            return client.version()
    raise AssertionError('handshake did not finish')


@pytest.fixture
def pki(tmp_path):
    ca_pem, cert, key = make_certificates(tmp_path)
    server = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    server.load_cert_chain(cert, key)
    return ca_pem, server


def test_tls_context_verifies_chain_and_hostname():
    context = transport.tls_context()
    assert context.verify_mode == ssl.CERT_REQUIRED and context.check_hostname is True
    assert context.minimum_version >= ssl.TLSVersion.TLSv1_2


def test_valid_chain_and_hostname_handshake_succeeds(pki):
    ca_pem, server = pki
    client = ssl.create_default_context(cadata=ca_pem)
    assert handshake(client, server, 'ftp.test.invalid').startswith('TLS')


def test_unknown_ca_and_wrong_hostname_are_rejected(pki):
    ca_pem, server = pki
    with pytest.raises(ssl.SSLCertVerificationError):
        handshake(transport.tls_context(), server, 'ftp.test.invalid')            # CA not trusted
    with pytest.raises(ssl.SSLCertVerificationError):
        handshake(ssl.create_default_context(cadata=ca_pem), server, 'other.test.invalid')   # hostname mismatch


class TlsFake(FakeFTP):
    """FTP_TLS double whose login() performs a real verifying handshake with the supplied context."""
    server = None
    context = None

    def login(self, user=None, passwd=None):
        self.calls.append(('auth_tls',))
        handshake(self.context, self.server, self.host)
        super().login(user, passwd)

    def connect(self, host=None, port=None, timeout=None):
        self.host = host
        super().connect(host, port, timeout)


def ftps_upload(monkeypatch, pki, host, context):
    ca_pem, server = pki
    monkeypatch.setitem(config.PROFILES, 'no', ('FTP_NO', '', True))
    fake = TlsFake()
    fake.server, fake.context = server, context
    getter = getter_for('FTP_NO', {'FTP_NO_HOST': host})
    result = transport.upload_portal_zip('no', NAME, ZIP, secret_getter=getter, ftp_factory=lambda settings: fake)
    return result, fake


def test_ftps_with_valid_chain_reaches_prot_p_then_stor(monkeypatch, pki):
    result, fake = ftps_upload(monkeypatch, pki, 'ftp.test.invalid', ssl.create_default_context(cadata=pki[0]))
    assert result.outcome == 'confirmed' and names(fake)[:5] == ['connect', 'auth_tls', 'login', 'prot_p', 'set_pasv']
    assert names(fake).index('prot_p') < names(fake).index('storbinary')


@pytest.mark.parametrize('host,context_name', [('ftp.test.invalid', 'system'), ('other.test.invalid', 'test_ca')])
def test_ftps_untrusted_or_mismatched_certificate_is_not_sent_without_downgrade(monkeypatch, pki, host, context_name):
    context = transport.tls_context() if context_name == 'system' else ssl.create_default_context(cadata=pki[0])
    result, fake = ftps_upload(monkeypatch, pki, host, context)
    assert (result.outcome, result.error_code) == ('not_sent', 'tls_failed')
    assert 'storbinary' not in names(fake) and 'login' not in names(fake)


def test_ftps_uses_a_verifying_context_by_default(monkeypatch):
    monkeypatch.setitem(config.PROFILES, 'no', ('FTP_NO', '', True))
    captured = {}

    class Capture:
        def __init__(self, context=None):
            captured['context'] = context
            raise OSError('stop here')
    monkeypatch.setattr(transport.ftplib, 'FTP_TLS', Capture)
    with pytest.raises(OSError):
        transport.upload_portal_zip('no', NAME, ZIP, secret_getter=getter_for('FTP_NO'))
    assert captured['context'].verify_mode == ssl.CERT_REQUIRED and captured['context'].check_hostname
