"""Real producer + receiver + delivery + existing uploader over synthetic I/O."""
from concurrent.futures import ThreadPoolExecutor
from contextlib import closing
import importlib
import io
import json
from pathlib import Path
import sqlite3
import subprocess
import sys
import threading
import types
import uuid

import pytest

from tests.peer_repository import idbmanager_root

from tests.investmentmanager.test_domestic_packages import data_root,isolated,sql,manifest
from tests.investmentmanager.test_export_handoff import SFTP,Channel
from InvestmentManager import export_handoff as server
from InvestmentManager.integrator import domestic_packages as prep
from InvestmentManager.integrator import export_attempts as attempts
from InvestmentManager.integrator.input_consistency import serialized_write,write_inputs

PEER=idbmanager_root()


def namespace(name,path):
    module=types.ModuleType(name);module.__path__=[str(path)];sys.modules[name]=module


namespace('delivery_test_modules',PEER/'modules')
namespace('delivery_test_engine',PEER/'portal_engine')
namespace('delivery_test_engine.portals',PEER/'portal_engine/portals')
delivery=importlib.import_module('delivery_test_modules.prepared_package_delivery')
uploader=importlib.import_module('delivery_test_engine.portals.service')


class Output:
    def __init__(self,stdin,client):self.stdin=stdin;self.client=client;self.channel=Channel();self.exit=0
    def read(self,limit):
        request=json.loads(self.stdin.getvalue());op=request.get('operation','verify')
        client=self.client;client.ops.append(op)
        if op in client.fail_before:raise OSError('simulated SSH failure')
        reply=server.dispatch_request(request)
        self.channel.recv_exit_status=lambda:0 if reply.get('ok') is True or reply.get('state')=='READY' else 1
        if client.after:client.after(op,request,reply)
        if op in client.drop_after:
            client.drop_after.remove(op);raise OSError('response lost after commit')
        return json.dumps(reply).encode()[:limit]


class Client:
    def __init__(self,root):
        self.root=root;self.mutate=None;self.ops=[];self.fail_before=set();self.drop_after=set();self.after=None
    def exec_command(self,command,timeout):
        assert command=='fixed-verifier'
        stdin=io.StringIO();stdin.channel=Channel()
        return stdin,Output(stdin,self),io.BytesIO()
    def open_sftp(self):return SFTP(self)


@pytest.fixture
def ftp(monkeypatch):
    class FTP:
        instances=[];mode=None;on_store=None;entered=None;release=None
        def __init__(self):self.sock=object();self.calls=[];self.bytes=None;self.instances.append(self)
        def connect(self,**kwargs):
            self.calls.append('connect')
            if self.mode=='connect':raise OSError('connect failed')
        def login(self,**kwargs):self.calls.append('login')
        def storbinary(self,command,stream):
            self.calls.append(command);self.bytes=stream.read()
            if self.on_store:self.on_store()
            if self.entered:self.entered.set()
            if self.release:assert self.release.wait(20)
            if self.mode in {'stor','lost_stor_reply'}:raise EOFError('uncertain STOR')
        def rename(self,source,target):
            self.calls.append(('rename',source,target))
            if self.mode=='rename':raise EOFError('rename may have succeeded')
        def quit(self):self.calls.append('quit');self.sock=None
        def close(self):self.sock=None
    monkeypatch.setattr(uploader.ftplib,'FTP',FTP)
    monkeypatch.setattr(uploader.ftplib,'FTP_TLS',lambda:pytest.fail('Domestic profiles must preserve existing FTP'))
    return FTP


def secrets(key):
    return 'synthetic' if key.endswith(('_HOST','_USERNAME','_PASSWORD')) else None


def selection(portal='no',action='add'):
    result=prep.prepare_package(17,portal,action)
    return {k:result[k] for k in ('package_id','portal','action')}|{'offer_id':17}


def send(root,selected,tmp_path,client=None,**kwargs):
    return delivery.deliver_package(client or Client(root),data_dir='/private/InvestmentData',
        command='fixed-verifier',temp_parent=tmp_path,secret_getter=secrets,transport=uploader,
        **selected,**kwargs)


def status(root,portal='no'):
    with closing(sqlite3.connect(root/'databases/IDB.db')) as conn:
        return conn.execute('SELECT is_published,needs_update,last_action FROM offer_portal_sync WHERE offer_id=17 AND portal_key=?',(portal,)).fetchone()


def stores(ftp):return sum(any(isinstance(c,str) and c.startswith('STOR ') for c in x.calls) for x in ftp.instances)


