"""Actual producer/receiver/uploader with synthetic plot data and fake wires."""
import json
import zipfile
import xml.etree.ElementTree as ET

import pytest

from tests.investmentmanager.test_domestic_packages import data_root, isolated, sql, manifest
from tests.investmentmanager.test_sync_tasks import country, rows, selection
from tests.investmentmanager.test_prepared_delivery_integration import (
    Client, ftp, send, stores, status, delivery,
)
from InvestmentManager.integrator import domestic_sets as sets, domestic_package_catalog as catalog
from InvestmentManager.integrator import export_attempts as attempts


def guru():
    return next((row for row in rows() if row['portal']=='gruntguru'), None)


def prepare(root, action='add'):
    assert sets.prepare_set(17,action)['replaced']
    pointer=sets.current(root/'exports/domestic',17,action)
    return dict(package_id=pointer['packages']['gruntguru'],offer_id=17,portal='gruntguru',action=action)


@pytest.mark.parametrize('kind',['Działka','działka','dzialka',' DZIALKA '])
def test_first_plot_publication_is_a_task(country,kind):
    sql(country,'UPDATE EstateData SET Typ_nieruchomosci=?',(kind,))
    task=guru()
    assert task['category']=='new' and task['operation']=='publish'
    assert task['package'] is None and task['issue'] is None
    chosen=prepare(country)
    assert guru()['package']['package_id']==chosen['package_id']
    assert guru()['send_allowed']


def test_other_property_has_three_portals_and_no_gruntguru(country):
    sql(country,"UPDATE EstateData SET Typ_nieruchomosci='mieszkanie'")
    assert guru() is None
    assert sets.prepare_set(17,'add')['replaced']
    assert len(sets.list_sets()['items'][0]['items'])==3


def test_current_set_receive_transport_and_ack_hide_synchronized_plot(country,tmp_path,ftp):
    chosen=prepare(country)
    checked=sets.verify_set(17,'add')
    assert checked['state']=='READY' and len(checked['items'])==4
    folder,item=manifest(country,chosen)
    with zipfile.ZipFile(folder/item['zip_name']) as archive:
        names=archive.namelist()
        assert 'definitions.xml' in names
        xml=next(name for name in names if name.startswith('EstiCRM_'))
        offer=ET.fromstring(archive.read(xml)).find('offer')
        assert offer.findtext('id')=='17' and offer.findtext('action')=='update'
        assert [p.text for p in offer.findall('./pictures/picture')]==['image_17_url_0.jpg','image_17_url_1.jpg']
    client=Client(country)
    result=send(country,chosen,tmp_path,client)
    assert result['ack_status']=='completed' and status(country,'gruntguru')==(1,0,'add')
    assert stores(ftp)==1 and ftp.instances[0].bytes==(folder/item['zip_name']).read_bytes()
    assert client.ops==['verify','verify','create_attempt','start_transport','record_transport_result','acknowledge_attempt']
    assert guru() is None


def test_update_uses_fingerprint_and_never_sends_stale_package(country,tmp_path,ftp):
    old=prepare(country)
    assert send(country,old,tmp_path)['ack_status']=='completed'
    sql(country,"UPDATE EstateData SET Cena='234567'")
    assert guru()['category']=='update' and guru()['package']['state']=='STALE'
    assert send(country,old,tmp_path)['ftp_attempted'] is False and stores(ftp)==1
    current=prepare(country)
    assert current['package_id']!=old['package_id']
    assert send(country,current,tmp_path)['ack_status']=='completed'
    assert stores(ftp)==2 and guru() is None


