"""Real v2 producer, wire, receiver, lifecycle, SQLite ACK and existing uploader.

Only external SSH/SFTP/FTP I/O is simulated. No live service is contacted.
"""
from contextlib import closing
import json
import sqlite3
import subprocess
import sys
import uuid

import pytest

from tests.investmentmanager.test_foreign_packages_v2 import foreign_root, prepare
from tests.investmentmanager.test_prepared_delivery_integration import Client, ftp, secrets, delivery, uploader
from InvestmentManager import foreign_offers_store as store, export_handoff as server
from InvestmentManager.integrator import export_attempts as attempts, foreign_consistency


@pytest.fixture
def env(foreign_root,monkeypatch):
    root,settings,calls=foreign_root
    for key,value in settings.items():
        monkeypatch.setenv(key,json.dumps(value) if isinstance(value,dict) else value)
    return foreign_root


def selected(env,portal='domiporta',action='add',group=False):
    if action=='delete': store.set_foreign_offer_active(11,False,user_id=1)
    result=prepare(env,kind='cyprus_development' if group else 'foreign_offer',identifier=7 if group else 11,portal=portal,action=action)
    return {k:result[k] for k in ('package_id','subject','portal','action')}|{'domain':'foreign'}


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


def create(env,choice,**kwargs):
    return attempts.create_attempt(**choice,settings=env[1],**kwargs)


def status(env):
    with sqlite3.connect(env[0]/'databases/foreign_offers.db') as conn:
        return conn.execute('SELECT foreign_offer_id,portal_key,is_published,needs_update,last_action,last_filename,last_bytes FROM foreign_offer_portal_sync ORDER BY 1,2').fetchall()


@pytest.mark.parametrize('portal',['domiporta','tabelaofert'])
@pytest.mark.parametrize('action',['add','delete'])
def test_full_wire_upload_ack_and_replay(env,ftp,tmp_path,portal,action):
    choice=selected(env,portal,action); result=send(env,choice,tmp_path)
    assert result['code']=='ack_completed',result
    item=attempts.get_attempt(result['attempt_id'],domain='foreign')
    assert item['state']=='ack_completed' and item['binding']['transport_profile']==('domiporta' if portal=='domiporta' else 'tabelaofert_primary')
    assert len(ftp.instances)==1
    if portal=='domiporta': assert any(isinstance(c,tuple) and c[0]=='rename' and c[2].startswith('ok-') for c in ftp.instances[0].calls)
    before=status(env)
    again=attempts.acknowledge_attempt(item['attempt_id'],item['binding'],domain='foreign',settings=env[1])
    assert again['already_acknowledged'] and status(env)==before
    assert attempts.start_transport(item['attempt_id'],item['binding'],domain='foreign',settings=env[1])['can_send'] is False


@pytest.mark.parametrize('mode,expected',[('connect','transport_failed'),('stor','transport_unknown'),('rename','transport_unknown'),(None,'ack_completed')])
def test_real_uploader_phases(env,ftp,tmp_path,mode,expected):
    ftp.mode=mode
    result=send(env,selected(env),tmp_path)
    assert result['durable_state']==expected,result
    assert len(ftp.instances)==1
    if expected=='transport_unknown':
        assert result['ftp_status']=='unknown' and result['ack_status']=='not_started'


@pytest.mark.parametrize('op',['create_attempt','start_transport','record_transport_result','acknowledge_attempt'])
@pytest.mark.parametrize('after',[False,True])
def test_ssh_failure_before_or_after_commit_never_resends(env,ftp,tmp_path,op,after):
    client=Client(env[0]); (client.drop_after if after else client.fail_before).add(op)
    result=send(env,selected(env),tmp_path,client)
    stores=sum(sum(isinstance(c,str) and c.startswith('STOR ') for c in f.calls) for f in ftp.instances)
    assert stores<=1
    if op in ('create_attempt','start_transport'): assert stores==0
    if op=='record_transport_result' and not after:
        assert result['durable_state']=='transport_unknown' and result['ftp_status']=='confirmed'
    if op=='acknowledge_attempt' and after: assert result['ack_status']=='completed'
    if result['durable_state']:
        delivery.inspect_attempt(Client(env[0]),'fixed-verifier',result['attempt_id'],domain='foreign',acknowledge=True)
        assert stores==sum(sum(isinstance(c,str) and c.startswith('STOR ') for c in f.calls) for f in ftp.instances)


