"""2B.3: local delivery lifecycle with real generators/catalog/SQLite and a fake network only."""
from contextlib import closing
import hashlib
import json
import sqlite3
import threading
import uuid

import pytest

from tests.investmentmanager.test_domestic_packages import data_root, isolated, sql, manifest
from tests.investmentmanager.test_foreign_packages_v2 import foreign_root as make_foreign_root
from InvestmentManager.integrator import domestic_packages as prep
from InvestmentManager.integrator import export_attempts as attempts
from InvestmentManager.integrator import export_start
from InvestmentManager.integrator import export_control as control
from InvestmentManager.integrator import export_jobs as jobs
from InvestmentManager.integrator import package_delivery as pd
from InvestmentManager.integrator import portal_transport as transport
from InvestmentManager.integrator.input_consistency import input_lock

ACTOR = 'user:7'


class FakeTransport:
    """Records every upload; never touches a network."""

    def __init__(self, outcome='confirmed', error_code=None, raises=None, on_upload=None):
        self.calls, self.outcome, self.error_code, self.raises, self.on_upload = [], outcome, error_code, raises, on_upload

    def upload_portal_zip(self, profile, name, body, *, secret_getter):
        self.calls.append({'profile': profile, 'name': name, 'sha': hashlib.sha256(body).hexdigest(), 'size': len(body)})
        if self.on_upload:
            self.on_upload()
        if self.raises:
            raise self.raises
        return transport.UploadResult(self.outcome, 'done' if self.outcome == 'confirmed' else 'stor', bytes_sent=len(body),
                                      bytes_complete=self.outcome == 'confirmed', stor_reply_code=226 if self.outcome == 'confirmed' else None,
                                      timings={'stor': {'seconds': 0.01, 'complete': self.outcome == 'confirmed'}},
                                      error_code=self.error_code)


def policy(**overrides):
    base = {key: dict(value) for key, value in pd.RETRY_POLICY.items()}
    for key, value in overrides.items():
        base[key].update(value)
    return base


def make_env(fake=None, *, hooks=None, sleep=None, secret=lambda key: 'synthetic', **kwargs):
    return pd.Env(secret_getter=secret, transport=fake or FakeTransport(), settings=pd._environment_settings,
                  sleep=sleep or (lambda seconds: None), hooks=hooks or {}, **kwargs)


@pytest.fixture
def world(data_root):
    assert jobs.init_schema(backup=False) == 'created'
    control.set_dispatch(True, changed_by='test')
    return data_root


def new_job(portal='no', action='add', mode='ensure_current', package=None, subject=17):
    package_spec = {'mode': mode} | ({'package_id': package} if mode == 'existing' else {})
    jobs.create_delivery({'domain': 'domestic', 'subject': {'kind': 'offer', 'id': subject}, 'portal': portal,
                          'action': action, 'package': package_spec},
                         actor=ACTOR, idempotency_key=uuid.uuid4().hex, dispatch_enabled=True)
    claim = jobs.claim_next('delivery')
    assert claim is not None
    return claim


def view(claim):
    return jobs.get_job(claim.job_id)


def attempt_state(claim_or_id, domain='domestic'):
    attempt_id = claim_or_id if isinstance(claim_or_id, str) else view(claim_or_id)['attempt_id']
    return attempts.inspect_attempt(attempt_id, domain=domain)['attempt']['state']


def publication(root):
    with closing(sqlite3.connect(root / 'databases/IDB.db')) as conn:
        try:
            return conn.execute('SELECT offer_id,portal_key,is_published,needs_update,last_action FROM offer_portal_sync ORDER BY 1,2').fetchall()
        except sqlite3.OperationalError:
            return []


def zip_bytes(root, package_id):
    from InvestmentManager.integrator.domestic_package_catalog import package_folder
    folder = package_folder(root / 'exports/domestic', package_id)
    item = json.loads((folder / 'manifest.json').read_text(encoding='utf8'))
    return folder / item['zip_name'], item


def run(claim, fake=None, **kwargs):
    fake = fake or FakeTransport()
    return pd.execute_delivery(claim, make_env(fake, **kwargs)), fake


