"""Stage 5B-2A: the transport arm (exports-arm.json) is the last line of defence before any real STOR."""
import json
import socket
import subprocess
import sys
import time
from pathlib import Path

import pytest

from InvestmentManager import scheduled_jobs
from InvestmentManager.integrator import export_arm as arm
from InvestmentManager.integrator import export_job_runner as runner
from InvestmentManager.integrator import export_jobs as jobs
from InvestmentManager.integrator import package_delivery as pd
from InvestmentManager.integrator import portal_transport as transport
from tests.investmentmanager.test_domestic_packages import data_root, isolated            # noqa: F401  (fixtures)
from tests.investmentmanager.test_local_package_delivery import (                          # noqa: F401
    FakeTransport, LockHolder, attempt_state, make_env, new_job, policy, publication, run, view, world)

REPO = Path(__file__).resolve().parents[2]


class Reached(Exception):
    pass


@pytest.fixture
def net(monkeypatch):
    """Any attempt to create a connection is counted and fails; ftplib objects are counted too."""
    calls = {'connect': 0, 'ftp': 0}

    def refuse_connect(self, *a, **k):
        calls['connect'] += 1
        raise Reached('network connect')
    monkeypatch.setattr(socket.socket, 'connect', refuse_connect)
    monkeypatch.setattr(socket, 'create_connection', refuse_connect)           # ftplib connects through this (and resolves DNS first)
    monkeypatch.setattr(socket, 'getaddrinfo', refuse_connect)
    import ftplib
    original = ftplib.FTP.__init__

    def counted(self, *a, **k):
        calls['ftp'] += 1
        original(self, *a, **k)
    monkeypatch.setattr(ftplib.FTP, '__init__', counted)
    return calls


@pytest.fixture
def scheduler_dir(tmp_path, monkeypatch):
    root = tmp_path / 'InvestmentData'
    root.mkdir(exist_ok=True)
    monkeypatch.setenv('DATA_DIR', str(root))
    return root / 'scheduler'


def write_arm(directory, **over):
    now = int(time.time())
    value = {'version': 1, 'arm_version': 1, 'profiles': ['no'], 'armed_at': arm._stamp(now - 5), 'expires_at': arm._stamp(now + 600), 'armed_by': 'test'}
    value.update(over)
    directory.mkdir(parents=True, exist_ok=True)
    (directory / arm.NAME).write_text(json.dumps(value), encoding='utf-8')


def settings_getter(key):
    return {'PORT': '21', 'TIMEOUT': '5'}.get(key.rsplit('_', 1)[-1], 'S3CR3T-' + key)


def upload(profile='no', factory_calls=None):
    def factory(settings):
        if factory_calls is not None:
            factory_calls.append(1)
        raise Reached('ftp object requested')
    return transport.upload_portal_zip(profile, 'no_1.zip', b'PK-data', secret_getter=settings_getter, ftp_factory=factory)


def refusals(directory):
    path = directory / 'exports.log'
    return [json.loads(line.split(' ', 2)[2])['transport_refused'] for line in path.read_text(encoding='utf-8').splitlines()] if path.exists() else []


# ------------------------------------------------------------------ the uploader itself
def test_missing_arm_forbids_transport_before_any_network_or_ftp_object(scheduler_dir, net):
    created = []
    result = upload(factory_calls=created)
    assert (result.outcome, result.phase, result.error_code) == ('not_sent', 'arm', 'arm_refused')
    assert created == [] and net == {'connect': 0, 'ftp': 0}
    assert refusals(scheduler_dir) == [{'code': 'arm_missing', 'profile': 'no'}]


@pytest.mark.parametrize('text', ['{', '[]', 'null', '{}', json.dumps({'version': 1}),
                                  json.dumps({'version': 2, 'arm_version': 1, 'profiles': ['no'], 'armed_at': '2026-01-01T00:00:00Z', 'expires_at': '2026-01-01T01:00:00Z', 'armed_by': 'x'})])
def test_corrupt_or_foreign_arm_forbids_transport(scheduler_dir, net, text):
    scheduler_dir.mkdir(parents=True)
    (scheduler_dir / arm.NAME).write_text(text, encoding='utf-8')
    assert upload().error_code == 'arm_refused' and net['connect'] == 0
    assert refusals(scheduler_dir)[-1]['code'] == 'arm_corrupt'