@pytest.mark.parametrize('change',['price','aba','member','membership','excluded','agent_failed'])
def test_confirmed_transport_survives_ack_rejection(env,ftp,tmp_path,change):
    choice=selected(env,'tabelaofert',group=True)
    def mutation():
        if change=='agent_failed':
            with foreign_consistency.input_lock():
                marker=foreign_consistency.external_start();foreign_consistency.external_finish(marker,failed=True)
        else:
            with closing(store.open_foreign_offers_connection()) as conn,conn:
                if change in ('price','aba'):
                    old=conn.execute('SELECT price_value FROM foreign_offers WHERE id=11').fetchone()[0]
                    conn.execute('UPDATE foreign_offers SET price_value=177000 WHERE id=11')
                    if change=='aba':conn.execute('UPDATE foreign_offers SET price_value=? WHERE id=11',(old,))
                elif change=='member':conn.execute("UPDATE foreign_offers SET offer_title=offer_title||' changed' WHERE id=13")
                elif change=='excluded':conn.execute("UPDATE foreign_offers SET offer_title=offer_title||' changed' WHERE id=12")
                else:conn.execute('UPDATE foreign_offers SET development_id=NULL WHERE id=13')
    ftp.on_store=staticmethod(mutation)
    before=status(env);result=send(env,choice,tmp_path)
    assert result['ftp_status']=='confirmed' and result['ack_status']=='rejected',result
    item=attempts.get_attempt(result['attempt_id'],domain='foreign')
    assert item['state']=='ack_rejected'
    with sqlite3.connect(env[0]/'databases/foreign_offers.db') as conn:
        assert conn.execute("SELECT COUNT(*) FROM foreign_offer_portal_sync_events WHERE event_type='export_attempt_v2' AND payload_json LIKE '%transport_confirmed%'").fetchone()[0]==1
    assert status(env)==before or change=='agent_failed'  # external dirtying is allowed; no stale ACK
    assert len(ftp.instances)==1


def test_group_atomic_rollback_then_ack_only_retry(env,ftp,tmp_path):
    choice=selected(env,'tabelaofert',group=True);before=status(env)
    with closing(store.open_foreign_offers_connection()) as conn,conn:
        conn.execute("CREATE TRIGGER test_ack_abort BEFORE UPDATE ON foreign_offer_portal_sync WHEN NEW.foreign_offer_id=13 BEGIN SELECT RAISE(ABORT,'test second member'); END")
    result=send(env,choice,tmp_path)
    assert result['ftp_status']=='confirmed' and result['ack_status']=='failed',result
    assert status(env)==before
    with closing(store.open_foreign_offers_connection()) as conn,conn:conn.execute('DROP TRIGGER test_ack_abort')
    recovered=delivery.inspect_attempt(Client(env[0]),'fixed-verifier',result['attempt_id'],domain='foreign',acknowledge=True)
    assert recovered['ack_status']=='completed' and len(ftp.instances)==1
    rows=[r for r in status(env) if r[1]=='tabelaofert' and r[0] in (11,13)]
    assert len(rows)==2 and all(r[2]==1 and r[3]==0 and r[4]=='add' for r in rows)


def test_single_send_permission_and_overlapping_group_attempt(env):
    choice=selected(env,'tabelaofert',group=True);a=create(env,choice)
    b=create(env,selected(env,'tabelaofert'))
    with pytest.raises(RuntimeError):attempts.start_transport(a['attempt_id'],a['binding'],domain='foreign',settings=env[1])
    first=attempts.start_transport(b['attempt_id'],b['binding'],domain='foreign',settings=env[1])
    assert first['can_send'] is True
    assert attempts.start_transport(b['attempt_id'],b['binding'],domain='foreign',settings=env[1])['can_send'] is False
    with pytest.raises(RuntimeError):create(env,choice)