# ----------------------------------------------------------------- success
def test_full_delivery_uploads_the_exact_package_bytes_once_and_acknowledges(world):
    claim = new_job()
    outcome, fake = run(claim)
    assert (outcome.job_state, outcome.reason, outcome.attempt_state, outcome.ack_status) == ('completed', 'ack_completed', 'ack_completed', 'completed')
    assert len(fake.calls) == 1 and outcome.uploader_calls == 1 and fake.calls[0]['profile'] == 'no'
    final = view(claim)
    path, item = zip_bytes(world, final['package_id'])
    assert fake.calls[0]['sha'] == hashlib.sha256(path.read_bytes()).hexdigest() == item['zip_sha256']
    assert fake.calls[0]['name'] == item['zip_name']
    assert final['state'] == 'completed' and final['phase'] == 'finished' and final['reason_code'] == 'ack_completed'
    assert publication(world) == [(17, 'no', 1, 0, 'add')]
    events = [e['event_type'] for e in jobs.list_events(claim.job_id)['items']]
    assert events[0] == 'accepted' and 'attempt_linked' in events and events[-1] == 'completed'
    assert {'qualification', 'preparation', 'snapshot', 'create', 'start', 'record', 'ack', 'ftp_stor'} <= set(final['metrics'])
    assert jobs.verify_integrity() == []


@pytest.mark.parametrize('portal', ['no', 'domiporta', 'tabelaofert', 'gruntguru'])
def test_each_domestic_profile_is_used(world, portal):
    claim = new_job(portal)
    outcome, fake = run(claim)
    assert outcome.job_state == 'completed' and fake.calls[0]['profile'] == portal


def test_existing_package_mode_uses_exactly_that_package(world):
    package = prep.prepare_package(17, 'no', 'add')['package_id']
    claim = new_job(mode='existing', package=package)
    outcome, fake = run(claim)
    assert outcome.job_state == 'completed' and view(claim)['package_id'] == package


def test_the_legacy_start_primitive_is_never_used(world, monkeypatch):
    monkeypatch.setattr(attempts, 'start_transport', lambda *a, **k: pytest.fail('legacy START used by the new delivery'))
    outcome, _ = run(new_job())
    assert outcome.job_state == 'completed'


# --------------------------------------------------------- upload outcomes
def test_unknown_upload_is_never_repeated_and_needs_review(world):
    claim = new_job()
    outcome, fake = run(claim, FakeTransport('unknown', 'stor_failed'))
    assert (outcome.job_state, outcome.reason, outcome.ftp_status) == ('needs_review', 'transport_unknown', 'unknown')
    assert len(fake.calls) == 1 and attempt_state(claim) == 'transport_unknown' and publication(world) == []
    with pytest.raises(jobs.ActiveJobConflict):          # the unit stays reserved until D09
        new_job()
    with pytest.raises(attempts.AttemptError):
        attempts.create_attempt(view(claim)['package_id'], 17, 'no', 'add')


def test_a_raising_transport_is_treated_as_unknown(world):
    claim = new_job()
    outcome, fake = run(claim, FakeTransport(raises=RuntimeError('boom')))
    assert outcome.reason == 'transport_unknown' and attempt_state(claim) == 'transport_unknown'


def test_certain_failure_before_stor_is_recorded_and_allows_a_conscious_retry(world):
    claim = new_job()
    outcome, fake = run(claim, FakeTransport('not_sent', 'connect_failed'))
    assert (outcome.job_state, outcome.reason, outcome.ftp_status) == ('failed', 'transport_failed', 'failed_before_send')
    assert attempt_state(claim) == 'transport_failed' and view(claim)['state'] == 'failed'
    package = view(claim)['package_id']
    retry = new_job(mode='existing', package=package)                       # new intent, new key
    outcome, fake = run(retry)
    assert outcome.job_state == 'completed' and len(fake.calls) == 1


# ------------------------------------------------------------ refusals
def test_missing_configuration_blocks_before_any_preparation(world):
    claim = new_job()
    outcome, fake = run(claim, secret=lambda key: None)
    assert (outcome.job_state, outcome.reason) == ('blocked', 'config_missing') and fake.calls == []
    assert view(claim)['package_id'] is None and view(claim)['attempt_id'] is None
    assert 'FTP_NO_HOST' in jobs.list_events(claim.job_id)['items'][-1]['details']['missing']


