"""Producer queue is authoritative, read-only and never invokes transport."""
from contextlib import closing
import json
import sqlite3

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
from InvestmentManager.integrator import sync_tasks as queue, domestic_sets as sets
from InvestmentManager.integrator import export_attempts as attempts
from InvestmentManager.integrator.portal_sync_state import _ensure_sync_tables
from InvestmentManager import export_handoff as server


@pytest.fixture
def foreign_root(tmp_path,monkeypatch):
    # Domestic autouse isolation already provisions tmp_path/InvestmentData.
    return make_foreign_root.__wrapped__(tmp_path/'foreign',monkeypatch)


@pytest.fixture
def country(data_root):
    (data_root/'databases/foreign_offers.db').unlink()  # this synthetic test is domestic only
    with closing(sqlite3.connect(data_root/'databases/IDB.db')) as conn, conn:
        _ensure_sync_tables(conn)
    return data_root


def rows(**kwargs):
    return queue.list_tasks(**kwargs)['items']


def selection(root,portal='no'):
    pointer=sets.current(root/'exports/domestic',17,'add')
    return dict(package_id=pointer['packages'][portal],offer_id=17,portal=portal,action='add')


def completed(root,portal='no'):
    item=attempts.create_attempt(**selection(root,portal))
    attempts.start_transport(item['attempt_id'],item['binding'])
    attempts.record_transport_result(item['attempt_id'],item['binding'],'confirmed')
    assert attempts.acknowledge_attempt(item['attempt_id'],item['binding'])['state']=='ack_completed'
    return item


def test_active_offer_is_not_proof_of_publication(country):
    result=rows()
    assert len(result)==4 and all(row['category']=='new' and not row['published'] for row in result)
    assert all(row['package'] is None and not row['send_allowed'] for row in result)


def test_package_presence_does_not_mark_offer_published(country):
    sets.prepare_set(17,'add')
    assert all(row['category']=='new' and row['package']['state']=='UNVERIFIED' for row in rows())


def test_only_successfully_synchronized_pairs_are_hidden(country):
    sets.prepare_set(17,'add')
    completed(country,'no')
    assert {row['portal'] for row in rows()}=={'domiporta','tabelaofert','gruntguru'}
    completed(country,'domiporta');completed(country,'tabelaofert');completed(country,'gruntguru')
    assert rows()==[]


def test_direct_source_change_detected_from_publication_fingerprint(country):
    sets.prepare_set(17,'add');completed(country)
    sql(country,"UPDATE EstateData SET Cena='177000'")
    task=next(row for row in rows() if row['portal']=='no')
    assert task['category']=='update' and task['operation']=='update'
    assert task['package']['state']=='STALE' and not task['send_allowed']
    sets.prepare_set(17,'add')
    fresh=next(row for row in rows() if row['portal']=='no')
    assert fresh['category']=='update' and fresh['package']['package_id']==selection(country)['package_id']


def test_withdrawal_uses_publication_not_offer_active_flag(country):
    sql(country,"UPDATE EstateData SET Status_oferty='Nieaktywna'")
    assert rows()==[]
    sql(country,"UPDATE EstateData SET Status_oferty='aktywna'")
    sets.prepare_set(17,'add');completed(country)
    sql(country,"UPDATE EstateData SET Status_oferty='Nieaktywna'")
    result=rows()
    assert len(result)==1 and result[0]['category']=='withdraw' and result[0]['action']=='delete'
    assert result[0]['package'] is None
    sets.prepare_set(17,'delete')
    assert rows()[0]['package'] is not None


@pytest.mark.parametrize('state',['prepared','transport_unknown','transport_failed','transport_confirmed','ack_failed','ack_rejected'])
def test_attempt_errors_and_uncertainty_are_durable_tasks(country,state):
    sets.prepare_set(17,'add')
    item=attempts.create_attempt(**selection(country))
    if state!='prepared':
        attempts.start_transport(item['attempt_id'],item['binding'])
        if state in {'transport_failed','transport_confirmed'}:
            attempts.record_transport_result(item['attempt_id'],item['binding'],'failed' if state=='transport_failed' else 'confirmed')
        elif state in {'ack_failed','ack_rejected'}:
            attempts.record_transport_result(item['attempt_id'],item['binding'],'confirmed')
            with attempts.transaction() as conn:
                attempts._append(conn,attempts._find(conn,item['attempt_id']),state)
    task=next(row for row in rows() if row['portal']=='no')
    assert task['category']=='error' and task['last_result']['state']==state
    assert task['last_result']['can_ack']==(state in {'transport_confirmed','ack_failed'})
    assert task['send_allowed']==(state in {'prepared','transport_failed'})
    assert next(row for row in rows() if row['portal']=='no')==task


