"""D09: resolution of UNKNOWN / ACK_REJECTED attempts (contract scenarios D09-T01..T27 plus recovery/concurrency).

A resolution only APPENDS history events and reconciles the job store. It never sends, STARTs, prepares or
acknowledges; the fixtures below make any such call fail the test.
"""
from contextlib import closing
import json
import sqlite3
import threading
import time
import uuid

import pytest

from InvestmentManager import scheduled_jobs
from InvestmentManager.integrator import domestic_batch, export_attempts as attempts
from InvestmentManager.integrator import export_start
from InvestmentManager.integrator import export_automation as auto
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_resolution as res
from InvestmentManager.integrator import export_transport_config as cfg
from InvestmentManager.integrator import package_delivery as pd
from InvestmentManager.integrator import portal_transport, sync_tasks
from InvestmentManager.integrator.input_consistency import LockBusy
from tests.investmentmanager import qualification_support as support

BASE = '/crm/offers/export-jobs'
USER = 'user:7'
UNKNOWN = ['prepared', 'transport_unknown']
REJECTED = ['prepared', 'transport_unknown', 'transport_confirmed', 'ack_rejected']


@pytest.fixture
def box(tmp_path, monkeypatch):
    root = tmp_path / 'InvestmentData'
    root.mkdir()
    monkeypatch.setenv('DATA_DIR', str(root))
    support.init_root(root)
    assert jobs.init_schema(backup=False) == 'created'
    control.set_dispatch(True, changed_by='test')
    forbidden = lambda *a, **k: pytest.fail('a resolution reached generation/transport/START/ACK')
    for owner, name in ((portal_transport, 'upload_portal_zip'), (domestic_batch, 'process_offer'), (pd, 'execute_delivery'),
                        (pd, 'execute_ack_only'), (export_start, 'start_qualified_transport'), (attempts, 'start_gated_transport'), (attempts, 'start_transport'),
                        (attempts, 'create_attempt'), (attempts, 'record_transport_result')):
        monkeypatch.setattr(owner, name, forbidden)
    return root


class Made:
    def __init__(self, root, attempt_id, package_id, offer, portal, job_id):
        self.root, self.attempt_id, self.package_id, self.offer, self.portal, self.job_id = root, attempt_id, package_id, offer, portal, job_id


def make(root, *, offer=10, portal='no', states=UNKNOWN, job='needs_review', open_marker=True):
    """An attempt with the given history and (optionally) its delivery job in the given state."""
    job_id = None
    attempt_id = uuid.uuid4().hex
    if job:
        receipt = jobs.create_delivery({'domain': 'domestic', 'subject': {'kind': 'offer', 'id': offer}, 'portal': portal, 'action': 'add',
                                        'package': {'mode': 'ensure_current'}}, actor=USER, idempotency_key=uuid.uuid4().hex, dispatch_enabled=True)
        job_id = receipt.job_id
        claim = jobs.claim_next('delivery')
        attempt_id = claim.planned_attempt_id
    with closing(sqlite3.connect(root / 'databases/IDB.db')) as conn, conn:
        package = support._domestic_attempt(conn, offer, portal, 'add', states, attempt_id=attempt_id)
        if open_marker:
            conn.execute("INSERT INTO offer_portal_sync_events(offer_id,portal_key,event_type,payload_json,created_at) VALUES (?,?,?,?,datetime('now'))",
                         (offer, portal, 'export_transport_open_v1', json.dumps({'attempt_id': attempt_id})))
    if job:
        binding = attempts.inspect_attempt(attempt_id)['attempt']['binding']
        claim = jobs.advance(claim, phase='transport', references={'package_id': package, 'binding_sha256': jobs.binding_digest(binding),
                                                                    'attempt_anchor_id': offer, 'attempt_id': attempt_id})
        if job == 'needs_review':
            jobs.advance(claim, state='needs_review', reason_code='transport_unknown' if 'ack_rejected' not in states else 'ack_rejected')
    return Made(root, attempt_id, package, offer, portal, job_id)


def attempt(made):
    return attempts.inspect_attempt(made.attempt_id)['attempt']


def profile(made):
    return cfg.profile_for('domestic', made.portal)


def stamp(epoch):
    return jobs.now_iso(epoch)


def evidence(made, epoch, **over):
    base = dict(source='importer_report', finding='present_exact', queue_state='consumed', observed_at=stamp(epoch),
                subject_ref=str(made.offer), portal=made.portal, profile=profile(made), package_id=made.package_id,
                zip_sha256='e' * 64, reference='raport importu 123', note='')
    base.update(over)
    return {key: value for key, value in base.items() if value is not None}


def resolve(made, outcome, *, epoch=None, now=None, key=None, actor=USER, expected=None, **over):
    now = jobs.clock() + 10 * 86400 if now is None else now
    epoch = now - 86400 if epoch is None else epoch
    expected = attempt(made)['event_id'] if expected is None else expected
    return res.resolve(domain='domestic', attempt_id=made.attempt_id, outcome=outcome, expected_event_id=expected,
                       evidence=evidence(made, epoch, **over), actor=actor, idempotency_key=key or uuid.uuid4().hex, now=now)


