"""2B.4: process death at every delivery boundary, both domains, real packages and SQLite, fake network.

A child process runs one tick and is killed (os._exit) at a named boundary; a second child then
recovers. Whatever the boundary, the (fake) uploader is entered at most once per job in total and
the final state matches what the durable attempt proves."""
from contextlib import closing
import json
import shutil
import sqlite3
import subprocess
import sys
import uuid
from pathlib import Path

import pytest

from tests.investmentmanager.test_domestic_packages import manifest as domestic_manifest
from tests.investmentmanager.test_foreign_packages_v2 import foreign_root as make_foreign_root, prepare as prepare_foreign
from InvestmentManager.integrator import domestic_dictionaries as dictionaries
from InvestmentManager.integrator import domestic_packages as prep
from InvestmentManager.integrator import export_attempts as attempts
from InvestmentManager.integrator import export_control as control
from InvestmentManager.integrator import export_jobs as jobs

REPO = Path(__file__).resolve().parents[2]
ACTOR = 'user:7'
KILL = 77
PRE_START = ['accepted', 'after_claim', 'after_qualification', 'after_preparation', 'after_snapshot', 'before_create',
             'after_create_commit', 'after_create', 'before_start']
BOUNDARIES = PRE_START + ['after_start', 'after_upload', 'after_record', 'after_ack', 'before_finish']

CHILD = r'''
import json, os, sys
from InvestmentManager.integrator import domestic_dictionaries as d, export_job_runner as r, package_delivery as pd, portal_transport as t
import socket
def forbidden(*a, **k): raise AssertionError('network forbidden')
socket.socket.connect = forbidden; socket.create_connection = forbidden
d._download = lambda url: b'<dictionary><item id="1" name="test"/></dictionary>'
log, kill = sys.argv[1], sys.argv[2]
class Fake:
    def upload_portal_zip(self, profile, name, body, *, secret_getter):
        with open(log, 'a', encoding='utf-8') as stream: stream.write(profile + ' ' + name + '\n')
        return t.UploadResult('confirmed', 'done', bytes_sent=len(body), bytes_complete=True, stor_reply_code=226)
hooks = {}
if kill != '-':
    def die(): os._exit(77)
    hooks[kill] = die
env = pd.Env(secret_getter=lambda k: 'x', transport=Fake(), settings=pd._environment_settings, sleep=lambda s: None, hooks=hooks)
print(json.dumps(r.tick_one(env=env)))
'''


def run_child(log, kill='-'):
    return subprocess.run([sys.executable, '-B', '-c', CHILD, str(log), kill], cwd=REPO, capture_output=True, text=True,
                          encoding='utf8', timeout=300)


@pytest.fixture(scope='module')
def templates(tmp_path_factory):
    from tests.export_generation import conftest as generation
    result = {}
    with pytest.MonkeyPatch.context() as mp:
        domestic = generation.data_root.__wrapped__(tmp_path_factory.mktemp('domestic-template'))
        mp.setenv('DATA_DIR', str(domestic))
        mp.setattr(dictionaries, '_download', lambda url: b'<dictionary><item id="1" name="test"/></dictionary>')
        dictionaries._cache.clear()
        package = prep.prepare_package(17, 'no', 'add')['package_id']
        jobs.init_schema(backup=False)
        control.set_dispatch(True, changed_by='template')
        result['domestic'] = (domestic, package, {})
    with pytest.MonkeyPatch.context() as mp:
        env = make_foreign_root.__wrapped__(tmp_path_factory.mktemp('foreign-template'), mp)
        mp.setattr(dictionaries, '_download', lambda url: b'<dictionary><item id="1" name="test"/></dictionary>')
        package = prepare_foreign(env, kind='cyprus_development', identifier=7, portal='tabelaofert', action='add')['package_id']
        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 AND portal_key='tabelaofert'")
        jobs.init_schema(backup=False)
        control.set_dispatch(True, changed_by='template')
        settings = {key: json.dumps(value) if isinstance(value, dict) else value for key, value in env[1].items()}
        result['foreign'] = (env[0], package, settings)
    dictionaries._cache.clear()
    return result


