"""Optional bounded pytest processes; each module belongs to exactly one shard.

No xdist dependency, shared fixtures, generated package cache or application code.
Reports always go to a new disposable directory outside the checkout.
"""
import argparse
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import time


ROOT = Path(__file__).resolve().parents[1]
SUPPORT = Path(__file__).resolve().parent / '_support'


def partition(nodes, workers, weights):
    groups = defaultdict(list)
    for node in nodes:
        groups[node.split('::')[0]].append(node)
    ranked = sorted(groups.values(), key=lambda group: sum(weights.get(n, 1.0) for n in group), reverse=True)
    shards = [[] for _ in range(min(workers, len(groups)))]
    loads = [0.0] * len(shards)
    for group in ranked:
        index = min(range(len(shards)), key=lambda i: loads[i])
        shards[index].extend(group)
        loads[index] += sum(weights.get(n, 1.0) for n in group)
    return shards


def load_weights(path):
    if path is None:
        return {}
    content = json.loads(path.read_text(encoding='utf-8'))
    if isinstance(content, dict):
        return content.get('durations', content)
    weights = defaultdict(float)
    for row in content:
        if 'phase' in row:
            weights[row.get('nodeid', row.get('node'))] += row.get('seconds', row.get('duration', 0.0))
    return weights


def run(args=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--workers', type=int, choices=range(1, 5), default=4)
    parser.add_argument('--weights', type=Path)
    parser.add_argument('--reverse', action='store_true')
    parser.add_argument('paths', nargs='*', default=['tests'])
    options = parser.parse_args(args)
    output = Path(tempfile.mkdtemp(prefix='investment_pytest_parallel_'))
    started = time.perf_counter()
    env = os.environ.copy()
    env['PYTHONDONTWRITEBYTECODE'] = '1'
    env['PYTHONIOENCODING'] = 'utf-8'
    env['PYTHONPATH'] = os.pathsep.join(filter(None, (str(SUPPORT), str(ROOT), env.get('PYTHONPATH'))))
    env.pop('INVESTMENT_PYTEST_SELECTION', None)
    base = [sys.executable, '-B', '-m', 'pytest', '-q', '-p', 'parallel_reports']

    def execute(label, selection=None):
        child = env.copy()
        report = output / (label + '.json')
        child['INVESTMENT_PYTEST_REPORT'] = str(report)
        command = [*base, *options.paths]
        if selection is None:
            command += ['--collect-only', '-o', 'addopts=']
        else:
            choice = output / (label + '-selection.json')
            choice.write_text(json.dumps(selection), encoding='utf-8')
            child['INVESTMENT_PYTEST_SELECTION'] = str(choice)
        begin = time.perf_counter()
        with (output / (label + '.log')).open('w', encoding='utf-8') as stream:
            result = subprocess.run(command, cwd=ROOT, env=child, stdout=stream, stderr=subprocess.STDOUT)
        if not report.is_file():
            raise RuntimeError(f'No pytest report: {label}; inspect {output}')
        data = json.loads(report.read_text(encoding='utf-8'))
        data['process_exit'] = result.returncode
        data['wall_seconds'] = time.perf_counter() - begin
        return data

    collection = execute('collection')
    if collection['process_exit'] != 0 or not collection['collected']:
        print(f'Collection failed; reports: {output}', flush=True)
        return collection['process_exit'] or 2
    nodes = collection['collected']
    if len(nodes) != len(set(nodes)):
        raise RuntimeError('Collection contains duplicate node IDs')
    shards = partition(nodes, options.workers, load_weights(options.weights))
    if options.reverse:
        shards = [list(reversed(shard)) for shard in shards]
    print(f'{len(nodes)} cases; {len(shards)} processes; reports: {output}', flush=True)
    with ThreadPoolExecutor(max_workers=len(shards)) as pool:
        futures = [pool.submit(execute, f'shard-{i}', shard) for i, shard in enumerate(shards)]
        results = [future.result() for future in futures]
    if any(result['collected'] != shard for result, shard in zip(results, shards)):
        raise RuntimeError('Executed collection differs from assigned selection')
    phases = [phase for result in results for phase in result['phases']]
    completed = [row['nodeid'] for row in phases if row['phase'] == 'teardown']
    if len(completed) != len(nodes) or set(completed) != set(nodes):
        raise RuntimeError('Missing, duplicate or interrupted test execution')
    counts = defaultdict(int)
    durations = defaultdict(float)
    for result in results:
        by_node = defaultdict(list)
        for row in result['phases']:
            by_node[row['nodeid']].append(row)
            durations[row['nodeid']] += row['seconds']
        for reports in by_node.values():
            if any(row['outcome'] == 'failed' for row in reports):
                counts['failed'] += 1
            elif any(row['outcome'] == 'skipped' for row in reports):
                counts['skipped'] += 1
            else:
                counts['passed'] += 1
    summary = dict(counts=counts, collected=len(nodes), durations=durations,
                   seconds=time.perf_counter() - started, shards=results,
                   warnings=sum(len(result['warnings']) for result in results))
    (output / 'summary.json').write_text(json.dumps(summary), encoding='utf-8')
    print(json.dumps({k: v for k, v in summary.items() if k not in {'shards', 'durations'}}), flush=True)
    # Never turn a failing test, interrupted process or safety violation into success.
    codes = [result['process_exit'] for result in results]
    return 1 if any(code < 0 for code in codes) else max(codes)


if __name__ == '__main__':
    raise SystemExit(run())