def refused(made, outcome, code, **kw):
    before = history(made)
    with pytest.raises(res.Refused) as info:
        resolve(made, outcome, **kw)
    assert info.value.code == code, info.value.code
    assert history(made) == before                                   # a refusal never writes
    return info.value


def history(made):
    with closing(sqlite3.connect(made.root / 'databases/IDB.db')) as conn:
        return conn.execute('SELECT id,event_type,payload_json FROM offer_portal_sync_events WHERE offer_id=? ORDER BY id', (made.offer,)).fetchall()


def events_of(made, kind):
    return [row for row in history(made) if row[1] == kind]


def set_window(profile_name, seconds=3600):
    return res.set_window(profile_name, seconds, verified_by='operator test', source='portal support ticket (test)')


def job_state(made):
    return jobs.get_job(made.job_id)['state'], jobs.get_job(made.job_id)['reason_code']


# ------------------------------------------------------------------ T01/T02 published_exact then ACK-only
def test_T01_published_exact_confirms_for_ack_only_without_touching_crm(box):
    made = make(box)
    out = resolve(made, 'published_exact')
    assert out['state'] == 'transport_confirmed' and out['replayed'] is False
    item = attempt(made)
    assert item['state'] == 'transport_confirmed' and item['resolution']['outcome'] == 'published_exact' and item['resolution']['decided_by'] == USER
    assert job_state(made)[0] == 'needs_review' and out['job']['resolution'] == 'awaiting_ack'      # reserved until ACK-only completes it
    with closing(sqlite3.connect(box / 'databases/IDB.db')) as conn:
        assert conn.execute('SELECT COUNT(*) FROM offer_portal_sync').fetchone()[0] == 0     # no is_published / needs_update written
    assert len(events_of(made, 'export_attempt_resolution_v1')) == 1
    audit = json.loads(events_of(made, 'export_attempt_resolution_v1')[0][2])
    assert audit['from_state'] == 'transport_unknown' and audit['evidence']['reference'] == 'raport importu 123' and audit['decided_by'] == USER
    assert not events_of(made, 'export_transport_closed_v1')                                 # closed only by ACK
    with pytest.raises(jobs.ActiveJobConflict):                                              # the unit stays reserved
        jobs.create_delivery(intent(), actor=USER, idempotency_key=uuid.uuid4().hex, dispatch_enabled=True)
    jobs.create_ack_recovery({'domain': 'domestic', 'attempt_id': made.attempt_id, 'subject_kind': 'offer', 'subject_id': 10, 'portal': 'no',
                              'action': 'add', 'package_id': made.package_id, 'binding_sha256': jobs.binding_digest(attempt(made)['binding']),
                              'attempt_anchor_id': 10}, actor=USER, idempotency_key=uuid.uuid4().hex, parent_job_id=made.job_id)
    jobs.complete_review(made.job_id, reason_code='recovered_by_ack_only')                   # what a successful ACK-only does to its parent
    assert job_state(made) == ('completed', 'recovered_by_ack_only')


def test_T02_ack_after_published_exact_rechecks_and_may_be_rejected(box):
    made = make(box)
    resolve(made, 'published_exact')
    ack = attempts.acknowledge_attempt(made.attempt_id, attempt(made)['binding'])       # package files do not exist here
    assert ack['state'] == 'ack_rejected'
    refused_made = made
    out = resolve(refused_made, 'obsolete_after_publish')
    assert out['state'] == 'resolved_obsolete'
    assert len(events_of(made, 'export_transport_closed_v1')) == 1


# ------------------------------------------------------------------ not_published
def full_not_published(made, **over):
    set_window(profile(made))
    return resolve(made, 'not_published', source='importer_report', finding='absent', queue_state='consumed', **over)


def test_T03_not_published_before_the_import_window_is_refused(box):
    made = make(box)
    set_window(profile(made), 3600)
    now = jobs.clock() + 5 * 86400
    refused(made, 'not_published', 'import_window_open', now=now, epoch=jobs.clock() + 1800, finding='absent')
    assert attempt(made)['state'] == 'transport_unknown' and job_state(made)[0] == 'needs_review'


def test_T04_missing_or_corrupt_window_blocks_not_published(box):
    made = make(box)
    refused(made, 'not_published', 'import_window_not_configured', finding='absent')
    (scheduled_jobs._directory(create=True) / res.WINDOWS_FILE).write_text('{')
    refused(made, 'not_published', 'import_window_not_configured', finding='absent')


def test_T05_old_file_possibly_still_queued_is_refused(box):
    made = make(box)
    set_window(profile(made))
    refused(made, 'not_published', 'file_may_be_queued', finding='file_still_queued', queue_state='still_queued')
    refused(made, 'not_published', 'file_may_be_queued', finding='absent', queue_state='unknown')
    refused(made, 'not_published', 'evidence_indeterminate', finding='indeterminate', queue_state='consumed')


def test_T27_one_master_resolves_not_published_alone_and_everything_is_audited(box):
    made = make(box)
    out = full_not_published(made)
    assert out['state'] == 'resolved_not_published' and job_state(made) == ('completed', 'resolved_not_published')
    item = attempt(made)
    assert item['resolution']['decided_by'] == USER and item['resolution']['outcome'] == 'not_published'
    assert len(events_of(made, 'export_transport_closed_v1')) == 1                    # legacy readers see the transport closed
    assert not attempts.has_unresolved_transport(sqlite3.connect(box / 'databases/IDB.db'), made.offer)


