"""2B.2: qualify_unit equivalence (differential), LockBusy, inspect_attempt, structure."""
from contextlib import closing
import hashlib
import json
import os
import shutil
import sqlite3
import threading
import errno

import pytest

from InvestmentManager import export_handoff as handoff
from InvestmentManager.integrator import export_attempts as attempts
from InvestmentManager.integrator import input_consistency as ic
from InvestmentManager.integrator import sync_tasks as queue
from tests.investmentmanager import qualification_support as support

SEEDS = list(range(100, 400))        # 300 seeds
PORTALS = ('no', 'domiporta', 'tabelaofert', 'gruntguru')


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


# ------------------------------------------------------------- the harness
def sut(root, unit):
    """qualify_unit on the START transaction connection of the right domain."""
    token = attempts._domain.set(unit['domain'])
    try:
        with attempts.transaction() as conn:
            return queue.qualify_unit(conn, root, unit)
    finally:
        attempts._domain.reset(token)


def domestic_unit(offer, portal):
    return {'domain': 'domestic', 'subject': {'kind': 'offer', 'id': offer}, 'portal': portal, 'action': 'add'}


def foreign_keys(data):
    keys = set()
    for offer, platform, development in data.foreign_offers:
        for portal in ('domiporta', 'tabelaofert'):
            for action in ('add', 'delete'):
                keys.add(('foreign_offer', offer, portal, action))
    for development in data.projects:
        keys.add(('cyprus_development', development, 'tabelaofert', 'add'))
    return keys


def oracle_snapshot(data, tmp_path, monkeypatch):
    """Existing queue code on D- (never-started attempts removed)."""
    clone = tmp_path / 'oracle'
    if clone.exists():
        shutil.rmtree(clone)
    support.clone_without_prepared(data, clone)
    monkeypatch.setenv('DATA_DIR', str(clone))
    try:
        domestic = {}
        for offer in list(data.domestic_offers) + [99]:
            for task in queue._domestic(clone, offer_id=offer):
                domestic[(offer, task['portal'])] = (task['category'], [task['issue']] if task['issue'] else [])
        units = {unit['key']: unit for unit in queue.qualify_foreign_units(clone)}
    finally:
        monkeypatch.setenv('DATA_DIR', str(data.root))
    return domestic, units


def compare(data, oracle, root):
    """Every unit of the dataset: SUT == oracle. Returns the list of differences."""
    domestic, units = oracle
    diffs = []
    for offer in list(data.domestic_offers) + [99]:
        for portal in PORTALS:
            q = sut(root, domestic_unit(offer, portal))
            expected = domestic.get((offer, portal), (None, []))
            if (q.category, q.issues) != expected or q.blocking != [i for i in q.issues if i != 'transport_failed']:
                diffs.append(('domestic', offer, portal, (q.category, q.issues), expected))
            if q.required and expected[0] is None:
                diffs.append(('domestic-required-without-task', offer, portal))
            if expected[0] in ('new', 'update', 'withdraw') and q.need != expected[0]:
                diffs.append(('domestic-need', offer, portal, q.need, expected[0]))
    for key in sorted(foreign_keys(data) | set(units)):
        kind, identifier, portal, action = key
        q = sut(root, {'domain': 'foreign', 'subject': {'kind': kind, 'id': identifier}, 'portal': portal, 'action': action})
        unit = units.get(key)
        if unit is None:
            if q.category is not None or q.required or q.members:
                diffs.append(('foreign-extra', key))
            continue
        got = (q.category, sorted(q.members), sorted(q.trigger_offer_ids), q.issues)
        want = (unit['category'], sorted(unit['members']), sorted(unit['trigger_offer_ids']), unit['issues'])
        if got != want:
            diffs.append(('foreign', key, got, want))
        if unit['category'] in ('new', 'update', 'withdraw') and q.need != unit['category']:
            diffs.append(('foreign-need', key, q.need, unit['category']))
    return diffs


def evaluate(tmp_path, monkeypatch, seeds, mutate=None):
    """Oracle pass (always unmodified code), then SUT pass under an optional mutant."""
    differences = 0
    for seed in seeds:
        root = tmp_path / f'd{seed}'
        root.mkdir()
        monkeypatch.setenv('DATA_DIR', str(root))
        data = support.build(root, seed)
        with support.patched(monkeypatch, data):
            oracle = oracle_snapshot(data, tmp_path, monkeypatch)
            if mutate is None:
                diffs = compare(data, oracle, root)
            else:
                with monkeypatch.context() as patch:
                    mutate(patch)
                    diffs = compare(data, oracle, root)
        if diffs and mutate is None:
            pytest.fail(f'seed {seed}: {diffs[:3]}')
        differences += bool(diffs)
        shutil.rmtree(root, ignore_errors=True)
    return differences


