"""2B.2: qualified START (atomic D03 qualification) with real packages and attempts."""
from contextlib import closing
import hashlib
import json
from pathlib import Path
import sqlite3
import subprocess
import sys
import uuid

import pytest

from tests.investmentmanager.test_domestic_packages import data_root, isolated, sql
from tests.investmentmanager.test_foreign_packages_v2 import foreign_root as make_foreign_root, prepare as prepare_foreign
from InvestmentManager import foreign_offers_store as store
from InvestmentManager.integrator import domestic_packages as prep
from InvestmentManager.integrator import export_attempts as attempts
from InvestmentManager.integrator import export_start
from InvestmentManager.integrator import export_control as control
from InvestmentManager.integrator import export_jobs as jobs
from InvestmentManager.integrator import sync_tasks as queue

REPO = Path(__file__).resolve().parents[2]
ACTOR = 'user:7'


@pytest.fixture
def ready(data_root):
    assert jobs.init_schema(backup=False) == 'created'
    control.set_dispatch(True, changed_by='test')
    return data_root


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


def linked_claim(intent, attempt, anchor):
    jobs.create_delivery(intent, actor=ACTOR, idempotency_key=uuid.uuid4().hex, dispatch_enabled=True)
    claim = jobs.claim_next('delivery')
    return jobs.advance(claim, phase='attempt_linked', references={
        'package_id': attempt['binding']['package_id'], 'binding_sha256': jobs.binding_digest(attempt['binding']),
        'attempt_anchor_id': anchor, 'attempt_id': attempt['attempt_id']})


def domestic_job(root, portal='no', action='add'):
    package = prep.prepare_package(17, portal, action)['package_id']
    attempt = attempts.create_attempt(package_id=package, offer_id=17, portal=portal, action=action)
    return attempt, linked_claim(domestic_intent(portal, action), attempt, 17)


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


def idb_events(root):
    with closing(sqlite3.connect(root / 'databases/IDB.db')) as conn:
        return conn.execute('SELECT COUNT(*) FROM offer_portal_sync_events').fetchone()[0]


def publication(root):
    with closing(sqlite3.connect(root / 'databases/IDB.db')) as conn:
        return conn.execute('SELECT * FROM offer_portal_sync ORDER BY 1,2').fetchall()


def test_own_prepared_is_qualified_and_only_the_first_start_may_send(ready):
    attempt, claim = domestic_job(ready)
    first = start(attempt, claim)
    assert first['can_send'] is True and first['state'] == 'transport_unknown' and 'reason' not in first
    again = start(attempt, claim)
    assert again['can_send'] is False and again['state'] == 'transport_unknown'
    assert attempts.get_attempt(attempt['attempt_id'])['state'] == 'transport_unknown'


def test_current_is_called_once_and_the_full_queue_is_never_run(ready, monkeypatch):
    attempt, claim = domestic_job(ready)
    calls = []
    original = attempts._current
    monkeypatch.setattr(attempts, '_current', lambda *a, **k: calls.append(1) or original(*a, **k))
    for name in ('list_tasks', 'list_offers', '_collect_tasks', 'qualify_foreign_units'):
        monkeypatch.setattr(queue, name, lambda *a, **k: pytest.fail('full queue called'))
    assert start(attempt, claim)['can_send'] is True
    assert calls == [1]


@pytest.mark.parametrize('setup,reason', [
    ('pause', 'dispatch_paused'), ('missing', 'dispatch_paused'), ('corrupt', 'control_unavailable'),
    ('requeued', 'claim_lost'), ('other_attempt', 'job_identity_mismatch'), ('other_binding', 'binding_changed'),
    ('inactive', None), ('published_current', None)])
def test_refusal_writes_nothing_and_keeps_the_attempt_prepared(ready, setup, reason):
    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})
    elif setup == 'inactive':
        sql(ready, "UPDATE EstateData SET Status_oferty='Nieaktywna'")
    elif setup == 'published_current':
        sql(ready, "INSERT INTO offer_portal_sync(offer_id,portal_key,is_published,needs_update,updated_at) VALUES (17,'no',1,0,'t')")
    events, flags = idb_events(ready), publication(ready)
    decision = start(attempt, claim)
    assert decision['can_send'] is False and decision['state'] == 'prepared'
    if reason:
        assert decision['reason'] == reason
    else:
        assert decision['reason'] in ('attempt_not_current', 'no_longer_required')
    assert idb_events(ready) == events and publication(ready) == flags
    assert attempts.get_attempt(attempt['attempt_id'])['state'] == 'prepared'


def test_legacy_start_ignores_pause_and_then_the_job_gets_no_permission(ready):
    attempt, claim = domestic_job(ready)
    control.set_dispatch(False, changed_by='test')
    legacy = attempts.start_transport(attempt['attempt_id'], attempt['binding'])     # DEC-01: legacy is not paused
    assert legacy['can_send'] is True
    control.set_dispatch(True, changed_by='test')
    decision = start(attempt, claim)
    assert decision['can_send'] is False and 'reason' not in decision