@pytest.mark.parametrize('over', [dict(profiles=[]), dict(profiles=['no', 'no']), dict(profiles=['otodom']), dict(profiles='no'),
                                  dict(armed_at='yesterday'), dict(expires_at='2099-01-01T00:00:00'), dict(arm_version=0), dict(armed_by=''),
                                  dict(extra=1)])
def test_malformed_fields_forbid_transport(scheduler_dir, net, over):
    write_arm(scheduler_dir, **over)
    assert upload().error_code == 'arm_refused' and net['connect'] == 0
    assert refusals(scheduler_dir)[-1]['code'] == 'arm_corrupt'


def test_arm_longer_than_24_hours_or_inverted_is_corrupt(scheduler_dir, net):
    now = int(time.time())
    write_arm(scheduler_dir, armed_at=arm._stamp(now), expires_at=arm._stamp(now + 24 * 3600 + 1))
    assert arm.check('no')['code'] == 'arm_corrupt'
    write_arm(scheduler_dir, armed_at=arm._stamp(now), expires_at=arm._stamp(now))
    assert arm.check('no')['code'] == 'arm_corrupt'
    assert net['connect'] == 0


def test_expired_arm_forbids_transport(scheduler_dir, net):
    now = int(time.time())
    write_arm(scheduler_dir, armed_at=arm._stamp(now - 7200), expires_at=arm._stamp(now - 3600))
    assert upload().error_code == 'arm_refused' and net['connect'] == 0
    assert refusals(scheduler_dir)[-1]['code'] == 'arm_expired'


def test_arm_expires_at_the_boundary_without_any_process_cooperation(scheduler_dir):
    write_arm(scheduler_dir)
    now = int(time.time())
    expires = arm._epoch(arm.read()['arm']['expires_at'])
    assert arm.check('no', now=expires - 1)['allowed'] is True
    assert arm.check('no', now=expires)['code'] == 'arm_expired'


def test_explicit_permanent_arm_keeps_the_profile_gate_and_can_be_disarmed(scheduler_dir):
    state = arm.arm(['no', 'tabelaofert_primary'], permanent=True, armed_by='test')
    assert state['arm']['expires_at'] == 'never'
    assert arm.check('no', now=time.time() + 100 * 365 * 86400)['allowed'] is True
    assert arm.check('tabelaofert_primary')['allowed'] is True
    assert arm.check('domiporta')['code'] == 'arm_profile_not_allowed'
    arm.disarm()
    assert arm.check('no')['code'] == 'arm_missing'


def test_future_dated_arm_is_not_valid_yet(scheduler_dir):
    now = int(time.time())
    write_arm(scheduler_dir, armed_at=arm._stamp(now + 3600), expires_at=arm._stamp(now + 7200))
    assert arm.check('no')['code'] == 'arm_not_yet_valid'


def test_profile_not_on_the_list_is_refused(scheduler_dir, net):
    write_arm(scheduler_dir, profiles=['domiporta'])
    assert upload('no').error_code == 'arm_refused' and net['connect'] == 0
    assert refusals(scheduler_dir)[-1] == {'code': 'arm_profile_not_allowed', 'profile': 'no'}
    for bad in (None, 5, 'otodom', ''):
        assert arm.check(bad)['allowed'] is False


def test_valid_arm_lets_exactly_the_listed_profile_reach_the_transport(scheduler_dir, net):
    write_arm(scheduler_dir, profiles=['no'])
    created = []
    with pytest.raises(Reached):
        upload('no', created)                      # the factory is reached: the arm allowed the upload to start
    assert created == [1]
    assert upload('gruntguru').error_code == 'arm_refused'


def test_refusal_audit_never_contains_secrets_hosts_or_paths(scheduler_dir):
    upload()
    text = (scheduler_dir / 'exports.log').read_text(encoding='utf-8')
    assert 'S3CR3T' not in text and 'FTP_' not in text and 'InvestmentData' not in text and 'host' not in text.lower()
    assert set(refusals(scheduler_dir)[0]) == {'code', 'profile'}
    arm.refuse('<script>', 'arm_missing')
    assert refusals(scheduler_dir)[-1]['profile'] == 'invalid'


