"""Real synthetic artifacts, no SSH/FTP or production data."""
from contextlib import closing
import io
import json
import os
import sqlite3
import subprocess
import sys
import threading
from pathlib import Path
from types import SimpleNamespace

import pytest

from tests.investmentmanager.test_domestic_packages import data_root, isolated, sql
from tests.investmentmanager.test_domestic_listing_performance import seed
from InvestmentManager import export_handoff as rpc
from InvestmentManager.integrator import domestic_packages as prep
from InvestmentManager.integrator import domestic_package_catalog as catalog
from InvestmentManager.integrator import domestic_storage as storage
from InvestmentManager.integrator import domestic_sets as sets
from InvestmentManager.integrator import export_attempts as attempts
from InvestmentManager.integrator import input_consistency as inputs
from InvestmentManager.integrator import export_performance as perf
from InvestmentManager.integrator import sync_tasks as queue


@pytest.fixture
def artifact(data_root):
    (data_root/'databases/foreign_offers.db').unlink()
    result = prep.prepare_package(17,'no','add')
    base = data_root/'exports/domestic'
    for identifier in range(1,4):seed(base,identifier)
    return result['package_id'],base


def selection(artifact):
    return dict(package_id=artifact[0],offer_id=17,portal='no',action='add')


def prepared(artifact):
    return attempts.create_attempt(**selection(artifact))


@pytest.mark.parametrize('operation,scans', [('verify',2),('confirm',2),('create',3),('start',2),('ack',2)])
def test_bounded_scans_keep_both_zip_and_input_checks(artifact,operation,scans):
    item = prepared(artifact) if operation in {'start','ack'} else None
    if operation == 'ack':
        attempts.start_transport(item['attempt_id'],item['binding'])
        attempts.record_transport_result(item['attempt_id'],item['binding'],'confirmed')
    with perf.capture() as record:
        if operation == 'verify':assert catalog.verify_package(artifact[0])['state']=='READY'
        elif operation == 'confirm':assert rpc.confirm_package(selection(artifact)|{'storage_layout':storage.LAYOUT})['state']=='READY'
        elif operation == 'create':prepared(artifact)
        elif operation == 'start':assert attempts.start_transport(item['attempt_id'],item['binding'])['can_send']
        else:assert attempts.acknowledge_attempt(item['attempt_id'],item['binding'])['state']=='ack_completed'
    assert record['counts']['storage_scans']==scans
    assert record['stages']['zip_integrity']['calls']==2
    assert record['stages']['input_state']['calls']==2
    assert record['stages']['input_lock.held']['calls']==1
    assert record['stages']['dictionary_lock.held']['calls']==1
    assert record['stages']['input_file_read']['calls']>=4
    assert record['stages']['business_validation']['calls']==1
    if operation in {'create','start','ack'}:
        assert record['stages']['sqlite_transaction']['calls']==1
    assert storage._lookup.get() is None


def test_index_requires_lock_and_is_not_retained(artifact):
    pid,base=artifact
    with pytest.raises(inputs.ConsistencyError):
        with storage.lookup_scope(base):pass
    assert catalog.verify_package(pid)['state']=='READY'
    (base/'99/add/no'/pid).mkdir(parents=True)
    assert catalog.verify_package(pid)['state']=='INVALID'
    assert storage._lookup.get() is None


@pytest.mark.parametrize('view',[queue.list_tasks,queue.list_offers])
def test_queue_reuses_locations_without_changing_classification(artifact,data_root,view):
    with closing(sqlite3.connect(data_root/'databases/IDB.db')) as conn, conn:
        row=list(conn.execute('SELECT * FROM EstateData WHERE ID=17').fetchone())
        location=list(conn.execute('SELECT * FROM Localization WHERE ID=17').fetchone())
        for identifier in range(1,4):
            row[0]=str(identifier);location[0]=str(identifier)
            conn.execute('INSERT INTO EstateData VALUES ('+','.join('?' for _ in row)+')',row)
            conn.execute('INSERT INTO Localization VALUES ('+','.join('?' for _ in location)+')',location)
    with perf.capture() as record:
        response=view(limit=20)
    assert response['ok'] and response['counts']['new']==16
    assert record['counts']['storage_scans']==2
    assert record['stages']['input_lock.held']['calls']==1
    assert 'zip_integrity' not in record['stages']  # domestic listing is metadata only
    assert storage._lookup.get() is None