def make_job(domain, package):
    if domain == 'domestic':
        intent = {'domain': 'domestic', 'subject': {'kind': 'offer', 'id': 17}, 'portal': 'no', 'action': 'add'}
    else:
        intent = {'domain': 'foreign', 'subject': {'kind': 'cyprus_development', 'id': 7}, 'portal': 'tabelaofert', 'action': 'add'}
    return jobs.create_delivery(intent | {'package': {'mode': 'existing', 'package_id': package}}, actor=ACTOR,
                                idempotency_key=uuid.uuid4().hex, dispatch_enabled=True)


def uploads(log):
    return log.read_text(encoding='utf8').splitlines() if log.exists() else []


@pytest.mark.parametrize('boundary', BOUNDARIES)
@pytest.mark.parametrize('domain', ['domestic', 'foreign'])
def test_death_at_each_boundary_never_repeats_the_upload_and_ends_in_the_durable_truth(templates, tmp_path, monkeypatch, domain, boundary):
    template, package, settings = templates[domain]
    root = tmp_path / 'run'
    shutil.copytree(template, root)
    monkeypatch.setenv('DATA_DIR', str(root))
    for key, value in settings.items():
        monkeypatch.setenv(key, value)
    log = tmp_path / 'uploads.log'
    receipt = make_job(domain, package)
    if boundary != 'accepted':
        killed = run_child(log, boundary)
        assert killed.returncode == KILL, (killed.stdout[-500:], killed.stderr[-1500:])
    assert len(uploads(log)) <= 1
    for _ in range(2):
        recovered = run_child(log)
        assert recovered.returncode == 0, recovered.stderr[-1500:]
    view = jobs.get_job(receipt.job_id)
    attempt_id = view['attempt_id']
    state = attempts.inspect_attempt(attempt_id, domain=domain)['attempt']['state'] if attempt_id else None
    done = len(uploads(log))
    if boundary in PRE_START:
        assert (view['state'], view['reason_code'], state, done) == ('completed', 'ack_completed', 'ack_completed', 1)
    elif boundary == 'after_start':
        assert (view['state'], view['reason_code'], state, done) == ('needs_review', 'transport_unknown', 'transport_unknown', 0)
    elif boundary == 'after_upload':
        assert (view['state'], view['reason_code'], state, done) == ('needs_review', 'transport_unknown', 'transport_unknown', 1)
    elif boundary == 'after_record':
        assert (view['state'], view['reason_code'], state, done) == ('needs_review', 'ack_pending', 'transport_confirmed', 1)
        item = attempts.inspect_attempt(attempt_id, domain=domain)['attempt']
        target = {'domain': domain, 'attempt_id': attempt_id, 'subject_kind': view['subject']['kind'], 'subject_id': view['subject']['id'],
                  'portal': view['portal'], 'action': view['action'], 'package_id': package,
                  'binding_sha256': jobs.binding_digest(item['binding']), 'attempt_anchor_id': item['binding']['offer_id']}
        jobs.create_ack_recovery(target, actor=ACTOR, idempotency_key=uuid.uuid4().hex, parent_job_id=receipt.job_id)
        assert run_child(log).returncode == 0
        assert attempts.inspect_attempt(attempt_id, domain=domain)['attempt']['state'] == 'ack_completed'
        assert jobs.get_job(receipt.job_id)['state'] == 'completed' and len(uploads(log)) == 1
    else:
        assert (view['state'], view['reason_code'], state, done) == ('completed', 'ack_completed', 'ack_completed', 1)
    assert jobs.verify_integrity() == []
    with closing(sqlite3.connect(root / 'databases/IDB.db')) as conn:
        assert conn.execute("SELECT COUNT(*) FROM export_jobs WHERE state='running'").fetchone()[0] == 0