def test_old_completed_add_cannot_undo_new_delete(env,ftp,tmp_path):
    add=send(env,selected(env),tmp_path);old=attempts.get_attempt(add['attempt_id'],domain='foreign')
    delete=send(env,selected(env,action='delete'),tmp_path)
    assert delete['ack_status']=='completed',delete
    before=status(env)
    replay=attempts.acknowledge_attempt(old['attempt_id'],old['binding'],domain='foreign',settings=env[1])
    assert replay['already_acknowledged'] is True and status(env)==before


def test_restart_read_durable_unknown(env):
    item=create(env,selected(env));attempts.start_transport(item['attempt_id'],item['binding'],domain='foreign',settings=env[1])
    code='from InvestmentManager.integrator.export_attempts import get_attempt; print(get_attempt('+repr(item['attempt_id'])+',domain="foreign")["state"])'
    child=subprocess.run([sys.executable,'-c',code],capture_output=True,text=True,check=True)
    assert child.stdout.strip()=='transport_unknown'


@pytest.mark.parametrize('field,value',[('domain','domestic'),('protocol_version',1),('transport_profile','tabelaofert'),('members',[999]),('input_revision','0'*64),('package_id','f'*32)])
def test_wire_rejects_forged_binding(env,field,value):
    item=create(env,selected(env));binding=dict(item['binding'])
    request={'protocol_version':2,'domain':'foreign','operation':'start_transport','attempt_id':item['attempt_id'],'binding':binding}
    if field in ('domain','protocol_version'):request[field]=value
    else:binding[field]=value
    assert server.dispatch_request(request)['ok'] is False
    assert attempts.get_attempt(item['attempt_id'],domain='foreign')['state']=='prepared'


def test_ordinary_http_cannot_confirm_transport(env):
    # Transport is private CLI only; the existing package HTTP module has no such actions.
    from InvestmentManager.routes import export_packages
    import inspect
    source=inspect.getsource(export_packages)
    assert 'record_transport_result' not in source and 'acknowledge_attempt' not in source


def test_real_concurrent_start_commits_only_one_permission(env):
    from concurrent.futures import ThreadPoolExecutor
    import threading
    item=create(env,selected(env)); barrier=threading.Barrier(2)
    def start():
        barrier.wait(timeout=10)
        try:
            return attempts.start_transport(item['attempt_id'],item['binding'],domain='foreign',settings=env[1])['can_send']
        except RuntimeError: return False  # fail-closed lock contention
    with ThreadPoolExecutor(max_workers=2) as pool:
        result=list(pool.map(lambda _:start(),range(2)))
    assert sum(result)==1
    assert attempts.get_attempt(item['attempt_id'],domain='foreign')['state']=='transport_unknown'


def test_pending_attempt_blocks_physical_deletion_and_survives(env):
    item=create(env,selected(env));attempts.start_transport(item['attempt_id'],item['binding'],domain='foreign',settings=env[1])
    with closing(store.open_foreign_offers_connection()) as conn:
        with pytest.raises(sqlite3.IntegrityError),conn:
            conn.execute('DELETE FROM foreign_offers WHERE id=11')
    assert attempts.get_attempt(item['attempt_id'],domain='foreign')['state']=='transport_unknown'


def test_busy_writer_or_import_prevents_send_permission(env):
    import os
    item=create(env,selected(env))
    code='''from InvestmentManager.integrator.input_consistency import input_lock
from pathlib import Path
import time,sys
with input_lock():
 Path(sys.argv[1]).write_text('locked')
 time.sleep(3)
'''
    marker=env[0]/'child-lock'
    child=subprocess.Popen([sys.executable,'-c',code,str(marker)])
    try:
        import time
        until=time.monotonic()+10
        while not marker.exists() and child.poll() is None and time.monotonic()<until:time.sleep(.02)
        assert marker.exists()
        with pytest.raises(RuntimeError):attempts.start_transport(item['attempt_id'],item['binding'],domain='foreign',settings=env[1])
    finally:child.wait(timeout=10)
    assert attempts.get_attempt(item['attempt_id'],domain='foreign')['state']=='prepared'


