"""Real queue producer and receiver validator, synthetic inputs, no connections."""
import importlib
from pathlib import Path
import sys
import types
from contextlib import closing
import sqlite3
import json

import pytest

from tests.peer_repository import idbmanager_root

from tests.investmentmanager.test_domestic_packages import data_root, isolated, sql
from tests.investmentmanager.test_sync_tasks import country, foreign_root
from InvestmentManager.integrator import sync_tasks as producer


@pytest.fixture
def consumer(monkeypatch):
    # Only configuration/connection boundaries are stubbed. Load the actual
    # receiver module, its transport selection validator and contract code.
    name='queue_contract_peer'
    package=types.ModuleType(name)
    package.__path__=[str(idbmanager_root()/'modules')]
    monkeypatch.setitem(sys.modules,name,package)
    def forbidden(*args,**kwargs):raise AssertionError('Contract test attempted configuration or SSH')
    classes=types.ModuleType(name+'.classes');classes.DatabaseConnectionManager=forbidden
    paths=types.ModuleType(name+'.runtime_paths');paths.setting=forbidden
    monkeypatch.setitem(sys.modules,classes.__name__,classes)
    monkeypatch.setitem(sys.modules,paths.__name__,paths)
    module=importlib.import_module(name+'.sync_tasks')
    yield module
    for key in tuple(sys.modules):
        if key.startswith(name+'.'):sys.modules.pop(key,None)


def envelope(tasks,offset=0,total=None,counts=None):
    return dict(queue_version=1,ok=True,offset=offset,limit=50,items=tasks,
                total=len(tasks) if total is None else total,
                counts=counts or {key:sum(row['category']==key for row in tasks) for key in producer.CATEGORIES})


@pytest.mark.parametrize('domain,portal,kind',[
    ('domestic','no','offer'),('domestic','domiporta','offer'),
    ('domestic','tabelaofert','offer'),('domestic','gruntguru','offer'),
    ('foreign','domiporta','foreign_offer'),('foreign','tabelaofert','foreign_offer'),
    ('foreign','tabelaofert','cyprus_development'),
])
def test_all_classification_history_and_package_variants_match(consumer,domain,portal,kind):
    checked=set()
    for active in (False,True):
        for published in (False,True):
            for dirty in (False,True):
                for issue in (None,'inputs_unavailable'):
                    for state in (None,'prepared','transport_unknown','transport_failed','transport_confirmed','ack_failed','ack_rejected','ack_completed'):
                        status=dict(is_published=int(published),needs_update=int(dirty),last_error=None)
                        subject=dict(kind=kind,id=7 if kind=='cyprus_development' else 17)
                        # Project deletes are never generated: the producer uses
                        # individual foreign_offer tasks for withdrawals.
                        if kind=='cyprus_development' and not active:continue
                        latest=None if state is None else dict(attempt_id='b'*32,state=state,
                            binding=dict(action='add',subject=subject,members=[17] if domain=='foreign' else [17]))
                        category,action=producer._classify(active,status,latest,issue=issue)
                        if category is None:continue
                        row=producer._task(domain,subject,[17],'Synthetic',portal,action,category,status,latest,issue)
                        for availability in (None,'UNVERIFIED','READY','STALE','INVALID','BLOCKED'):
                            row['package']=None if availability is None else dict(package_id='a'*32,state=availability,prepared_at='2026-11-01T00:00:00Z',checked_at=None)
                            row['send_allowed']=(not row['issue'] and row['package'] is not None and
                                availability in ({'UNVERIFIED','READY'} if domain=='domestic' else {'READY'}))
                            value=envelope([row]);assert consumer.validate_page(value,0,50)==value
                            checked.add((category,availability))
    assert {'new','update','error'} <= {category for category,_ in checked}
    if kind!='cyprus_development':assert 'withdraw' in {category for category,_ in checked}