@pytest.mark.parametrize('operation',['confirm','create','start','ack'])
def test_duplicate_introduced_after_first_scan_cannot_authorize(artifact,monkeypatch,operation):
    pid,base=artifact
    item=prepared(artifact) if operation in {'start','ack'} else None
    if operation=='ack':
        attempts.start_transport(item['attempt_id'],item['binding'])
        attempts.record_transport_result(item['attempt_id'],item['binding'],'confirmed')
    original=prep._state;changed=[]
    def mutate(*args,**kwargs):
        result=original(*args,**kwargs)
        if not changed:
            (base/'99/add/no'/pid).mkdir(parents=True)
            changed.append(True)
        return result
    monkeypatch.setattr(prep,'_state',mutate)
    if operation=='confirm':assert rpc.confirm_package(selection(artifact)|{'storage_layout':storage.LAYOUT})['state']=='BLOCKED'
    elif operation=='ack':assert attempts.acknowledge_attempt(item['attempt_id'],item['binding'])['state']=='ack_rejected'
    else:
        with pytest.raises(inputs.ConsistencyError):
            prepared(artifact) if operation=='create' else attempts.start_transport(item['attempt_id'],item['binding'])
    assert storage._lookup.get() is None
    if operation=='start':assert attempts.get_attempt(item['attempt_id'])['state']=='prepared'


