"""Real Investment verification + IDB receiver over a controlled transport."""
import importlib.util
import io
import json
from pathlib import Path
import types
import subprocess
import sys

import pytest

from tests.peer_repository import idbmanager_root

from tests.investmentmanager.test_domestic_packages import data_root,isolated,sql,manifest
from InvestmentManager.export_handoff import confirm_package as production_confirm
from InvestmentManager.integrator import domestic_packages as prep
from InvestmentManager.integrator import domestic_dictionaries as dictionaries
from InvestmentManager.integrator import domestic_package_catalog as catalog

def confirm_package(request):
    if isinstance(request,dict) and set(request)=={'package_id','offer_id','portal','action'}:
        request = request | {'storage_layout':'offer-operation-portal-v1'}
    return production_confirm(request)


IDB=idbmanager_root()/'modules/prepared_packages.py'
# Preserve the receiver's package context for relative instrumentation imports.
# This remains an isolated namespace, never Investment's own `modules` package.
package=types.ModuleType('isolated_idb_receiver_modules')
package.__path__=[str(IDB.parent)]
sys.modules[package.__name__]=package
spec=importlib.util.spec_from_file_location(package.__name__+'.prepared_packages',IDB)
receiver=importlib.util.module_from_spec(spec)
sys.modules[spec.name]=receiver
spec.loader.exec_module(receiver)


@pytest.fixture(autouse=True)
def no_ftp(monkeypatch):
    import ftplib
    def forbidden(*args,**kwargs):raise AssertionError('FTP forbidden')
    monkeypatch.setattr(ftplib,'FTP',forbidden);monkeypatch.setattr(ftplib,'FTP_TLS',forbidden)


class Channel:
    def settimeout(self,value):pass
    def shutdown_write(self):pass
    def close(self):pass
    def recv_exit_status(self):return 0


class Output:
    channel=Channel()
    def __init__(self,stdin,client):self.stdin=stdin;self.client=client
    def read(self,limit):
        self.client.calls+=1
        result=confirm_package(json.loads(self.stdin.getvalue()))
        return json.dumps(result).encode()[:limit]


class SFTP:
    def __init__(self,client):self.client=client
    def __enter__(self):return self
    def __exit__(self,*args):pass
    def get_channel(self):return Channel()
    def path(self,remote):
        assert remote.startswith('/private/InvestmentData')
        return self.client.root/remote.removeprefix('/private/InvestmentData').lstrip('/')
    def normalize(self,path):return path
    def lstat(self,path):return self.path(path).lstat()
    def get(self,remote,local,callback,prefetch):
        body=self.path(remote).read_bytes();Path(local).write_bytes(body);callback(len(body),len(body))
        if remote.endswith('.zip') and self.client.mutate:self.client.mutate()


class Client:
    def __init__(self,root,mutate=None):self.root=root;self.mutate=mutate;self.calls=0
    def exec_command(self,command,timeout):
        stdin=io.StringIO();stdin.channel=Channel()
        return stdin,Output(stdin,self),io.BytesIO()
    def open_sftp(self):return SFTP(self)


def receive(root,selection,tmp_path,mutate=None):
    return receiver.receive_package(Client(root,mutate),data_dir='/private/InvestmentData',command='test-verifier',temp_parent=tmp_path,**selection)


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


def test_real_ready_and_no_database_or_manifest_writes(data_root,selection,tmp_path):
    before={p:p.read_bytes() for p in data_root.rglob('*') if p.is_file()}
    with receive(data_root,selection,tmp_path) as result:
        assert result['zip_path'].is_file() and result['outcome']=='received_verified'
    assert all(p.read_bytes()==body for p,body in before.items())
    extra={p.name for p in data_root.rglob('*') if p.is_file() and p not in before}
    assert extra == {'.verification.json', '.handoff-pin.json'}  # lock exists since preparation


def test_old_panel_ready_is_not_used(data_root,selection,tmp_path):
    assert catalog.verify_package(selection['package_id'])['state']=='READY'
    sql(data_root,"UPDATE EstateData SET Cena='177000'")
    with pytest.raises(receiver.ReceiveError) as error:
        with receive(data_root,selection,tmp_path):pass
    assert error.value.code=='server_stale'


@pytest.mark.parametrize('change',['price','status','zip','manifest'])
def test_change_during_transfer_is_rejected(data_root,selection,tmp_path,change):
    folder=manifest(data_root,selection)[0]
    def mutate():
        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':
            p=folder/'no_17.zip';body=p.read_bytes();p.write_bytes(body[:-1]+bytes([body[-1]^1]))
        else:
            p=folder/'manifest.json';item=json.loads(p.read_bytes());item['prepared_at']='2026-01-01T00:00:00+00:00';p.write_text(json.dumps(item),encoding='utf8')
    with pytest.raises(receiver.ReceiveError):
        with receive(data_root,selection,tmp_path,mutate):pass
    assert not list(tmp_path.glob('idb-receive-*'))


def test_unavailable_required_dictionary_is_blocked(data_root,tmp_path,monkeypatch):
    result=prep.prepare_package(17,'domiporta','add')
    selection={k:result[k] for k in ['package_id','portal','action']}|{'offer_id':17}
    dictionaries._cache.clear()
    def unavailable(url):raise OSError('offline')
    monkeypatch.setattr(dictionaries,'_download',unavailable)
    with pytest.raises(receiver.ReceiveError) as error:
        with receive(data_root,selection,tmp_path):pass
    assert error.value.code=='server_blocked'


def test_confirm_selection_and_missing_permissions(data_root,selection,monkeypatch):
    assert confirm_package({**selection,'offer_id':18})['state']=='INVALID'
    def denied(*args):raise PermissionError('private path')
    monkeypatch.setattr(catalog,'_open',denied)
    result=confirm_package(selection)
    assert result['state']=='BLOCKED' and result['reasons'][0]['code']=='permission_denied'
    assert 'private path' not in json.dumps(result)


@pytest.mark.parametrize('body',[{},[],{'package_id':'../bad'},None])
def test_invalid_request(body):
    assert confirm_package(body)['state']=='BLOCKED'


def test_real_cli_returns_only_protocol_json(data_root,selection):
    root=Path(__file__).resolve().parents[2]
    result=subprocess.run([sys.executable,'-B','-m','InvestmentManager.export_handoff'],
                          input=json.dumps(selection|{'storage_layout':'offer-operation-portal-v1'}),cwd=root,capture_output=True,text=True,encoding='utf8',timeout=30)
    assert result.returncode==0,result.stderr
    response=json.loads(result.stdout)
    assert response['state']=='READY' and response['permissions_checked'] is True
    assert response['package_id']==selection['package_id']
    assert str(data_root) not in result.stdout