def test_unit_qualification_equals_queue_for_300_seeds(tmp_path, monkeypatch):
    assert evaluate(tmp_path, monkeypatch, SEEDS) == 0


def mutant_own_prepared_counted(patch):
    original = queue._history
    patch.setattr(queue, '_history', lambda conn, domain, ignore_prepared=False, **kw: original(conn, domain, ignore_prepared=False, **kw))


def mutant_assignment_events_ignored(patch):
    patch.setattr(queue, '_foreign_project_changes', lambda conn, context: (set(), set()))


def mutant_needs_update_ignored(patch):
    original = queue.business_need
    def broken(active, state, source_changed=False):
        state = dict(state, needs_update=0) if state else state
        return original(active, state, source_changed)
    patch.setattr(queue, 'business_need', broken)


def mutant_foreign_unknown_ignored(patch):
    original = queue._history
    def broken(conn, domain, ignore_prepared=False, **kw):
        items = original(conn, domain, ignore_prepared=ignore_prepared, **kw)
        return [i for i in items if i['state'] in ('ack_completed', 'prepared')] if domain == 'foreign' else items
    patch.setattr(queue, '_history', broken)


def mutant_blocking_dropped(patch):
    original = queue._qualification
    def broken(need, category, members, triggers, issues):
        return original(need, category, members, triggers, [])
    patch.setattr(queue, '_qualification', broken)


def mutant_members_limited_to_triggers(patch):
    original = queue._qualification
    def broken(need, category, members, triggers, issues):
        return original(need, category, triggers, triggers, issues)
    patch.setattr(queue, '_qualification', broken)


def mutant_domestic_legacy_pending_ignored(patch):
    patch.setattr(attempts, '_legacy_pending', lambda conn, offer, portal=None: False)


MUTANTS = [mutant_own_prepared_counted, mutant_assignment_events_ignored, mutant_needs_update_ignored,
           mutant_foreign_unknown_ignored, mutant_blocking_dropped, mutant_members_limited_to_triggers,
           mutant_domestic_legacy_pending_ignored]


@pytest.mark.parametrize('mutant', MUTANTS, ids=[m.__name__ for m in MUTANTS])
def test_harness_detects_each_mutant(tmp_path, monkeypatch, mutant):
    assert evaluate(tmp_path, monkeypatch, SEEDS[:60], mutate=mutant) > 0


# --------------------------------------------------- directed scenarios
def attempt_state_dataset(tmp_path, monkeypatch, states, *, published=0, needs_update=0, active='aktywna'):
    root = tmp_path / 'one'
    root.mkdir()
    monkeypatch.setenv('DATA_DIR', str(root))
    support.init_root(root)
    with closing(sqlite3.connect(root / 'databases/IDB.db')) as conn, conn:
        conn.execute("INSERT INTO EstateData VALUES ('10',?,'T','mieszkanie')", (active,))
        conn.execute("INSERT INTO offer_portal_sync(offer_id,portal_key,is_published,needs_update,updated_at) VALUES (10,'no',?,?,'t')",
                     (published, needs_update))
        for number, path in enumerate(states):
            support._domestic_attempt(conn, 10, 'no', 'add', path, package_id=f'{number:032x}')
    return root


@pytest.mark.parametrize('states,published,expected', [
    ([['prepared']], 0, ('new', [])),                                        # own prepared alone: need survives
    ([['prepared'], ['prepared']], 0, ('new', [])),                         # older and newer prepared
    ([['prepared', 'transport_unknown']], 0, ('error', ['attempt_unresolved'])),
    ([['prepared', 'transport_unknown', 'transport_confirmed'], ['prepared']], 0, ('error', ['attempt_unresolved'])),
    ([['prepared', 'transport_unknown', 'transport_failed'], ['prepared']], 0, ('error', [])),   # resolved failure: retry allowed
    ([['prepared', 'transport_unknown', 'transport_confirmed', 'ack_rejected']], 0, ('error', ['attempt_unresolved'])),
])
def test_prepared_attempts_never_create_or_hide_need(tmp_path, monkeypatch, states, published, expected):
    root = attempt_state_dataset(tmp_path, monkeypatch, states, published=published)
    data = support.Dataset(root)
    with support.patched(monkeypatch, data):
        q = sut(root, domestic_unit(10, 'no'))
    assert (q.category, q.issues) == expected
    assert q.required and q.need == 'new' and q.action == 'add'
    assert q.blocking == [i for i in expected[1]]