@pytest.mark.parametrize('phase',['failed','started'])
def test_unresolved_agent_mutation_blocks_start(env,phase):
    item=create(env,selected(env))
    with foreign_consistency.input_lock():
        marker=foreign_consistency.external_start()
        if phase=='failed':foreign_consistency.external_finish(marker,failed=True)
    with pytest.raises(RuntimeError):attempts.start_transport(item['attempt_id'],item['binding'],domain='foreign',settings=env[1])
    assert attempts.get_attempt(item['attempt_id'],domain='foreign')['state']=='prepared'


def test_unavailable_investment_never_reaches_ftp(env,ftp,tmp_path):
    client=Client(env[0]);client.fail_before.add('verify')
    result=send(env,selected(env),tmp_path,client)
    assert result['verification']=='failed' and result['ftp_status']=='not_started' and not ftp.instances


def test_group_send_binds_exact_original_bytes(env,ftp,tmp_path):
    choice=selected(env,'tabelaofert',group=True)
    folder=env[0]/'exports/foreign'/choice['package_id']
    manifest=json.loads((folder/'manifest.json').read_bytes());body=(folder/manifest['zip_name']).read_bytes()
    result=send(env,choice,tmp_path)
    assert result['ack_status']=='completed',result
    assert result['members']==[11,13] and len(ftp.instances)==1 and ftp.instances[0].bytes==body
    item=attempts.get_attempt(result['attempt_id'],domain='foreign')
    assert item['binding']['subject']=={'kind':'cyprus_development','id':7}


def test_receiver_rejects_local_profile_or_manifest_rewrite(env,ftp,tmp_path):
    choice=selected(env,'tabelaofert');client=Client(env[0])
    folder=env[0]/'exports/foreign'/choice['package_id']
    def mutate():
        path=folder/'manifest.json';obj=json.loads(path.read_bytes());obj['transport_profile']='tabelaofert';path.write_text(json.dumps(obj))
    client.mutate=mutate
    result=send(env,choice,tmp_path,client)
    assert result['ftp_status']=='not_started' and not ftp.instances


@pytest.mark.parametrize('stage',['config','login','partial_stor'])
def test_early_and_partial_upload_failures(env,ftp,tmp_path,stage,monkeypatch):
    choice=selected(env)
    if stage=='config':
        monkeypatch.setattr(uploader,'_get_portal_config',lambda *a,**k:(_ for _ in ()).throw(RuntimeError('missing config')))
    elif stage=='login':
        monkeypatch.setattr(ftp,'login',lambda *a,**k:(_ for _ in ()).throw(OSError('login failed')))
    else:
        def partial(self,command,stream):
            self.calls.append(command);self.bytes=stream.read(16);raise EOFError('partial STOR')
        monkeypatch.setattr(ftp,'storbinary',partial)
    result=send(env,choice,tmp_path)
    assert result['durable_state']==('transport_unknown' if stage=='partial_stor' else 'transport_failed'),result
    assert result['ack_status']=='not_started'


def test_only_primary_secret_names_used_for_foreign_tabela(env,ftp,tmp_path,monkeypatch):
    keys=[];old=uploader._get_portal_config
    def config(profile,secret_getter):
        assert profile=='tabelaofert_primary'
        def get(key):keys.append(key);return secrets(key)
        return old(profile,get)
    monkeypatch.setattr(uploader,'_get_portal_config',config)
    result=send(env,selected(env,'tabelaofert'),tmp_path)
    assert result['ack_status']=='completed',result
    assert keys and all(key.startswith('FTP_TABELAOFERT_PRIMARY_') for key in keys)


