#!/usr/bin/env python3
import argparse
import json
from pathlib import Path
import runpy
import shutil
import subprocess
import sys
import tarfile
from tempfile import TemporaryDirectory

from image import verify
from policy import sha256


parser = argparse.ArgumentParser(description='Package and verify independent router performance builds')
for name in ('candidate', 'repeat', 'baseline', 'output'):
    parser.add_argument(name, type=Path)
parser.add_argument('--test-report', type=Path)
args = parser.parse_args()
image = 'r5s-rtl8125-lan-repair.img'
manifest = f'{Path(image).stem}.manifest.json'
first, repeat = (directory / image for directory in (args.candidate, args.repeat))
if first.samefile(repeat) or sha256(first) != sha256(repeat):
    parser.error('candidate and repeat must be independent, byte-identical images')
verified = {}
for label, path in (('candidate', first), ('repeat', repeat), ('baseline', args.baseline / image)):
    embedded = verify(path)
    if embedded != json.loads(path.with_name(manifest).read_text()):
        parser.error(f'embedded and external manifests differ for {path}')
    verified[label] = embedded

scripts = Path(__file__).resolve().parent
root = scripts.parent
archive = runpy.run_path(str(scripts / 'package-router'))['archive']
args.output.parent.mkdir(parents=True, exist_ok=True)
with TemporaryDirectory(dir=args.output.parent) as temp:
    work = Path(temp)
    stage = work / 'stage'
    for label, directory in (('candidate', args.candidate), ('baseline', args.baseline)):
        dest = stage / label
        dest.mkdir(parents=True)
        for name in (image, manifest, 'system.system',
                     'layout-report.json', 'microkit-report.txt'):
            shutil.copyfile(directory / name, dest / name)
    for directory, names in (
        ('scripts', [path.name for path in scripts.glob('*.py')] +
         ['benchmark-router-board', 'decode-b51-uart', 'flash-sd', 'read-b51-udp',
          'read-r5s-platform', 'verify-image']),
        ('docs', ['r5s-datapath-performance.md', 'r5s-optimization-report.md', 'r5s-overlay-writer.md',
                  'rtl8125-b51-root-cause.md', 'sd-writing.md',
                  'tso-capability.md', 'tso-hardware-validation.md', 'zero-copy-forwarding.md']),
        ('protocol', ['diagnostics-v2.json']),
    ):
        (stage / directory).mkdir()
        for name in names:
            target = stage / directory / name
            shutil.copyfile(root / directory / name, target)
            if directory == 'scripts' and target.suffix != '.py':
                target.chmod(0o755)
    (stage / 'reproducibility.txt').write_text(
        f'Candidate and independent repeat passed image verification.\nSHA256 {sha256(first)}\n')
    comparison = {key: dict(sha256=sha256(path), profile=verified[key]['profile'],
                           schedule=verified[key].get('router_schedule'),
                           offload_requests={field: verified[key][field]
                                             for field in ('tx_ipv4_checksum_requested', 'tso_requested', 'tso_ipv6')
                                             if field in verified[key]},
                           options=verified[key].get('optimization_options', {}))
                  for key, path in (('candidate', first), ('baseline', args.baseline / image))}
    before, after = (comparison[label]['options'] for label in ('baseline', 'candidate'))
    comparison['same_sdk_configuration'] = (before.get('R5S_SDK_CONFIG', 'debug')
                                              == after.get('R5S_SDK_CONFIG', 'debug'))
    comparison['option_differences'] = {
        key: dict(baseline=before.get(key), candidate=after.get(key))
        for key in sorted(before.keys() | after.keys()) if before.get(key) != after.get(key)
    }
    (stage / 'comparison.json').write_text(json.dumps(comparison, indent=2, sort_keys=True) + '\n')
    (stage / 'README.md').write_text(
        '# NanoPi R5S performance images\n\n'
        'Run `sha256sum -c SHA256SUMS` from this directory. Image verification requires '
        'Python 3, `fsck.fat` and `mcopy`.\n\n'
        f'- Candidate image at `candidate/{image}`.\n'
        f'- Comparison image at `baseline/{image}`.\n'
        '- Image hashes, schedules and recorded build options are in `comparison.json`.\n'
        '- Follow the [guarded SD deployment and board benchmarks](docs/r5s-datapath-performance.md#validation-and-deployment).\n')
    if args.test_report:
        shutil.copyfile(args.test_report, stage / 'test-report.md')
    sums = {path.relative_to(stage): sha256(path) for path in sorted(stage.rglob('*')) if path.is_file()}
    (stage / 'SHA256SUMS').write_text(''.join(f'{digest}  {path}\n' for path, digest in sums.items()))
    staged_archive = work / args.output.name
    archive(stage, staged_archive, executable_scripts=True)
    extracted = work / 'extracted'
    with tarfile.open(staged_archive) as bundle:
        bundle.extractall(extracted, filter='data')
    if any(sha256(extracted / path) != digest for path, digest in sums.items()):
        sys.exit('extracted bundle checksum mismatch')
    for label in ('candidate', 'baseline'):
        subprocess.run([extracted / 'scripts/verify-image', extracted / label / image],
                       check=True, stdout=subprocess.DEVNULL)
    archive(stage, args.output, executable_scripts=True)