def test_two_processes_produce_exactly_one_permission(ready):
    attempt, claim = domestic_job(ready)
    spec = ready / 'start.json'
    spec.write_text(json.dumps({'attempt_id': attempt['attempt_id'], 'binding': attempt['binding']}), encoding='utf8')
    code = ("import json,sys,time\n"
            "from InvestmentManager.integrator import domestic_dictionaries as d, export_attempts as a, export_jobs as j, export_start as s\n"
            "from InvestmentManager.integrator.input_consistency import LockBusy\n"
            "d._download=lambda url: b'<dictionary><item id=\"1\" name=\"test\"/></dictionary>'\n"
            "spec=json.load(open(sys.argv[1]))\n"
            "d.dictionary_inputs(spec['binding']['portal'])\n"
            "claim=j.orphans()[0]\n"
            "while True:\n"
            "    try:\n"
            "        r=s.start_qualified_transport(spec['attempt_id'],spec['binding'],job_claim=claim);break\n"
            "    except LockBusy: time.sleep(0.02)\n"
            "print(json.dumps([r['can_send'],r['state'],r.get('reason')]))")
    procs = [subprocess.Popen([sys.executable, '-B', '-c', code, str(spec)], cwd=REPO, stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE, text=True) for _ in range(2)]
    results = []
    for proc in procs:
        out, err = proc.communicate(timeout=180)
        assert proc.returncode == 0, err[-1500:]
        results.append(json.loads(out.strip().splitlines()[-1]))
    assert sorted(item[0] for item in results) == [False, True]
    assert all(item[1] == 'transport_unknown' for item in results)
    with closing(sqlite3.connect(ready / 'databases/IDB.db')) as conn:
        unknown = [row for row in conn.execute("SELECT payload_json FROM offer_portal_sync_events WHERE event_type='export_attempt_v1'")
                   if json.loads(row[0])['state'] == 'transport_unknown']
    assert len(unknown) == 1


def test_start_cannot_race_a_cancel_or_claim_of_another_owner(ready):
    attempt, claim = domestic_job(ready)
    jobs.advance(claim, state='queued', phase='paused')
    other = jobs.claim_next('delivery')
    assert other.owner_id != claim.owner_id
    assert start(attempt, claim)['reason'] == 'claim_lost'
    assert start(attempt, other)['can_send'] is True


def test_busy_input_lock_raises_lock_busy_not_a_refusal(ready):
    import threading
    from InvestmentManager.integrator.input_consistency import input_lock, LockBusy
    attempt, claim = domestic_job(ready)
    held, release = threading.Event(), threading.Event()

    def holder():
        with input_lock():
            held.set()
            release.wait(20)
    thread = threading.Thread(target=holder)
    thread.start()
    held.wait(20)
    try:
        with pytest.raises(LockBusy):
            start(attempt, claim)
    finally:
        release.set()
        thread.join()
    assert attempts.get_attempt(attempt['attempt_id'])['state'] == 'prepared'
    assert start(attempt, claim)['can_send'] is True


# ----------------------------------------------------------------- foreign
@pytest.fixture
def foreign(tmp_path, monkeypatch):
    foreign_root = make_foreign_root.__wrapped__(tmp_path / 'foreign', monkeypatch)
    root, settings, calls = foreign_root
    for key, value in settings.items():
        monkeypatch.setenv(key, json.dumps(value) if isinstance(value, dict) else value)
    assert jobs.init_schema(backup=False) == 'created'
    control.set_dispatch(True, changed_by='test')
    return foreign_root


def foreign_job(env, kind='foreign_offer', identifier=11, portal='domiporta', action='add'):
    root, settings, _ = env
    result = prepare_foreign(env, kind=kind, identifier=identifier, portal=portal, action=action)
    choice = {k: result[k] for k in ('package_id', 'subject', 'portal', 'action')}
    attempt = attempts.create_attempt(**choice, settings=settings, domain='foreign')
    intent = {'domain': 'foreign', 'subject': result['subject'], 'portal': portal, 'action': action,
              'package': {'mode': 'ensure_current'}}
    return attempt, linked_claim(intent, attempt, attempt['binding']['offer_id'])


def foreign_start(env, attempt, claim):
    return export_start.start_qualified_transport(attempt['attempt_id'], attempt['binding'], job_claim=claim,
                                              settings=env[1], domain='foreign')


def flag(env, offer, portal, **values):
    with closing(sqlite3.connect(env[0] / 'databases/foreign_offers.db')) as conn, conn:
        for key, value in values.items():
            conn.execute(f'UPDATE foreign_offer_portal_sync SET {key}=? WHERE foreign_offer_id=? AND portal_key=?', (value, offer, portal))