def test_no_caller_supplied_factory_or_clock_can_bypass_the_check(scheduler_dir, net):
    import inspect
    params = inspect.signature(transport.upload_portal_zip).parameters
    assert not any('arm' in name for name in params)                       # no parameter exists that could skip it
    created = []
    result = transport.upload_portal_zip('no', 'no_1.zip', b'x', secret_getter=lambda k: 'v', ftp_factory=lambda s: created.append(1) or None)
    assert result.error_code == 'arm_refused' and created == []


# ------------------------------------------------------------------ the whole delivery path (real transport module, socket blocked)
def real_env(**kw):
    return make_env(transport, secret=lambda key: settings_getter(key), **kw)


def test_runner_cannot_bypass_unarmed_delivery_is_blocked_before_any_attempt(world, net):
    claim = new_job()
    outcome = pd.execute_delivery(claim, real_env())
    assert (outcome.job_state, outcome.reason, outcome.uploader_calls) == ('blocked', 'transport_not_armed', 0)
    assert net == {'connect': 0, 'ftp': 0}
    assert view(claim)['attempt_id'] is None                              # refused before CREATE/START: no attempt, no UNKNOWN
    assert refusals(Path(scheduled_jobs._directory()))[-1]['code'] == 'arm_missing'


def test_tick_with_dispatch_on_and_automation_cannot_bypass_either(world, net, monkeypatch):
    from InvestmentManager.integrator import export_automation as auto, export_control as control, sync_tasks
    new_job_claim = new_job()
    jobs.advance(new_job_claim, state='queued', phase='paused')           # give the job back to the queue
    auto.enable(portals=['no'], changed_by='test')
    monkeypatch.setattr(sync_tasks, 'list_task_rows', lambda **kw: {'items': [], 'total': 0})
    result = runner.tick_one(env=real_env())
    assert result['outcome'] == 'executed' and result['executed']['state'] == 'blocked' and result['executed']['reason'] == 'transport_not_armed'
    assert net == {'connect': 0, 'ftp': 0}


def test_armed_delivery_reaches_the_network_and_a_failed_connect_is_a_certain_no_send(world, net):
    arm.arm(['no'], minutes=5, armed_by='test')
    claim = new_job()
    outcome = pd.execute_delivery(claim, real_env())
    assert net['connect'] == 1                                            # the arm let the uploader go as far as connect (blocked by the fixture)
    assert (outcome.job_state, outcome.reason, outcome.ftp_status) == ('failed', 'transport_failed', 'failed_before_send')


def test_arm_for_another_profile_still_blocks_this_delivery(world, net):
    arm.arm(['domiporta'], minutes=5, armed_by='test')
    outcome = pd.execute_delivery(new_job(), real_env())
    assert outcome.reason == 'transport_not_armed' and net['connect'] == 0


def test_expiry_between_the_early_gate_and_the_upload_is_caught_by_the_final_guard(world, net, monkeypatch):
    arm.arm(['no'], minutes=5, armed_by='test')
    verdicts = iter([{'allowed': True, 'code': 'armed'}])                 # early gate passes, the final guard sees an expired arm
    original = arm.check
    monkeypatch.setattr(arm, 'check', lambda profile, **kw: next(verdicts, None) or {'allowed': False, 'code': 'arm_expired'})
    outcome = pd.execute_delivery(new_job(), real_env())
    assert net['connect'] == 0 and outcome.job_state == 'failed' and outcome.ftp_status == 'failed_before_send'
    monkeypatch.setattr(arm, 'check', original)


# ------------------------------------------------------------------ operations without FTP are unaffected
def test_ack_only_works_while_unarmed_and_never_touches_the_network(world, net):
    holder = LockHolder()
    claim = new_job()
    outcome, fake = run(claim, hooks={'after_record': holder.acquire}, policy=policy(ack={'attempts': 3, 'total': 100.0}))
    holder.stop()
    assert outcome.reason == 'ack_pending' and attempt_state(claim) == 'transport_confirmed'
    record = view(claim)
    jobs.create_ack_recovery({'domain': 'domestic', 'attempt_id': record['attempt_id'], 'subject_kind': 'offer', 'subject_id': 17, 'portal': 'no',
                              'action': 'add', 'package_id': record['package_id'],
                              'binding_sha256': jobs.binding_digest(__import__('InvestmentManager.integrator.export_attempts', fromlist=['x']).inspect_attempt(record['attempt_id'])['attempt']['binding']),
                              'attempt_anchor_id': 17}, actor='user:7', idempotency_key='a' * 32, parent_job_id=claim.job_id)
    result = pd.execute_ack_only(jobs.claim_next('ack_only'), real_env())          # the REAL transport module, no arm
    assert result.job_state == 'completed' and attempt_state(claim) == 'ack_completed' and net == {'connect': 0, 'ftp': 0}
    assert refusals(Path(scheduled_jobs._directory())) == []                      # the arm was never even consulted