@pytest.mark.parametrize('change', ['inactive','reclassified'])
def test_withdrawal_updates_only_gruntguru_publication(country,tmp_path,ftp,change):
    assert send(country,prepare(country),tmp_path)['ack_status']=='completed'
    sql(country,"UPDATE EstateData SET "+("Status_oferty='Nieaktywna'" if change=='inactive' else "Typ_nieruchomosci='dom'"))
    assert guru()['category']=='withdraw' and guru()['action']=='delete'
    chosen=prepare(country,'delete')
    folder,item=manifest(country,chosen)
    with zipfile.ZipFile(folder/item['zip_name']) as archive:
        assert len(archive.namelist())==2
        xml=next(name for name in archive.namelist() if name.startswith('EstiCRM_'))
        offer=ET.fromstring(archive.read(xml)).find('offer')
        assert [node.tag for node in offer]==['id','companyId','action']
        assert offer.findtext('action')=='delete'
    assert send(country,chosen,tmp_path)['ack_status']=='completed'
    assert status(country,'gruntguru')==(0,0,'delete') and guru() is None


def _published_plot(country,tmp_path):
    assert send(country,prepare(country),tmp_path)['ack_status']=='completed'
    assert guru() is None


@pytest.mark.parametrize('change,sql_text',[('inactive',"Status_oferty='Nieaktywna'"),('reclassified',"Typ_nieruchomosci='dom'")])
def test_withdrawal_is_classified_without_an_issue(country,tmp_path,ftp,change,sql_text):
    """Regression: a withdrawal never depends on the source comparison, which cannot validate a reclassified plot as 'add'."""
    _published_plot(country,tmp_path)
    sql(country,'UPDATE EstateData SET '+sql_text)
    task=guru()
    assert (task['category'],task['action'],task['operation'],task['issue'])==('withdraw','delete','withdraw',None)
    assert task['published'] is True


def test_active_published_plot_update_still_compares_the_source(country,tmp_path,ftp,monkeypatch):
    from InvestmentManager.integrator import sync_tasks
    _published_plot(country,tmp_path)
    calls=[]
    real=sync_tasks._source_changed
    monkeypatch.setattr(sync_tasks,'_source_changed',lambda *a,**k:(calls.append(1),real(*a,**k))[1])
    assert guru() is None and calls          # unchanged source: compared, nothing to do
    sql(country,"UPDATE EstateData SET Cena='345678'")
    task=guru()
    assert (task['category'],task['action'],task['issue'])==('update','add',None)


def test_unpublished_plot_is_a_new_publication_without_source_comparison(country,monkeypatch):
    from InvestmentManager.integrator import sync_tasks
    calls=[]
    monkeypatch.setattr(sync_tasks,'_source_changed',lambda *a,**k:calls.append(1) or False)
    task=guru()
    assert (task['category'],task['action'],task['operation'],task['issue'])==('new','add','publish',None)
    assert calls==[]


@pytest.mark.parametrize('mode,phase',[('connect','failed_before_send'),('stor','unknown')])
def test_transport_failure_and_recovery_never_duplicate_unknown(country,tmp_path,ftp,mode,phase):
    chosen=prepare(country);ftp.mode=mode
    result=send(country,chosen,tmp_path)
    assert result['ftp_status']==phase and result['ack_status']=='not_started'
    task=guru()
    assert task['category']=='error' and task['send_allowed']==(phase=='failed_before_send')
    count=stores(ftp)
    recovered=delivery.inspect_attempt(Client(country),'fixed-verifier',result['attempt_id'],acknowledge=True)
    assert recovered['ack_status']=='not_started'
    if phase=='unknown':
        assert send(country,chosen,tmp_path)['ftp_attempted'] is False
        assert stores(ftp)==count


def test_pending_ack_can_be_recovered_without_new_ftp(country,tmp_path,ftp):
    chosen=prepare(country);client=Client(country);client.fail_before.add('acknowledge_attempt')
    result=send(country,chosen,tmp_path,client)
    assert result['ftp_status']=='confirmed' and result['ack_status']=='pending'
    assert guru()['last_result']['can_ack'] and not guru()['send_allowed']
    recovered=delivery.inspect_attempt(Client(country),'fixed-verifier',result['attempt_id'],acknowledge=True)
    assert recovered['ack_status']=='completed' and stores(ftp)==1 and guru() is None