def test_not_needed_operation_completes_without_creating_anything(world):
    from InvestmentManager.integrator.portal_sync_state import _ensure_sync_tables
    with closing(sqlite3.connect(world / 'databases/IDB.db')) as conn, conn:
        _ensure_sync_tables(conn)
    sql(world, "INSERT INTO offer_portal_sync(offer_id,portal_key,is_published,needs_update,updated_at) VALUES (17,'no',1,0,'t')")
    claim = new_job()
    outcome, fake = run(claim)
    assert (outcome.job_state, outcome.reason) == ('completed', 'no_action') and fake.calls == []
    assert view(claim)['attempt_id'] is None


def test_changed_action_is_blocked(world):
    claim = new_job(action='delete')
    outcome, fake = run(claim)
    assert (outcome.job_state, outcome.reason) == ('blocked', 'qualification_changed') and fake.calls == []


def test_pause_requeues_without_losing_the_attempt_and_resume_continues_it(world):
    claim = new_job()
    control.set_dispatch(False, changed_by='test')
    outcome, fake = run(claim)
    assert (outcome.job_state, outcome.reason) == ('queued', 'dispatch_paused') and fake.calls == []
    state = view(claim)
    assert (state['state'], state['phase']) == ('queued', 'paused') and attempt_state(claim) == 'prepared'
    control.set_dispatch(True, changed_by='test')
    again = jobs.claim_next('delivery')
    assert again.job_id == claim.job_id and again.attempt_id == state['attempt_id']
    outcome, fake = run(again)
    assert outcome.job_state == 'completed' and len(fake.calls) == 1 and view(claim)['attempt_id'] == state['attempt_id']


def test_package_identity_is_fixed_once_saved(world):
    claim = new_job()
    control.set_dispatch(False, changed_by='test')
    run(claim)
    saved = view(claim)['package_id']
    control.set_dispatch(True, changed_by='test')
    again = jobs.claim_next('delivery')
    assert again.package_id == saved and again.binding_sha256


def test_package_replaced_after_save_blocks_the_job(world, monkeypatch):
    claim = new_job()
    control.set_dispatch(False, changed_by='test')
    run(claim)
    control.set_dispatch(True, changed_by='test')
    again = jobs.claim_next('delivery')
    real = pd.freeze_package

    def other_binding(*args, **kwargs):
        import dataclasses
        return dataclasses.replace(real(*args, **kwargs), binding_sha256='0' * 64)
    monkeypatch.setattr(pd, 'freeze_package', other_binding)
    outcome = pd.execute_delivery(again, make_env())
    assert (outcome.job_state, outcome.reason) == ('blocked', 'package_changed') and attempt_state(claim) == 'prepared'

# ------------------------------------------------------- frozen bytes
def test_file_changed_before_start_is_refused_and_nothing_is_sent(world):
    claim = new_job()

    def tamper():
        package = jobs.get_job(claim.job_id)['package_id']
        path, _ = zip_bytes(world, package)
        path.write_bytes(path.read_bytes() + b'x')
    outcome, fake = run(claim, hooks={'after_create': tamper})
    assert outcome.job_state == 'blocked' and fake.calls == [] and attempt_state(claim) == 'prepared'


def test_file_changed_after_start_still_uploads_the_frozen_bytes_and_ack_refuses(world):
    claim = new_job()
    original = {}

    def tamper():
        package = jobs.get_job(claim.job_id)['package_id']
        path, item = zip_bytes(world, package)
        original['sha'] = item['zip_sha256']
        path.write_bytes(path.read_bytes() + b'x')
    outcome, fake = run(claim, hooks={'after_start': tamper})
    assert len(fake.calls) == 1 and fake.calls[0]['sha'] == original['sha']          # snapshot bytes, not the swapped file
    assert outcome.job_state == 'needs_review' and outcome.reason == 'ack_rejected'
    assert attempt_state(claim) == 'ack_rejected' and publication(world) == []