def foreign_events(env):
    with closing(sqlite3.connect(env[0] / 'databases/foreign_offers.db')) as conn:
        return conn.execute('SELECT COUNT(*) FROM foreign_offer_portal_sync_events').fetchone()[0]


def test_foreign_update_is_qualified_and_published_current_unit_is_refused(foreign):
    flag(foreign, 11, 'domiporta', needs_update=1)
    attempt, claim = foreign_job(foreign)
    assert foreign_start(foreign, attempt, claim)['can_send'] is True
    # a second, unmodified unit has no business need -> refusal and no event
    attempt2, claim2 = foreign_job(foreign, identifier=13)
    before = foreign_events(foreign)
    decision = foreign_start(foreign, attempt2, claim2)
    assert decision['can_send'] is False and decision['reason'] == 'no_longer_required'
    assert foreign_events(foreign) == before and attempts.get_attempt(attempt2['attempt_id'], domain='foreign')['state'] == 'prepared'


def test_cyprus_project_requires_the_full_membership(foreign):
    flag(foreign, 11, 'tabelaofert', needs_update=1)
    attempt, claim = foreign_job(foreign, kind='cyprus_development', identifier=7, portal='tabelaofert')
    assert sorted(attempt['binding']['members']) == [11, 13]
    # a member leaves the project after the package was prepared: START must refuse
    with closing(store.open_foreign_offers_connection()) as conn:
        conn.execute('BEGIN IMMEDIATE')
        conn.execute('UPDATE foreign_offers SET is_active=0 WHERE id=13')
        conn.commit()
    before = foreign_events(foreign)
    decision = foreign_start(foreign, attempt, claim)
    assert decision['can_send'] is False
    assert decision['reason'] in ('membership_changed', 'attempt_not_current')
    assert foreign_events(foreign) == before


def test_cyprus_project_start_with_unchanged_membership(foreign):
    flag(foreign, 11, 'tabelaofert', needs_update=1)
    attempt, claim = foreign_job(foreign, kind='cyprus_development', identifier=7, portal='tabelaofert')
    decision = foreign_start(foreign, attempt, claim)
    assert decision['can_send'] is True and decision['attempt_id'] == attempt['attempt_id']


def test_foreign_job_fence_is_read_from_the_job_database_while_foreign_transaction_is_open(foreign):
    flag(foreign, 11, 'domiporta', needs_update=1)
    attempt, claim = foreign_job(foreign)
    jobs.advance(claim, state='queued', phase='paused')
    assert foreign_start(foreign, attempt, claim)['reason'] == 'claim_lost'


# --------------------------------------------------------- pause vs START
def test_a_confirmed_pause_is_never_followed_by_a_grant_in_100_rounds(ready):
    attempt, claim = domestic_job(ready)
    for number in range(100):
        control.set_dispatch(True, changed_by='round')
        confirmed = control.set_dispatch(False, changed_by='round')
        assert confirmed['dispatch_enabled'] is False
        decision = start(attempt, claim)
        assert decision['can_send'] is False and decision['reason'] == 'dispatch_paused', number
    assert attempts.get_attempt(attempt['attempt_id'])['state'] == 'prepared'


def test_concurrent_pause_and_start_resolve_by_commit_order(ready):
    import random
    import threading
    from InvestmentManager.integrator.input_consistency import LockBusy
    rng = random.Random(7)
    granted_total = 0
    for portal in ('no', 'domiporta', 'tabelaofert', 'gruntguru'):
        attempt, claim = domestic_job(ready, portal)
        granted = None
        for _ in range(60):
            control.set_dispatch(True, changed_by='race')
            outcome, barrier = {}, threading.Barrier(2)
            delay = rng.random() * 0.01

            def pauser():
                barrier.wait()
                import time
                time.sleep(delay)
                while True:
                    try:
                        outcome['pause'] = control.set_dispatch(False, changed_by='race')
                        return
                    except control.ControlBusy:
                        time.sleep(0.002)

            def starter():
                barrier.wait()
                try:
                    outcome['start'] = start(attempt, claim)
                except LockBusy:
                    outcome['start'] = {'can_send': False, 'reason': 'lock_busy'}
            threads = [threading.Thread(target=pauser), threading.Thread(target=starter)]
            for thread in threads:
                thread.start()
            for thread in threads:
                thread.join()
            assert outcome['pause']['dispatch_enabled'] is False                    # a pause is always confirmed eventually
            decision = outcome['start']
            assert decision['can_send'] is True or decision['reason'] in ('dispatch_paused', 'lock_busy', 'control_unavailable'), decision
            if decision['can_send'] is True:
                granted = decision
                break
        if granted:
            granted_total += 1
            assert attempts.get_attempt(attempt['attempt_id'])['state'] == 'transport_unknown'
            control.set_dispatch(False, changed_by='race')
            assert start(attempt, claim)['can_send'] is False                        # exactly one permission, never a second
        else:
            assert attempts.get_attempt(attempt['attempt_id'])['state'] == 'prepared'
    assert granted_total >= 1