def test_published_current_offer_with_older_prepared_has_no_need(tmp_path, monkeypatch):
    root = attempt_state_dataset(tmp_path, monkeypatch, [['prepared']], published=1, needs_update=0)
    with support.patched(monkeypatch, support.Dataset(root)):
        q = sut(root, domestic_unit(10, 'no'))
    assert not q.required and q.category is None and q.need is None


@pytest.mark.parametrize('published,needs_update,active,need', [
    (0, 0, 'aktywna', 'new'), (1, 1, 'aktywna', 'update'), (1, 0, 'nieaktywna', 'withdraw'),
    (0, 0, 'nieaktywna', None), (1, 0, 'aktywna', None)])
def test_business_need_matrix(tmp_path, monkeypatch, published, needs_update, active, need):
    root = attempt_state_dataset(tmp_path, monkeypatch, [['prepared']], published=published, needs_update=needs_update, active=active)
    with support.patched(monkeypatch, support.Dataset(root)):
        q = sut(root, domestic_unit(10, 'no'))
    assert q.need == need and q.required == (need is not None)


def test_business_need_is_the_shared_core_of_classify():
    for active in (True, False):
        for published in (0, 1):
            for needs in (0, 1):
                for changed in (False, True):
                    state = {'is_published': published, 'needs_update': needs}
                    category, action = queue._classify(active, state, None, changed, None)
                    need = queue.business_need(active, state, changed)
                    assert (category, action) == (need.category, need.action)
    # presentation override still wins for errors
    assert queue._classify(True, {'is_published': 1, 'needs_update': 0, 'last_error': 'x'}, None)[0] == 'error'
    assert queue._classify(True, None, {'state': 'prepared'})[0] == 'error'


def test_qualify_unit_restores_row_factory_and_never_runs_the_full_queue(tmp_path, monkeypatch):
    root = attempt_state_dataset(tmp_path, monkeypatch, [['prepared']])
    for name in ('list_tasks', 'list_offers', '_collect_tasks', 'qualify_foreign_units', '_foreign'):
        monkeypatch.setattr(queue, name, lambda *a, **k: pytest.fail('full queue called'))
    with support.patched(monkeypatch, support.Dataset(root)):
        with attempts.transaction() as conn:
            before = conn.row_factory
            queue.qualify_unit(conn, root, domestic_unit(10, 'no'))
            assert conn.row_factory is before
        # foreign path as well
        token = attempts._domain.set('foreign')
        try:
            with attempts.transaction() as conn:
                queue.qualify_unit(conn, root, {'domain': 'foreign', 'subject': {'kind': 'foreign_offer', 'id': 20},
                                                'portal': 'domiporta', 'action': 'add'})
        finally:
            attempts._domain.reset(token)


@pytest.mark.parametrize('count', [50, 5000])
def test_domestic_sql_statement_count_is_independent_of_offer_count(tmp_path, monkeypatch, count):
    root = tmp_path / 'n'
    root.mkdir()
    monkeypatch.setenv('DATA_DIR', str(root))
    support.init_root(root)
    with closing(sqlite3.connect(root / 'databases/IDB.db')) as conn, conn:
        conn.executemany("INSERT INTO EstateData VALUES (?,?,?,?)",
                         [(str(i), 'aktywna', 'T', 'dzialka') for i in range(1, count + 1)])
    seen = []
    with support.patched(monkeypatch, support.Dataset(root)):
        token = attempts._domain.set('domestic')
        try:
            with attempts.transaction() as conn:
                conn.set_trace_callback(lambda statement: seen.append(statement))
                queue.qualify_unit(conn, root, domestic_unit(7, 'no'))
                conn.set_trace_callback(None)
        finally:
            attempts._domain.reset(token)
    test_domestic_sql_statement_count_is_independent_of_offer_count.counts = getattr(
        test_domestic_sql_statement_count_is_independent_of_offer_count, 'counts', {})
    test_domestic_sql_statement_count_is_independent_of_offer_count.counts[count] = len(seen)
    counts = test_domestic_sql_statement_count_is_independent_of_offer_count.counts
    if len(counts) == 2:
        assert counts[50] == counts[5000], counts