# ---------------------------------------------- W1: retries around the writes
class LockHolder:
    """Holds the input lock in another thread until `release_after` sleeps (or forever)."""

    def __init__(self, release_after=None):
        self.release_after, self.sleeps, self.thread = release_after, 0, None
        self.held, self.release = threading.Event(), threading.Event()

    def acquire(self):
        def body():
            with input_lock():
                self.held.set()
                self.release.wait(60)
        self.thread = threading.Thread(target=body)
        self.thread.start()
        assert self.held.wait(20)

    def sleep(self, seconds):
        self.sleeps += 1
        if self.release_after is not None and self.sleeps >= self.release_after:
            self.stop()

    def stop(self):
        self.release.set()
        if self.thread:
            self.thread.join(20)


def test_crm_write_during_the_end_of_stor_is_survived_by_bounded_retries(world):
    holder = LockHolder(release_after=3)
    claim = new_job()
    outcome, fake = run(claim, hooks={'after_upload': holder.acquire}, sleep=holder.sleep)
    holder.stop()
    assert outcome.job_state == 'completed' and outcome.reason == 'ack_completed'
    assert holder.sleeps >= 3 and len(fake.calls) == 1
    assert attempt_state(claim) == 'ack_completed'


def test_exhausted_result_retries_leave_unknown_and_record_an_observation_only(world):
    holder = LockHolder()
    claim = new_job()
    small = policy(record={'attempts': 3, 'total': 100.0})
    outcome, fake = run(claim, hooks={'after_upload': holder.acquire}, sleep=lambda s: None, policy=small)
    holder.stop()
    assert outcome.job_state == 'needs_review' and outcome.reason == 'result_unsaved' and len(fake.calls) == 1
    assert attempt_state(claim) == 'transport_unknown'                      # never promoted to confirmed
    assert publication(world) == []                                          # and never acknowledged
    last = [e for e in jobs.list_events(claim.job_id)['items'] if e['event_type'] == 'result_unsaved']
    assert last and last[0]['details'] == {'observed': 'confirmed', 'observation_only': True}
    assert view(claim)['state'] == 'needs_review'


def test_exhausted_ack_retries_leave_confirmed_and_ack_only_finishes_it(world):
    holder = LockHolder()
    claim = new_job()
    small = policy(ack={'attempts': 3, 'total': 100.0})
    outcome, fake = run(claim, hooks={'after_record': holder.acquire}, policy=small)
    holder.stop()
    assert (outcome.job_state, outcome.reason, outcome.ack_status) == ('needs_review', 'ack_pending', 'pending')
    assert attempt_state(claim) == 'transport_confirmed' and publication(world) == [] and len(fake.calls) == 1
    # ACK-only recovery: no preparation, no CREATE, no START, no FTP
    record = view(claim)
    receipt = jobs.create_ack_recovery({'domain': 'domestic', 'attempt_id': record['attempt_id'], 'subject_kind': 'offer',
                                        'subject_id': 17, 'portal': 'no', 'action': 'add', 'package_id': record['package_id'],
                                        'binding_sha256': jobs.claim_next.__globals__['binding_digest'](
                                            attempts.inspect_attempt(record['attempt_id'])['attempt']['binding']),
                                        'attempt_anchor_id': 17}, actor=ACTOR, idempotency_key=uuid.uuid4().hex,
                                       parent_job_id=claim.job_id)
    ack_claim = jobs.claim_next('ack_only')
    assert ack_claim.job_id == receipt.job_id
    second = FakeTransport()
    result = pd.execute_ack_only(ack_claim, make_env(second))
    assert result.job_state == 'completed' and second.calls == [] and attempt_state(claim) == 'ack_completed'
    assert view(claim)['state'] == 'completed' and view(claim)['reason_code'] == 'recovered_by_ack_only'
    assert publication(world) == [(17, 'no', 1, 0, 'add')]