def test_unknown_transport_end_needs_an_importer_report(box):
    """Without a job there is no trustworthy upper bound of the transfer: absence is not enough, 'consumed' by the importer is."""
    made = make(box, job=None)
    set_window(profile(made))
    refused(made, 'not_published', 'transport_end_unknown', finding='absent')
    refused(made, 'not_published', 'evidence_invalid', finding='file_consumed', source='public_listing')
    out = resolve(made, 'not_published', finding='file_consumed', source='importer_report', queue_state='consumed')
    assert out['state'] == 'resolved_not_published' and out['job'] is None


def test_consumed_by_the_importer_still_respects_the_window_from_the_attempt_event(box):
    made = make(box, job=None)
    set_window(profile(made), 3600)
    now = jobs.clock() + 5 * 86400
    refused(made, 'not_published', 'import_window_open', now=now, epoch=jobs.clock() + 600, finding='file_consumed', source='importer_report')
    assert resolve(made, 'not_published', now=now, epoch=jobs.clock() + 7200, finding='file_consumed', source='importer_report')['state'] == 'resolved_not_published'


def backdate_attempt(made, seconds):
    """Move the attempt's events into the past (the transfer then ended long before the executor was declared stopped)."""
    from datetime import datetime, timezone
    when = datetime.fromtimestamp(time.time() - seconds, timezone.utc).isoformat()
    with closing(sqlite3.connect(made.root / 'databases/IDB.db')) as conn, conn:
        conn.execute('UPDATE offer_portal_sync_events SET created_at=? WHERE offer_id=? AND event_type LIKE ?', (when, made.offer, 'export_attempt%'))


def test_the_executor_stop_time_not_the_start_time_bounds_absence(box):
    """The window is counted from when the executor was known to have stopped (the needs_review event), not from START."""
    made = make(box)
    backdate_attempt(made, 2 * 86400)                                  # START two days ago; the executor was declared stopped just now
    set_window(profile(made), 3600)
    stopped = res._epoch(jobs.review_since(made.job_id))
    now = stopped + 100000
    refused(made, 'not_published', 'import_window_open', now=now, epoch=stopped + 1000, finding='absent')       # past START+window, inside stopped+window
    out = resolve(made, 'not_published', now=now, epoch=stopped + 3700, finding='absent', source='importer_report')
    assert out['state'] == 'resolved_not_published'


# ------------------------------------------------------------------ evidence validation
@pytest.mark.parametrize('over', [dict(portal='domiporta'), dict(profile='gruntguru'), dict(subject_ref='999'), dict(package_id='a' * 32),
                                  dict(zip_sha256='0' * 64)])
def test_T06_evidence_for_another_portal_account_offer_or_package_is_a_mismatch(box, over):
    made = make(box)
    refused(made, 'published_exact', 'evidence_mismatch', **over)


def test_T07_evidence_before_the_attempt_or_in_the_future_is_refused(box):
    made = make(box)
    now = jobs.clock() + 10 * 86400
    refused(made, 'published_exact', 'evidence_invalid', now=now, epoch=jobs.clock() - 3600)             # before the attempt's own event
    refused(made, 'published_exact', 'evidence_invalid', now=now, epoch=now + 3600)                      # in the future
    refused(made, 'published_exact', 'evidence_invalid', observed_at='yesterday')


@pytest.mark.parametrize('over,code', [(dict(source='public_listing'), 'evidence_invalid'), (dict(finding='present_different'), 'evidence_invalid'),
                                       (dict(package_id=None), 'evidence_missing'), (dict(zip_sha256=None), 'evidence_missing'),
                                       (dict(reference=None), 'evidence_missing'), (dict(reference='x' * 301), 'evidence_invalid'),
                                       (dict(note='n' * 501), 'evidence_invalid'), (dict(extra='x'), 'invalid_request')])
def test_published_exact_evidence_shape(box, over, code):
    made = make(box)
    refused(made, 'published_exact', code, **over)


def test_evidence_text_is_stored_as_text_not_markup(box):
    made = make(box)
    resolve(made, 'published_exact', note='<script>alert(1)</script>', reference='<b>x</b>')
    audit = json.loads(events_of(made, 'export_attempt_resolution_v1')[0][2])
    assert audit['evidence']['note'] == '<script>alert(1)</script>' and audit['evidence']['reference'] == '<b>x</b>'


def test_superseded_needs_present_different_evidence(box):
    made = make(box)
    refused(made, 'superseded', 'evidence_invalid', finding='absent')
    out = resolve(made, 'superseded', finding='present_different', package_id=None, zip_sha256=None)
    assert out['state'] == 'resolved_superseded' and job_state(made) == ('completed', 'resolved_superseded')
    assert len(events_of(made, 'export_transport_closed_v1')) == 1


def test_obsolete_after_publish_requires_that_the_data_really_changed(box, monkeypatch):
    made = make(box, states=REJECTED)
    monkeypatch.setattr(attempts, '_current', lambda *a, **k: None)                          # the package is still current
    refused(made, 'obsolete_after_publish', 'data_still_current')