def test_legacy_unknown_is_not_implicitly_retried(country):
    sql(country,"INSERT INTO offer_portal_sync_events(offer_id,portal_key,event_type,payload_json,created_at) VALUES (17,'no','legacy_attempt_started','{}','test')")
    task=next(row for row in rows() if row['portal']=='no')
    assert task['category']=='error' and task['issue']=='legacy_unresolved' and not task['send_allowed']


def test_deleted_published_source_stays_visible_as_error(country):
    sets.prepare_set(17,'add');completed(country)
    sql(country,'DELETE FROM EstateData')
    task=rows()[0]
    assert task['category']=='error' and task['issue']=='source_offer_missing'


def test_listing_does_not_write_databases_or_download_dictionaries(country,monkeypatch):
    sets.prepare_set(17,'add')
    before={p:p.read_bytes() for p in country.rglob('*') if p.is_file()}
    def forbidden(*args,**kwargs):raise AssertionError('Listing downloaded dictionaries')
    monkeypatch.setattr(sets.dictionaries,'dictionary_inputs',forbidden)
    sets.dictionaries._cache.clear()
    assert rows()
    assert {p:p.read_bytes() for p in country.rglob('*') if p.is_file()}==before


def test_rpc_schema_pagination_and_compatibility_failure(country):
    reply=server.dispatch_request({'operation':'list_sync_tasks','offset':0,'limit':2})
    assert reply['ok'] and reply['total']==4 and len(reply['items'])==2
    assert reply['counts']=={'new':4,'update':0,'withdraw':0,'error':0}
    for body in ({'operation':'list_sync_tasks'}, {'operation':'list_sync_tasks','offset':False,'limit':2},
                 {'operation':'list_sync_tasks','offset':0,'limit':101}):
        assert server.dispatch_request(body)['ok'] is False


def test_foreign_group_is_one_current_task_and_updates_after_ack(foreign_root):
    root,settings,_=foreign_root
    # The synthetic fixture starts with published rows; require an update.
    sql(root,"UPDATE foreign_offer_portal_sync SET needs_update=1",db='foreign_offers.db')
    current=prepare(foreign_root,'cyprus_development',7,'tabelaofert')
    task=next(row for row in rows(settings=settings) if row['domain']=='foreign' and row['subject']=={'kind':'cyprus_development','id':7})
    assert task['category']=='update' and task['offer_ids']==[11,13]
    assert task['package']['package_id']==current['package_id'] and task['send_allowed']
    choice={k:current[k] for k in ('package_id','subject','portal','action')}
    item=attempts.create_attempt(**choice,domain='foreign',settings=settings)
    attempts.start_transport(item['attempt_id'],item['binding'],domain='foreign',settings=settings)
    attempts.record_transport_result(item['attempt_id'],item['binding'],'confirmed',domain='foreign')
    attempts.acknowledge_attempt(item['attempt_id'],item['binding'],domain='foreign',settings=settings)
    remaining=[row for row in rows(settings=settings) if row['domain']=='foreign' and row['portal']=='tabelaofert' and row['action']=='add']
    assert remaining==[]


def test_foreign_unpublished_active_and_published_inactive_are_distinct(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')
    result=[row for row in rows(settings=settings) if row['domain']=='foreign']
    assert any(row['category']=='new' and 11 in row['offer_ids'] for row in result)
    assert any(row['category']=='withdraw' and row['subject']=={'kind':'foreign_offer','id':13} for row in result)


def test_old_pending_attempt_does_not_make_its_package_current(country):
    sets.prepare_set(17,'add')
    old=attempts.create_attempt(**selection(country))
    attempts.start_transport(old['attempt_id'],old['binding'])
    sets.prepare_set(17,'add')
    current=selection(country)['package_id']
    task=next(row for row in rows() if row['portal']=='no')
    assert current!=old['binding']['package_id']
    assert task['package']['package_id']==current
    assert task['last_result']['attempt_id']==old['attempt_id']
    assert task['operation']=='reconcile' and not task['send_allowed']


def test_newest_foreign_package_is_not_replaced_with_valid_history(foreign_root):
    root,settings,_=foreign_root
    sql(root,"UPDATE foreign_offer_portal_sync SET needs_update=1",db='foreign_offers.db')
    old=prepare(foreign_root,'foreign_offer',11,'domiporta')
    current=prepare(foreign_root,'foreign_offer',11,'domiporta')
    # Give the new generation an unambiguous later preparation time.
    folder=root/'exports/foreign'/current['package_id']
    manifest=folder/'manifest.json'
    value=json.loads(manifest.read_text())
    value['prepared_at']='2099-01-01T00:00:00Z'
    manifest.write_text(json.dumps(value))
    for path in folder.glob('*.zip'):path.write_bytes(b'corrupt synthetic ZIP')
    task=next(row for row in rows(settings=settings) if row['domain']=='foreign' and row['portal']=='domiporta' and row['subject']['id']==11)
    assert old['package_id']!=current['package_id']
    assert task['package']['package_id']==current['package_id']
    assert task['package']['state']=='INVALID' and not task['send_allowed']