def test_record_commit_then_exception_adopts_the_durable_state_without_a_second_write(world, monkeypatch):
    real, calls = attempts.record_transport_result, []

    def flaky(*args, **kwargs):
        calls.append(1)
        item = real(*args, **kwargs)
        raise OSError('commit succeeded, reply lost')
    monkeypatch.setattr(attempts, 'record_transport_result', flaky)
    claim = new_job()
    outcome, fake = run(claim)
    assert outcome.job_state == 'completed' and calls == [1] and len(fake.calls) == 1


def test_record_exception_before_commit_is_retried_after_reading_unknown(world, monkeypatch):
    real, calls = attempts.record_transport_result, []

    def flaky(*args, **kwargs):
        calls.append(1)
        if len(calls) == 1:
            raise sqlite3.DatabaseError('disk I/O error before commit')
        return real(*args, **kwargs)
    monkeypatch.setattr(attempts, 'record_transport_result', flaky)
    claim = new_job()
    outcome, fake = run(claim)
    assert outcome.job_state == 'completed' and calls == [1, 1] and len(fake.calls) == 1


def test_start_commit_then_exception_is_unknown_review_and_never_uploads(world, monkeypatch):
    real = export_start.start_qualified_transport

    def flaky(*args, **kwargs):
        real(*args, **kwargs)
        raise OSError('START committed, reply lost')
    monkeypatch.setattr(export_start, 'start_qualified_transport', flaky)
    claim = new_job()
    outcome, fake = run(claim)
    assert (outcome.job_state, outcome.reason) == ('needs_review', 'start_uncertain') and fake.calls == []
    assert attempt_state(claim) == 'transport_unknown'


def test_start_exception_before_commit_is_retried_and_then_sends_once(world, monkeypatch):
    real, calls = export_start.start_qualified_transport, []

    def flaky(*args, **kwargs):
        calls.append(1)
        if len(calls) == 1:
            raise sqlite3.DatabaseError('write failed before commit')
        return real(*args, **kwargs)
    monkeypatch.setattr(export_start, 'start_qualified_transport', flaky)
    claim = new_job()
    outcome, fake = run(claim)
    assert outcome.job_state == 'completed' and calls == [1, 1] and len(fake.calls) == 1


def test_busy_input_lock_exhausting_start_retries_requeues_without_unknown(world):
    holder = LockHolder()
    claim = new_job()
    small = policy(start={'attempts': 3, 'total': 100.0})
    outcome, fake = run(claim, hooks={'after_create': holder.acquire}, policy=small)
    holder.stop()
    assert (outcome.job_state, outcome.reason) == ('queued', 'lock_busy') and fake.calls == []
    assert attempt_state(claim) == 'prepared' and view(claim)['phase'] == 'waiting_resource'


def test_create_reply_lost_adopts_the_committed_attempt(world, monkeypatch):
    real = attempts.create_attempt

    def flaky(*args, **kwargs):
        real(*args, **kwargs)
        raise OSError('CREATE committed, reply lost')
    monkeypatch.setattr(attempts, 'create_attempt', flaky)
    claim = new_job()
    outcome, fake = run(claim)
    assert outcome.job_state == 'completed' and len(fake.calls) == 1


def test_lost_job_fence_stops_the_executor_before_any_upload(world):
    claim = new_job()

    def lose():
        # another owner takes over while START is about to be requested
        current = jobs.orphans()[0]
        jobs.adopt(current)
    outcome = None
    with pytest.raises(jobs.ClaimLost):
        pd.execute_delivery(claim, make_env(hooks={'before_start': lose}))
    assert attempt_state(claim) == 'prepared'


def test_busy_classification_walks_the_cause_chain():
    from InvestmentManager.integrator.input_consistency import LockBusy, ConsistencyError
    try:
        try:
            raise LockBusy('x')
        except LockBusy as inner:
            raise attempts.AttemptError('wrapped') from inner
    except attempts.AttemptError as exc:
        assert pd.is_busy(exc)
    assert not pd.is_busy(attempts.AttemptError('refusal')) and not pd.is_busy(ConsistencyError('plain'))
    assert pd.is_busy(sqlite3.OperationalError('database is locked')) and not pd.is_busy(sqlite3.OperationalError('no such table'))
    assert pd.is_busy(jobs.StorageBusy('storage_busy'))