# ------------------------------------------------------------------ state matrix
@pytest.mark.parametrize('states', [['prepared'], ['prepared', 'transport_unknown', 'transport_confirmed'],
                                    ['prepared', 'transport_unknown', 'transport_confirmed', 'ack_failed'],
                                    ['prepared', 'transport_unknown', 'transport_failed'],
                                    ['prepared', 'transport_unknown', 'transport_confirmed', 'ack_completed']])
def test_T08_only_unknown_and_ack_rejected_are_resolvable(box, states):
    made = make(box, states=states, job=None)
    refused(made, 'published_exact', 'attempt_not_resolvable')
    refused(made, 'superseded', 'attempt_not_resolvable', finding='present_different')


def test_T09_ack_rejected_only_accepts_superseded_or_obsolete(box):
    made = make(box, states=REJECTED)
    refused(made, 'published_exact', 'attempt_not_resolvable')
    refused(made, 'not_published', 'attempt_not_resolvable', finding='absent')
    assert resolve(made, 'superseded', finding='present_different')['state'] == 'resolved_superseded'


# ------------------------------------------------------------------ permissions
@pytest.mark.parametrize('actor', ['system:runner', 'policy:auto', 'user:', 'user:abc', '', None, 'master'])
def test_T10_only_a_user_actor_can_resolve(box, actor):
    made = make(box)
    refused(made, 'published_exact', 'forbidden', actor=actor)


# ------------------------------------------------------------------ idempotency, CAS, concurrency
def test_T12_same_key_repeats_the_result_and_releases_once(box):
    made = make(box)
    key = uuid.uuid4().hex
    seen = attempt(made)['event_id']
    now = jobs.clock() + 10 * 86400
    first = resolve(made, 'superseded', key=key, expected=seen, now=now, finding='present_different')
    second = resolve(made, 'superseded', key=key, expected=seen, now=now, finding='present_different')      # the lost-response retry: same body, CAS value now stale
    assert second['replayed'] is True and second['resolution_event_id'] == first['resolution_event_id']
    assert len(events_of(made, 'export_attempt_resolution_v1')) == 1
    recovered = [e for e in jobs.list_events(made.job_id)['items'] if e['event_type'] == 'recovered']
    assert len(recovered) == 1


def test_T13_same_key_different_decision_is_a_conflict(box):
    made = make(box)
    key = uuid.uuid4().hex
    resolve(made, 'published_exact', key=key)
    with pytest.raises(res.Refused) as info:
        resolve(made, 'published_exact', key=key, reference='another reference')
    assert info.value.code == 'idempotency_conflict'


def test_T14_stale_expected_event_is_refused(box):
    made = make(box)
    refused(made, 'published_exact', 'attempt_changed', expected=attempt(made)['event_id'] - 1)
    refused(made, 'published_exact', 'invalid_request', expected=0)


def test_T15_running_delivery_or_open_ack_only_blocks(box):
    made = make(box, job='running')
    refused(made, 'published_exact', 'delivery_in_progress')
    other = make(box, offer=11)
    jobs.create_ack_recovery({'domain': 'domestic', 'attempt_id': other.attempt_id, 'subject_kind': 'offer', 'subject_id': 11, 'portal': 'no',
                              'action': 'add', 'package_id': other.package_id, 'binding_sha256': jobs.binding_digest(attempt(other)['binding']),
                              'attempt_anchor_id': 11}, actor=USER, idempotency_key=uuid.uuid4().hex)
    refused(other, 'published_exact', 'ack_in_progress')


def test_T16_a_newer_attempt_of_the_unit_blocks(box):
    made = make(box)
    with closing(sqlite3.connect(box / 'databases/IDB.db')) as conn, conn:
        support._domestic_attempt(conn, 10, 'no', 'add', ['prepared'])
    refused(made, 'published_exact', 'later_attempt_exists')


def test_T25_a_pending_legacy_transport_blocks(box):
    made = make(box)
    with closing(sqlite3.connect(box / 'databases/IDB.db')) as conn, conn:
        conn.execute("INSERT INTO offer_portal_sync_events(offer_id,portal_key,event_type,payload_json,created_at) VALUES (10,'no','legacy_attempt_started','{\"x\":1}',datetime('now'))")
    refused(made, 'published_exact', 'legacy_attempt_unsupported')


def test_two_simultaneous_resolutions_have_exactly_one_winner(box):
    made = make(box)
    barrier, outcomes = threading.Barrier(2), []

    def worker():
        barrier.wait()
        try:
            outcomes.append(resolve(made, 'published_exact', key=uuid.uuid4().hex)['replayed'])
        except (res.Refused, LockBusy) as exc:
            outcomes.append(getattr(exc, 'code', 'lock_busy'))
    threads = [threading.Thread(target=worker) for _ in range(2)]
    [t.start() for t in threads]
    [t.join() for t in threads]
    assert outcomes.count(False) == 1
    assert len(events_of(made, 'export_attempt_resolution_v1')) == 1
    assert job_state(made)[0] == 'needs_review'                                                # reserved: ACK-only completes it


