#!/usr/bin/env python3
"""Pflichtabnahme mit fixiertem Fremdbestand und zugeordneter Runner-Messung."""
import json
import os
from pathlib import Path
import platform
import subprocess
import sys
import tempfile
import distribution as dist

output = Path('acceptance')
output.mkdir()
revision = subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip()
report = dict(revision=revision, passed=False, buildhost=platform.platform(),
              run_url=os.environ.get('TB_RUN_URL', ''), foreign=False, inventory=False,
              workspace=False, benchmarks=False, native_ide=False)
try:
    repo = Path(os.environ['TB_VBDOS_REPO'])
    with (output / 'acceptance.log').open('wb') as log:
        dist.run([sys.executable, dist.ROOT / 'tests/support/release-abnahme.py', '--vbdos-repo', repo],
                 stdout=log, stderr=subprocess.STDOUT)
    with tempfile.TemporaryDirectory(prefix='tb-ci-runtime-') as temporary:
        runtime = Path(temporary) / 'runtime'
        with (output / 'native-ide.log').open('wb') as log:
            dist.run([sys.executable, dist.ROOT / 'tests/support/build-runtime.py',
                      '--target', dist.HOSTS[(platform.system(), platform.machine())],
                      '--output', runtime / dist.HOSTS[(platform.system(), platform.machine())]],
                     stdout=log, stderr=subprocess.STDOUT)
            dist.run(['cargo', 'test', '--locked', '-p', 'tb-cli', '--bin', 'tbc',
                      'ide_acceptance::real_native_ide_exports_and_source_free_cli_library_consumer',
                      '--', '--exact', '--ignored', '--nocapture'],
                     env=dict(os.environ, TB_IDE_RUNTIME_DIR=str(runtime)), stdout=log, stderr=subprocess.STDOUT)
    report.update(passed=True, native_ide=True, foreign=True, inventory=True, workspace=True, benchmarks=True)
finally:
    report['log_sha256'] = dist.digest(output / 'acceptance.log') if (output / 'acceptance.log').exists() else None
    (output / 'acceptance.json').write_text(json.dumps(report, indent=2) + '\n')