def test_retry_helper_stops_at_attempt_limit_and_never_retries_refusals():
    from InvestmentManager.integrator.input_consistency import LockBusy
    sleeps, calls = [], []
    env = make_env(sleep=sleeps.append, policy=policy(start={'attempts': 4, 'total': 1000.0}), rng=lambda: 0.5)

    def busy():
        calls.append(1)
        raise LockBusy('busy')
    with pytest.raises(LockBusy):
        pd.retry_busy(env, 'start', busy)
    assert len(calls) == 4 and sleeps == [0.25, 0.5, 1.0]
    refusals = []
    with pytest.raises(attempts.AttemptError):
        pd.retry_busy(env, 'start', lambda: refusals.append(1) or (_ for _ in ()).throw(attempts.AttemptError('no')))
    assert refusals == [1]


# ---------------------------------------------------------------- ACK-only
def ack_job(world, mutate=None):
    claim = new_job()
    outcome, fake = run(claim, FakeTransport('unknown'))
    record = view(claim)
    item = attempts.inspect_attempt(record['attempt_id'])['attempt']
    if mutate:
        mutate(item)
    return claim, record, item


def ack_claim(record, item, **overrides):
    target = {'domain': 'domestic', 'attempt_id': record['attempt_id'], 'subject_kind': 'offer', 'subject_id': 17,
              'portal': 'no', 'action': 'add', 'package_id': record['package_id'],
              'binding_sha256': jobs.binding_digest(item['binding']), 'attempt_anchor_id': 17} | overrides
    jobs.create_ack_recovery(target, actor=ACTOR, idempotency_key=uuid.uuid4().hex)
    return jobs.claim_next('ack_only')


def test_ack_only_for_unknown_and_missing_attempts_never_acks(world):
    claim, record, item = ack_job(world)
    result = pd.execute_ack_only(ack_claim(record, item), make_env())
    assert (result.job_state, result.reason) == ('needs_review', 'ack_not_recoverable') and publication(world) == []


def test_ack_only_missing_attempt_and_binding_mismatch(world):
    claim, record, item = ack_job(world)
    missing = pd.execute_ack_only(ack_claim(record, item, attempt_id='e' * 32), make_env())
    assert (missing.job_state, missing.reason) == ('blocked', 'attempt_not_found')
    other = pd.execute_ack_only(ack_claim(record, item, binding_sha256='0' * 64), make_env())
    assert (other.job_state, other.reason) == ('needs_review', 'binding_changed')


def test_ack_only_after_completed_ack_is_idempotent(world):
    claim = new_job()
    run(claim)
    record = view(claim)
    item = attempts.inspect_attempt(record['attempt_id'])['attempt']
    fake = FakeTransport()
    result = pd.execute_ack_only(ack_claim(record, item), make_env(fake))
    assert (result.job_state, result.reason) == ('completed', 'already_acknowledged') and fake.calls == []


# ----------------------------------------------------------------- foreign
@pytest.fixture
def foreign(tmp_path, monkeypatch):
    env = make_foreign_root.__wrapped__(tmp_path / 'foreign', monkeypatch)
    for key, value in env[1].items():
        monkeypatch.setenv(key, json.dumps(value) if isinstance(value, dict) else value)
    assert jobs.init_schema(backup=False) == 'created'
    control.set_dispatch(True, changed_by='test')
    with closing(sqlite3.connect(env[0] / 'databases/foreign_offers.db')) as conn, conn:
        conn.execute("UPDATE foreign_offer_portal_sync SET needs_update=1 WHERE foreign_offer_id=11")
    return env


def foreign_job(kind, identifier, portal, action='add'):
    jobs.create_delivery({'domain': 'foreign', 'subject': {'kind': kind, 'id': identifier}, 'portal': portal, 'action': action,
                          'package': {'mode': 'ensure_current'}}, actor=ACTOR, idempotency_key=uuid.uuid4().hex,
                         dispatch_enabled=True)
    return jobs.claim_next('delivery')