def test_a_concurrent_ack_move_makes_the_decision_stale(box):
    """The attempt changed (state moved) between the operator's read and the decision."""
    made = make(box)
    seen = attempt(made)['event_id']
    with closing(sqlite3.connect(box / 'databases/IDB.db')) as conn, conn:
        payload = dict(attempt(made))
        payload.pop('event_id')
        payload['state'] = 'transport_confirmed'
        conn.execute("INSERT INTO offer_portal_sync_events(offer_id,portal_key,event_type,payload_json,created_at) VALUES (10,'no','export_attempt_v1',?,datetime('now'))",
                     (json.dumps(payload),))
    refused(made, 'published_exact', 'attempt_not_resolvable', expected=seen)


def test_T26_busy_input_lock_writes_nothing(box, monkeypatch):
    made = make(box)
    before = history(made)

    def busy():
        raise LockBusy('busy')
    monkeypatch.setattr(attempts, 'input_lock', busy)
    with pytest.raises(LockBusy):
        resolve(made, 'published_exact')
    assert history(made) == before


# ------------------------------------------------------------------ recovery between the two databases
def test_T18_crash_before_the_decision_changes_nothing_and_retry_works(box, monkeypatch):
    made = make(box)
    before = history(made)
    original = attempts._append
    monkeypatch.setattr(attempts, '_append', lambda *a, **k: (_ for _ in ()).throw(RuntimeError('crash')))
    with pytest.raises(RuntimeError):
        resolve(made, 'published_exact')
    monkeypatch.setattr(attempts, '_append', original)
    assert history(made) == before and job_state(made)[0] == 'needs_review'                   # rolled back: no half decision
    assert resolve(made, 'published_exact')['state'] == 'transport_confirmed'


def test_T17_crash_after_the_decision_is_reconciled_by_the_next_tick_without_ftp(box, monkeypatch):
    made = make(box)
    original_settle = res.settle_job
    monkeypatch.setattr(res, 'settle_job', lambda *a, **k: None)                                  # process dies before the job update
    resolve(made, 'superseded', finding='present_different')
    assert attempt(made)['state'] == 'resolved_superseded' and job_state(made)[0] == 'needs_review'
    monkeypatch.setattr(res, 'settle_job', original_settle)
    forbidden = lambda *a, **k: pytest.fail('recovery reached FTP')
    for owner, name in ((portal_transport, 'upload_portal_zip'), (pd, 'execute_delivery'), (pd, 'execute_ack_only')):
        monkeypatch.setattr(owner, name, forbidden)
    result = runner.tick_one(env=None)
    assert result['resolutions_reconciled'] == [{'job_id': made.job_id, 'resolution': 'completed', 'outcome': 'superseded'}]
    assert job_state(made) == ('completed', 'resolved_superseded')
    assert 'resolutions_reconciled' not in runner.tick_one(env=None)                              # released exactly once
    assert [e['event_type'] for e in jobs.list_events(made.job_id)['items']].count('recovered') == 1


def test_reconcile_ignores_unresolved_attempts(box):
    made = make(box)
    assert res.reconcile() == [] and job_state(made)[0] == 'needs_review'


# ------------------------------------------------------------------ after the decision
def test_T19_a_not_published_package_is_never_reused_and_the_unit_is_released(box):
    made = make(box)
    full_not_published(made)
    assert attempts.RESOLVED_STATES.isdisjoint(sync_tasks.UNRESOLVED)
    pointer = {'packages': {'no': made.package_id}, 'action': 'add', 'offer_id': 10}
    assert domestic_batch._completed_portals(box, pointer, [{'portal': 'no', 'action': 'add'}]) == ['no']   # forces manual new package
    other = {'packages': {'no': uuid.uuid4().hex}, 'action': 'add', 'offer_id': 10}
    assert domestic_batch._completed_portals(box, other, [{'portal': 'no', 'action': 'add'}]) == []


def intent(subject=10, portal='no'):
    return {'domain': 'domestic', 'subject': {'kind': 'offer', 'id': subject}, 'portal': portal, 'action': 'add', 'package': {'mode': 'ensure_current'}}


def automatic(subject=10, slot='s1'):
    return dict(intent=intent(subject), actor='policy:auto', idempotency_key=uuid.uuid4().hex, dispatch_enabled=True, source='automation',
                policy={'id': 'auto', 'version': 1, 'slot': slot})


def test_T20_automation_cannot_create_the_first_job_after_not_published(box):
    made = make(box)
    full_not_published(made)
    spec = automatic()
    with pytest.raises(jobs.ManualFirstRequired):
        jobs.create_delivery(spec.pop('intent'), **spec)
    # still refused much later (cooldown long over) and with a different slot / "after a restart": the proof is durable
    for slot in ('s2', 's3'):
        spec = automatic(slot=slot)
        with pytest.raises(jobs.ManualFirstRequired):
            jobs.create_delivery(spec.pop('intent'), **spec)
    assert _auto_count() == 0
    # a manual job created after the decision satisfies the rule once it was really attempted (not cancelled)
    manual = jobs.create_delivery(intent(), actor=USER, idempotency_key=uuid.uuid4().hex, dispatch_enabled=True)
    jobs.cancel_job(manual.job_id, expected_version=1, actor=USER)
    spec = automatic(slot='s4')
    with pytest.raises(jobs.ManualFirstRequired):
        jobs.create_delivery(spec.pop('intent'), **spec)                                            # a cancelled job proves nothing
    second = jobs.create_delivery(intent(), actor=USER, idempotency_key=uuid.uuid4().hex, dispatch_enabled=True)
    claim = jobs.claim_next('delivery')
    jobs.advance(claim, state='failed', reason_code='transport_failed')
    assert second.job_id == claim.job_id
    spec = automatic(slot='s5')
    assert jobs.create_delivery(spec.pop('intent'), **spec).state == 'queued'