@pytest.mark.parametrize('portal',['no','domiporta','tabelaofert','gruntguru'])
@pytest.mark.parametrize('action',['add','delete'])
def test_full_ready_receive_upload_ack_exact_bytes(data_root,tmp_path,ftp,portal,action):
    selected=selection(portal,action);folder,item=manifest(data_root,selected)
    expected=(folder/item['zip_name']).read_bytes();client=Client(data_root)
    result=send(data_root,selected,tmp_path,client)
    assert result['verification']=='received_verified'
    assert result['ftp_status']=='confirmed' and result['ack_status']=='completed' and result['result_saved'] is True
    assert status(data_root,portal)==(int(action=='add'),0,action)
    assert stores(ftp)==1 and ftp.instances[0].bytes==expected
    assert 'STOR '+item['zip_name'] in ftp.instances[0].calls
    if portal=='domiporta':assert ('rename',item['zip_name'],'ok-'+item['zip_name']) in ftp.instances[0].calls
    assert client.ops==['verify','verify','create_attempt','start_transport','record_transport_result','acknowledge_attempt']
    assert not list(tmp_path.glob('idb-receive-*'))


@pytest.mark.parametrize('change',['price','status','zip','binding'])
def test_non_ready_or_wrong_binding_never_uploads(data_root,tmp_path,ftp,change):
    selected=selection();folder,item=manifest(data_root,selected)
    if change=='price':sql(data_root,"UPDATE EstateData SET Cena='177000'")
    elif change=='status':sql(data_root,"UPDATE EstateData SET Status_oferty='sprzedane'")
    elif change=='zip':(folder/item['zip_name']).write_bytes(b'bad zip')
    else:selected['offer_id']=18
    result=send(data_root,selected,tmp_path)
    assert result['verification']=={'price':'STALE','status':'BLOCKED','zip':'INVALID','binding':'INVALID'}[change]
    assert result['ftp_attempted'] is False and not ftp.instances


@pytest.mark.parametrize('operation',['verify','create_attempt','start_transport'])
def test_rpc_failure_before_send_never_uploads(data_root,tmp_path,ftp,operation):
    selected=selection();client=Client(data_root);client.fail_before.add(operation)
    result=send(data_root,selected,tmp_path,client)
    assert result['ftp_attempted'] is False and not ftp.instances


def test_lost_start_reply_is_not_permission_and_restart_does_not_send(data_root,tmp_path,ftp):
    selected=selection();client=Client(data_root);client.drop_after.add('start_transport')
    result=send(data_root,selected,tmp_path,client)
    assert result['durable_state']=='transport_unknown' and not ftp.instances
    read=delivery.inspect_attempt(Client(data_root),'fixed-verifier',result['attempt_id'],acknowledge=True)
    assert read['durable_state']=='transport_unknown' and read['ack_status']=='not_started'
    again=send(data_root,selected,tmp_path)
    assert again['ftp_attempted'] is False and not ftp.instances


@pytest.mark.parametrize('mode,portal,phase',[('connect','no','failed_before_send'),('stor','no','unknown'),('rename','domiporta','unknown'),('lost_stor_reply','no','unknown')])
def test_transport_failures_and_no_duplicate_after_rerun(data_root,tmp_path,ftp,mode,portal,phase):
    selected=selection(portal);ftp.mode=mode
    result=send(data_root,selected,tmp_path)
    assert result['ftp_status']==phase and result['ack_status']=='not_started'
    before=stores(ftp)
    delivery.inspect_attempt(Client(data_root),'fixed-verifier',result['attempt_id'],acknowledge=True)
    if phase=='unknown':
        send(data_root,selected,tmp_path)
        assert stores(ftp)==before


@pytest.mark.parametrize('lost_operation',['record_transport_result','acknowledge_attempt'])
def test_lost_write_reply_is_recovered_by_read_only_lookup(data_root,tmp_path,ftp,lost_operation):
    selected=selection();client=Client(data_root);client.drop_after.add(lost_operation)
    result=send(data_root,selected,tmp_path,client)
    assert result['ftp_status']=='confirmed' and result['ack_status']=='completed'
    assert stores(ftp)==1 and 'get_attempt' in client.ops
    assert delivery.inspect_attempt(Client(data_root),'fixed-verifier',result['attempt_id'],acknowledge=True)['ack_status']=='completed'
    assert stores(ftp)==1


