"""S4.5 parity of the qualified START: gate order, one transaction, refusals, events, durable state and the domain ContextVar.

Location-independent: the START entry point is resolved at import time (`export_start.start_qualified_transport` after S4.5, the old
`export_attempts.start_qualified_transport` before it), so these tests were written and passed on the OLD code and must pass unchanged
after the gates move to `export_start`.
"""
from contextlib import closing
import sqlite3

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 (  # noqa: F401  (fixtures and helpers)
    ready, foreign, domestic_job, foreign_job, idb_events, publication, foreign_events, flag)
from InvestmentManager.integrator import export_attempts as attempts
from InvestmentManager.integrator import export_control as control
from InvestmentManager.integrator import export_jobs as jobs
from InvestmentManager.integrator import sync_tasks as queue
from InvestmentManager.integrator.input_consistency import _held, input_lock

try:
    from InvestmentManager.integrator import export_start
    _START = export_start.start_qualified_transport
except ImportError:                                  # before S4.5
    _START = attempts.start_qualified_transport


def start(attempt, claim, **kwargs):
    return _START(attempt['attempt_id'], attempt['binding'], job_claim=claim, **kwargs)


def _spy(monkeypatch, order, trace):
    """Record the order of the START steps, the connection they get, whether it is inside a transaction and whether input_lock is held."""
    def wrap(owner, name, tag, conn_index=None):
        original = getattr(owner, name)

        def call(*args, **kwargs):
            conn = args[conn_index] if conn_index is not None and len(args) > conn_index else None
            order.append(tag)
            trace.append((tag, id(conn) if conn is not None else None, getattr(conn, 'in_transaction', None), _held.get() is not None,
                          attempts._foreign()))
            return original(*args, **kwargs)
        monkeypatch.setattr(owner, name, call)
    wrap(jobs, 'check_fence', 'fence', 1)
    wrap(control, 'dispatch_enabled', 'dispatch')
    wrap(attempts, '_current', 'current', 0)
    wrap(queue, 'qualify_unit', 'qualify', 0)
    wrap(attempts, '_append', 'append', 0)


def _event_counts(root):
    with closing(sqlite3.connect(root / 'databases/IDB.db')) as conn:
        return dict(conn.execute('SELECT event_type, COUNT(*) FROM offer_portal_sync_events GROUP BY 1'))


# ------------------------------------------------------------------------------------------------ gate order, one transaction
def test_gates_run_in_the_documented_order_inside_one_locked_transaction(ready, monkeypatch):
    attempt, claim = domestic_job(ready)
    order, trace = [], []
    _spy(monkeypatch, order, trace)
    before = _event_counts(ready)
    decision = start(attempt, claim)
    assert decision['can_send'] is True and decision['state'] == 'transport_unknown'
    assert order == ['fence', 'dispatch', 'current', 'qualify', 'append']            # _current exactly once, UNKNOWN last
    connections = {entry[1] for entry in trace if entry[1] is not None}
    assert len(connections) == 1                                                       # fence, _current, qualification and the write share ONE connection
    assert all(entry[2] is True for entry in trace if entry[1] is not None)            # ... inside an open transaction
    assert all(entry[3] is True for entry in trace)                                    # ... with input_lock held for every step
    assert all(entry[4] is False for entry in trace)
    after = _event_counts(ready)
    assert {k: after.get(k, 0) - before.get(k, 0) for k in set(after) | set(before) if after.get(k, 0) != before.get(k, 0)} == {
        'export_attempt_v1': 1, 'export_transport_open_v1': 1}                       # exactly the UNKNOWN state event and its open marker
    durable = attempts.get_attempt(attempt['attempt_id'])
    assert durable['state'] == 'transport_unknown' and 'can_send' not in durable      # permission is never persisted, only the state
    assert _held.get() is None                                                         # lock released


REFUSALS = {                       # setup -> (reason, steps executed before the refusal)
    'requeued': ('claim_lost', ['fence']),
    'pause': ('dispatch_paused', ['fence', 'dispatch']),
    'missing': ('dispatch_paused', ['fence', 'dispatch']),
    'corrupt': ('control_unavailable', ['fence', 'dispatch']),
    'other_attempt': ('job_identity_mismatch', ['fence', 'dispatch']),
    'other_binding': ('binding_changed', ['fence', 'dispatch']),
}


@pytest.mark.parametrize('setup', sorted(REFUSALS))
def test_a_refusal_stops_at_the_failing_gate_and_writes_nothing(ready, monkeypatch, setup):
    attempt, claim = domestic_job(ready)
    scheduler = ready / 'scheduler'
    if setup == 'pause':
        control.set_dispatch(False, changed_by='test')
    elif setup == 'missing':
        (scheduler / control.NAME).unlink()
    elif setup == 'corrupt':
        (scheduler / control.NAME).write_text('{broken', encoding='utf8')
    elif setup == 'requeued':
        jobs.advance(claim, state='queued', phase='waiting_resource')
    elif setup == 'other_attempt':
        claim = claim.__class__(**{**claim.__dict__, 'attempt_id': 'a' * 32})
    elif setup == 'other_binding':
        claim = claim.__class__(**{**claim.__dict__, 'binding_sha256': '0' * 64})
    order, trace = [], []
    _spy(monkeypatch, order, trace)
    events, flags, counts = idb_events(ready), publication(ready), _event_counts(ready)
    decision = start(attempt, claim)
    reason, steps = REFUSALS[setup]
    assert decision['can_send'] is False and decision['reason'] == reason and decision['state'] == 'prepared'
    assert order == steps                                                              # later gates (and _current / UNKNOWN) never ran
    assert idb_events(ready) == events and publication(ready) == flags and _event_counts(ready) == counts
    assert attempts.get_attempt(attempt['attempt_id'])['state'] == 'prepared'


