"""Child process for the legacy handoff record/replay test (not a test module).

usage: python legacy_replay_child.py REPO_DIR DATA_DIR PACKAGES_JSON
Runs a fixed request sequence against InvestmentManager.export_handoff from REPO_DIR (either the
current tree or an archive of HEAD) and prints the JSON list of [request, response].
"""
import json
import os
import sys
import threading

repo, data, packages_file = sys.argv[1:4]
os.chdir(repo)
sys.path.insert(0, repo)
os.environ['DATA_DIR'] = data
os.environ['INVESTMENT_LEGACY_STORAGE'] = '0'

import socket


def forbidden(*args, **kwargs):
    raise AssertionError('network forbidden')


socket.socket.connect = forbidden
socket.create_connection = forbidden

from InvestmentManager.integrator import domestic_dictionaries as dictionaries
dictionaries._download = lambda url: b'<dictionary><item id="1" name="test"/></dictionary>'
dictionaries._cache.clear()
from InvestmentManager import export_handoff as handoff
from InvestmentManager.integrator import input_consistency as ic

packages = json.load(open(packages_file, encoding='utf-8'))
log = []
bindings = {}
A = lambda n: ('%032x' % n)
VOLATILE = {'checked_at', 'generated_at', 'page_offset'}


RUN_SPECIFIC = {'package_id', 'zip_sha256', 'manifest_sha256', 'input_fingerprint', 'zip_size', 'zip_name', 'last_filename', 'prepared_at'}


def clean(value):
    if isinstance(value, dict):
        return {k: ('<' + k + '>' if k in RUN_SPECIFIC else clean(v)) for k, v in value.items() if k not in VOLATILE}
    if isinstance(value, list):
        return [clean(v) for v in value]
    return value


def call(request, note=None):
    reply = handoff.dispatch_request(request)
    log.append([clean(request), clean(reply)])
    return reply


def create(portal, attempt, action='add'):
    reply = call({'operation': 'create_attempt', 'attempt_id': attempt, 'package_id': packages[portal],
                  'offer_id': 17, 'portal': portal, 'action': action})
    if reply.get('ok'):
        bindings[attempt] = reply['attempt']['binding']
    return reply


def op(name, attempt, **extra):
    return call({'operation': name, 'attempt_id': attempt, 'binding': bindings[attempt], **extra})


# --- malformed and unknown requests (error paths)
for request in ['not a dict', {}, {'operation': 'zzz'}, {'operation': 'get_attempt'}, {'operation': 'get_attempt', 'attempt_id': 'x'},
                {'operation': 'get_attempt', 'attempt_id': A(1), 'extra': 1},
                {'operation': 'create_attempt', 'attempt_id': A(2), 'package_id': 'bad', 'offer_id': 17, 'portal': 'no', 'action': 'add'},
                {'operation': 'create_attempt', 'attempt_id': A(2), 'package_id': packages['no'], 'offer_id': True, 'portal': 'no', 'action': 'add'},
                {'operation': 'create_attempt', 'attempt_id': A(2), 'package_id': packages['no'], 'offer_id': 17, 'portal': 'otodom', 'action': 'add'},
                {'operation': 'create_attempt', 'attempt_id': A(2), 'package_id': packages['no'], 'offer_id': 17, 'portal': 'no', 'action': 'update'},
                {'operation': 'create_attempt', 'attempt_id': A(2), 'package_id': 'f' * 32, 'offer_id': 17, 'portal': 'no', 'action': 'add'},
                {'operation': 'start_transport', 'attempt_id': A(3)},
                {'operation': 'record_transport_result', 'attempt_id': A(3), 'binding': {}, 'outcome': 'confirmed'},
                {'operation': 'get_attempt', 'attempt_id': A(4)},
                {'protocol_version': 2, 'domain': 'foreign', 'operation': 'nope'},
                {'protocol_version': 3, 'domain': 'foreign', 'operation': 'get_attempt', 'attempt_id': A(5)},
                {'operation': 'list_sync_tasks', 'offset': -1, 'limit': 1}]:
    call(request)

# --- full lifecycle on 'no'
create('no', A(10))
create('no', A(10))                                     # idempotent re-create
call({'operation': 'get_attempt', 'attempt_id': A(10)})
op('start_transport', A(10))
op('start_transport', A(10))                            # no second permission
op('record_transport_result', A(10), outcome='confirmed')
op('record_transport_result', A(10), outcome='confirmed')
op('record_transport_result', A(10), outcome='failed')  # refused: completed result is immutable
op('acknowledge_attempt', A(10))
op('acknowledge_attempt', A(10))                        # already acknowledged
call({'operation': 'get_attempt', 'attempt_id': A(10)})
create('no', A(11))                                     # returns the existing ack_completed attempt

# --- failed before STOR, then a conscious second attempt
create('domiporta', A(20))
op('start_transport', A(20))
op('record_transport_result', A(20), outcome='failed')
op('acknowledge_attempt', A(20))                        # refused
create('domiporta', A(21))
altered = dict(bindings[A(21)], zip_sha256='0' * 64)
call({'operation': 'start_transport', 'attempt_id': A(21), 'binding': altered})
op('start_transport', A(21))
op('record_transport_result', A(21), outcome='unknown')
create('domiporta', A(22))                              # refused: unresolved transport
op('acknowledge_attempt', A(21))                        # refused: no confirmed transport

# --- prepared attempts, then lock contention in other threads
create('tabelaofert', A(30))
create('gruntguru', A(31))
held, release = threading.Event(), threading.Event()


def holder():
    with ic.input_lock():
        held.set()
        release.wait(30)


thread = threading.Thread(target=holder)
thread.start()
held.wait(30)
try:
    call({'operation': 'get_attempt', 'attempt_id': A(30)})
    op('start_transport', A(30))
    op('record_transport_result', A(30), outcome='confirmed')
    op('acknowledge_attempt', A(30))
    call({'operation': 'create_attempt', 'attempt_id': A(32), 'package_id': packages['tabelaofert'], 'offer_id': 17,
          'portal': 'tabelaofert', 'action': 'add'})
    call({'operation': 'list_sync_tasks', 'offset': 0, 'limit': 5})
    call({'operation': 'list_sync_offers', 'offset': 0, 'limit': 5, 'categories': [], 'portals': [], 'snapshot': None})
finally:
    release.set()
    thread.join()

# --- after the lock is released everything works again
call({'operation': 'get_attempt', 'attempt_id': A(30)})
op('start_transport', A(31))
op('record_transport_result', A(31), outcome='confirmed')
op('acknowledge_attempt', A(31))
call({'operation': 'list_sync_tasks', 'offset': 0, 'limit': 50})
call({'operation': 'list_sync_offers', 'offset': 0, 'limit': 20, 'categories': [], 'portals': [], 'snapshot': None})
call({'protocol_version': 2, 'domain': 'foreign', 'operation': 'get_attempt', 'attempt_id': A(40)})

print(json.dumps(log, sort_keys=True))
