"""Exercise one installed SDK starter through its public API in a new directory.

Run with the SDK's Python and pass the separate engine interpreter. Explicitly
compiles and runs all fixtures, then registers the package in a private test store.
"""
import argparse
import hashlib
import json
from pathlib import Path


def main():
    from pycforge_sdk import SDK, __version__

    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--engine-python', type=Path, required=True)
    parser.add_argument('--compiler', required=True)
    parser.add_argument('--template', required=True)
    parser.add_argument('--work-dir', type=Path, required=True)
    args = parser.parse_args()
    work = args.work_dir.resolve()
    work.mkdir(parents=True, exist_ok=False)
    sdk = SDK(engine_python=args.engine_python, cache=work/'cache', timeout=90)
    project = work/'project'
    package = work/'extension.pcfplugin'
    summary = {'template': args.template, 'sdk_version': __version__, 'passed': False, 'steps': []}

    def check(label, result, status='succeeded'):
        summary['steps'].append({'action': label, 'status': result.status})
        if result.status != status:
            detail = json.dumps(result.to_dict(), indent=2, ensure_ascii=False)
            (work/'unexpected-result.json').write_text(detail+'\n', encoding='utf-8')
            raise ValueError(f'{label} returned {result.status}, expected {status}')
        return result.data

    try:
        connection = check('connect', sdk.connect())
        summary['connection'] = connection
        templates = check('templates', sdk.templates())['templates']
        if args.template not in {item['id'] for item in templates}:
            raise ValueError('Requested starter is absent from the selected engine')
        check('new', sdk.create_project(project, author='SDK workflow qualification', template=args.template))
        scan = check('scan', sdk.scan(project))['scan']
        if scan['state'] != 'ready-to-verify' or scan['verification'] != 'not-run':
            raise ValueError('Unexpected scan state before verification')
        check('build before verification', sdk.build(project, package), 'rejected')
        if package.exists():
            raise ValueError('Premature build created an output')
        report = check('verify', sdk.verify(project, compiler=args.compiler))['report']
        declared = json.loads((project/'project.json').read_bytes())['cases']
        if ([case['name'] for case in report['cases']] != [case['name'] for case in declared]
                or any(case['passed'] is not True for case in report['cases'])):
            raise ValueError('Verification missed or failed a declared fixture')
        summary.update(compiler=report['compiler'], evidence_sha256=report['evidence_sha256'],
                       cases=[{'name': c['name'], 'kind': c['expected']['kind'], 'passed': c['passed']}
                              for c in report['cases']])
        readiness = check('readiness', sdk.readiness(project, compiler=args.compiler))['readiness']
        if readiness['state'] != 'ready-to-package':
            raise ValueError('Passing verification did not produce package readiness')
        built = check('build', sdk.build(project, package, compiler=args.compiler))
        second = work/'repeat.pcfplugin'
        check('repeat build', sdk.build(project, second, compiler=args.compiler))
        original = package.read_bytes()
        if second.read_bytes() != original:
            raise ValueError('Repeated package bytes differ for identical evidence')
        row = check('register', sdk.register(package, store=work/'registry.json'))['registration']
        summary.update(package_format=built['package_format'], namespace=row['namespace'],
                       package_sha256=hashlib.sha256(original).hexdigest())
        if row['package_sha256'] != summary['package_sha256'] or row['status'] != 'Ready':
            raise ValueError('Registered package identity differs from the built package')
        # Make a real author edit using the same optimistic save gate as the UI.
        document = json.loads((project/'project.json').read_bytes())
        document['metadata']['description'] += ' Edited after verification.'
        check('save edit', sdk.save_project(project, document, expected_sha256=scan['project_sha256']))
        result = sdk.build(project, package, compiler=args.compiler)
        check('build stale project', result, 'rejected')
        if ([d['code'] for d in result.diagnostics] != ['SDK_STALE_EVIDENCE']
                or package.read_bytes() != original):
            raise ValueError('A stale build did not preserve the verified package')
        summary['passed'] = True
    finally:
        (work/'workflow.json').write_text(json.dumps(summary, indent=2)+'\n', encoding='utf-8')
    return 0


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