def _auto_count():
    with jobs._reader(jobs.WORKER_TIMEOUT) as conn:
        return conn.execute("SELECT COUNT(*) FROM export_jobs WHERE source='automation'").fetchone()[0]


def test_T20_the_automation_module_reports_the_hard_block(box):
    made = make(box)
    full_not_published(made)
    auto.enable(portals=['no'], changed_by='test')
    task = {'domain': 'domestic', 'subject': {'kind': 'offer', 'id': 10}, 'portal': 'no', 'action': 'add', 'category': 'new', 'issue': None,
            'last_result': None, 'offer_ids': [10]}
    summary = auto.run(rows_fn=lambda **k: {'items': [task], 'total': 1}, destination_ok=lambda t: True)
    assert summary['skipped'] == {'manual_first_required': 1} and summary['created'] == 0 and _auto_count() == 0


def test_automation_is_unaffected_for_other_units(box):
    made = make(box)
    full_not_published(made)
    spec = automatic(subject=11)
    assert jobs.create_delivery(spec.pop('intent'), **spec).state == 'queued'


# ------------------------------------------------------------------ architecture
def test_T22_resolution_code_has_no_transport_start_or_ack_path():
    import inspect
    forbidden = ('portal_transport', 'package_delivery', 'start_qualified_transport', 'start_gated_transport', 'export_start', 'start_transport', 'upload', 'ftplib', 'socket',
                 'create_attempt', 'acknowledge_attempt', 'record_transport_result', 'subprocess', 'is_published', 'needs_update')
    source = inspect.getsource(res)
    core = inspect.getsource(attempts.resolve_attempt)
    for text in (source, core):
        lowered = text.lower()
        for word in forbidden:
            assert word.lower() not in lowered, word
    assert 'offer_portal_sync ' not in source and 'offer_portal_sync(' not in source          # never writes publication rows


def test_resolve_only_appends_history_events(box):
    made = make(box)
    before = {row[0] for row in history(made)}
    resolve(made, 'published_exact')
    after = history(made)
    assert before <= {row[0] for row in after}                                                  # nothing was rewritten or removed
    assert {row[1] for row in after if row[0] not in before} == {'export_attempt_resolution_v1', 'export_attempt_v1'}


# ------------------------------------------------------------------ import-window configuration and CLI
def test_import_windows_are_explicit_verified_and_bounded(box):
    assert res.read_windows() == {'status': 'missing', 'windows': {}}
    for bad in (dict(profile='nope', seconds=3600), dict(profile='no', seconds=5), dict(profile='no', seconds=10 ** 9),
                dict(profile='no', seconds=3600, verified_by=' '), dict(profile='no', seconds=3600, source='')):
        kw = dict(verified_by='op', source='ticket') | {k: v for k, v in bad.items() if k not in ('profile', 'seconds')}
        with pytest.raises(ValueError):
            res.set_window(bad['profile'], bad['seconds'], **kw)
    out = set_window('no', 7200)
    assert out['windows']['no']['seconds'] == 7200 and out['windows']['no']['verified_by'] == 'operator test'


def test_cli_import_window(box, capsys):
    assert runner.main(['import-window-status']) == 0 and json.loads(capsys.readouterr().out)['status'] == 'missing'
    assert runner.main(['import-window-set', '--profile', 'no', '--seconds', '3600']) == 1          # provenance is mandatory
    capsys.readouterr()
    assert runner.main(['import-window-set', '--profile', 'no', '--seconds', '3600', '--verified-by', 'op', '--source', 'ticket']) == 0
    assert json.loads(capsys.readouterr().out)['windows']['no']['seconds'] == 3600


def test_info_lists_outcomes_requirements_and_blockers(box):
    made = make(box)
    info = res.info('domestic', made.attempt_id)
    assert info['resolvable'] and info['state'] == 'transport_unknown' and info['profile'] == profile(made)
    assert [o['outcome'] for o in info['outcomes']] == ['published_exact', 'not_published', 'superseded']
    blockers = {o['outcome']: o['blockers'] for o in info['outcomes']}
    assert blockers['not_published'] == ['import_window_not_configured'] and blockers['published_exact'] == []
    assert info['executor_stopped_at'] and info['attempt_event_at']
    set_window(profile(made))
    assert res.info('domestic', made.attempt_id)['outcomes'][1]['blockers'] == []
    done = make(box, offer=12, states=['prepared', 'transport_unknown', 'transport_confirmed', 'ack_completed'], job=None)
    assert res.info('domestic', done.attempt_id)['resolvable'] is False
    with pytest.raises(res.Refused):
        res.info('domestic', uuid.uuid4().hex)