def test_foreign_offer_delivery_uses_the_foreign_profile_and_acknowledges(foreign):
    claim = foreign_job('foreign_offer', 11, 'domiporta')
    outcome, fake = run(claim)
    assert outcome.job_state == 'completed' and fake.calls[0]['profile'] == 'domiporta' and len(fake.calls) == 1
    with closing(sqlite3.connect(foreign[0] / 'databases/foreign_offers.db')) as conn:
        assert conn.execute("SELECT needs_update FROM foreign_offer_portal_sync WHERE foreign_offer_id=11 AND portal_key='domiporta'").fetchone()[0] == 0


def test_cyprus_project_is_one_job_on_the_primary_account_with_all_members_acknowledged(foreign):
    claim = foreign_job('cyprus_development', 7, 'tabelaofert')
    outcome, fake = run(claim)
    assert outcome.job_state == 'completed' and [c['profile'] for c in fake.calls] == ['tabelaofert_primary']
    item = attempts.inspect_attempt(view(claim)['attempt_id'], domain='foreign')['attempt']
    assert sorted(item['binding']['members']) == [11, 13] and item['state'] == 'ack_completed'
    with closing(sqlite3.connect(foreign[0] / 'databases/foreign_offers.db')) as conn:
        rows = conn.execute("SELECT foreign_offer_id,needs_update FROM foreign_offer_portal_sync WHERE portal_key='tabelaofert' AND foreign_offer_id IN (11,13) ORDER BY 1").fetchall()
    assert rows == [(11, 0), (13, 0)]


def test_foreign_primary_profile_without_its_own_keys_is_blocked_with_no_fallback(foreign):
    claim = foreign_job('cyprus_development', 7, 'tabelaofert')
    polish_only = lambda key: 'x' if key.startswith('FTP_TABELAOFERT_') and 'PRIMARY' not in key else None
    outcome, fake = run(claim, secret=polish_only)
    assert (outcome.job_state, outcome.reason) == ('blocked', 'config_missing') and fake.calls == []


# ------------------------------------------------ package integrity (snapshot)
def _tamper_zip(world, package):
    path, _ = zip_bytes(world, package)
    path.write_bytes(path.read_bytes() + b'x')


def _tamper_manifest(world, package):
    from InvestmentManager.integrator.domestic_package_catalog import package_folder
    folder = package_folder(world / 'exports/domestic', package)
    data = json.loads((folder / 'manifest.json').read_text(encoding='utf8'))
    data['zip_sha256'] = '0' * 64
    (folder / 'manifest.json').write_text(json.dumps(data), encoding='utf8')


def _traversal_name(world, package):
    from InvestmentManager.integrator.domestic_package_catalog import package_folder
    folder = package_folder(world / 'exports/domestic', package)
    data = json.loads((folder / 'manifest.json').read_text(encoding='utf8'))
    data['zip_name'] = '..\\evil.zip'
    (folder / 'manifest.json').write_text(json.dumps(data), encoding='utf8')


def _duplicate_uuid(world, package):
    import shutil
    from InvestmentManager.integrator.domestic_package_catalog import package_folder
    folder = package_folder(world / 'exports/domestic', package)
    shutil.copytree(folder, world / 'exports/domestic' / '999' / 'add' / 'no' / package)


def _stale_input(world, package):
    sql(world, "UPDATE EstateData SET Cena='999999'")


def _symlinked_zip(world, package):
    import os
    path, _ = zip_bytes(world, package)
    target = path.with_name('real-copy.bin')
    target.write_bytes(path.read_bytes())
    path.unlink()
    try:
        os.symlink(target, path)
    except OSError:
        pytest.skip('symlink privilege unavailable on this platform (reported as a limitation, not a pass)')


def _limit(name, value):
    def apply(world, package):
        from InvestmentManager.integrator import domestic_package_catalog as catalog
        pytest.MonkeyPatch().setattr(catalog, name, value)
    return apply


@pytest.mark.parametrize('tamper', [_tamper_zip, _tamper_manifest, _traversal_name, _duplicate_uuid, _stale_input, _symlinked_zip,
                                    _limit('MAX_ZIP', 100), _limit('MAX_MANIFEST', 10), _limit('MAX_ZIP_ENTRIES', 0)],
                         ids=lambda f: f.__name__ if hasattr(f, '__name__') else str(f))