def test_newer_external_publication_cannot_be_overwritten(env):
    item=create(env,selected(env));binding=item['binding']
    attempts.start_transport(item['attempt_id'],binding,domain='foreign',settings=env[1])
    attempts.record_transport_result(item['attempt_id'],binding,'confirmed',domain='foreign')
    with closing(store.open_foreign_offers_connection()) as conn,conn:
        conn.execute("UPDATE foreign_offer_portal_sync SET is_published=0,last_action='delete' WHERE foreign_offer_id=11 AND portal_key='domiporta'")
        store._insert_portal_event(conn,11,'domiporta','deleted',{'mode':'delete'})
    before=status(env)
    result=attempts.acknowledge_attempt(item['attempt_id'],binding,domain='foreign',settings=env[1])
    assert result['state']=='ack_rejected' and status(env)==before


def test_ack_preserves_other_portal_dirty_state(env,ftp,tmp_path):
    with closing(store.open_foreign_offers_connection()) as conn,conn:
        conn.execute("UPDATE foreign_offer_portal_sync SET needs_update=1 WHERE foreign_offer_id=11 AND portal_key='tabelaofert'")
    result=send(env,selected(env),tmp_path)
    assert result['ack_status']=='completed',result
    with sqlite3.connect(env[0]/'databases/foreign_offers.db') as conn:
        assert conn.execute('SELECT needs_update FROM foreign_offers WHERE id=11').fetchone()[0]==1
        assert conn.execute("SELECT needs_update FROM foreign_offer_portal_sync WHERE foreign_offer_id=11 AND portal_key='tabelaofert'").fetchone()[0]==1


def test_real_cli_restart_and_domain_isolation(env):
    item=create(env,selected(env))
    request={'protocol_version':2,'domain':'foreign','operation':'get_attempt','attempt_id':item['attempt_id']}
    child=subprocess.run([sys.executable,'-B','-m','InvestmentManager.export_handoff'],
        input=json.dumps(request),capture_output=True,text=True,timeout=30)
    assert child.returncode==0,child.stderr
    reply=json.loads(child.stdout)
    assert set(reply)=={'protocol_version','domain','operation','ok','attempt'}
    assert reply['attempt']['binding']==item['binding']
    assert set(reply['attempt'])=={'attempt_id','binding','state'}
    assert server.dispatch_request({'operation':'get_attempt','attempt_id':item['attempt_id']})['ok'] is False


def test_trusted_ssh_identity_is_not_ftp_attestation(env,ftp):
    # Explicit threat-model evidence: an OS publisher can claim confirmed.
    # The browser has no corresponding HTTP operation or form field.
    item=create(env,selected(env));common={'protocol_version':2,'domain':'foreign',
        'attempt_id':item['attempt_id'],'binding':item['binding']}
    assert server.dispatch_request(common|{'operation':'start_transport'})['attempt']['can_send'] is True
    assert server.dispatch_request(common|{'operation':'record_transport_result','outcome':'confirmed'})['ok'] is True
    assert server.dispatch_request(common|{'operation':'acknowledge_attempt'})['attempt']['state']=='ack_completed'
    assert not ftp.instances


def test_two_parallel_foreign_deliveries_only_one_ftp(env,ftp,tmp_path):
    from concurrent.futures import ThreadPoolExecutor
    import threading
    choice=selected(env,'tabelaofert',group=True)
    ftp.entered=threading.Event();ftp.release=threading.Event()
    with ThreadPoolExecutor(max_workers=2) as pool:
        first=pool.submit(send,env,choice,tmp_path)
        try:
            assert ftp.entered.wait(20)
            second=pool.submit(send,env,choice,tmp_path).result(timeout=30)
            assert second['ftp_attempted'] is False
        finally:ftp.release.set()
        assert first.result(timeout=30)['ack_status']=='completed'
    assert len(ftp.instances)==1


def test_ftp_confirmed_without_ssh_result_or_lookup_requires_reconciliation(env,ftp,tmp_path):
    choice=selected(env);client=Client(env[0]);client.fail_before.update({'record_transport_result','get_attempt'})
    result=send(env,choice,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(env[0]),'fixed-verifier',result['attempt_id'],domain='foreign',acknowledge=True)
    assert recovered['durable_state']=='transport_unknown' and len(ftp.instances)==1