# ------------------------------------------------------------------ foreign domain
def test_foreign_unknown_attempt_can_be_resolved_and_closes_its_marker(box):
    from InvestmentManager import foreign_offers_store as store
    with closing(store.open_foreign_offers_connection()) as conn:
        conn.execute('BEGIN IMMEDIATE')
        conn.execute("INSERT OR IGNORE INTO foreign_developments(id,name) VALUES (7,'P7')")
        for offer in (100, 101):
            conn.execute("INSERT INTO foreign_offers(id,source_platform,source_url,offer_title,is_active,development_id) VALUES (?,?,?,?,1,7)",
                         (offer, 'cyprus_constructions', f'https://x.invalid/{offer}', f'F{offer}'))
        support._foreign_attempt(conn, 100, 'tabelaofert', 'add', ['prepared', 'transport_unknown'], members=[100, 101],
                                 subject={'kind': 'cyprus_development', 'id': 7}, revision=0)
        conn.execute("INSERT INTO foreign_offer_portal_sync_events(foreign_offer_id,portal_key,event_type,payload_json) VALUES (100,'tabelaofert','export_transport_open_v2',?)",
                     (json.dumps({'attempt_id': 'x'}),))
        conn.commit()
    with closing(sqlite3.connect(box / 'databases/foreign_offers.db')) as conn:
        row = conn.execute("SELECT payload_json FROM foreign_offer_portal_sync_events WHERE event_type='export_attempt_v2'").fetchone()
    item = json.loads(row[0])
    attempt_id, binding = item['attempt_id'], item['binding']
    with closing(sqlite3.connect(box / 'databases/foreign_offers.db')) as conn, conn:
        conn.execute("UPDATE foreign_offer_portal_sync_events SET payload_json=? WHERE event_type='export_transport_open_v2'", (json.dumps({'attempt_id': attempt_id}),))
        event_id = conn.execute("SELECT MAX(id) FROM foreign_offer_portal_sync_events WHERE event_type='export_attempt_v2'").fetchone()[0]
    now = jobs.clock() + 10 * 86400
    ev = dict(source='importer_report', finding='present_different', queue_state='consumed', observed_at=stamp(now - 86400), subject_ref='7',
              portal='tabelaofert', profile=cfg.profile_for('foreign', 'tabelaofert'), reference='r1')
    out = res.resolve(domain='foreign', attempt_id=attempt_id, outcome='superseded', expected_event_id=event_id, evidence=ev, actor=USER,
                      idempotency_key=uuid.uuid4().hex, now=now)
    assert out['state'] == 'resolved_superseded'
    with closing(sqlite3.connect(box / 'databases/foreign_offers.db')) as conn:
        types = [r[0] for r in conn.execute('SELECT event_type FROM foreign_offer_portal_sync_events ORDER BY id')]
    assert 'export_attempt_resolution_v1' in types and types.count('export_transport_closed_v2') == 1
    assert attempts.inspect_attempt(attempt_id, domain='foreign')['attempt']['state'] == 'resolved_superseded'


# ------------------------------------------------------------------ legacy / compatibility
def test_T24_legacy_readers_stay_fail_closed(box):
    made = make(box)
    full_not_published(made)
    import InvestmentManager.export_handoff as handoff
    import inspect
    assert 'resolved_not_published' not in inspect.getsource(handoff)                 # old RPC answers 'operation_unavailable'
    assert 'resolved_' in inspect.getsource(sync_tasks) and attempts.PACKAGE_CONSUMED >= {'ack_completed'}
    import InvestmentManager.integrator.input_consistency as consistency
    assert all(state in inspect.getsource(consistency) for state in attempts.RESOLVED_STATES)       # pending-phase set kept in sync


def test_closing_outcomes_also_release_a_needs_review_ack_only_job(box):
    made = make(box, states=REJECTED)
    ack = jobs.create_ack_recovery({'domain': 'domestic', 'attempt_id': made.attempt_id, 'subject_kind': 'offer', 'subject_id': 10, 'portal': 'no',
                                    'action': 'add', 'package_id': made.package_id, 'binding_sha256': jobs.binding_digest(attempt(made)['binding']),
                                    'attempt_anchor_id': 10}, actor=USER, idempotency_key=uuid.uuid4().hex, parent_job_id=made.job_id)
    claim = jobs.claim_next('ack_only')
    jobs.advance(claim, state='needs_review', reason_code='ack_rejected')
    out = resolve(made, 'superseded', finding='present_different')
    assert set(out['job']['released']) == {made.job_id, ack.job_id}
    assert jobs.get_job(ack.job_id)['state'] == 'completed' and job_state(made)[0] == 'completed'


def test_T24_legacy_rpc_sees_confirmed_but_refuses_unknown_resolved_states(box):
    import InvestmentManager.export_handoff as handoff
    made = make(box)
    ask = lambda: handoff.dispatch_request({'operation': 'get_attempt', 'attempt_id': made.attempt_id})
    assert ask()['ok'] is True and ask()['attempt']['state'] == 'transport_unknown'
    other = make(box, offer=12)
    resolve(other, 'published_exact')
    assert handoff.dispatch_request({'operation': 'get_attempt', 'attempt_id': other.attempt_id})['attempt']['state'] == 'transport_confirmed'
    resolve(made, 'superseded', finding='present_different')
    denied = ask()
    assert denied['ok'] is False and denied['error'] == 'operation_unavailable'                  # old readers fail closed


