"""Qualify every customized starter through an installed SDK and selected engine."""
from concurrent.futures import ThreadPoolExecutor
import argparse
import json
from pathlib import Path
import subprocess
import sys
from pycforge_sdk import SDK

p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--engine-python', type=Path, required=True)
p.add_argument('--compiler', action='append', required=True, help='Repeat for independently installed drivers')
p.add_argument('--work-dir', type=Path, required=True)
a = p.parse_args()
out = a.work_dir.resolve(); out.mkdir(parents=True, exist_ok=False)
# Preserve virtual-environment interpreter links; resolving them escapes the
# selected installation and can import a different engine.
engine = a.engine_python.absolute()
labels = [Path(c).name for c in a.compiler]
assert len(set(labels)) == len(labels), 'Use drivers with distinct basenames'
sdk = SDK(engine_python=engine, cache=out/'catalogue')
result = sdk.templates(); assert result.ok, result.to_dict()
templates = [t['id'] for t in result.data['templates']]
tool = Path(__file__).with_name('qualify_customized_starter.py')

def qualify(compiler):
    driver = Path(compiler).name
    directory = out/driver; directory.mkdir(); rows = []
    for template in templates:
        with (directory/(template+'.log')).open('w') as log:
            result = subprocess.run([sys.executable, str(tool), '--engine-python', str(engine),
                '--compiler', compiler, '--template', template, '--work-dir', str(directory/template)],
                stdout=log, stderr=subprocess.STDOUT, timeout=900)
        rows.append(dict(template=template, exit_code=result.returncode))
        (directory/'results.json').write_text(json.dumps(rows, indent=2)+'\n')
        print(driver, template, result.returncode, flush=True)
        if result.returncode:
            raise RuntimeError((driver, template))
    return rows

with ThreadPoolExecutor(max_workers=min(2, len(a.compiler))) as pool:
    list(pool.map(qualify, a.compiler))
(out/'complete.json').write_text(json.dumps(dict(passed=True, templates=templates, compilers=a.compiler), indent=2)+'\n')
