"""S4.5: the qualified START orchestration lives in `export_start`; `export_attempts` only runs caller-supplied gates in its ONE transaction."""
import ast
import inspect
from pathlib import Path

import pytest

from tests.investmentmanager.test_domestic_packages import data_root, isolated  # noqa: F401  (fixtures used by `ready`)
from tests.investmentmanager.test_export_job_start import ready, domestic_job  # noqa: F401
from InvestmentManager.integrator import export_attempts as attempts
from InvestmentManager.integrator import export_start
from InvestmentManager.integrator import sync_tasks as queue

INTEGRATOR = Path(__file__).resolve().parents[2] / 'InvestmentManager' / 'integrator'
HIGHER = ('sync_tasks', 'export_jobs', 'export_control')


def _imports(path):
    """[(dotted names, is_inside_a_function)] for every import statement of the file."""
    tree = ast.parse(path.read_text(encoding='utf-8-sig'))
    top = {id(node) for node in tree.body}
    found = []
    for node in ast.walk(tree):
        if isinstance(node, ast.Import):
            found.append(([alias.name for alias in node.names], id(node) not in top))
        elif isinstance(node, ast.ImportFrom):
            base = node.module or ''
            names = [base] + [f'{base}.{alias.name}'.strip('.') for alias in node.names]
            found.append((names, id(node) not in top))
    return found


def test_export_attempts_imports_none_of_the_orchestration_modules_at_any_level():
    forbidden = HIGHER + ('export_start', 'package_delivery')
    for names, _lazy in _imports(INTEGRATOR / 'export_attempts.py'):
        for name in names:
            assert name.split('.')[-1] not in forbidden, name


def test_the_old_entry_point_is_gone_from_export_attempts_and_the_new_one_is_public_and_domain_wrapped():
    assert not hasattr(attempts, 'start_qualified_transport')                    # no alias: it would bring the cycle back
    assert hasattr(attempts.start_gated_transport, '__wrapped__')                # domain_api applied
    parameters = inspect.signature(attempts.start_gated_transport.__wrapped__).parameters
    assert list(parameters) == ['attempt_id', 'binding', 'pre', 'qualification', 'settings']


def test_export_start_keeps_the_call_signature_and_the_lazy_imports():
    parameters = inspect.signature(export_start.start_qualified_transport).parameters
    assert list(parameters) == ['attempt_id', 'binding', 'job_claim', 'settings', 'domain']
    assert parameters['job_claim'].kind is inspect.Parameter.KEYWORD_ONLY and parameters['settings'].default is None
    assert parameters['domain'].default == 'domestic'
    for names, lazy in _imports(INTEGRATOR / 'export_start.py'):
        if any(name.split('.')[-1] in HIGHER for name in names):
            assert lazy, names                                                   # the three modules stay lazy, exactly as before the move
    top_level = [names for names, lazy in _imports(INTEGRATOR / 'export_start.py') if not lazy]
    assert {name for names in top_level for name in names} <= {'re', '', '.', '.export_attempts', 'export_attempts'}


def test_sync_tasks_exposes_the_source_root_under_a_public_name_without_a_second_function():
    assert queue.source_root is queue._source_root


def test_start_gated_transport_hands_the_gates_the_connection_and_the_item_and_a_refusal_writes_nothing(ready):
    attempt, claim = domestic_job(ready)
    seen = []

    def pre(conn, item):
        seen.append(('pre', conn.in_transaction, item['attempt_id'], item['state'], attempts._foreign()))
        return 'my_reason'

    def qualification(conn, item):                                              # must never run after a refusal in `pre`
        seen.append(('qualification',))

    decision = attempts.start_gated_transport(attempt['attempt_id'], attempt['binding'], pre=pre, qualification=qualification)
    assert decision['can_send'] is False and decision['reason'] == 'my_reason' and decision['state'] == 'prepared'
    assert seen == [('pre', True, attempt['attempt_id'], 'prepared', False)]
    assert attempts.get_attempt(attempt['attempt_id'])['state'] == 'prepared'


def test_start_gated_transport_validates_the_domain_and_restores_the_context_after_a_gate_error(ready):
    attempt, claim = domestic_job(ready)
    with pytest.raises(attempts.AttemptError, match='^Invalid domain$'):
        attempts.start_gated_transport(attempt['attempt_id'], attempt['binding'], pre=lambda c, i: None,
                                       qualification=lambda c, i: None, domain='bogus')

    def explode(conn, item):
        raise RuntimeError('gate exploded')
    with pytest.raises(RuntimeError, match='gate exploded'):
        attempts.start_gated_transport(attempt['attempt_id'], attempt['binding'], pre=explode, qualification=lambda c, i: None)
    assert attempts._domain.get() == 'domestic'
    assert attempts.get_attempt(attempt['attempt_id'])['state'] == 'prepared'