# ------------------------------------------------------------------ HTTP
def login(client, level='master', user=7):
    with client.session_transaction() as session:
        session.clear()
        session['access_level'] = level
        if user is not None:
            session['user_id'] = user


@pytest.fixture
def web(client, box):
    login(client)
    client.box = box
    return client


def token(client):
    return client.get(BASE).json['csrf_token']


def http(client, made, outcome='published_exact', *, body=None, key=None, headers=None, csrf=True, **over):
    body = body if body is not None else {'domain': 'domestic', 'outcome': outcome, 'expected_event_id': attempt(made)['event_id'],
                                          'evidence': evidence(made, int(time.time()), **over)}
    headers = dict(headers or {})
    if csrf:
        headers.setdefault('X-Scheduler-CSRF', token(client))
    if key is not False:
        headers.setdefault('Idempotency-Key', key or uuid.uuid4().hex)
    return client.post(f'{BASE}/attempts/{made.attempt_id}/resolve', json=body, headers=headers)


def code(response):
    return response.json['error']['code']


def test_http_resolution_end_to_end(web):
    made = make(web.box)
    info = web.get(f'{BASE}/attempts/{made.attempt_id}/resolution-info?domain=domestic')
    assert info.status_code == 200 and info.json['resolvable'] and 'no-store' in info.headers['Cache-Control']
    time.sleep(1.2)
    key = uuid.uuid4().hex
    body = {'domain': 'domestic', 'outcome': 'published_exact', 'expected_event_id': attempt(made)['event_id'],
            'evidence': evidence(made, int(time.time()))}
    response = http(web, made, key=key, body=body)
    assert response.status_code == 201 and response.json['state'] == 'transport_confirmed' and response.json['replayed'] is False
    assert response.json['job']['resolution'] == 'awaiting_ack'
    again = http(web, made, key=key, body=body)                                                  # the lost-response retry
    assert again.status_code == 200 and again.json['replayed'] is True
    other = http(web, made, key=key, body=dict(body, outcome='superseded'))
    assert other.status_code == 409 and code(other) == 'idempotency_conflict'
    assert len(events_of(made, 'export_attempt_resolution_v1')) == 1


def test_http_security_and_validation(web):
    made = make(web.box)
    time.sleep(1.2)
    assert code(http(web, made, csrf=False)) == 'csrf_failed'
    assert code(http(web, made, key=False)) == 'invalid_request'
    assert code(http(web, made, headers={'Origin': 'https://evil.example'})) == 'origin_forbidden'
    assert code(http(web, made, body={'domain': 'domestic', 'outcome': 'published_exact', 'expected_event_id': 1, 'evidence': {},
                                      'is_published': True})) == 'invalid_request'
    assert code(http(web, made, body={'domain': 'domestic', 'outcome': 'published_exact', 'expected_event_id': 1, 'evidence': {},
                                      'actor': 'user:1'})) == 'invalid_request'
    assert code(http(web, made, body={'domain': 'domestic', 'outcome': 'force_ack', 'expected_event_id': 1, 'evidence': {}})) == 'invalid_request'
    stale = http(web, made, body={'domain': 'domestic', 'outcome': 'published_exact', 'expected_event_id': attempt(made)['event_id'] + 5,
                                  'evidence': evidence(made, int(time.time()))})
    assert stale.status_code == 412 and code(stale) == 'attempt_changed'
    assert code(http(web, made, package_id='a' * 32)) == 'evidence_mismatch'
    assert web.get(f'{BASE}/attempts/{"0" * 32}/resolution-info?domain=domestic').status_code == 404
    assert web.get(f'{BASE}/attempts/zz/resolution-info?domain=domestic').status_code == 400
    assert len(events_of(made, 'export_attempt_resolution_v1')) == 0


@pytest.mark.parametrize('level,user', [('agent', 7), ('manager', 7), ('master', None)])
def test_T10_http_non_master_gets_403(web, level, user):
    made = make(web.box)
    login(web, level, user)
    assert web.get(f'{BASE}/attempts/{made.attempt_id}/resolution-info?domain=domestic').status_code == 403
    response = web.post(f'{BASE}/attempts/{made.attempt_id}/resolve', json={}, headers={'Idempotency-Key': uuid.uuid4().hex})
    assert response.status_code == 403 and (user is None or code(response) == 'forbidden')
    assert len(events_of(made, 'export_attempt_resolution_v1')) == 0


def test_http_busy_lock_is_503_and_writes_nothing(web, monkeypatch):
    made = make(web.box)
    time.sleep(1.2)
    monkeypatch.setattr(attempts, 'input_lock', lambda: (_ for _ in ()).throw(LockBusy('busy')))
    response = http(web, made)
    assert response.status_code == 503 and code(response) == 'storage_busy'
    assert len(events_of(made, 'export_attempt_resolution_v1')) == 0
