"""Machine-readable pytest reports for the optional isolated-process runner."""
import json
import os
from pathlib import Path

import pytest


RESULT = {'collected': [], 'phases': [], 'warnings': []}


def pytest_collection_modifyitems(config, items):
    selection = os.environ.get('INVESTMENT_PYTEST_SELECTION')
    if not selection:
        return
    wanted = json.loads(Path(selection).read_text(encoding='utf-8'))
    indexed = {item.nodeid: item for item in items}
    if len(wanted) != len(set(wanted)) or not set(wanted) <= indexed.keys():
        raise pytest.UsageError('Invalid or incomplete parallel test selection')
    selected = set(wanted)
    config.hook.pytest_deselected(items=[item for item in items if item.nodeid not in selected])
    items[:] = [indexed[node] for node in wanted]


def pytest_collection_finish(session):
    RESULT['collected'] = [item.nodeid for item in session.items]


def pytest_runtest_logreport(report):
    RESULT['phases'].append({
        'nodeid': report.nodeid, 'phase': report.when, 'seconds': report.duration,
        'outcome': report.outcome, 'xfail': getattr(report, 'wasxfail', None),
        'detail': str(report.longrepr) if report.failed or report.skipped else None,
    })


def pytest_warning_recorded(warning_message, when, nodeid, location):
    RESULT['warnings'].append({
        'category': warning_message.category.__name__, 'message': str(warning_message.message),
        'nodeid': nodeid, 'when': when,
    })


def pytest_sessionfinish(session, exitstatus):
    RESULT['exit'] = int(exitstatus)
    Path(os.environ['INVESTMENT_PYTEST_REPORT']).write_text(json.dumps(RESULT), encoding='utf-8')