# ------------------------------------------------------------- LockBusy
def test_lock_busy_hierarchy_message_and_batch_scope(home):
    assert issubclass(ic.LockBusy, ic.ConsistencyError) and issubclass(ic.LockBusy, RuntimeError)
    (home / 'databases').mkdir()
    held, release, result = threading.Event(), threading.Event(), {}

    def holder():
        with ic.input_lock():
            held.set()
            release.wait(10)
    thread = threading.Thread(target=holder)
    thread.start()
    held.wait(10)
    try:
        with pytest.raises(ic.LockBusy) as busy:
            with ic.input_lock():
                pass
        assert 'zajęte' in str(busy.value) and isinstance(busy.value.__cause__, OSError)
        from InvestmentManager.integrator import domestic_batch_limits as limits
        with limits.scope():
            with pytest.raises(limits.BatchStop) as stop:
                with ic.input_lock():
                    pass
        assert stop.value.code == 'lock_busy'
    finally:
        release.set()
        thread.join()
    with ic.input_lock():
        pass


def test_non_busy_oserror_stays_a_plain_consistency_error(home, monkeypatch):
    (home / 'databases').mkdir()
    def broken(*args, **kwargs):
        raise OSError(errno.EIO, 'io')
    if os.name == 'nt':
        import msvcrt
        monkeypatch.setattr(msvcrt, 'locking', broken)
    else:
        import fcntl
        monkeypatch.setattr(fcntl, 'flock', broken)
    with pytest.raises(ic.ConsistencyError) as raised:
        with ic.input_lock():
            pass
    assert not isinstance(raised.value, ic.LockBusy)

def test_legacy_handoff_still_maps_busy_to_operation_blocked(home, monkeypatch):
    def busy():
        raise ic.LockBusy('Dane eksportu są zajęte lub blokada jest niedostępna. Ponów operację.')
    monkeypatch.setattr(attempts, 'get_attempt', lambda attempt_id, **kw: busy())
    reply = handoff.dispatch_request({'operation': 'get_attempt', 'attempt_id': 'a' * 32})
    assert reply == {'protocol_version': 1, 'operation': 'get_attempt', 'ok': False, 'error': 'operation_blocked'}


# --------------------------------------------------------- inspect_attempt
def test_inspect_attempt_is_read_only_and_distinguishes_outcomes(tmp_path, monkeypatch):
    root = attempt_state_dataset(tmp_path, monkeypatch, [['prepared', 'transport_unknown']])
    with closing(sqlite3.connect(root / 'databases/IDB.db')) as conn:
        attempt_id = json.loads(conn.execute("SELECT payload_json FROM offer_portal_sync_events WHERE event_type='export_attempt_v1' "
                                             "ORDER BY id LIMIT 1").fetchone()[0])['attempt_id']
    before = hashlib.sha256((root / 'databases/IDB.db').read_bytes()).hexdigest()
    found = attempts.inspect_attempt(attempt_id)
    assert found['state'] == 'found' and found['attempt']['state'] == 'transport_unknown'
    assert attempts.inspect_attempt(attempt_id, anchor_id=10, portal='no')['state'] == 'found'
    assert attempts.inspect_attempt(attempt_id, anchor_id=11, portal='no')['state'] == 'absent'
    assert attempts.inspect_attempt('b' * 32)['state'] == 'absent'
    assert hashlib.sha256((root / 'databases/IDB.db').read_bytes()).hexdigest() == before
    with closing(sqlite3.connect(root / 'databases/IDB.db')) as conn, conn:
        conn.execute("UPDATE offer_portal_sync_events SET payload_json='{bad' WHERE event_type='export_attempt_v1'")
    assert attempts.inspect_attempt(attempt_id)['state'] in ('inconsistent', 'unavailable')


def test_inspect_attempt_without_tables_or_database(tmp_path, monkeypatch):
    root = tmp_path / 'bare'
    (root / 'databases').mkdir(parents=True)
    monkeypatch.setenv('DATA_DIR', str(root))
    assert attempts.inspect_attempt('a' * 32)['reason'] == 'database_missing'
    sqlite3.connect(root / 'databases/IDB.db').close()
    before = (root / 'databases/IDB.db').read_bytes()
    assert attempts.inspect_attempt('a' * 32) == {'state': 'absent', 'attempt': None, 'reason': 'no_history_table'}
    assert (root / 'databases/IDB.db').read_bytes() == before        # no schema initialisation
    assert attempts.inspect_attempt('a' * 32, domain='foreign')['reason'] == 'database_missing'
    with pytest.raises(attempts.AttemptError):
        attempts.inspect_attempt('zz')
