"""Run with the installed engine after qualify_all_customized; public admission only."""
import argparse
import json
from pathlib import Path
import subprocess

from pycforge import PythonToCConverter, ConversionRequest, SourceBundle, SourceDocumentInput
from pycforge.converter.runtime_values.service import request_options
from pycforge.crucible import ImportRegistrationStore

p = argparse.ArgumentParser()
p.add_argument('--packages-dir', type=Path, required=True)
p.add_argument('--pcfc11', type=Path, required=True)
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)
store = ImportRegistrationStore(out/'registry.json')
for template in ['scalar-cube-root', 'dot-product-starter', 'value-starter', 'text-starter']:
    row = store.register_file(a.packages_dir/template/'extension.pcfplugin')
    assert row.status == 'Ready'

primary = '''import workflow
def main():
    print(workflow.evaluate(' {"label":" alpha beta ","values":[1.0,2.0],"weights":[3.0,4.0]} '))
    return 0
'''
companion = '''*import custom_scalar_cube_root as measure
*import custom_dot_product_starter as weights
*import custom_value_starter as records
*import custom_text_starter as text
def evaluate(payload):
    row = records.my_decode(text.my_trim(payload))
    a = weights.my_vector(row["values"], dtype="float64")
    b = weights.my_vector(row["weights"], dtype="float64")
    score = weights.my_score(a, b)
    label = text.my_join("-", text.my_tokens(text.my_trim(row["label"])))
    root = measure.my_cbrt(27.0)
    if not abs(root - 3.0) <= 1e-12:
        raise ValueError("Cube-root result exceeds the example's error bound")
    return records.my_encode({"label": label, "score": score, "root": round(root)})
'''
(out/'main.py').write_text(primary)
(out/'workflow.py').write_text(companion)
documents = [SourceDocumentInput('main.py', primary, 'main'),
             SourceDocumentInput('workflow.py', companion, 'workflow')]
result = PythonToCConverter(extension_registry=store.snapshot()).convert(
    ConversionRequest(SourceBundle(documents[0], tuple(documents[1:])), **request_options()))
(out/'conversion.json').write_text(json.dumps(result.semantic_dict(), indent=2)+'\n')
assert result.generated_c is not None
(out/'program.c').write_text(result.generated_c)
expected = '{"label": "alpha-beta", "score": 11.0, "root": 3}\n'
(out/'expected.txt').write_text(expected)
rows = []
for name, compiler, flags in [
    ('gcc-O0', 'gcc', ['-O0']), ('gcc-O2', 'gcc', ['-O2']),
    ('gcc-ubsan', 'gcc', ['-O1', '-fsanitize=undefined', '-fno-sanitize-recover=all']),
    ('pcfc11-O0', str(a.pcfc11.resolve()), ['-O0']),
    ('pcfc11-O1', str(a.pcfc11.resolve()), ['-O1']),
]:
    executable = out/name
    command = [compiler, '-std=c11', *flags, '-DPYCF_RUNTIME_MAIN', '-fno-fast-math', '-ffp-contract=off',
               str(out/'program.c'), '-lm', '-o', str(executable)]
    build = subprocess.run(command, capture_output=True, text=True, timeout=180)
    (out/(name+'-compile.log')).write_text(build.stdout+build.stderr)
    assert build.returncode == 0, (name, build.stderr)
    run = subprocess.run([str(executable)], capture_output=True, text=True, timeout=30)
    rows.append(dict(profile=name, command=command, stdout=run.stdout, stderr=run.stderr,
                     exit_code=run.returncode, passed=(run.returncode == 0 and run.stdout == expected and not run.stderr)))
    (out/'results.json').write_text(json.dumps(rows, indent=2)+'\n')
    assert rows[-1]['passed'], rows[-1]
print('Four independently packaged families compose across five native profiles')