def test_untrustworthy_packages_are_refused_before_any_attempt_or_upload(world, monkeypatch, tamper):
    package = prep.prepare_package(17, 'no', 'add')['package_id']
    claim = new_job(mode='existing', package=package)
    from InvestmentManager.integrator import domestic_package_catalog as catalog
    original = {name: getattr(catalog, name) for name in ('MAX_ZIP', 'MAX_MANIFEST', 'MAX_ZIP_ENTRIES')}
    try:
        if tamper.__name__ == 'apply':
            name = tamper.__closure__[0].cell_contents
            value = tamper.__closure__[1].cell_contents
            monkeypatch.setattr(catalog, name, value)
        else:
            tamper(world, package)
        outcome, fake = run(claim)
    finally:
        for name, value in original.items():
            setattr(catalog, name, value)
    assert outcome.job_state == 'blocked' and fake.calls == []
    assert view(claim)['attempt_id'] is None and publication(world) == []


# ------------------------------------------- W1: job store and reads
def test_transient_job_store_busy_is_retried(world, monkeypatch):
    real, state = jobs.advance, {'calls': 0}

    def flaky(claim, **kwargs):
        state['calls'] += 1
        if state['calls'] in (2, 3):
            raise jobs.StorageBusy('storage_busy')
        return real(claim, **kwargs)
    monkeypatch.setattr(jobs, 'advance', flaky)
    outcome, fake = run(new_job())
    assert outcome.job_state == 'completed' and len(fake.calls) == 1 and state['calls'] > 5


def test_failed_intent_write_before_start_fails_closed_without_upload(world, monkeypatch):
    real = jobs.advance

    def refuse(claim, **kwargs):
        if kwargs.get('phase') == 'start_requested':
            raise jobs.StorageBusy('storage_busy')
        return real(claim, **kwargs)
    monkeypatch.setattr(jobs, 'advance', refuse)
    claim = new_job()
    with pytest.raises(pd.StorageFailure):
        pd.execute_delivery(claim, make_env(policy=policy(advance={'attempts': 2, 'total': 100.0})))
    assert attempt_state(claim) == 'prepared' and view(claim)['state'] == 'running'


def test_unwritable_final_state_leaves_the_job_running_and_the_next_tick_closes_it_without_ftp(world, monkeypatch):
    from InvestmentManager.integrator import export_job_runner as runner
    real, fake = jobs.advance, FakeTransport()

    def refuse_terminal(claim, **kwargs):
        if kwargs.get('state') in ('completed', 'needs_review', 'blocked', 'failed'):
            raise jobs.StorageBusy('storage_busy')
        return real(claim, **kwargs)
    claim = new_job()
    with monkeypatch.context() as patch:
        patch.setattr(jobs, 'advance', refuse_terminal)
        with pytest.raises(pd.StorageFailure):
            pd.execute_delivery(claim, make_env(fake, policy=policy(advance={'attempts': 2, 'total': 100.0})))
    assert view(claim)['state'] == 'running' and attempt_state(claim) == 'ack_completed' and len(fake.calls) == 1
    result = runner.tick_one(env=make_env(FakeTransport()))
    assert result['recovered'][0]['resolution'] == 'completed'
    assert view(claim)['state'] == 'completed' and len(fake.calls) == 1


def test_unreadable_attempt_after_an_uncertain_start_is_reviewed_and_never_uploads(world, monkeypatch):
    real = export_start.start_qualified_transport

    def committed_then_lost(*args, **kwargs):
        real(*args, **kwargs)
        raise OSError('reply lost')
    monkeypatch.setattr(export_start, 'start_qualified_transport', committed_then_lost)
    monkeypatch.setattr(attempts, 'inspect_attempt', lambda *a, **k: {'state': 'unavailable', 'attempt': None, 'reason': 'storage_unavailable'})
    claim = new_job()
    outcome, fake = run(claim, policy=policy(read={'attempts': 2, 'total': 100.0}))
    assert (outcome.job_state, outcome.reason) == ('needs_review', 'attempt_unreadable') and fake.calls == []