@pytest.mark.parametrize('change',['source','zip','symlink'])
def test_fresh_checks_survive_location_reuse(artifact,data_root,monkeypatch,change):
    pid,base=artifact;folder=storage.folder(base,pid)
    _,manifest,_=catalog._metadata(base,pid)
    original=prep._state;changed=[];original_link=catalog._link
    def mutate(*args,**kwargs):
        result=original(*args,**kwargs)
        if not changed:
            changed.append(True)
            if change=='source':sql(data_root,"UPDATE EstateData SET Cena='123'")
            elif change=='zip':
                path=folder/manifest['zip_name'];body=bytearray(path.read_bytes());body[len(body)//2]^=1;path.write_bytes(body)
            else:monkeypatch.setattr(catalog,'_link',lambda path:path==folder/'manifest.json' or original_link(path))
        return result
    monkeypatch.setattr(prep,'_state',mutate)
    result=catalog.verify_package(pid)
    assert result['state'] in {'BLOCKED','INVALID'} and not result['transport_eligible']
    assert storage._lookup.get() is None


@pytest.mark.parametrize('phase',['start','ack'])
def test_concurrent_attempts_remain_single_use(artifact,phase):
    item=prepared(artifact)
    if phase=='ack':
        attempts.start_transport(item['attempt_id'],item['binding'])
        attempts.record_transport_result(item['attempt_id'],item['binding'],'confirmed')
    barrier=threading.Barrier(2);results=[];errors=[]
    def run():
        try:
            barrier.wait(5)
            function=attempts.start_transport if phase=='start' else attempts.acknowledge_attempt
            results.append(function(item['attempt_id'],item['binding']))
        except BaseException as exc:errors.append(exc)
    threads=[threading.Thread(target=run) for _ in range(2)]
    for thread in threads:thread.start()
    for thread in threads:thread.join(10)
    assert not errors and len(results)==2 and all(not thread.is_alive() for thread in threads)
    if phase=='start':assert sorted(r['can_send'] for r in results)==[False,True]
    else:
        assert all(r['state']=='ack_completed' for r in results)
        assert sum(r.get('already_acknowledged',False) for r in results)==1


def test_listing_and_verification_preserve_serialized_snapshot(artifact,monkeypatch):
    entered,release,reader_started,done=map(lambda _:threading.Event(),range(4))
    original=prep._state;calls=[];errors=[];records=[]
    def state(*a,**kw):
        if not calls:
            calls.append(True);entered.set();assert release.wait(5)
        return original(*a,**kw)
    monkeypatch.setattr(prep,'_state',state)
    def verify():
        try:assert catalog.verify_package(artifact[0])['state']=='READY'
        except BaseException as exc:errors.append(exc)
    def read():
        try:
            reader_started.set()
            with perf.capture() as record:
                assert sets.list_sets()['total']==3
            records.append(record)
        except BaseException as exc:errors.append(exc)
        finally:done.set()
    first=threading.Thread(target=verify);first.start();assert entered.wait(5)
    second=threading.Thread(target=read);second.start();assert reader_started.wait(5)
    assert not done.wait(.05)
    release.set();first.join(10);second.join(10)
    assert not errors and not first.is_alive() and not second.is_alive()
    assert records[0]['stages']['dictionary_lock.wait']['seconds']>=.04


def test_process_exit_releases_lock_and_drops_lookup(artifact,data_root):
    env=os.environ.copy();env['DATA_DIR']=str(data_root);env['PYTHONUTF8']='1'
    code=f'''from pathlib import Path
import os
from InvestmentManager.integrator.input_consistency import input_lock
from InvestmentManager.integrator.domestic_storage import lookup_scope
with input_lock(), lookup_scope(Path({str(artifact[1])!r})):
 os._exit(0)
'''
    result=subprocess.run([sys.executable,'-B','-c',code],env=env,cwd=Path(__file__).resolve().parents[2],capture_output=True,timeout=15)
    assert result.returncode==0
    assert catalog.verify_package(artifact[0])['state']=='READY'


def test_exception_resets_scope_and_no_verification_is_cached(artifact,monkeypatch):
    original=prep._state
    def fail(*a,**kw):raise RuntimeError('PRIVATE_INTERNAL_PATH')
    monkeypatch.setattr(prep,'_state',fail)
    result=catalog.verify_package(artifact[0]);assert result['state']=='BLOCKED'
    assert 'PRIVATE_INTERNAL_PATH' not in json.dumps(result) and storage._lookup.get() is None
    monkeypatch.setattr(prep,'_state',original)
    assert catalog.verify_package(artifact[0])['state']=='READY'


def test_cli_diagnostics_are_opt_in_and_do_not_change_stdout(monkeypatch):
    import dotenv
    monkeypatch.setattr(dotenv,'load_dotenv',lambda *a,**kw:False)
    monkeypatch.setattr(rpc,'dispatch_request',lambda request:{'ok':True})
    for enabled in (False,True):
        monkeypatch.setenv('INVESTMENT_EXPORT_DIAGNOSTICS','1' if enabled else '0')
        stdout,stderr=io.StringIO(),io.StringIO()
        monkeypatch.setattr(sys,'stdin',SimpleNamespace(buffer=io.BytesIO(b'{"private":"DO_NOT_LOG"}')))
        monkeypatch.setattr(sys,'stdout',stdout);monkeypatch.setattr(sys,'stderr',stderr)
        assert rpc.main()==0 and json.loads(stdout.getvalue())=={'ok':True}
        assert bool(stderr.getvalue())==enabled and 'DO_NOT_LOG' not in stderr.getvalue()
        if enabled:assert json.loads(stderr.getvalue())['export_performance']['total_seconds']>=0


def test_timing_errors_and_exceptions_do_not_change_business_result(monkeypatch):
    with perf.capture() as record:
        with pytest.raises(ValueError,match='business'):
            with perf.stage('test_failure'):raise ValueError('business')
    assert record['stages']['test_failure']['incomplete']==1
    def fail():raise RuntimeError('clock failure')
    monkeypatch.setattr(perf,'perf_counter',fail)
    with perf.capture() as record:
        with perf.stage('test'):result='unchanged'
    assert result=='unchanged' and record['timing_error']


def test_busy_file_lock_is_measured_without_lookup_or_waiting(artifact):
    errors=[];records=[]
    def read():
        with perf.capture() as record:
            try:catalog.verify_package(artifact[0])
            except inputs.ConsistencyError:errors.append(True)
        records.append(record)
    with inputs.input_lock():
        thread=threading.Thread(target=read);thread.start();thread.join(5)
        assert not thread.is_alive()
    assert errors==[True] and not records[0]['counts']
    assert records[0]['stages']['input_lock.wait']['incomplete']==1
    assert 'input_lock.held' not in records[0]['stages']


def test_dictionary_refresh_and_locked_check_are_separate_ownership(artifact,monkeypatch):
    from InvestmentManager.integrator import domestic_dictionaries
    package=prep.prepare_package(17,'domiporta','add')
    def forbidden(*a,**kw):raise AssertionError('Instrumentation must not fetch dictionaries')
    monkeypatch.setattr(domestic_dictionaries,'_download',forbidden)
    with perf.capture() as record:
        result=rpc.confirm_package(dict(package_id=package['package_id'],offer_id=17,
            portal='domiporta',action='add',storage_layout=storage.LAYOUT))
    assert result['state']=='READY'
    assert record['stages']['dictionary_lock.held']['calls']==2
    assert record['stages']['input_lock.held']['calls']==1
    assert record['stages']['dictionary_lock.held']['seconds']<=record['total_seconds']