def test_wrong_ack_binding_is_refused_and_original_can_finish(country):
    chosen=prepare(country)
    item=attempts.create_attempt(**chosen)
    attempts.start_transport(item['attempt_id'],item['binding'])
    attempts.record_transport_result(item['attempt_id'],item['binding'],'confirmed')
    with pytest.raises(attempts.AttemptError):
        attempts.acknowledge_attempt(item['attempt_id'],item['binding']|{'portal':'no'})
    assert status(country,'gruntguru') is None
    assert attempts.acknowledge_attempt(item['attempt_id'],item['binding'])['state']=='ack_completed'


def test_older_three_portal_pointer_is_read_without_reset_or_gg_fallback(country):
    chosen=prepare(country)
    base=country/'exports/domestic';path=base/'17/add/current.json'
    value=json.loads(path.read_text());value['packages'].pop('gruntguru')
    path.write_text(json.dumps(value))  # synthetic pre-extension pointer
    before=path.read_bytes()
    assert len(sets.list_sets()['items'][0]['items'])==3
    assert guru()['category']=='new' and guru()['package'] is None
    assert catalog.verify_package(chosen['package_id'])['state']=='STALE'
    assert path.read_bytes()==before
    assert sets.prepare_set(17,'add')['replaced']
    assert len(sets.current(base,17,'add')['packages'])==4


def test_gg_partial_failure_preserves_previous_complete_set(country,monkeypatch):
    from InvestmentManager.integrator import domestic_packages as prep
    prepare(country);base=country/'exports/domestic';before=sets.current(base,17,'add')
    original=prep.prepare_package
    def fail(offer,portal,action,**kwargs):
        if portal=='gruntguru':raise prep.PreparationError('refused','Synthetic GG failure')
        return original(offer,portal,action,**kwargs)
    monkeypatch.setattr(prep,'prepare_package',fail)
    assert not sets.prepare_set(17,'add')['replaced']
    assert sets.current(base,17,'add')==before


def test_replacement_preserves_inflight_gg_and_allows_only_original_ack(country):
    chosen=prepare(country)
    folder,_=manifest(country,chosen)
    item=attempts.create_attempt(**chosen)
    attempts.start_transport(item['attempt_id'],item['binding'])
    newer=prepare(country)
    assert newer['package_id']!=chosen['package_id'] and folder.is_dir()
    assert catalog.verify_package(chosen['package_id'])['state']=='STALE'
    assert not guru()['send_allowed'] and guru()['package']['package_id']==newer['package_id']
    attempts.record_transport_result(item['attempt_id'],item['binding'],'confirmed')
    assert attempts.acknowledge_attempt(item['attempt_id'],item['binding'])['state']=='ack_completed'
    cleanup=sets.cleanup(offer_id=17,action='add')
    assert chosen['package_id'] in cleanup['retained'] and folder.is_dir()
    assert guru() is None


def test_type_change_during_preparation_cannot_activate_incomplete_portal_scope(country,monkeypatch):
    from InvestmentManager.integrator import domestic_packages as prep
    sql(country,"UPDATE EstateData SET Typ_nieruchomosci='dom'")
    prepare_result=sets.prepare_set(17,'add')
    assert prepare_result['replaced']
    base=country/'exports/domestic';before=sets.current(base,17,'add')
    original=prep.prepare_package;changed=[]
    def change(offer,portal,action,**kwargs):
        if not changed:
            changed.append(True)
            sql(country,"UPDATE EstateData SET Typ_nieruchomosci='dzialka'")
        return original(offer,portal,action,**kwargs)
    monkeypatch.setattr(prep,'prepare_package',change)
    result=sets.prepare_set(17,'add')
    assert not result['replaced'] and sets.current(base,17,'add')==before


def test_existing_legacy_gruntguru_attempt_still_blocks_new_transport(country,tmp_path,ftp):
    chosen=prepare(country)
    sql(country,"INSERT INTO offer_portal_sync_events(offer_id,portal_key,event_type,payload_json,created_at) VALUES (17,'gruntguru','legacy_attempt_started','{}','test')")
    task=guru()
    assert task['issue']=='legacy_unresolved' and task['category']=='error' and not task['send_allowed']
    assert send(country,chosen,tmp_path)['ftp_attempted'] is False
    assert not ftp.instances and status(country,'gruntguru') is None