def test_successful_ftp_without_durable_result_never_permits_ack_or_resend(data_root,tmp_path,ftp):
    selected=selection();client=Client(data_root);client.fail_before.add('record_transport_result')
    result=send(data_root,selected,tmp_path,client)
    assert result['ftp_status']=='confirmed' and result['durable_state']=='transport_unknown'
    assert result['result_saved'] is False and result['ack_status']=='not_started'
    assert 'acknowledge_attempt' not in client.ops
    send(data_root,selected,tmp_path)
    assert stores(ftp)==1


def test_ack_failure_after_ftp_can_resume_only_ack(data_root,tmp_path,ftp):
    selected=selection();client=Client(data_root);client.fail_before.add('acknowledge_attempt')
    result=send(data_root,selected,tmp_path,client)
    assert result['ftp_status']=='confirmed' and result['ack_status']=='pending'
    recovered=delivery.inspect_attempt(Client(data_root),'fixed-verifier',result['attempt_id'],acknowledge=True)
    assert recovered['ack_status']=='completed' and stores(ftp)==1


@pytest.mark.parametrize('change',['description','photo','agent','agent_photo','price','status'])
def test_change_during_upload_refuses_ack_and_preserves_dirty(data_root,tmp_path,ftp,change):
    selected=selection()
    @serialized_write
    def mutate():
        write_inputs(offer_ids=[17])
        if change=='price':sql(data_root,"UPDATE EstateData SET Cena='177000'")
        elif change=='status':sql(data_root,"UPDATE EstateData SET Status_oferty='sprzedane'")
        elif change=='agent':sql(data_root,"UPDATE agents_v2 SET phone='999'",db='agents.db')
        else:
            names={'description':'offers/17/description_17.md','photo':'offers/17/image_17_url_0.jpg','agent_photo':'agents/agent_7.jpg'}
            (data_root/names[change]).write_bytes(b'changed')
    ftp.on_store=staticmethod(mutate)
    result=send(data_root,selected,tmp_path)
    assert result['ftp_status']=='confirmed' and result['ack_status']=='rejected'
    assert status(data_root)[1]==1 and stores(ftp)==1


def test_two_parallel_deliveries_same_portal_cannot_duplicate_ftp(data_root,tmp_path,ftp):
    selected=selection();ftp.entered=threading.Event();ftp.release=threading.Event()
    with ThreadPoolExecutor(max_workers=2) as pool:
        first=pool.submit(send,data_root,selected,tmp_path)
        try:
            assert ftp.entered.wait(20)
            second=pool.submit(send,data_root,selected,tmp_path).result(timeout=20)
            assert second['ftp_attempted'] is False
        finally:ftp.release.set()
        assert first.result(timeout=20)['ack_status']=='completed'
    assert stores(ftp)==1


def test_independent_portals_and_completed_request_never_resend(data_root,tmp_path,ftp):
    a=selection();b=selection('tabelaofert')
    assert send(data_root,a,tmp_path)['ack_status']=='completed'
    assert send(data_root,b,tmp_path)['ack_status']=='completed'
    repeat=send(data_root,a,tmp_path)
    assert repeat['ack_status']=='completed' and repeat['ftp_attempted'] is False and stores(ftp)==2


@pytest.mark.parametrize('payload',[
    {'operation':'exec','attempt_id':'a'*32,'command':'echo forbidden'},
    {'operation':'get_attempt','attempt_id':'../bad'},
    {'operation':'get_attempt','attempt_id':'a'*32,'command':'whoami'},
    {'operation':'record_transport_result','attempt_id':'a'*32,'binding':{},'outcome':'confirmed'},
    {'operation':'create_attempt','attempt_id':'a'*32,'package_id':'b'*32,'offer_id':True,'portal':'no','action':'add'},
    {'operation':'create_attempt','attempt_id':'a'*32,'package_id':'b'*32,'offer_id':17,'portal':'otodom','action':'add'},
])
def test_cli_strict_schema_rejects_commands_and_invalid_fields(data_root,payload):
    result=server.dispatch_request(payload)
    assert result['ok'] is False and result['error']=='invalid_request'


def test_real_cli_get_after_process_restart_and_public_response_whitelist(data_root,tmp_path,ftp):
    result=send(data_root,selection(),tmp_path)
    request={'operation':'get_attempt','attempt_id':result['attempt_id']}
    repo=Path(__file__).resolve().parents[2]
    process=subprocess.run([sys.executable,'-B','-m','InvestmentManager.export_handoff'],cwd=repo,
        input=json.dumps(request),capture_output=True,text=True,encoding='utf8',timeout=30)
    reply=json.loads(process.stdout)
    assert process.returncode==0 and reply['attempt']['state']=='ack_completed'
    assert set(reply['attempt'])=={'attempt_id','binding','state'}
    assert 'baseline' not in process.stdout and str(data_root) not in process.stdout