def test_other_profiles_and_non_ftp_paths_do_not_depend_on_the_arm(scheduler_dir):
    assert arm.check('no')['allowed'] is False                            # default OFF
    # reading, status and the CLI status never require an arm
    assert runner.main(['arm-status']) == 0


# ------------------------------------------------------------------ restart and CLI
def test_state_survives_a_process_restart_and_cannot_be_left_on(scheduler_dir):
    write_arm(scheduler_dir, profiles=['no'])
    code = "from InvestmentManager.integrator import export_arm as a;import json;print(json.dumps([a.check('no'),a.check('gruntguru')]))"
    out = subprocess.run([sys.executable, '-B', '-c', code], cwd=REPO, capture_output=True, text=True, encoding='utf-8', timeout=120)
    assert out.returncode == 0, out.stderr[-500:]
    allowed, other = json.loads(out.stdout.strip().splitlines()[-1])
    assert allowed == {'allowed': True, 'code': 'armed'} and other['code'] == 'arm_profile_not_allowed'
    (scheduler_dir / arm.NAME).unlink()
    out = subprocess.run([sys.executable, '-B', '-c', code], cwd=REPO, capture_output=True, text=True, encoding='utf-8', timeout=120)
    assert json.loads(out.stdout.strip().splitlines()[-1])[0]['code'] == 'arm_missing'


def test_cli_arm_disarm_status_and_limits(scheduler_dir, capsys):
    assert runner.main(['arm-status']) == 0 and json.loads(capsys.readouterr().out)['status'] == 'missing'
    assert runner.main(['arm', '--arm-profiles', 'no']) == 1                 # minutes are mandatory
    capsys.readouterr()
    assert runner.main(['arm', '--arm-profiles', 'otodom', '--arm-minutes', '10']) == 1
    assert runner.main(['arm', '--arm-profiles', 'no', '--arm-minutes', '1441']) == 1
    assert runner.main(['arm', '--arm-profiles', 'no', '--arm-minutes', '0']) == 1
    assert runner.main(['arm', '--arm-profiles', 'no', '--arm-minutes', '5', '--arm-permanent']) == 1
    capsys.readouterr()
    assert not (scheduler_dir / arm.NAME).exists()                           # refused requests arm nothing
    assert runner.main(['arm', '--arm-profiles', 'no,domiporta', '--arm-minutes', '30']) == 0
    state = json.loads(capsys.readouterr().out)
    assert state['status'] == 'ok' and state['arm']['profiles'] == ['no', 'domiporta'] and state['arm']['arm_version'] == 1
    assert arm.check('no')['allowed'] and arm.check('domiporta')['allowed'] and not arm.check('gruntguru')['allowed']
    assert runner.main(['arm', '--arm-profiles', 'no', '--arm-minutes', '5']) == 0       # re-arming replaces, never extends silently
    assert json.loads(capsys.readouterr().out)['arm']['profiles'] == ['no']
    assert runner.main(['arm', '--arm-profiles', 'no,tabelaofert_primary', '--arm-permanent']) == 0
    permanent = json.loads(capsys.readouterr().out)['arm']
    assert permanent['expires_at'] == 'never' and permanent['profiles'] == ['no', 'tabelaofert_primary']
    assert runner.main(['disarm']) == 0 and not arm.check('no')['allowed']
    assert runner.main(['disarm']) == 0                                      # idempotent


def test_arming_is_off_by_default_and_nothing_in_the_code_arms_by_itself():
    import inspect
    sources = {name: inspect.getsource(module) for name, module in
               (('runner', runner), ('portal', transport), ('delivery', pd))}
    for name, text in sources.items():
        assert 'export_arm.arm(' not in text.replace("export_arm.arm(args.arm_profiles", ''), name        # only the explicit CLI branch arms
    from InvestmentManager.integrator import export_automation, export_resolution, export_control
    for module in (export_automation, export_resolution, export_control):
        assert 'export_arm' not in inspect.getsource(module)