def test_qualification_and_currency_refusals_run_current_before_qualification(ready, monkeypatch):
    from tests.investmentmanager.test_domestic_packages import sql
    attempt, claim = domestic_job(ready)
    sql(ready, "INSERT INTO offer_portal_sync(offer_id,portal_key,is_published,needs_update,updated_at) VALUES (17,'no',1,0,'t')")
    order, trace = [], []
    _spy(monkeypatch, order, trace)
    decision = start(attempt, claim)
    assert decision['can_send'] is False and decision['state'] == 'prepared'
    assert order[:3] == ['fence', 'dispatch', 'current'] and 'append' not in order


def test_a_second_start_of_an_unknown_attempt_runs_no_gate(ready, monkeypatch):
    attempt, claim = domestic_job(ready)
    assert start(attempt, claim)['can_send'] is True
    order, trace = [], []
    _spy(monkeypatch, order, trace)
    again = start(attempt, claim)
    assert again['can_send'] is False and again['state'] == 'transport_unknown' and order == []


# ------------------------------------------------------------------------------------------------ ContextVar (domain)
def test_the_domain_is_visible_to_every_gate_and_restored_afterwards(foreign, monkeypatch):
    flag(foreign, 11, 'domiporta', needs_update=1)
    attempt, claim = foreign_job(foreign)
    order, trace = [], []
    _spy(monkeypatch, order, trace)
    assert attempts._domain.get() == 'domestic'
    decision = start(attempt, claim, settings=foreign[1], domain='foreign')
    assert decision['can_send'] is True
    assert order == ['fence', 'dispatch', 'current', 'qualify', 'append']
    assert all(entry[4] is True for entry in trace)                                    # _foreign() was True during every step
    assert trace[0][1] is None                                                         # the foreign fence reads the job DB on its OWN connection
    assert attempts._domain.get() == 'domestic' and attempts._foreign() is False


def test_a_domestic_start_never_sees_the_foreign_domain(ready, monkeypatch):
    attempt, claim = domestic_job(ready)
    order, trace = [], []
    _spy(monkeypatch, order, trace)
    start(attempt, claim)
    assert all(entry[4] is False for entry in trace) and trace[0][1] is not None       # the domestic fence shares the transaction connection


def test_a_claim_of_another_domain_is_refused_as_job_identity_mismatch(ready):
    attempt, claim = domestic_job(ready)
    foreign_claim = claim.__class__(**{**claim.__dict__, 'domain': 'foreign'})
    decision = start(attempt, foreign_claim)
    assert decision['can_send'] is False and decision['reason'] == 'job_identity_mismatch' and decision['state'] == 'prepared'
    assert attempts._domain.get() == 'domestic'


@pytest.mark.parametrize('bad', ['bogus', '', None, 'Domestic'])
def test_an_invalid_domain_raises_before_any_gate_and_leaves_the_context_unchanged(ready, monkeypatch, bad):
    attempt, claim = domestic_job(ready)
    order, trace = [], []
    _spy(monkeypatch, order, trace)
    with pytest.raises(attempts.AttemptError, match='^Invalid domain$'):
        start(attempt, claim, domain=bad)
    assert order == [] and attempts._domain.get() == 'domestic'
    assert attempts.get_attempt(attempt['attempt_id'])['state'] == 'prepared'


@pytest.mark.parametrize('domain', ['domestic', 'foreign'])
def test_the_context_and_the_lock_are_restored_after_an_exception_in_a_gate(domain, request, monkeypatch):
    env = request.getfixturevalue('foreign' if domain == 'foreign' else 'ready')
    if domain == 'foreign':
        flag(env, 11, 'domiporta', needs_update=1)
        attempt, claim = foreign_job(env)
        extra = {'settings': env[1], 'domain': 'foreign'}
    else:
        attempt, claim = domestic_job(env)
        extra = {}

    def boom():
        assert attempts._foreign() == (domain == 'foreign')                            # the failing gate still saw the right domain
        raise RuntimeError('control exploded')
    original = control.dispatch_enabled
    monkeypatch.setattr(control, 'dispatch_enabled', boom)
    with pytest.raises(RuntimeError, match='control exploded'):
        start(attempt, claim, **extra)
    assert attempts._domain.get() == 'domestic' and attempts._foreign() is False       # ContextVar reset
    assert _held.get() is None
    with input_lock():                                                                 # the file lock was released (no leak)
        pass
    monkeypatch.setattr(control, 'dispatch_enabled', original)
    state = attempts.get_attempt(attempt['attempt_id'], **({'domain': 'foreign'} if domain == 'foreign' else {}))['state']
    assert state == 'prepared'                                                         # nothing was committed


def test_concurrent_contexts_do_not_leak_the_domain(foreign, ready_unused=None):
    import contextvars
    token_domain = []
    ctx = contextvars.copy_context()
    ctx.run(lambda: attempts._domain.set('foreign'))
    assert attempts._domain.get() == 'domestic'                                        # a set in another context does not change this one
    assert ctx.run(attempts._domain.get) == 'foreign'