@pytest.mark.parametrize('point',['sftp','post_receive'])
def test_receive_disconnects_never_reach_ftp(data_root,tmp_path,ftp,point):
    client=Client(data_root);selected=selection()
    if point=='sftp':
        def unavailable():raise EOFError('SFTP interrupted')
        client.open_sftp=unavailable
    else:
        def after(op,request,reply):
            if op=='verify' and client.ops.count('verify')==2:raise EOFError('SSH lost after downloading')
        client.after=after
    result=send(data_root,selected,tmp_path,client)
    assert result['ftp_attempted'] is False and not ftp.instances


def test_ftp_success_and_ssh_unavailable_for_result_and_lookup(data_root,tmp_path,ftp):
    selected=selection();client=Client(data_root)
    client.fail_before.update({'record_transport_result','get_attempt'})
    result=send(data_root,selected,tmp_path,client)
    assert result['ftp_status']=='confirmed' and result['result_saved'] is False
    assert result['durable_state']=='transport_unknown' and result['ack_status']=='not_started'
    recovered=delivery.inspect_attempt(Client(data_root),'fixed-verifier',result['attempt_id'],acknowledge=True)
    assert recovered['durable_state']=='transport_unknown' and stores(ftp)==1


def test_failure_before_stor_with_lost_result_is_not_silently_retryable(data_root,tmp_path,ftp):
    selected=selection();client=Client(data_root);ftp.mode='connect'
    client.fail_before.add('record_transport_result')
    result=send(data_root,selected,tmp_path,client)
    assert result['ftp_status']=='failed_before_send' and result['result_saved'] is False
    assert result['durable_state']=='transport_unknown' and result['code']=='result_save_uncertain'
    count=len(ftp.instances);send(data_root,selected,tmp_path)
    assert len(ftp.instances)==count


def test_actual_ack_storage_failure_after_ftp_is_separate(data_root,tmp_path,ftp,monkeypatch):
    original=attempts._append
    def failed(conn,item,state,*args):
        if state=='ack_completed':raise sqlite3.OperationalError('synthetic ACK failure')
        return original(conn,item,state,*args)
    monkeypatch.setattr(attempts,'_append',failed)
    result=send(data_root,selection(),tmp_path)
    assert result['ftp_status']=='confirmed' and result['ack_status']=='failed'
    assert result['durable_state']=='ack_failed' and status(data_root) is None
    monkeypatch.setattr(attempts,'_append',original)
    assert delivery.inspect_attempt(Client(data_root),'fixed-verifier',result['attempt_id'],acknowledge=True)['ack_status']=='completed'
    assert stores(ftp)==1


def test_bad_send_permission_type_never_uploads(data_root,tmp_path,ftp):
    client=Client(data_root)
    def corrupt(op,request,reply):
        if op=='start_transport' and reply.get('ok'):reply['attempt']['can_send']=1
    client.after=corrupt
    result=send(data_root,selection(),tmp_path,client)
    assert result['durable_state']=='transport_unknown' and not ftp.instances


def test_local_zip_change_after_creation_is_blocked_before_start(data_root,tmp_path,ftp):
    def change(op,request,reply):
        if op=='create_attempt':
            copy=next(tmp_path.glob('idb-receive-*/verified/*.zip'))
            copy.write_bytes(b'changed locally')
    client=Client(data_root);client.after=change
    result=send(data_root,selection(),tmp_path,client)
    assert result['code']=='local_artifact_changed' and not ftp.instances and 'start_transport' not in client.ops


def test_trusted_ssh_publisher_is_not_cryptographic_ftp_attestation(data_root,ftp):
    selected=selection();identifier=uuid.uuid4().hex
    created=server.dispatch_request({'operation':'create_attempt','attempt_id':identifier,**selected})
    binding=created['attempt']['binding']
    before=server.dispatch_request({'operation':'record_transport_result','attempt_id':identifier,'binding':binding,'outcome':'confirmed'})
    assert before['ok'] is False
    assert server.dispatch_request({'operation':'start_transport','attempt_id':identifier,'binding':binding})['attempt']['can_send']
    # A trusted OS publisher already has shell/database access. The CLI cannot
    # turn that principal's statement into independent evidence from a portal.
    claimed=server.dispatch_request({'operation':'record_transport_result','attempt_id':identifier,'binding':binding,'outcome':'confirmed'})
    assert claimed['ok'] is True and stores(ftp)==0


