"""2B.2: legacy START/RPC compatibility.

tests/investmentmanager/golden/legacy_handoff_replay.json was recorded by running
legacy_replay_child.py against an archive of HEAD (the code before Stage 2B) on this very data root
(run-specific hashes and package ids are normalised). The same sequence on the working tree must
produce byte-identical responses, including the lock-contention paths.
"""
import json
from pathlib import Path
import shutil
import subprocess
import sys

from tests.investmentmanager.test_domestic_packages import data_root, isolated
from InvestmentManager.integrator import domestic_packages as prep

REPO = Path(__file__).resolve().parents[2]
CHILD = Path(__file__).with_name('legacy_replay_child.py')
GOLDEN = Path(__file__).parent / 'golden' / 'legacy_handoff_replay.json'


def run_child(repo, data, packages):
    result = subprocess.run([sys.executable, '-B', str(CHILD), str(repo), str(data), str(packages)], capture_output=True,
                            text=True, encoding='utf8', timeout=300)
    assert result.returncode == 0, result.stderr[-2000:]
    return json.loads(result.stdout.strip().splitlines()[-1])


def prepare(data_root, tmp_path):
    packages = {portal: prep.prepare_package(17, portal, 'add')['package_id'] for portal in ('no', 'domiporta', 'tabelaofert', 'gruntguru')}
    (tmp_path / 'packages.json').write_text(json.dumps(packages), encoding='utf8')
    copy = tmp_path / 'data-copy'
    shutil.copytree(data_root, copy)
    return copy, tmp_path / 'packages.json'


def test_handoff_responses_match_the_pre_stage_2b_recording(data_root, tmp_path):
    copy, packages = prepare(data_root, tmp_path)
    after = run_child(REPO, copy, packages)
    before = json.loads(GOLDEN.read_text(encoding='utf8'))
    assert len(before) >= 50
    assert before == after
    outcomes = {(entry[1].get('ok'), entry[1].get('error')) for entry in before}
    assert (True, None) in outcomes and (False, 'operation_blocked') in outcomes and (False, 'invalid_request') in outcomes
    assert any(entry[1].get('attempt', {}).get('can_send') is True for entry in before)
    assert any(entry[1].get('attempt', {}).get('already_acknowledged') for entry in before)
    busy = [entry for entry in before if isinstance(entry[0], dict) and entry[0].get('operation') in ('get_attempt', 'start_transport') and entry[1].get('error') == 'operation_blocked']
    assert len(busy) >= 2
    assert any(entry[1].get('error') == 'queue_unavailable' for entry in before)