def test_real_queue_without_packages_and_foreign_states_passes(consumer,foreign_root):
    root,settings,_=foreign_root
    sql(root,"UPDATE foreign_offer_portal_sync SET is_published=0 WHERE foreign_offer_id=11",db='foreign_offers.db')
    sql(root,"UPDATE foreign_offers SET is_active=0 WHERE id=13",db='foreign_offers.db')
    value=producer.list_tasks(settings=settings)
    assert consumer.validate_page(value,0,50)==value
    assert {'new','withdraw'} <= {row['category'] for row in value['items']}


def test_real_missing_source_errors_for_supported_portals_pass(consumer,country):
    for portal in ('no','domiporta','tabelaofert','gruntguru'):
        sql(country,"INSERT INTO offer_portal_sync(offer_id,portal_key,is_published,updated_at) VALUES (999,?,1,'test')",(portal,))
    value=producer.list_tasks()
    assert consumer.validate_page(value,0,50)==value


@pytest.mark.parametrize('published',[0,1])
def test_real_legacy_otodom_missing_source_is_display_only(consumer,country,published):
    # Valid historical state schema permits Otodom, while v1 transport excludes
    # it. The missing-source branch emits this error without filtering portal.
    sql(country,"INSERT INTO offer_portal_sync(offer_id,portal_key,is_published,last_error,updated_at) VALUES (999,'otodom',?,'synthetic legacy error','test')",(published,))
    value=producer.list_tasks()
    row=next(row for row in value['items'] if row['portal']=='otodom')
    assert row['category']=='error' and row['issue']=='source_offer_missing'
    assert row['package'] is None and row['send_allowed'] is False
    assert consumer.validate_page(value,0,50)==value
    with pytest.raises(consumer._selection.__globals__['ReceiveError']):
        consumer._selection('a'*32,999,'otodom','delete')


@pytest.mark.parametrize('mutate',[
    lambda row:row.update(send_allowed=True),
    lambda row:row.update(package={'package_id':'a'*32,'state':'READY'}),
    lambda row:row.update(last_result={'attempt_id':'b'*32,'domain':'domestic','state':'transport_confirmed','can_ack':True}),
    lambda row:row.update(category='new'),lambda row:row.update(action='add'),
    lambda row:row.update(issue='other'),lambda row:row.update(operation='reconcile'),
    lambda row:row.update(published=1),lambda row:row.update(portal='unknown'),
])
def test_display_only_exception_never_authorizes_transport(consumer,country,mutate):
    sql(country,"INSERT INTO offer_portal_sync(offer_id,portal_key,is_published,updated_at) VALUES (999,'otodom',1,'test')")
    value=producer.list_tasks();row=next(row for row in value['items'] if row['portal']=='otodom')
    mutate(row)
    with pytest.raises(ValueError):consumer.validate_page(value,0,50)


def test_last_partial_page_and_safe_rule_index(consumer):
    tasks=[]
    for i in range(343):
        category='new' if i<322 else 'update' if i<340 else 'error'
        status=dict(is_published=int(category=='update'),needs_update=1,last_error='synthetic legacy error' if category=='error' else None)
        orphan=i==342
        tasks.append(producer._task('domestic',dict(kind='offer',id=i+1),[i+1],
            'Synthetic title never diagnostic','otodom' if orphan else 'no',
            'delete' if orphan else 'add',category,status,None,'source_offer_missing' if orphan else None))
    value=envelope(tasks[300:],offset=300,total=343,counts={'new':322,'update':18,'withdraw':0,'error':3})
    assert consumer.validate_page(value,300,50)==value
    value['items'][42]['subject']['id']='synthetic-private-id'
    with pytest.raises(consumer.QueueReadError) as caught:
        consumer._response(json.dumps(value).encode(),0,False,300,50)
    assert caught.value.rule=='task.subject_id' and caught.value.index==42
    message=consumer.safe_diagnostic(caught.value)
    assert 'task.subject_id' in message and '42' in message
    assert 'synthetic-private-id' not in message and 'Synthetic title' not in message