@pytest.mark.parametrize('portal',['no','domiporta','tabelaofert','gruntguru'])
def test_all_remote_operations_in_fresh_cli_processes(data_root,portal):
    selected=selection(portal);identifier=uuid.uuid4().hex
    script='''from InvestmentManager.integrator import domestic_dictionaries as d
d._download=lambda url:b'<dictionary><item id="1" name="test"/></dictionary>'
from InvestmentManager.export_handoff import main
raise SystemExit(main())'''
    repo=Path(__file__).resolve().parents[2]
    def call(operation,**fields):
        result=subprocess.run([sys.executable,'-B','-c',script],cwd=repo,
            input=json.dumps({'operation':operation,'attempt_id':identifier,**fields}),capture_output=True,text=True,encoding='utf8',timeout=30)
        reply=json.loads(result.stdout)
        assert result.returncode==0 and reply['ok'] is True,reply
        return reply['attempt']
    item=call('create_attempt',**selected)
    assert call('start_transport',binding=item['binding'])['can_send'] is True
    # Simulated trusted transport report; this test performs no FTP.
    assert call('record_transport_result',binding=item['binding'],outcome='confirmed')['state']=='transport_confirmed'
    assert call('acknowledge_attempt',binding=item['binding'])['state']=='ack_completed'
    assert call('get_attempt')['state']=='ack_completed'
    assert call('acknowledge_attempt',binding=item['binding'])['already_acknowledged'] is True


def test_crash_after_start_before_stor_leaves_durable_unknown(data_root,tmp_path,ftp,monkeypatch):
    class ProcessCrash(BaseException):pass
    identifier=uuid.uuid4().hex;selected=selection()
    def crashed(*args,**kwargs):raise ProcessCrash()
    monkeypatch.setattr(ftp,'connect',crashed)
    with pytest.raises(ProcessCrash):send(data_root,selected,tmp_path,attempt_id=identifier)
    recovered=delivery.inspect_attempt(Client(data_root),'fixed-verifier',identifier,acknowledge=True)
    assert recovered['durable_state']=='transport_unknown' and recovered['ack_status']=='not_started'
    assert stores(ftp)==0
    repo=Path(__file__).resolve().parents[2]
    response=subprocess.run([sys.executable,'-B','-m','InvestmentManager.export_handoff'],cwd=repo,
        input=json.dumps({'operation':'get_attempt','attempt_id':identifier}),capture_output=True,text=True,encoding='utf8',timeout=30)
    assert json.loads(response.stdout)['attempt']['state']=='transport_unknown'


@pytest.mark.parametrize('body',[
    '{"operation":"get_attempt","operation":"record_transport_result","attempt_id":"'+'a'*32+'"}',
    'x'*16385,
])
def test_cli_duplicate_or_oversized_json_never_writes(data_root,body):
    repo=Path(__file__).resolve().parents[2]
    before=(data_root/'databases/IDB.db').read_bytes()
    result=subprocess.run([sys.executable,'-B','-m','InvestmentManager.export_handoff'],cwd=repo,
        input=body,capture_output=True,text=True,encoding='utf8',timeout=30)
    assert result.returncode==1 and json.loads(result.stdout).get('ok') is not True
    assert (data_root/'databases/IDB.db').read_bytes()==before


def test_parallel_cli_processes_grant_transport_exactly_once(data_root):
    selected=selection();identifier=uuid.uuid4().hex
    item=server.dispatch_request({'operation':'create_attempt','attempt_id':identifier,**selected})['attempt']
    request={'operation':'start_transport','attempt_id':identifier,'binding':item['binding']}
    repo=Path(__file__).resolve().parents[2]
    def start():
        result=subprocess.run([sys.executable,'-B','-m','InvestmentManager.export_handoff'],cwd=repo,
            input=json.dumps(request),capture_output=True,text=True,encoding='utf8',timeout=30)
        return json.loads(result.stdout)
    with ThreadPoolExecutor(max_workers=2) as pool:
        responses=list(pool.map(lambda _:start(),range(2)))
    assert sum(r.get('attempt',{}).get('can_send') is True for r in responses)==1
    assert attempts.get_attempt(identifier)['state']=='transport_unknown'
